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
930,347
Use GraphQL without writing GraphQL
👍 Follow me on Twitter @andycoupedev In this walkthrough, we are going to create a full stack...
0
2021-12-19T12:49:45
https://dev.to/andrewmcoupe/use-graphql-without-writing-graphql-53ae
graphql, react, webdev, typescript
👍 Follow me on Twitter [@andycoupedev](https://twitter.com/andycoupedev) In this walkthrough, we are going to create a full stack application with full type safety using GraphQL without writing any actual GraphQL with the star of the show being GenQL. Below is a list of tools we will be using. - [TypeScript](https://www.typescriptlang.org/) - typed JavaScript from the future. - [Hasura](hasura.io) - instant GraphQL and REST APIs on new or existing data sources. - [React Query](https://react-query.tanstack.com/overview) - manage fetching, caching and server state easily. - [GenQL](https://genql.vercel.app/) - Generate a type safe GraphQL client for our GraphQL API. - [NextJS](https://nextjs.org/) - Arguably the best React framework. ## Create our frontend To generate our frontend let's create our NextJS TypeScript project with the following command from a directory of your choice. `npx create-next-app@latest your-app-name --ts` ## Create our GraphQL API For our GraphQL API, let's head over to [Hasura](hasura.io) and create a project - you'll need to create an account. Once you've done that, select the create project option and select all of the free tier options. Click "Launch Console" and you should be presented with the Hasura console. We have rapidly generated the frontend and API layers of our application, leaving just the DB layer left. Thankfully, Hasura has our back. Click on the "Data" tab from the Hasura console and you should see a button to connect a database. From here, there should be a "Create Heroku database" option. Follow these steps (you may have to sign up to Heroku if you're not already signed up) and we'll have a Postgres database managed by Heroku, connected to our GraphQL API. ![app diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rskzyyop9660a6y1b8an.png) ## Create our database Now, let's create a table. For this application I'm going with a football (soccer) theme so let's name our table `teams`. ![creating a table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xtfosbwybp77b4l6lixm.png) The frequently used columns button is useful and lets us quickly add columns `id`, `created_at` and `updated_at`. Add a column of type `Text` named `name` to store our team names as well. ![adding a new table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7d1i01canyokv05l5i5r.png) Click "Add table" to create the table. After creating the table, the insert row tab will allow us to manually create a row in the table, let's do that and hit "Save". ![Creating a row](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r86muczguhmtz0r4lz4g.png) Head over to the "API" tab and you will now be able to query the data from our database using Hasura's playground 😎. ![querying data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k38tityinso6vv239m46.png) ## Back to the frontend We have our backend setup. To interact with our GraphQL API from our frontend we are going to generate a GraphQL client using [GenQL](https://genql.vercel.app/) so we need to install some dependencies in our NextJS application. ``` npm i -D @genql/cli # cli to generate the client code npm i @genql/runtime graphql # runtime dependencies ``` @genql/cli is a dev dependency because it is only required to generate the client, @genql/runtime instead is a direct dependency of the generated code. To generate our client we can use the following command. ``` genql --endpoint <your graphql endpoint from hasura console> --output ./genql-generated -H 'x-hasura-admin-secret: <your admin secret from hasura console>' ``` The generated files expose a function `createclient`. This creates a client you can use to send requests. Let's create a file at the root of our project named `genql-client.ts` with the following contents to create our client. ```javascript import { createClient } from "./genql-generated"; const client = createClient({ url: <your graphql endpoint from the hasura console>, headers: { 'x-hasura-admin-secret': <your hasura admin secret from hasura console>, }, }) ``` With our GraphQL client in our holster, we're ready to start firing requests. We are going to use React Query to manage fetching and server state. ``` npm i react-query ``` For the purpose of this walkthrough we will just make the request in the default index page provided by NextJS. So head to `pages/index.tsx` and import our client below the rest of the existing imports. I like to work inside the `src` directory so your imports may be a level higher than mine. NextJS supports moving the `pages` directory into a `src` directory out of the box. ```javascript // ...existing imports import { client } from '../../genql-client' ``` Let's create a function to fetch the teams in our database. Don't just copy and past the code below. Type it out and appreciate the autocompletion using CMD or CTRL + SPACE depending on your OS 😎 ```javascript const fetchTeams = () => { return client.query({ teams: [{}, { id: true, name: true, created_at: true }], }); }; ``` Consult the GenQL docs on the syntax but you can get the general idea of how to build a query. Once again, autocompletion will guide you like a good friend. Our generated files also export an object called `everything` which allows us to query all fields in a type instead of providing a boolean to every type, like so. ```javascript // ...existing imports import { everything } from "../../genql-generated"; const fetchTeams = () => { return client.query({ teams: [{}, everything] }); }; ``` Now let's bring in `useQuery` from React Query and wire it up to our fetchTeams function. ```javascript // ...existing imports import { client } from "../../genql-client"; import { everything } from "../../genql-generated"; import { useQuery } from "react-query"; ``` Invoke the `useQuery` hook inside the `Home` page component and provide it with your query key and query function as the second and third arguments respectively. ```javascript const { data } = useQuery("teams", fetchTeams); ``` Almost there! We need to wrap our app in a `<QueryClientProvider />` component provided to us by React Query. This will have to be added further up the tree in the `_app.tsx` file. Update `_app.tsx` with the following code. ```javascript import type { AppProps } from "next/app"; import { QueryClientProvider, QueryClient } from "react-query"; const queryClient = new QueryClient(); function MyApp({ Component, pageProps }: AppProps) { return ( <QueryClientProvider client={queryClient}> <Component {...pageProps} /> </QueryClientProvider> ); } export default MyApp; ``` Let's update our `index.tsx` page to look like the following and we should be seeing our team rendering on the page. ```javascript import type { NextPage } from "next"; import styles from "../styles/Home.module.css"; import { useQuery } from "react-query"; import { client } from "../../genql-client"; import { everything } from "../../genql-generated"; const fetchTeams = () => { return client.query({ teams: [{}, everything] }); }; const Home: NextPage = () => { const { data, isLoading } = useQuery("teams", fetchTeams); return ( <div className={styles.container}> <h1>Teams</h1> {isLoading && <p>Loading...</p>} {data && data.teams.map((team) => <p key={team.id}>{team.name}</p>)} </div> ); }; export default Home; ``` There are certain best practices to follow when using React Query with SSR/NextJS that are beyond the scope of this walkthrough which can be found [here](https://react-query.tanstack.com/guides/ssr). I may do a follow up post using mutations and GenQL to create a CRUD application but hopefully this has shown you the power of GenQL
andrewmcoupe
930,403
Rust in Linux, AoT Compiler in React
Some interesting things are happening in the development space as we head into 2022. I will highlight...
0
2021-12-20T10:27:04
https://dev.to/keymannerdawid/rust-in-linux-aot-compiler-in-react-2a44
rust, react, linux
--- title: Rust in Linux, AoT Compiler in React published: true description: tags: rust, reactjs, linux //cover_image: https://www.youtube.com/watch?v=lGEMwh32soc //https://direct_url_to_image.jpg //comments: https://deliverystack.net/2021/06/25/comparing-rust-and-c/ --- Some interesting things are happening in the development space as we head into 2022. I will highlight two ### Rust I am very excited about conversations materializing into Rust's adoption as [linux's second language] (https://www.zdnet.com/article/rust-takes-a-major-step-forward-as-linuxs-second-official-language/) (also the [preamble](https://www.zdnet.com/article/rust-in-the-linux-kernel-why-it-matters-and-whats-happening-next/), and [here too] (https://www.theregister.com/2021/11/10/where_rust_fits_into_linux/)). This is of-course great news for Rust's adoption metrics, but as an applications developer, I believe this will expose some application developers to start using Rust. Personally I have wanted to adapt a systems programming language, since this will make for a better developer, and Rust is my top candidate I believe Rust stands on its own merit on speed and memory safety, and this is no mean feat i.e. writing code without sacrificing safety - and not depending on garbage collection for this by enforcing proper coding conventions. Memory safety enhances application security and stability. The speed metric is comparable to C, C++ > As revealed by a Microsoft engineer in early 2019, about 70% of all vulnerabilities in their products are due to [memory safety issues.](https://www.zdnet.com/article/microsoft-70-percent-of-all-security-bugs-are-memory-safety-issues/) I hope Rust will **a)** either be adapted into a major game engine or **b)** one of Rust's game engine will have wide scale adoption. This will encourage development of games with surety of the aforementioned features, in essence increasing adoption.. well.. my adoption at-least 😬. > some game engines https://github.com/PistonDevelopers https://www.libhunt.com/l/rust/topic/game-engine https://github.com/rg3dengine/rg3d https://medium.com/pragmatic-programmers/game-development-with-rust-31147f7b6096 Rust is a newer generation language that stands on the shoulders of its predecessors, adopting years of learnings and research in language design. In this regard, Rust tries to bridge the worlds of Application and System development. Rust also has high priority for [interop](https://sebnilsson.com/blog/from-csharp-to-rust-introduction/) with other languages [Rust in C#](https://codingupastorm.dev/2020/05/04/executing-rust-from-csharp/), [Rust in Unreal](https://ejmahler.github.io/rust_in_unreal/) ### React I think I have waxed lyrical on Svelte [enough times](https://keymannerdawid.medium.com/react-hooks-svelte-knockoutjs-angular1-in-2021-cd7c647d47a9). Svelte popularized Ahead-of-Time compilation in front-end frameworks, eliminating the use of [shipping a runtime with compiled code](https://www.syntaxsuccess.com/viewarticle/optimizing-applications-using-svelte), but I digress. The idea of Ahead-of-Time compilation for app memoization is currently being researched in React Labs, the [auto-memoization compiler](https://youtu.be/lGEMwh32soc), ensuring optimized output. I really do commend the approach of the react team on implementing updates: New features are introduced whilst ensuring backwards compatibility, giving developers enough time to migrate to the 'new normal'. 👍🏽 Happy Holidays, Onwards to 2022
keymannerdawid
930,468
Understanding Web Cookies
Web cookies often have a negative connotation. In reality, they are indispensable tools for websites...
15,975
2021-12-19T12:30:42
https://dev.to/clementgaudiniere/understanding-web-cookies-3161
webdev, codenewbie, beginners, productivity
_Web cookies often have a negative connotation. In reality, they are indispensable tools for websites and sometimes save you time. In this article, we will look at how cookies work, the different types of cookies, what benefits they can bring to your website or the regulations concerning them... In a next article we will see how to implement them in our web page code._ --- ### Received ideas Since the creation of cookies, many rumors have developed: - Cookies are like viruses, they infect users' hard drives. - Cookies are used to send spam. - Cookies are used only for advertising. We will see in this article that all these rumors are false. ![Cookie hide](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yk5xpfo9ced5u7l0t9ie.png) --- ### How it works ? A web cookie is defined by the HTTP communication protocol as a small text sent by an HTTP server to an HTTP client, which the latter will send back the next time it connects to servers sharing the same domain name. It consists of a text containing an arbitrary sequence of key-value pairs. It is stored on the client's computer for a specific period of time. For example, if you log in to a website and don't want to log in the next time, sometimes you can check the box "keep my session active" or "remember me". In this case, one or more cookies are created and stored on your computer to automatically log you in the next time you access that website. The cookies can be the following: - nickname : mypseudo - password : azerty (In reality the password cookies are often encrypted, for security) --- ### A bit of history Now we can ask ourselves how long have cookies been around ? The term cookie is a derivation of magic cookie. In programming, a magic cookie is a packet of data that a program receives and sends back unchanged. In 1994, Lou Montulli, an American computer scientist, had the idea of using cookies for client-server exchanges on the Web. At the time, he was an employee of Netscape Communications, a company developing Web browsers. ![Netscape Browser logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1pk6hze5urugnrxx8cmz.jpg) The first use of cookies was to determine whether visitors to the Netscape website had visited the site before. After being implemented in the Netscape 0.9 beta Web browser in 1994, cookies were integrated into Internet Explorer 2, released in October 1995. Cookies were accepted by default in browser settings, and users were not informed of their presence. The general public only learned of their existence after the Financial Times published an article on February 12, 1996. That same year, cookies received a lot of media attention because of possible privacy intrusions. From the end of 2014, we see a banner about cookies on many sites. Depending on the country and continent, the regulations are not the same. ![Cookie Banner exemple](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6wxnjuy5d4298fb8dggy.jpg) --- ### Why they have a bad reputation ? So why do they have such a bad reputation ? On the one hand, cookies are stored on the customer's computer and therefore take up storage space. Even if it is often tiny, the accumulation of cookies can end up weighing a real weight in the storage of the device. On the other hand, as we have seen before, they can be an intrusion of privacy. Indeed, other types of cookies, called third-party cookies, can track users through the different sites they visit. For example, some advertising companies can track users across all pages where they have placed advertising images or a spy pixel. The knowledge of the pages visited by the user allows the advertising companies to target the user's advertising preferences. The ability to build a user profile is considered by some to be an invasion of privacy, especially when tracking is done through different domains using third-party cookies. For this reason, some countries have cookie legislation. --- ### To be in order To be sure to comply with regulations, it is best to set up a cookie banner warning users. Ideally, the user can either accept all cookies or manage their preferences. To save time when developing websites, many developers use cookie consent libraries. This way, their site follows the legislation, without requiring a large development effort. For my part, I use [this library](https://github.com/clement-gaudiniere/librairie-cookie-consent), developed by myself 😆. It is very easy to use, and offers a clean and customizable banner for your website. To understand how it works, just read the github documentation. I will make an article detailing it later. {% github clement-gaudiniere/librairie-cookie-consent %} --- I hope you learned something about cookies, feel free to ask me any questions you may have. 👍 --- You want to support me ? [![Buymeacoffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4b9u45k83m0gjbk2vo8m.png)](https://www.buymeacoffee.com/clemgaudiniere) OR [![Patreon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e784und5tziinkkhg0im.png)](https://www.patreon.com/clementGaudiniere)
clementgaudiniere
930,507
Done is better than perfect
Introduction "Done is better than perfect" is a lesson that I learned from working in a...
0
2021-12-19T15:13:24
https://www.itsnikhil.codes/posts/done-is-better-than-perfect/
motivation, computerscience, startup
## Introduction "_Done is better than perfect_" is a lesson that I learned from working in a fast-paced competitive startup environment.. and agile software development in general. Every new codebase I used to touch, I could find some place where something can be improved by using a different data structure, or an algorithm, or some design pattern avoiding nested if-else, or simply abstracting big functions into smaller ones. But as when I started working on big features I came to realize this famous saying. In this article, I would like to share some of my thoughts on this ideology and hopefully give you some motivation to release your next amazing startup or project you are working on and not get yourself stuck in catch-22. ## Perfection > the state or quality of being perfect In software development world - When you’ve developed a working product, it’s normal to take pride in its performance you’ve worked hard on it. It’s normal to want to hold off on release until it’s got _this_ feature, or _that’s_ been tweaked, or it’s gone through yet another round of testing. _Source:_ [_The ‘done is better than perfect’ approach to programming - Parker Software_](https://www.parkersoftware.com/blog/the-done-is-better-than-perfect-approach-to-programming/) ## Chasing perfection If somebody asks me if the system I have developed is perfect or not? I would say comeback after couple of years and ask the same question as I cannot answer it today. Gone are the days where software was sold via floppy disk/DVDs, now software's are getting more personalized and unique to each and every customer. System once perfect needs to evolve with new requirements which one would have never anticipated while designing/developing it. Over-engineering is often identified with design changes that increase a factor of safety, add functionality, or overcome perceived design flaws that most users would accept. It can be desirable when safety or performance is critical (e.g. in aerospace vehicles and luxury road vehicles), or when extremely broad functionality is required (e.g. diagnostic and medical tools, power users of products). As a design philosophy, it is the opposite of the minimalist ethos of "less is more" (or: “worse is better”) and a disobedience of the KISS principle. _- Wikipedia_ ### Example Let's say you are a student and as an assignment your teacher asks you to submit a research report on sustainable future or solar energy before next week. If you submit your assignment after the deadline, your marks will get affected even though how in-depth you went into research analyzing sun's orientation, affect of weather, calculating perfect tilt angle, finding how much power output one solar panel can generate, finding return on investment... doing justice to the topic. Even if your teacher was generous and because of your amazing report gave you full marks. This is not always the case, imagine if this was a question part of your final exam and if you spend all the time answering it so well, you will not get enough time to answer other questions. Some might argue in the above example a short-crisp, to the point answer would have been perfect. In reality it takes a lot of good efforts, right knowledge and experience, to setup a great foundation and even then you have to adapt to changes and keep on enhancing the product. Maybe this example is not perfect, so are the projects we work on. There are memes around project requirement not being clear enough. Not everyone is building a medical device where margin of error is a difference of life and death where you have to consider using special tools like [ROS](https://www.ros.org/ "ROS") to control system clock and scheduler. Not every requirement is like [The Thames Barrier must never fail. Here's why it doesn't. - YouTube](https://www.youtube.com/watch?v=eY-XHAoVEeU) ## Finding the balance ### Understand the requirements Let's say you are working on a feature that will be very important for winter vacation season sale - Chrisman and New Year. Then this is a strict requirement which you have to follow. Christmas is always on 25th of dec. and if your feature is not ready by then business can get affected. That being said not all requirements are strict and it is important to understand them well to avoid doing unnecessary work. Writing good readable code, following coding standards (linters) and writing testcases should be part of requirements of a good tech team and should be caught in code reviews. Once I was almost about to write a wrapper library on top of RestAPIs of one of our web service. Was it part of the project requirements? - No! Were estimates taken in account for writing the library? - No! ### Know your customer Your customer is the consumer of the features you build. You should be aware of the impact it can have on them not just positively but repercussion if anything goes wrong. This provides sense of responsibility you have, skipping on testcases and not doing non-functional requirements testing reduces your confidence so it is advised to given them attention. Trust me, it makes you happy seeing your customers are happy. Will customer's care about the technology used? - No/maybe! Will customers have a bad experience if they are not able to login? - Definitely! ### What are your expertise One cannot have knowledge of everything. You should know your boundaries and capabilities. Technology evolves rapidly and it's very hard to keep up-to date with everything. This not only restricted to knowledge of a particular programming-language/framework. If you are asked to make changes in a totally new codebase, You are no longer an expert and it's your responsibility to get enough context/knowledge from the right person to do full justice to the requirements and communicate this thing clearly to your manager. ### Engineering process is a loop ![Is the following diagrams correct for RAD and Agile ...](https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.stack.imgur.com%2FKdKKT.png&f=1&nofb=1) We(Software engineers) have luxury to ship the Minimal Viable Product (MVP) and constantly evolve it incrementally. We do not need to know the final state of the project in the beginning. We should be able to collect necessary feedback and act upon data what works and what does not. This also applies to issues, gives us ability to accept stop gaps while actual fix gets released in next sprint. _Good read:_ [_Scaling with common sense - Zerodha Tech Blog_](https://zerodha.tech/blog/scaling-with-common-sense/)
itsnikhil
930,512
Frontend Challenge #9, Base Apparel Component
Follow me as I briefly describe my coding journey to build the Base Apparel component from Frontend...
15,949
2021-12-20T02:27:41
https://dev.to/jcsmileyjr/frontend-challenge-9-base-apparel-component-3g68
beginners, challenge, devjournal, codenewbie
Follow me as I briefly describe my coding journey to build the Base Apparel component from [Frontend Mentors](https://www.frontendmentor.io/home). I’m a firm believer in learning in public, not being perfect, and each day improving by 1%. I welcome feedback from anyone and will update the final project as time allows. Frontend Mentors is a online platform that provide front-end challenges that include professional web designs. **The goal is to build this:** ![desktop design from Frontend Mentors](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8e3p1f42sq1v5ymim6k7.jpg) ## Step 1: First Stumbling block, the mobile responsive layout In my mind, the visual layout can be sectioned into a header, main content, and image areas that are layered differently on the mobile and desktop designs. I needed to use CSS-Grid to move them around based on those two different designs. This led to my first stumbling block in that I've forgotten how to use CSS-Grid. I revisited several of my favorite resources, [CSS-Tricks](https://css-tricks.com/) and [CSS Generator](https://cssgrid-generator.netlify.app/), for guidance. While these resources were helpful, a simple spelling error cost me several days of frustrations. ![CSS Grid code with error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jw7pa09kxxpcov3ecpqm.png) ## Step 2: Lessons relearned in every project I’m ashamed to say but I just can’t remember CSS variables and routine styling for background images. So I’m explicitly posting this here so I can pull up next quicker. _Code block showing CSS Variables_ ![Block of code demoing CSS Variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijiuyyhz9v0a76lh2bgf.PNG) ![Block of code demoing CSS Variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/955xfxbxxbho9ykogya7.PNG) _Code block showing CSS style for background images_ ![Block of code demoing CSS style for background images](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jn0ypdfaao5zoxhgbqud.PNG) ## Step 3: Styling the content in the mobile layout While this didn't take a long time, I think I gained some valuable experience. 1. Use CSS Variables to apply consistent colors quickly 2. There are so many ways to style a header. For this project, I needed it's text uppercase, center align, huge font size, spacing between the letters. ![Block of code demoing styling H1 element](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r4ffi444gcqkh0pq4ihy.PNG) ## Step 4: Major pain in the neck was an input field with a SVG inside of it While this looked simple, my first attempt at using CSS to position the SVG inside the input field failed miserably. So I burned that code to the ground and started over. This time, I use a div with an input and image inside of it with Flexbox to the rescue. ![mobile design layout](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cso13tbkidx65d81s61l.PNG) # Step 5: Desktop responsive layout design This wasn’t hard but a short grind to make tiny changes to each element’s layout and styled based on the larger designs. ![Desktop design layout](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mhlnup2ft2ojzg2hdb05.PNG) # Step 6: The final task is developing an active state with JavaScript The last task is when a user inputs an incorrect email format into the input field, an error image and message is shown. I’m sure there are better methods but my default is to add and remove a “hide” class on an element. I added an additional image within the input field and a label for the message below the input field. _JavaScript functionality_ ![Block of code showing the functionality](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z2hgtyag8lywipb6ecyy.PNG) _HTML layout for error handling_ ![Block of code showing the HTML of the error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k2u4tyy6izf1spd3csda.PNG) _Image of the error results_ ![Live demo of the error handling](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5nz0cnxn86gte580v1fy.PNG) ## Final Outcome ![Finished Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gr0t82tj7udkq4cw9jbm.png) You can find the completed code [here](https://github.com/jcsmileyjr/Base-Apparel-Component) and play with site [here](https://jcsmileyjr.github.io/Base-Apparel-Component/). ## What I learned 1. How to change an HTML input's placeholder color. 2. CSS Grid is great for creating dynamic layouts. 3. I still don’t understand SVG and how to use them properly. ## Resources used 1. [CSS-Tricks blog post on CSS Grid](https://css-tricks.com/) 2. [CSS Generator tool](https://cssgrid-generator.netlify.app/) 3. [CSS-Tricks blog post on Linear gradients](https://css-tricks.com/almanac/properties/b/background-image/) 4. [CSS-Tricks blog post on CSS gradients](https://css-tricks.com/a-complete-guide-to-css-gradients/) 5. [w3schools documentation on Input's Placeholders with CSS ](https://www.w3schools.com/howto/howto_css_placeholder.asp) 6. [Mozilla.org documentation on checking validity](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/checkValidity ) 7. [Mozilla.org documentation on creating event listeners](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) ### Thank you for reading, let's connect: Obviously, this isn’t a perfect solution. I couldn't figure out the desktop's background image perfectly and other things. Thank you for reading my learning journey and if you have tips, please DM me on [Twitter](https://twitter.com/JCSmiley4) or [LinkedIn](https://www.linkedin.com/in/jcsmileyjr/).
jcsmileyjr
930,627
Lista de ingresos de cripto
Aquí les dejo una primera parte de una lista de plataformas que pagan y generan ingresos en...
0
2021-12-19T18:16:14
https://dev.to/devtothemoon/lista-de-ingresos-de-cripto-hii
cripto, ingresos, criptomonedas
Aquí les dejo una primera parte de una lista de plataformas que pagan y generan ingresos en conjunto: [Stormgain](https://app-stormgain.com/friend/BNS63509693) Mineria en la nube [LBRY](https://odysee.com/%24/invite/@pronet:c) Ver videos desentralizados [THETHA.TV](https://www.theta.tv/invite/udtg9c) Ver Directos descentralizados [Binance](https://www.binance.com/es/register?ref=53372403) Para que creen su cuenta en binance y comiencen a acumular sus ganancias y ganar intereses en staking [LEDGER](https://shop.ledger.com/pages/back-to-school?r=b4cf2d3b206e) Para comprar tu wallet ledger con descuento [Gana Bitcoins](https://freebitco.in/?r=38749528) Una página faucet que te regala pequeñas partes de bitcoin. [CoinMarketCap](https://coinmarketcap.com/invite?ref=4MJ2ECM8) Para ganar en los airdrops y los programas que tienen. [BingBon](https://invite.bingbon.com/SAKNN0) Un exchange donde incluye el servicio de copytrading Los ingresos pueden variar según su desempeño y tiempo dedicado. Pueden ir con inversión o sin inversión, si deciden invertir dependerá de la cantidad que introduzcan. Pero todas te pueden generar ingresos.
devtothemoon
930,633
tldr: Remember your commands
What is tldr? tldr is an open-source command line tool distributed both via npm and pip3...
15,976
2021-12-19T18:35:38
https://newcurrent.se/posts/tldr
bash, productivity, opensource, todayilearned
## What is `tldr`? `tldr` is an open-source command line tool distributed both via `npm` and `pip3` that lets you easily look up common use cases for various commands. Have you ever been in the position where you: - Forgot how to use the `tar` command? - Forgot how to open an `ssh` tunnel? - Forgot how `git rebase` works? - Forgot how to `…` in the terminal? Well, I have. `tldr` lets you easily look up common uses cases for commands and subcommands. All the `tldr` pages are open-source and community driven, and if a command you are trying to use `tldr` for is not available, you can always add it yourself to help out both yourself and others. --- ## How do I install it? To get your hands on `tldr`, all you have to do is install it in one of the following ways: - `npm install -g tldr` - `pip3 install tldr` After that, provided the package location is in your path, all you need to do is run `tldr git rebase` for example. Here's an example of what that might look like: ![tldr_img](https://newcurrent.se/images/tldr.png) --- ## More information If you have further interest in this, please visit [https://tldr.sh/](https://tldr.sh/)
simonnystrom
930,653
What is Collaborative IoT?
The problem After building the platform "House-Of-Iot"(HOI) that required users to have...
0
2021-12-19T19:20:12
https://dev.to/ronaldthenerdsuperuser/what-is-collaborative-iot-5b74
rust, react, algorithms, nextjs
## The problem After building the platform "House-Of-Iot"(HOI) that required users to have direct authentication credentials for the HOI general server, I realized there is no easy way to collaborate with others with less of a risk. HOI isn't the only platform that lacks built in minimal risk collaboration. The platform "Home Assistant"(HA) suffers from the same issue as HOI and requires direct access for collaboration. ## The solution The solution was to build a system that allows owners of an IoT server to temporarily and safely give others access, with the ability to easily revoke access. Users will join "Rooms", communicate in a clubhouse like environment and yield temporary control over their IoT server. ## What makes this safer than giving direct access? Direct access means users could directly communicate with a server with no restrictions, possibly even modify settings of the server and mess up the underlying functionality. ### Revoking/Giving access Users have permission levels when they join a room, each room has an "IoT Board" which is the panel for concurrently controlling multiple IoT servers at once. Once a user with mod permissions spawns a connection to their IoT server, they can give permission to anyone in the room to control it. When this user disconnects from collaborative or anything goes wrong with its communication, the user's spawned connection to the IoT server is destroyed along with everyone who had access. When this user decides they don't want a specific user to have control anymore, they can revoke access. Revoking access just removes the ability to control a specific spawned IoT server connection.
ronaldthenerdsuperuser
930,662
Using Docker Run inside of GitHub actions
With a specific action added in your job, you can use docker run to fire off singular containerized processes during one of your deployment steps.
0
2022-01-11T03:03:18
https://aschmelyun.com/blog/using-docker-run-inside-of-github-actions/
docker, devops
--- title: Using Docker Run inside of GitHub actions published: true canonical_url: https://aschmelyun.com/blog/using-docker-run-inside-of-github-actions/ description: With a specific action added in your job, you can use docker run to fire off singular containerized processes during one of your deployment steps. tags: docker, devops cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trmv6l2at98rguqa0ab0.jpg --- Recently I decided to take on the task of automating my site's build and deployment process through [GitHub Actions](https://github.com/features/actions). I'm using my own static site generator [Cleaver](https://github.com/aschmelyun/cleaver) to handle that, which requires both Node + PHP to be installed in order to run the asset compilation and build process. Now, GitHub Actions _supports_ both of those runtimes out of the box, but I had just created a perfectly good [Docker image](https://github.com/aschmelyun/cleaver-docker) for using Cleaver, and instead wanted to use that. Ultimately it was a mixture of just wanting the fine-grain control that a single Docker image provides, and because, well **I just wanted to see how to do it!** ## What Didn't Work So, you're able to actually use Docker images in GitHub actions, but by default you're only able to use them one of two ways. ```yaml jobs: compile: name: Compile site assets runs-on: ubuntu-latest container: image: aschmelyun/cleaver:latest ``` This first option is as the base for an entire job. Normally a lot of GitHub actions have you start off with an Ubuntu distro as the base for the VM (there are other OS's you can choose from as well) and then add in your container image. But the entire rest of the job uses _whatever container you specify_ as the starting point for **all** of the rest of the job's steps. ```yaml jobs: compile: name: Compile site assets runs-on: ubuntu-latest steps: - name: Run the build process with Docker uses: docker://aschmelyun/cleaver ``` This second option is as an action in the steps for a job. Instead of something like `uses: actions/checkout@v2`, you can instead specify a Docker image from the hub to run in its place. The problem with this one though is that you have to generate a Docker image that runs **specifically like a GitHub action expects**. That means things like avoiding `WORKDIR` and `ENTRYPOINT` attributes, as they're handled internally by the GitHub Actions worker. What I wanted was simply to be able to use `docker run ...` under a _single_ action in a job. ## What Worked I ended up finding an action available on GitHub by **addnab** called [docker-run-action](https://github.com/addnab/docker-run-action) that works exactly how I wanted. You specify an image, any options, and a list of commands to run with it, and only during that step of the build process is it used. ```yaml jobs: compile: name: Compile site assets runs-on: ubuntu-latest steps: - name: Check out the repo uses: actions/checkout@v2 - name: Run the build process with Docker uses: addnab/docker-run-action@v3 with: image: aschmelyun/cleaver:latest options: -v ${{ github.workspace }}:/var/www run: | composer install npm install npm run production ``` Let me break down what each of these lines does: ```yaml image: aschmelyun/cleaver:latest ``` This one is pretty obvious, it specifies the image that's pulled and used in the docker run command. I'm using mine for Cleaver that's on the public [Docker Hub](https://hub.docker.com/r/aschmelyun/cleaver), but you can also use a privately-owned image as well. ```yaml options: -v ${{ github.workspace }}:/var/www ``` Here I'm creating a bind mount from the current workspace to `/var/www`, which is the working directory that my Docker image expects. `github.workspace` includes all of the code checked out from our current repo, and I'm mounting that whole directory as that's what my build process expects. Because I'm using a bind mount, **anything done to this code will then be available to GitHub Actions** in any following step (like a deployment). ```yaml run: | composer install npm install npm run production ``` This is where I specify the actual commands I want to run against my container image. This action **ignores the entrypoint of the container image**, so even though normally using `docker run aschmelyun/cleaver:latest` it would run those three commands, using this action I have to actually specify them out again in the yaml. Once they complete, GitHub should now have a new `dist` folder in the workspace containing the compiled site assets that can then be deployed out to a production server. Once the job finishes up, that's removed and is never committed to the repo or accessible to a separate job. ## Wrapping Up Sometimes during a CI/CD process it's helpful to use a ready-made Docker image to run one-off commands and processes. This could be especially helpful if the software you need isn't available on the actions platform, or requires a lengthy setup process that's already written out in a Dockerfile. If you have any questions about anything in this article, or if you'd like to get more smaller pieces of regular content regarding Docker and other web dev stuff, feel free to follow or reach out to me on [Twitter](https://twitter.com/aschmelyun)!
aschmelyun
930,668
Weekly Digest 50/2021
Welcome to my Weekly Digest #50 and Happy Holidays everyone! This weekly digest contains a lot of...
10,701
2021-12-19T20:23:09
https://dev.to/marcobiedermann/weekly-digest-502021-2i3o
css, javascript, webdev, react
Welcome to my Weekly Digest #50 and Happy Holidays everyone! This weekly digest contains a lot of interesting and inspiring articles, videos, tweets, podcasts, and designs I consumed during this week. --- ## Interesting articles to read ### HTTP compression HTTP compression is an important part of the big web performance picture. We’ll cover the history, the current state, and the future of web compression. [HTTP compression](https://calendar.perfplanet.com/2021/http-compression/) ### **How to write a binary search algorithm in JavaScript** The binary search algorithm is a classic algorithm that lets us find an item in a *sorted* array in O(log n) time complexity. In this post, we’ll review how the algorithm works and learn how to implement it in Javascript. [How to write a binary search algorithm in JavaScript](https://typeofnan.dev/how-to-write-a-binary-search-algorithm-in-javascript/) ### **React Conf 2021 Recap** Last week we hosted our 6th React Conf. In previous years, we’ve used the React Conf stage to deliver industry-changing announcements such as *React Native* and *React Hooks*. This year, we shared our multi-platform vision for React, starting with the release of React 18 and the gradual adoption of concurrent features. [React Conf 2021 Recap - React Blog](https://reactjs.org/blog/2021/12/17/react-conf-2021-recap.html) --- ## Some great videos I watched this week ### Monorepos - How the Pros Scale Huge Software Projects Big companies, like Google & Facebook, store all their code in a single monolithic repository or monorepo… but why? Learn how to use tools like NPM or Yarn workspaces, Lerna, Nx, and Turborepo to scale your codebase {% youtube 9iU_IE6vnJ8 %} by [Fireship](https://twitter.com/fireship_dev) ### Dark mode - Designing in the Browser On this episode of Designing in the Browser, we’re going to take a look at dark mode with our host Una Kravets. {% youtube xococe8wq_g %} by [Google Chrome Developers](https://twitter.com/ChromiumDev) ### Authoring colors with DevTools Let’s take a look at some of the color features in DevTools. {% youtube TuR27BxCRVk %} by [Google Chrome Developers](https://twitter.com/ChromiumDev) --- ## Useful GitHub repositories ### Tech Interview Cheat Sheet Studying for a tech interview sucks. Here's an open-source cheat sheet to help {% github TSiege/Tech-Interview-Cheat-Sheet %} ### React Native Skia High-performance React Native Graphics using Skia {% github Shopify/react-native-skia %} --- ## dribbble shots ### Ride Booking ![by [Raju Husen](https://dribbble.com/shots/17092583-Ride-Booking)](https://cdn.dribbble.com/users/4205502/screenshots/17092583/media/d17b997aa32387e8d48e5e7cd4b9a687.png) by [Raju Husen](https://dribbble.com/shots/17092583-Ride-Booking) ### Lazy Daisy UI ![by [Halo Mobile](https://dribbble.com/shots/17090995-Lazy-Daisy-UI)](https://cdn.dribbble.com/users/26642/screenshots/17090995/media/6fd8c2f4200c2df1117c94b572dec575.png) by [Halo Mobile](https://dribbble.com/shots/17090995-Lazy-Daisy-UI) ### Online Course Dashboard ![by [Nela Rosdiana](https://dribbble.com/shots/17087509-Ajarin-Online-Course-Dashboard)](https://cdn.dribbble.com/users/5963189/screenshots/17087509/media/77ede34aabbea5e38654cb70c6435c78.png) by [Nela Rosdiana](https://dribbble.com/shots/17087509-Ajarin-Online-Course-Dashboard) --- ## Tweets {% twitter 1470417701931728909 %} {% twitter 1471216118236954630 %} {% twitter 1471158826288226306 %} {% twitter 1471743877916737537 %} {% twitter 1471855546580049925 %} --- ## Picked Pens ### 3D Stopwatch {% codepen https://codepen.io/jh3y/pen/JjrNZXa %} by [Jhey](https://twitter.com/jh3yy) ### Progress Clock {% codepen https://codepen.io/jkantner/pen/MWEmExB %} by [Jon Kantner](https://twitter.com/jonkantner) --- ## Podcasts worth listening ### Syntax – How To Do Things In Svelte In this Hasty Treat, Wes and Scott talk about how to do things in Svelte. {% spotify spotify:episode:5ToWTCq4n54SAET5pJYVmR %} ### CodePen Radio – With Ben Evans You might recognize [Ben Evans](https://codepen.io/ivorjetski) from his absolutely incredible CSS “paintings”, like the [portrait of his daughter](https://codepen.io/ivorjetski/pen/dBYWWZ) or the [still life](https://codepen.io/ivorjetski/pen/xMJoYO). Paintings aren’t the quiet word as Ben designs them all to be entirely scalable. {% spotify spotify:episode:5AhpnyteZEq9lgfyboqAq7 %} --- Thank you for reading, talk to you next week, and stay safe! 👋
marcobiedermann
930,730
AWS Connect and Lex the future of customer services
What is Customer Service? Customer service is the service provided by companies in order to interact...
0
2021-12-19T21:41:39
https://dev.to/aws-builders/aws-connect-and-lex-the-future-of-customer-services-2g68
aws, contactcenter, awsbuilders, amazonconnectandamazonlex
**_What is Customer Service?_** Customer service is the service provided by companies in order to interact with customers and anticipate the satisfaction of their needs. It is a very effective tool for interacting with customers, providing adequate advice to ensure the correct use of a product or service. **_What is Amazon connect and Amazon Lex?_** **Amazon Lex** is a service for building conversational interfaces in any application that uses voice and text. Amazon Lex provides advanced automatic speech recognition deep learning capabilities for converting speech to text and Natural Language Understanding. It also allows you to create applications with highly attractive user experiences. Amazon Lex uses the same deep learning technology that powers **Amazon _Alexa._** ![Natural Language Understanding](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9bbjd934hj8d13sz0vwt.jpeg) **Amazon Connect** is a fully cloud-based call center platform that can be configured in minutes, customized, and used by the customer service department. You can accept incoming calls and make outgoing calls, including optional toll-free numbers. Let's all go throughout an scenario where Connect and Lex could help your company's contact center. Title: **The unexpected day** When: **Today** **_Perfect world_** Three months prior to this day, it has been predicted that 250 agents were need it to work for 8 hours. The goal is to assist with 2500 possible calls based on historical data. 80% of these calls have to be answered between 20-30 seconds this service level benchmarks can varied depending on the customer service center. If the forecast is in place and all goes as planned the service level agreement will be at 90% which is consider a good day. **_Chaos_** Like any other type of service, there are always unexpected days where you have no control of what is happening. Some the scenarios that frequently affect customer service levels usually are : - The volume of calls is higher than forecast. This scenario impacts customer service levels (SL) by not having enough full-time equivalents (FTEs) to help with the number of uncalculated calls. - The volume of calls is lower than forecast. This scenario affects the investment budget by having extra full time equivalent (FTE), Part timers and other agents that were offert over time. - A higher number of absenteeism than calculated. - Extreme weather conditions. - Average Transaction Duration (AHT) in a nutshell poor time management during a transaction whether on the phone, responding to an email or in person. Taking these factors into account, a great solution that could be integrated to help during this unplanned moments is Amazon Lex assistant with a priority level 2. **_what do I mean by this?_** It means that when your company is short in agents or some aspect of your WFM team plan did not go as it was planned Amazon Lex could compensate with the required assistant need it during this hard times. Although technology offers other options, human interaction is vital to maintaining relationships between clients and servers. Here is a list of leading companies that offer a fully cloud-based customer service center - (The order of this list does not represent that one company is better than another in this article). - Amazon Connect - Talkdesk - Genesys PureCloud - LiveAgent eTollFree - Predictive Dialer - Greenlight CRM - AuguTech ## **How to create an Amazon Connect and Amazon Lex?** In this demo I am building from start to finish a Amazon Connect contact center with an Amazon Lex assistant. Amazon Lex is in charge of directing calls to corresponding groups according to the request. Amazon Lex will understand natural language at the time of the request. **_How to establish Amazon Connect._** **6 steps** 1. Select Amazon Connect 2. Identity Management 3. Administrator 4. Telephony Option 5. Data Storage 6. Review and Create **Under Customer Engagement Select Amazon Connect** ![connect](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/by06gsx5pjgr60dveii2.png) **Identity Management** In this step it is necessary to establish a unique name. Example "Support" - click on next (Next step). ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q1esy9kzhl1ibceewaxe.png) **Administrator** Enter your personal information or the respective administrator. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qz20js9cvxig5gndj9vb.png) **Telephony Options** You could establish a few type of connections: 1. service lines to receive calls only 2. service lines to contact clients only 3. you can also set the two types of services if the company needs it. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dfzn11iru98ava7u41xx.png) **Data Storage** Amazon Connect stores all information directly in S3 so you don't need to create a new database. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k5fg2ndeni7hfhmi64ly.png) **Final step review and create** ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a4wy7ocyf760oadkqk7y.png) ## **How to create a Lex Bot** **Click Amazon Lex** ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ts2iwcbv0tbpmtxb4n57.png) Amazon Lex allows any developer to create chatbots quickly and easily. With Amazon Lex, to get started, you can choose one of the sample bots provided below and build a new custom robot from scratch. **Create Lex** - Select Custom Bot - Select a name (Bot name) - Select voice (OutpuT voice) - Connection time assignment. 5 minutes (Session timeout) - Data Storage - Children's Online Privacy Protection Rule ("COPPA") (Important to click yes / yes) - Create ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xecq7r4cbkj5nc0tytv6.png) **Create an Intent** - Assign a unique name ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hhic3jh9uwjhhrtzxtj.png) **Sample expressions (Sample utterances)** Phrases to use for example. How can I help you? ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vipykdokfnjy0hgme57r.png) ## Connet & Lex hand by hand Now that the two services are established, it is time to bring them together. Now it's time to go back and open Amazon Connect. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5haum4wwyarzaf6tjlgp.png) Next is to choose the phone number from a predetermined list. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zsi6v2v9j5zlfo60z2yb.png) This is how the agent's control panel will look on AWS Connect UI. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0y9bjagg8t2h3gp4tdv6.png) Next go to the configuration guide. The first step will be to create a customer service department with a new number. Click Queue. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/upybmvjuol4uzmby6ile.png) Complete the department setup. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29skx6bmciqo5wrlc8mm.png) Then Create an agent profile. Click on Users (Routing profile) ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xou32745wnj19g4b4j8g.png) Set up the agent profile. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yoqsvzec9qbn8j4hemgn.png) Now that your agent was created. The agent can be assigned to any department. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dy4i6cn64j8uzwxif763.png) Next click on contact flow ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfbolvhoh7wdd3iwfsu0.png) Assign the contact flow ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rh4vc7f1trpqw970yvfx.png) Once the flow is created, you would able to see the contact flow connection create for you and ready to use out of the box. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3t5rh220wp7mhx6cu28.png) Hanging in there we are almost ready. Next step is to connect Amazon Lex ​​with the phone number created earlier. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d00cl4p0ray5xlgb1tmn.png) Testing the Amazon Lex ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/chfr09pmjabzrmf1e6et.png) You could also dial the phone number created earlier and hear the commands that you set during this project creation. ## conclusion I hope this article has shown you a simpler side of how easy it is to create an extraordinary and safe service in a short period of time and at a low price.
valaug
930,746
Minitutorial Android Studio: Utilizar ListView con arreglo
Bienvenido a un nuevo minitutorial El día de hoy les enseñaré como recorrer un arreglo...
0
2021-12-19T22:38:13
https://dev.to/fynio/minitutorial-android-studio-utilizar-listview-con-arreglo-1318
android, espanol, minitutorial, listview
#Bienvenido a un nuevo minitutorial El día de hoy les enseñaré como recorrer un arreglo utilizando un ListView. ![ListView](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tn66aljj3kmab3p2ppm8.png) ##Vamos al código! #activity_main.xml En nuestro **activiy_main.xml** agregaremos un **linearlayout** con orientación vertical y agregaremos un **listview** al cual le asignaremos un id al que llamaremos **listView1** ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> ``` #MainActivity En nuestro MainActivity crearemos un objeto llamado **lista** de tipo **ListView**. Dentro del método onCreate le asignaremos el id que creamos en el activity_main el cual era **ListView1** de manera que el código quede así: ``` public class MainActivity extends AppCompatActivity { ListView lista; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lista = findViewById(R.id.listView1); }}; ``` Debajo de nuestra lista crearemos un arreglo de tipo **String** al cual llamaremos **datos**. ``` final String[] datos = new String[]{"UNO", "DOS", "TRES"}; ``` Posteriormente agregaremos un **ArrayAdapter** tipo **String** y le asignaremos un layout tipo simple_list_item_1 y le pasaremos el arreglo llamado **datos** ``` ArrayAdapter<String> adaptador = new ArrayAdapter<String>( getApplicationContext(), android.R.layout.simple_list_item_1, datos); ``` Por último solo nos resta asignar ese adapter a nuestro listView llamado lista. ``` lista.setAdapter(adaptador); ``` Si desean obtener el valor seleccionado de la lista les dejo el siguiente código ``` lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Toast.makeText(getApplicationContext(), "Opcion seleccionada" + adapterView.getItemAtPosition(i).toString(), Toast.LENGTH_SHORT).show(); } }); ``` Con esto hemos finalizado el tutorial. Espero seguirles enseñando más de Android Studio en los próximos días, ¡¡¡saludos!!!. Les dejo el código completo en el siguiente enlace [Clic aquí para ver el código](https://github.com/fynio/arreglo_listview_android_studio.git) ##Hasta la próxima.
fynio
930,842
What is A/B Testing? A Definitive Guide
A/B testing is the process where we experiment with different variations of the website and analyze which variations work well in getting more traction. A/B Testing looks for potential changes and enables data-driven decisions for ensuring positive outcomes.
0
2021-12-20T03:52:26
https://dev.to/vijaykhatri96/what-is-ab-testing-a-definitive-guide-3pk2
testing
--- title: What is A/B Testing? A Definitive Guide published: True description: A/B testing is the process where we experiment with different variations of the website and analyze which variations work well in getting more traction. A/B Testing looks for potential changes and enables data-driven decisions for ensuring positive outcomes. tags: Testing //cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1s42kt1xtrqhsncq7s0l.png --- Due to a considerable dependency on data, every company is now moving to data-driven marketing. The time had changed when people made decisions based on the assumptions and lacked efficiency of the outcome. Now, marketers use the scientific approach that relies on data and tests them to get a favorable outcome. One of the best ways to test the massive amount of data is A/B testing, eliminating the uncertainty by focusing on facts and concrete data to get results. Today, millions of businesses use A/B Testing to understand the customer’s behavior and the website elements, getting more traffic. To implement successful A/B Testing, you need to create a detailed process, set it up, and learn new tools to get accurate results. You will get a degree of freedom to experiment and improve the performance of your website. This article will learn about A/B testing, how to perform A/B testing, different approaches, and its benefits. ## What is A/B Testing? Sometimes, It can be called split testing, but there is a fine line between them. A/B testing is the process where we experiment with different variations of the website and analyze which variations work well in getting more traction. A/B Testing looks for potential changes and enables data-driven decisions for ensuring positive outcomes. It is not only limited to proving how changes impact the conversions in the short term. It allows the business to focus on its next step towards success. In A/B testing, A is considered the original testing variable, while B is the newly created ‘variation’ of the original testing variable. The variation that brings more traction to your business is the ‘winner.’ You can implement those changes to your website to optimize and increase business ROI. You can use this data to analyze user behavior, engagement rate, pain points, etc. it is essential to implement A/B Testing or lose out on potential business. ## Different A/B testing approach In performing A/B testing, you do not have to worry about learning all the maths involved to analyze the results. You can only work with statistics to improve the performance. You can perform A/B testing using two main statistical methods. Let’s have a look. * Frequentist approach Using this approach, you will get the reliability of your results based on the confidence level. If the result is at a 95% level or above, it is most likely to have a 95% chance of being correct. But the value of the confidence level is worthless until the test ends itself to provide the exact value. * [Bayesian approach](https://www.sciencedirect.com/topics/engineering/bayesian-approach) You will get a probability result using this approach once the test starts. This approach overcomes the drawback of frequentist, as you do not have to wait till the end of the test. You can then interpret and analyze the data once you get the probability. But it also comes with a challenge- You must read the estimated confidence interval while the test is running. It will help you to believe with the generated probability and help in improving the winning variant as per the intermediate confidence level values. ## Benefits of implementing A/B Testing Before implementing A/B testing, you must understand the importance of accurate results. We have come up with some benefits that you can leverage with A/B testing. * Better user engagement For any online business, user engagement is one of the topmost priorities. But how to find those elements considered by the users and improve them accordingly. Using A/B testing, you can analyze the trend using data and various variants. It will provide you with the scope for improvement and change. Once you get the details for the required changes, it will improve the user engagement to success. * Engaging content Testing several variants requires creating a list of all potential improvements. One of the items on the list is to improve the quality of the content. With A/B testing, you can also analyze the behavior of the users towards your content, and if it requires improvement, you can change it to make it more effective to generate more leads. * Reduced bounce rates One of the major concerns of any business is the bounce rate of the users. If the user is not spending enough time on the website and moving to competitors, it will be a loss. It helps improve those components of the website that ensure that users will spend more time on the website and make sales. * Increased conversion rates Once you analyze the data to get the insights of your website using A/B testing, you can make the required changes to improve the performance and enhance the user experience. This will influence the users to make sales and increase the conversion rates. * Ease of analysis A/B test is straightforward to provide an accurate result and metrics. Earlier A/B testing metrics included only the raw numbers that were insufficient to decide. But with the introduction of various tools, it has become easier to make concrete analyses and improve the business’s performance. * Everything is testable It is capable of testing every component of the website, including forms, images, and text, along with any element of the app. Implementing the required changes based on the tests can improve user engagement and conversion rates. * Reduced risks By A/B testing, you can avoid costly and time-intensive changes resulting in well-informed decisions. Avoiding such mistakes will reduce the risk and increase the chances of quick success. ### Limitations of A/B Testing Well, you know how A/B testing can help your business boost its productivity and performance. But, it also comes with limitations that you should know while implementing A/B testing and how you can overcome them to leverage its actual benefits. So, here are some limitations that you might concern. * For conducting A/B testing, your business must ensure high traffic so you can analyze data and provide trustworthy outcomes. * As A/B testing results will help your business make further decisions, if you do not have the correct sample data, it can lead to wrong decisions that can impact your business and reduce the leads. * If your website is not getting traction and you want to make changes. But deciding what to change and improve is challenging as marketers do not know which element impacts sales. * It is an iterative process, and if you do not continue it for a long time, you will not get the optimum result. So it could be challenging for the marketers to continue it for a long time. ### Best practices for A/B Testing For implementing any process, there are some standard procedures. Also, for carrying out A/B testing, you can follow the below-mentioned best practices for better results. * Make sure that you consider testing a single element at a time, as it will give you clarity in changing which element will impact your sales. Also, it will not impact other elements. * You should carry out at least one A/A testing on every variation to compare the results of A/B testing and web analytics platform. * Also, make sure that you frequently run the A/B test for gathering periodic data and then act accordingly to improve the website’s performance. * Ensure that your website receives sufficient traffic for each variation to make further decisions about which variation to keep and make it available as the final version. In case of less traffic, you will not have the concrete and enough data to carry out the next cycle of the A/B test. ## How do you perform an A/B test? ### 1. Choose the elements to test First, create a list of all the elements you want to test and improve. These elements could be anything from a small font to a change in heading. If you want to improve the incoming traffic, you can consider changing the SEO and other aspects of the website. Making this list is crucial as you don’t know which change can impact your business positively. ### 2. Set goals After that, set your long-term and short-term goals and make strategies to achieve them using A/B testing. Focus on improving one element at a time to get better insights into your changes. ### 3. Analyse data Nextstep is to analyze the existing data using various tools. It will help you understand which metric requires improvement. This will provide you with the starting point to start making changes. You can then decide which page you want to make and analyze your business based on the metrics. ### 4. Create a variant After analyzing the data, you will make the required changes to your website. These changes will create a variant of your website specifying various changes you have decided on in the previous step. ### 5. Design your test Now, make sure you choose the right tool to carry out the A/B testing as per your ease. Then make the test and select the criteria you want to test against your elements. You have to consider various factors such as specifying the time duration for the test to run, which devices you want to collect data from, etc. ### 6. Accumulate data Many [A/B testing software](https://absmartly.com/), such as Crazy Egg, will automatically provide you with data insights. You can consistently review your test’s progress, time duration of the test, etc. You will receive all the necessary data insights that you can use to get hold of the trend and improve accordingly. ### 7. Analyse the A/B testing outcomes Once you draw conclusions based on various variations and outcomes, you will better understand how different customers behave against various variations. This will give you more visibility towards having the right element within your website. ## How Much Time Does A/B Testing Take? A/B testing is not a lengthy process, but it entirely depends on the incoming traffic. Testing each element may vary from a few days to a week. Make sure to run a single test at a time for better results, and you can analyze them appropriately. Also, make sure that the test has run its course. Only then can you get the accurate output. Also, if you run a test for a longer time, you can give skewed results as you cannot control variables over a more extended period. Also, consider every aspect that might affect your test to eliminate the chances of certain anomalies in your results. It is worth running the complete test for a more optimum result. ## Conclusion There is no doubt on the efficiency of the A/B testing to improve the performance of your website and improve customer engagement. It is a simple testing process that keeps iterating until you get the optimum results to perform better. You can follow several strategies to implement A/B testing within your business. We have mentioned a few steps as a roadmap for how you can implement A/B testing and leverage its benefits. Implementing it with a complete proof plan will reduce many risks involved when performing an optimization program. It will surely improve your website’s user experience and performance by eliminating all customers’ pain points by finding the most optimized version of your website.
vijaykhatri96
930,974
Fixing "Authentication plugin 'caching_sha2_password' cannot be loaded" errors
Summary You have installed MySQL 8 and are unable to connect your database using your...
0
2021-12-20T09:31:48
https://chrisshennan.com/blog/fixing-authentication-plugin-cachingsha2password-cannot-be-loaded-errors
mysql, webdev
## Summary You have installed MySQL 8 and are unable to connect your database using your MySQL client (Sequel Pro, HeidiSQL etc). Every attempt to connect using your MySQL client results in the following error > Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/mysql/lib/plugin/caching_sha2_password.so, 2): image not found or > Authentication plugin 'caching_sha2_password' cannot be loaded. The specific module can not be found ## Reason As of MySQL 8.0, `caching_sha2_password` is now the default authentication plugin rather than `mysql_native_password` which was the default in previous versions. This means that clients (Sequel Pro, HeidiSQL etc) that rely on the `mysql_native_password` won't be able to connect because of this change. ## Resolution 1) You can, at a server level, revert to the `mysql_native_password` mechanism by adding the following to your MySQL configuration files ```bash [mysqld] default_authentication_plugin=mysql_native_password ``` 2) You can, at a user level, revert to the `mysql_native_password` mechanism via the following process Open a terminal window and connect to your MySQL instance via the command line ```sh mysql -u [USERNAME] -p ``` Enter your MySQL password and press enter and you should be logged into your MySQL instance. Now run the following SQL command, replacing `[USERNAME]`, `[PASSWORD]` and `[HOST]` as appropriate. Note: `[HOST]` can be the IP address of your computer which would allow access from your computer only or, in the case of a local development environment, you can use `%` to allow from any host. ```sql ALTER USER '[USERNAME]'@'[HOST]' \ IDENTIFIED WITH mysql_native_password \ BY '[PASSWORD]'; ``` or ```sql ALTER USER '[USERNAME]'@'%' \ IDENTIFIED WITH mysql_native_password \ BY '[PASSWORD]'; ``` Now you should be able to go back to your MySQL client and connect as normal. ## References - 2.11.4 Changes in MySQL 8.0 - [https://dev.mysql.com/doc/refman/8.0/en/upgrading-from-previous-series.html](https://dev.mysql.com/doc/refman/8.0/en/upgrading-from-previous-series.html) - 6.4.1.2 Caching SHA-2 Pluggable Authentication - [https://dev.mysql.com/doc/refman/8.0/en/caching-sha2-pluggable-authentication.html](https://dev.mysql.com/doc/refman/8.0/en/caching-sha2-pluggable-authentication.html)
chrisshennan
930,998
Center a div in tailwind css (flexbox method)
https://youtu.be/N03Itadk-oM Center a div in tailwind css flexbox method If you liked our content...
0
2021-12-20T10:00:02
https://dev.to/shatud/center-a-div-in-tailwind-css-flexbox-method-33jg
webdev, tailwindcss, beginners, html
https://youtu.be/N03Itadk-oM Center a div in tailwind css flexbox method If you liked our content help us by subscribing on the channel and leaving a nice comment
shatud
931,021
What is the importance of the NFT Marketplace?
NFT stands for Non-Fungible Token is a blockchain-based tool that enables anyone to monetize digital...
0
2021-12-20T10:48:55
https://dev.to/nexonnft/what-is-the-importance-of-the-nft-marketplace-2cng
blockchain, digital, artwork, nft
NFT stands for [Non-Fungible Token](https://nexonnft.medium.com/what-is-an-nft-non-fungible-tokens-explained-ea768219bf75) is a blockchain-based tool that enables anyone to monetize digital content. With a turnover exceeding $10 billion in the third quarter of 2021 alone, it has become clear that this emerging technology is evolving into a major industry. When digital artist Beeple sold a tokenized digital artwork for $69 million through Christie's auction house, it started to get noticed. But there are a few more incidents that helped it to get all the hype. NBA's Top Shot, which is owned by crypto platform Dapper Labs and enables fans to buy and sell tokenized video clips of basketball game highlights, has generated more than $715 million in transaction volume. Another one on the list is musician 3LAU, who collaborated with crypto startup Origin Protocol in March this year to create an exclusive platform to sell his new album as an NFT, where it eventually sold for $11.6 million. With the above few examples, it may look like NFT Marketplace is about generating huge money, which is right but it has more to offer and more to explore. In this article, we will be talking about NFT Marketplace and why they are important to the world. <h2>What is an NFT marketplace?</h2> NFT Marketplaces are like eCommerce sites or any other physical marketplace, with the only difference being that it is only a market for digital goods or content. Anyone can buy or sell any digital asset or NFT token using NFT crypto on these marketplaces. These marketplaces are also used to store and display trading and to create NFT tokens or any digital asset. By using blockchain technology, these platforms also verify the origin of digital content. NFTs are digital tokens or tokens of authenticity for digital content including artwork, images, memes, games, soundtracks, 3D models, or any artistic creation with information of their ownership and authenticity. These digital assets can be sold or bought on the NFT Marketplace using NFT crypto. <h2>Why is the NFT Marketplace so important?</h2> <b>Some of the essential aspects of NFT Marketplace are mentioned below:</b> <h3>Unlimited Expansion</h3> The NFT market is a huge digital pool consisting of large daily transactions that take place in this market. Everyone will have access to this marketplace and they can buy or sell whatever they want. It is considered the future of the digital market. <h3>Non-traceable</h3> Since NFT markets are virtual locations, it has no physical presence. This makes them practically non-detectable. Digital wallets and protection also make tracing hard. <h3>Easily compatible</h3> There are many digital platforms as well as crypto wallets. All you have to do is choose a crypto wallet compatible with the blockchain network system. In order to buy or sell any digital asset on an Ethereum based platform, one needs to use a crypto wallet that is compatible with it, such as MetaMask, and then they can easily access the NFT marketplace. <h3>Amazing Usability</h3> NFT Marketplace has unmatched usability, it is like a market where anyone can sell their digital art. It provides unmatched opportunities to everyone without any limitation. <h3>Authenticity and authorization</h3> Without making a profile, a person cannot buy or sell anything from these marketplaces. It is necessary to set up an account, which will also ensure authenticity and authority in the market. <h3>Easy to use</h3> NFT Marketplaces have simple working procedures. There are no time-wasting things in the process. Users will get the digital goods instantly after making the transaction. However, even after all these positive things most of the NFT marketplaces are a total mess. Either these platforms have technical issues or management issues, which is worrying the crypto enthusiast. That’s where [NexonNFT](https://www.nexonnft.io/) fits in, NexonNFT is developing a futuristic NFT marketplace that will be easy to use, easy to understand, well-organized, and with lots of incredible features. So, bookmark our website to stay up-to-date, and invest in Nexon token to be a part of this NFT revolution.
nexonnft
931,032
Advent of code Day 20
Finally a day where I can feel satisfied with my code results. I explain this code in the detail on...
0
2021-12-20T11:23:05
https://dev.to/marcoservetto/advent-of-code-day-20-1n10
adventofcode, adventofcode2021, syntax, beginners
Finally a day where I can feel satisfied with my code results. I explain this code in the detail on my youtube channel, (https://www.youtube.com/watch?v=lqA_XT0U4ng) ``` reuse [L42.is/AdamsTowel] Fs = Load:{reuse[L42.is/FileSystem]} Point = Data.AddList:Data:{ I x, I y method Point +(Point that) = \(x=this.x()+that.x(),y=this.y()+that.y()) method Point max(Point that)=( (x0,y0) = this (x1,y1) = that Point(x=x0.max(x1),y=y0.max(y1)) ) method Point min(Point that) = this.with(x=\x.min(that.x()))<:This.with(y=\y.min(that.y())) } Map = Data:{ M = Collection.map(key=Point,val=Bool) mut M map=\() var Bool outer=Bool.false() var Point topLeft = Point(x=0I,y=0I) var Point bottomRight = Point(x=0I,y=0I) mut method Void put(Point key, Bool val) = ( \#map.put(key=key,val=val) \topLeft(\topLeft.min(key)) \bottomRight(\bottomRight.max(key)) ) read method Bool val(Point key) = \map.val(key=key).val(orElse=this.outer()) read method I nearBin(Point that) = 0I.acc()(( var n = 512I for xi in Range(I"-1" to=2I), for yi in Range(I"-1" to=2I) ( n/=2I if this.val(key=Point(x=xi,y=yi)+that) \add(n) ) )) read method mut This step(Key that) = ( mut This new = This() (x0,y0) = \topLeft (x1,y1) = \bottomRight for x in Range(x0-1I to=x1+2I), for y in Range(y0-1I to=y1+2I) ( key=Point(x=x,y=y) i=\nearBin(key) X[i.isInRange(0I to=512I)] // is my binary conversion correct? new.put(key=key,val=that.val(i)) ) new.outer(if this.outer() that.right() else that.left()) new ) } Key = Collection.list(Bool) Main=( input = Fs.Real.#$of().read(\"input").split(S.nl()++S.nl()) imm key = Key()( for i in input().split() \add(i==S"#") ) X[key.size()==512I] var map = Map() for line in input().split(S.nl()), li in Range.unbounded() ( for c in line.split(), ci in Range.unbounded() ( map.put(key=\(x=li,y=ci),val=c==S"#") ) ) for i in Range(2I) ( map:=map.step(key) ) //50I tot = 0I.acc()(for (val) in map.map() \addIf(val)) Debug(tot) ) ```
marcoservetto
931,036
MySQL Cheat sheet
Creating tables 📑 CREATE TABLE BookHistory ( Auther VARCHAR(129), title VARCHAR(129), ...
0
2021-12-24T15:36:50
https://dev.to/shubhamathawane/mysql-cheat-sheet-2hgp
mysql, javascript, beginners, database
1. Creating tables 📑 ```sql CREATE TABLE BookHistory ( Auther VARCHAR(129), title VARCHAR(129), btype VARCHAR(129), year CHAR(4) ); ``` 1. To drop table column ```sql ALTER TABLE tableName DROP column-Name; ex. ALTER TABLE BookHistory DROP Auther; ``` 1. How to delete Data from a MySQL table ? ```sql // Delete Statement is used to delete data, DELETE FROM table_name WHERE column_name = VALUE EX. DELETE FROM BookHistory WHERE title = 'JungleBook' ``` 1. Inserting Value into Table. ```sql INSERT INTO table_name (Column1, Column2, Column3 ) VALUES (value1, value3, value3); EX. INSERT INTO BookHistory (Author, title, btype, year) VALUES ("James Camron", "Avatar", "Adventure", 2006); ``` 1. Update column name. ```sql ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name; EX. ALTER TABLE BookHistory RENAME COLUMN btype TO Book_type; ``` 1. Add new column in table ```sql ALTER TABLE table_name ADD column_name DATATYPE; EX. ALTER TABLE BookHistory ADD price INT(4); ``` 1. The Select Command : DQL- DATA QUERY LANGUAGE Command. Used to visualize the table content. ```sql SELECT * FROM table_name; EX. SELECT * FROM BookHistory; // It will show all data present inside the BookHistory table ``` We can use SELECT command to retrieve specific data from the table using WHERE clause . Like below ```sql SELECT * FROM table_name WHERE condition; EX. SELECT * FROM BookHistory WHERE Book_type = "hacking"; ``` 1. MySQL numeric Data types MySQL has numeric data types for Integer, Fixed-point, Floating-Point and bit etc. *Numeric can be singed or unsinged | 1. TINYINT | 6. FLOAT | | --- | --- | | 2. SMALLINT | 7. DOUBLE | | 3. MEDIUMINT | 8. BIT | | 4. INT | | | 5. BIGINT | | 2. String Data type. | 1. CHAR | 5. TINYBLOB | | --- | --- | | 2. VARCHAR | 6. MEDIUMBLOB | | 3. BINARY | 7. LONGBLOB | | 4. VARBINARY | | 3. Temporal Data Types in MySQL 1. **DATE** - A date value in 'CCYY-MM-DD' 2. **TIME**- Time in 'HH:MM:SS' 3. **DATETIME** - Date-Time - 'CCVV-MM-DD HH:MM:SS' 4. **TIMESTAMP** - 'CCVV-MM-DD' HH:MM:SS 5. **YEAR** - CCYY or YY 4. Create user in MySQL ```sql CREATE USE 'user-name' IDENTIFIED BY 'sample-password'; ``` 1. **What are the "VIEWS" ?** → In MySQL , A view consists of a set of rows that returned if particular query is executed. → It also known as "Virtual Table" → Advantages : Simplicity, security, not consume any memory, maintainability. 1. How to you create & Execute VIEWS in MySQL ? → We can create views using the **CREATE VIEW** Statement; -> A view is table in database that has no values, The views are created by joining one or more tables. -> Syntax for creating Views ```sql CREATE [or REPLACE] VIEW view_name AS SELECT columns FROM TABLES [ WHERE CONDITION ] ``` 2. SELECT AND command. ```sql SELECT * FROM cust_tbl WHERE f_name = "shubham" AND cust_id > 3; ``` 1. **Truncate :** It removes complete data without removing it’s structure. It is a DDL Command ```sql TRUNCATE TABLE table_name; EX. TRUNCATE TABLE BookHistory; ``` 1. Update Command in MySQL. ```sql UPDATE 'table_name' SET 'column_name' = 'new_value' [WHERE CONDITION]; EX. UPDATE BookHistory SET 'Auther' = 'James Bond' WHERE Auther = "JB"; ``` 1. BETWEEN : Get values between particular condition. ```sql SELECT * FROM cus_tbl WHERE ID = 8 AND 11; ``` 1. Find version of installed MySQL. Type Following Command. ```sql SHOW VARIABLES LIKE "%version%"; ``` 1. ENUM and SET. ENUM data type is used in the MySQL datatypes to select any one value from the predefined list. Ex ```sql CREATE DATABASE newEnum; CREATE TABLE Clients ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), memberShip ENUM('silver', 'gold', 'Diamond'), interested SET('Movie', 'Music', 'concert'); ) ``` > Cannot set multiple in ENUM but we can set multiple values in SET. 4. What is different between Primary key and Foreign Key ? -> The database table uses Primary key to identify each row uniquely, It is necessary to declare a primary key on those tables that require tp create a relationship among them. - One or More field of table can be declared as primary key -> When primary key of any table is used in another table as the primary key or anther field for making a database relation then it is called Foreign Key. -> **Primary Key :** Identified a record whereas foreign key refers the primary key of another tables. Primary key never accepts not null value. But Foreign key accepts null value. 2. Filter duplicate values. -> A **DISTINCT** keyword is used to identify the duplicate data from table while retrieving the records. EX. ```sql SELECT * FROM items ``` output: | id | name | type | brand | man_id | | --- | --- | --- | --- | --- | | 1 | samsung | mobile | samsung | 1 | | 2 | iPhone | mobile | apple | 2 | | 3 | Sony | TV | Sony | 3 | - Using **DISTINCT** Keyword ```sql SELECT DISTINCT type FROM items; ``` output: | type | | --- | | mobile | | TV | 1. Which statement is used in a select query statement for partial matching ? → REGEXP and LIKE statement can be used in a select query for partial matching. - **REGEXP** : used to Search records bases on the pattern matching - **LIKE** : Is used to search any record by matching string at beginning or end or middle of particular filed value. Ex. 1. REGEXP (Search records start with ‘S’); ```sql SELECT * FROM BookHistory WHERE name REGEXP "^s"; ``` Ex. 2. LIKE ```sql SELECT * FROM BookHistory WHERE name LIKE "A%"; ``` 1. Rename Table ```sql RENAME TABLE table_name TO new_table_name; EX. RENAME TABLE items TO Products; ``` 1. Retrieve a portion of any Column value by using select Query ? → * **SUBSTR()** Function is used to retrieve the portion of any column. EX > OR we can we ‘**SUBSTRING**’ keyword > ```sql SELECT SUBSTR(name, 1, 5) FROM Products; ``` output: | Samsu | | --- | | iPhon | | Sony | 1. Calculate Sum of any Column of table ? → **SUM() Function is used to calculate the sum of any column. EX.** ```sql SUM(DISTINCT expression) EX. SELECT SUM(Price) as total FROM Products; ``` output: | total | | --- | | 2109.00 | # The Practical Approach 1. Fetch FIRST_NAME from worker table. ```sql SELECT First_name as worker_name from Woker; //will return all first_name 's ``` 1. Fetch FIRST_NAME as Upper Case ```sql SELECT upper(First_name) FROM Worker // Will return all name in upper case ``` 1. Fetch unique Values from Department ```sql SELECT DISTINCT department FROM Worker; ``` output : | department | | --- | | HR | | ADMIN | | ACCOUNT | 1. Find position of alphabets (”a”) in first_name column ‘Amitabh’ from worker. ```sql SELECT INSTR(first_name, BINARY'a') FROM worker WHERE first_name = "Amitabh"; ``` output : | INSTR( first_name, BINARY ’a’ ) | | --- | | 5 | 1. Remove white Spaces 1. **RTRIM** : To remove white spaces from right side. EX ```sql SELECT RTRIM(first_name) FROM Worker; ``` b. **LTRIM** : To remove white spaces from left side. EX ```sql SELECT LTRIM(Department) FROM Worker; ``` 2. Query to print **`first_name`** and **`salary`** from worker table into a single column NAME_SALARY → We use CONCAT() keyword to get combined result from two or more tables. EX ```sql SELECT CONCAT(first_name, "=" , Salary) AS 'NAME_SALARY' FROM Worker; ``` 1. Query to print all worker details from worker table order by First_Name Ascending. ```sql SELECT * FROM Worker ORDER BY First_Name ASC; ``` 1. Print details for worker with First_name as ‘Shubham’ and ‘NICK’ from worker table. ```sql SELECT * FROM Worker WHERE First_Name In('Shubham', 'NICK'); ``` 1. Query to fetch the count of employee working in the department ‘admin’. → The count function return cunt of given queries : EX. ```sql SELECT COUNT(*) FROM Worker WHERE Department = 'Admin'; ``` output : | count(4) | | --- | | 4 | # AGGREGATE FUNCTIONS : - SQL Aggregate functions is used to perform calculations on multiple row of a single column of a table it return single value. 1. COUNT() 2. SUM() 3. AVG() 4. MAX() 5. MIN() --- 1. **COUNT()** → Count the number of rows in database; It uses function COUNT(*) that return all rows ```sql SELECT COUNT(*) FROM Worker WHERE Department = 'Admin'; ``` | count(4) | | --- | | 4 | 1. SUM() → SUM() Function is used to calculate the sum of all selected columns. it only work on numeric values. Syntax: sum(); ```sql SELECT SUM(salary) FROM Worker; or SELECT ``` 1. AVG() → Used to calculate average value of the numeric type. AVG function return the average of all non-null values. Syntax: AVG(); ```sql SELECT Avg(salary) FROM Workder; ``` 1. MAX(): → Max function used to find the maximum value of a certain column . This function determines the largest value of all selected values of column. Syntax: MAX(); ```sql SELECT MAX(SALARY) FROM Worker; ``` 1. MIN(); → MIN used to find minimum value of a certain column. this function determines the smallest value of all selected of a column. ```sql SELECT MIN(SALARY) FROM Worker ``` # Joins ### Two relations 1. Personal 2. Professional ```sql select * from personal; ``` ```sql +----+----------+---------+-----------+ | id | name | address | contact | +----+----------+---------+-----------+ | 10 | ankit | kapali | 838405939 | | 20 | ankush | kapali | 835403953 | | 30 | akhilesh | mango | 335502953 | | 40 | altaf | sakchi | 985402953 | +----+----------+---------+-----------+ ``` ```sql select * from professional; ``` ```sql +------------+-------+------+ | work | dep | id | +------------+-------+------+ | teacher | bca | 20 | | docktor | mbbs | 40 | | teacher | mba | 50 | | programmer | java | 60 | | cashier | icici | 10 | +------------+-------+------+ ``` ## 1. Natural Join ```sql select * from personal natural join professional; ``` Output: ```sql +----+--------+---------+-----------+---------+-------+ | id | name | address | contact | work | dep | +----+--------+---------+-----------+---------+-------+ | 10 | ankit | kapali | 838405939 | cashier | icici | | 20 | ankush | kapali | 835403953 | teacher | bca | | 40 | altaf | sakchi | 985402953 | docktor | mbbs | +----+--------+---------+-----------+---------+-------+ ``` ## 2. Inner Join ```sql select name,contact,dep from personal inner join professional on [personal.id](http://personal.id/) = [professional.id](http://professional.id/); ``` output: ```sql +--------+-----------+-------+ | name | contact | dep | +--------+-----------+-------+ | ankit | 838405939 | icici | | ankush | 835403953 | bca | | altaf | 985402953 | mbbs | +--------+-----------+-------+ ``` ## 3. Cross Join ```sql select * from personal cross join professional; ``` output: ```sql +----+----------+---------+-----------+------------+-------+------+ | id | name | address | contact | work | dep | id | +----+----------+---------+-----------+------------+-------+------+ | 10 | ankit | kapali | 838405939 | teacher | bca | 20 | | 20 | ankush | kapali | 835403953 | teacher | bca | 20 | | 30 | akhilesh | mango | 335502953 | teacher | bca | 20 | | 40 | altaf | sakchi | 985402953 | teacher | bca | 20 | | 10 | ankit | kapali | 838405939 | docktor | mbbs | 40 | | 20 | ankush | kapali | 835403953 | docktor | mbbs | 40 | | 30 | akhilesh | mango | 335502953 | docktor | mbbs | 40 | | 40 | altaf | sakchi | 985402953 | docktor | mbbs | 40 | | 10 | ankit | kapali | 838405939 | teacher | mba | 50 | | 20 | ankush | kapali | 835403953 | teacher | mba | 50 | | 30 | akhilesh | mango | 335502953 | teacher | mba | 50 | | 40 | altaf | sakchi | 985402953 | teacher | mba | 50 | | 10 | ankit | kapali | 838405939 | programmer | java | 60 | | 20 | ankush | kapali | 835403953 | programmer | java | 60 | | 30 | akhilesh | mango | 335502953 | programmer | java | 60 | | 40 | altaf | sakchi | 985402953 | programmer | java | 60 | | 10 | ankit | kapali | 838405939 | cashier | icici | 10 | | 20 | ankush | kapali | 835403953 | cashier | icici | 10 | | 30 | akhilesh | mango | 335502953 | cashier | icici | 10 | | 40 | altaf | sakchi | 985402953 | cashier | icici | 10 | +----+----------+---------+-----------+------------+-------+------+ ``` ## 4. Left outer join ```sql select name, address, dep, work from personal left outer join professional on [personal.id](http://personal.id/) = [professional.id](http://professional.id/); ``` output: ```sql +----------+---------+-------+---------+ | name | address | dep | work | +----------+---------+-------+---------+ | ankush | kapali | bca | teacher | | altaf | sakchi | mbbs | docktor | | ankit | kapali | icici | cashier | | akhilesh | mango | NULL | NULL | +----------+---------+-------+---------+ ``` ## 5. Right outer join ```sql select name, address, dep, work from personal right outer join professional on [personal.id](http://personal.id/) = [professional.id](http://professional.id/); ``` Outupt: ```sql +--------+---------+-------+------------+ | name | address | dep | work | +--------+---------+-------+------------+ | ankit | kapali | icici | cashier | | ankush | kapali | bca | teacher | | altaf | sakchi | mbbs | docktor | | NULL | NULL | mba | teacher | | NULL | NULL | java | programmer | +--------+---------+-------+------------+ ```
shubhamathawane
931,055
Multi-Region Serverless deployments on AWS with custom domains
In this post, I will be extending the article on Serverless Framework which we use at FINN actively,...
0
2021-12-20T11:48:24
https://www.saral.dev/multi-region-serverless-deployments-on-aws-with-custom-domains/
webdev, serverless, aws, cloud
In this post, I will be extending [the article](https://www.serverless.com/blog/build-multiregion-multimaster-application-dynamodb-global-tables) on [Serverless Framework](https://www.serverless.com) which we use at [FINN](https://www.finn.auto) actively, and tell you how to implement a service with custom domains and multiple regions. # What is Serverless? Serverless is a way of providing backend services only when needed for use (for our case: [AWS Lambda](https://aws.amazon.com/lambda/)). We will be using the [Serverless Framework](https://www.serverless.com/framework) described as Zero-friction development tooling for auto-scaling apps on [AWS Lambda](https://aws.amazon.com/lambda/). It simply deploys your services to AWS Lambda and creates a restful API (your choice) for your service. You can attach a custom domain to any stage of your deployment. # Steps Now let's deploy our application to both `staging` and `production` environments with their relevant custom domains. In the end, we will have four deployments on both `Europe (eu-central-1)` and `US East (us-east-1)` regions with the routing setting based on `latency`: - Domain: `stg-multi-region.saral.dev` Stage: `staging` Region: `eu-central-1` - Domain: `stg-multi-region.saral.dev` Stage: `staging` Region: `us-east-1` - Domain: `multi-region.saral.dev` Stage: `production` Region: `eu-central-1` - Domain: `multi-region.saral.dev` Stage: `production` Region: `us-east-1` ## 1) Install Serverless plugins Assuming you already [installed serverless](https://www.serverless.com/framework/docs/getting-started). In order to manage custom domains, install [serverless-domain-manager](https://www.serverless.com/plugins/serverless-domain-manager): ``` yarn add -D serverless-domain-manager ``` Then install [stage manager](https://www.serverless.com/plugins/serverless-stage-manager): ``` yarn add -D serverless-stage-manager ``` ## 2) Setup the serverless.yml This is just an example. ```yaml service: multi-region-service app: myapp org: myorg frameworkVersion: '2' provider: name: aws endpointType: REGIONAL runtime: nodejs14.x memorySize: 256 stage: ${opt:stage, 'staging'} region: ${opt:region, 'eu-central-1'} tags: author: saral.dev custom: domains: production: multi-region.saral.dev staging: stg-multi-region.saral.dev environments: staging: staging production: production customDomain: domainName: ${self:custom.domains.${self:provider.stage}} basePath: '' stage: ${self:provider.stage} createRoute53Record: true endpointType: 'regional' certificateRegion: ${opt:region, 'eu-central-1'} route53Params: routingPolicy: latency stages: - staging - production plugins: - serverless-domain-manager - serverless-stage-manager - serverless-offline ``` ## 3) Create domains with regions - Create `stg-multi-region.saral.dev` on `eu-central-1` region: ``` serverless create_domain --stage staging ``` or ``` serverless create_domain --stage staging --region eu-central-1 ``` - Create `stg-multi-region.saral.dev` on `us-east-1` region: ``` serverless create_domain --stage staging --region us-east-1 ``` - Create `multi-region.saral.dev` on `eu-central-1` region: ``` serverless create_domain --stage production ``` or ``` serverless create_domain --stage production --region eu-central-1 ``` - Create `multi-region.saral.dev` on `us-east-1` region: ``` serverless create_domain --stage production --region us-east-1 ``` ## 4) Deploy services to AWS - Deploy `staging` on `eu-central-1` region: ``` serverless deploy --stage staging ``` or ``` serverless deploy --stage staging --region eu-central-1 ``` - Deploy `staging` on `us-east-1` region: ``` serverless deploy --stage staging --region us-east-1 ``` - Deploy production on eu-central-1 region: ``` serverless deploy --stage production ``` or ``` serverless deploy --stage production --region eu-central-1 ``` - Deploy `production` on `us-east-1` region: ``` serverless deploy --stage production --region us-east-1 ``` # How to convert an existing Edge service to Regional By default, Serverless does not deploy regional endpoints. Let's assume you have a setup like this in your `serverless.yml`: ```yaml customDomain: domainName: ${self:custom.domains.${self:custom.stage}} basePath: '' stage: ${self:custom.stage} createRoute53Record: true ``` Before you do any multi-region changes, you should first run the following commands and remove your custom domains because, at the moment, it's not possible to alter the endpoint type. ``` serverless delete_domain --stage staging serverless delete_domain --stage production ``` After that, you can start steps 3 and 4 above. Unfortunately, there will be a downtime until your deployment is done. --------- If you want to log the region in your lambda, the environment variable `AWS_REGION` is available via AWS Lambda. So you can print it with `console.log(process.env.AWS_REGION)`. You can also check your deployments on [Serverless Dashboard](https://www.serverless.com/dashboard/). I hope you enjoyed the post. Don't forget to show some love. :)
ebsaral
931,215
Elixir in the eyes of Node.js developer
Cover photo by Kaizen Nguyễn on Unsplash I got into Elixir some time ago, but at that time, I was...
0
2021-12-20T13:50:33
https://dev.to/czystyl/elixir-in-the-eyes-of-nodejs-developer-fee
elixir, javascript, node, webdev
_Cover photo by <a href="https://unsplash.com/@kaizennguyen?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Kaizen Nguyễn</a> on <a href="https://unsplash.com/?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>_ --- I got into Elixir some time ago, but at that time, I was more interested in statically typed languages. I didn't exclude Elixir at that time, but instead, I moved it to a second plan. One of the signals to give Elixir a try was the talk from _Saša Jurić - The Soul of Erlang and Elixir_. I highly recommend watching this talk. I discovered that the BEAM VM and Elixir features could offer many benefits. So I decided to try and see how all the pieces are working together in an actual application. I'd like to share some critical ecosystem points that convinced me to try. 1. **Community** One of the first things that I noticed when I started was the community libraries. Almost all the libraries shared the same structure and had all the API interfaces generated along with the type spec. So I searched for a few libraries that I often use, like web framework, GraphQL implementation or Database management. I can say that all of them look solid, and the documentation also contains a lot of guidelines, so I didn't need to leave the page to have a good understanding of them. 2. **Phoenix framework** The Phoenix is a web framework that makes building web servers easy and fast. Great thing is that Phoenix has a built-in code generator. This generator is done via the mix task and you can generate almost all needed parts for creating an endpoint, context or database schema. Additionally, the documentation and guidelines described in the next point make you much more comfortable in the first place. 3. **Testing and documentation** When looking back on different projects, documentation and testing are some of the forgotten things during development. Within the Elixir, those things are built in the language, making a considerable change for development and maintenance. You can write the documentation and examples right next to the code, and as we advance, you can turn these examples into quick tests. It was a nice thing that convinced me to write more tests and documentation. 4. **GenServer** The GenServer allows you to abstract logic around small services. For example, all these services might have a separate state and business logic encapsulated inside. The service code is executed as a lightweight BEAM process, which is fast compared to standalone microservice solutions. Therefore, you do not need any extra HTTP layer or queue to communicate within the service. 5. **Type system, pattern matching and language itself** I need to say that I'm a big fan of statically typed languages. So, when I heard about the Elixir for the first time, missing a type system was a big downside for me. Also, I understand that making such a dynamic language static would be a big challenge. To fill this gap, I used Dialixir and Typespecs. The experience is slightly different, but you have some tangibility of the type system, called success typing. Elixir has a functional language style that fits my personality best, but everyone can feel differently. On top of this, you have a great set of language features like With statements, function guards, the pipe operator and excellent pattern matching. 6. **BEAM virtual machine** I think it was one of the biggest deal-breaker for using the Elixir heavier. The BEAM architecture, combined with the language features described above, make it a great combo! The virtual machine is responsible for running your code in small, cheap and fast processes. One of the philosophies that are coming from Erlang is `Let it fail`. The philosophy allows writing the system that is working more consistently and reliably. I could compare this to our systems like Linux, Windows or macOS. The system is working, but some programs that we installed are crashing from time to time, but usually, your system is still working, and only what you have to do is open your program once again. Like BEAM VM, one process might crash, but the whole system is still working as usual. Overall, I feel surprised how good working with Elixir was. One of the gaps is the lack of a static type system. To fill this gap, I used Credo, Dialixir and TypeSpecs to analyze the codebase statically. The language features make writing the code quicker, easier and cleaner to maintain. For example, built-in documentation and testing might turn your codebase into an environment that is a pleasure to work with. The last piece of this whole stack is that all of this runs on BEAM VM, which is the cherry on the cake! So I need to say that the lack of a static type system is no longer a significant disadvantage with such a combo! It is the first blog about my elixir journey, and I plan to share more detailed knowledge soon in my next blog.
czystyl
931,355
About some CSS topics
Overview: So Today we will going to discuss some CSS properties which are advanced and not usually...
0
2021-12-20T17:18:31
https://dev.to/thekawsarhossain/about-some-css-topics-2cf
css
Overview: So Today we will going to discuss some CSS properties which are advanced and not usually used frequently like other properties. **Float:** The CSS float property is used to align the items to the left, right. That means we can create a simple layout using float. Nowadays float property isn’t used by the developers. Float property values are left, right and none using the default value is none we can align the element to the right using right and if we want if the element start’s in right then we can align them left if we want and we can also use the none value for removing the left, right value. When we use the float property sometimes we need the clear property as well because when we use the float property some elements are overlapped in other elements that are we need to use this clear property. In clear property set the value to left, right and both that means of the element overlapped on the left side then we can use the left value and if right then we can use the right value and if we need then we can add both values which will clear the overlapping from left and right as well. **Animation:** We can make an animation to use in our webpage using CSS animation. To make animation we have to use the @keyframes this property. And here we can make different kinds of animation make first we have to define an animation-name so that we can call it where we need it. We can make animation in keyframes using from and to or using the units like %, pixel. We can use the animation where we want in CSS to call the animation we have to use the animation-name property, we can also more animation properties like animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, animation-play-state. And these properties have multiple values we can use all these properties in shorthand using only animation property. **Variable: ** we can make variables in CSS and these variables have access to the DOM, and CSS variables are can be global or local scope. To make a global variable in CSS what we have to do is we have to declare the variable inside the :root{} inside this we have to declare the variable using – two dashes like this root{–color: #ffffff;} and we have to use these variables using var(variable name) like this h2{background-color:var(--color)} the advantage of variable in CSS are it makes code easier to read and if we need any changes then we don’t need to change everywhere we can simply change the variable value. **Empty-cells:** using empty-cell we can hide the cell border and background in the table. It tells the browser not to draw the borders around the table cell. The empty-cell property has two values shown and hides the default value is shown which means it will show the border whether the value is available or not and if we use the value hide the border will be hidden. **Resize: ** Using resize property we can set elements to resizable or in which direction. The default value of resize property is none. We can make the element resizeable from both sides using both values and the user will be able to make or resize the width and the height of the element. We can also make horizontal or vertical using the horizontal and vertical value in horizontal user can resize the element width and the vertical the user can be able to resize the height of the element. We can also use the value initial and inherit **Tab-size:** The tab-size property mark the width of the tab character like if we add the value of tab-size 4 then it will take the width of 4 tab size. The tab character is usually displayed as a single space character, except for some elements like textarea, pre. **White-space:** The white-space property is used to set the space inside an element, and it helps to control the line breaks, space within the element’s text. In white space, we can set the value to nowrap, normal, and pre, and the normal value is the default. If we use nowrap then our content will go out of the screen and the screen will be scrollable which is not responsive for mobile. And if we use the pre then the content/text will be aligned line depending on the screen.
thekawsarhossain
931,499
Create AI Art in three easy steps
Recently a good colleague and friend of mine, showed me how to create AI Art using a Tensor Flow...
0
2021-12-20T19:34:39
https://jamesmiller.blog/ai-art/
ai, machinelearning, deeplearning, art
--- title: Create AI Art in three easy steps published: true date: 2021-11-21 19:06:33 UTC tags: artificialintelligence,machinelearning,deeplearning,art canonical_url: https://jamesmiller.blog/ai-art/ cover_image: https://i2.wp.com/jamesmiller.blog/wp-content/uploads/2021/10/me.png --- Recently a good colleague and friend of mine, showed me how to create AI Art using a Tensor Flow Neural style Transfer algorithm in Google Colab. Unlike other uses of [Machine Learning that require a developer](https://jamesmiller.blog/training-ai-with-tensorflow-js/), it turns out that creating art using AI is super duper easy and doesn’t need you to be a ‘coder’! In this tutorial, I will go step by step on how to create your own AI Art, so that you can do the same ![🙂](https://s.w.org/images/core/emoji/13.1.0/72x72/1f642.png) ## Instructions to create AI Art ### Step 1 Visit this Tensorflow [Style Transfer](https://www.tensorflow.org/tutorials/generative/style_transfer) Machine learning model and click ‘Run in Google Colab’ button. ![A screenshot of the Tensorflow 'Style Transfer' page, see the 'Run in Google Colab' button - which you need to click on.](https://i2.wp.com/jamesmiller.blog/wp-content/uploads/2021/12/Screenshot-2021-11-21-at-19.07.22.png?resize=640%2C430&ssl=1) _A screenshot of the Tensorflow ‘Style Transfer’ page, see the ‘Run in Google Colab’ button – which you need to click on._ ### Step 2 Once loaded, scroll down the page to the ‘Setup’ section and replace the following: - ‘ **content\_path** ‘ replace the url + file with an image you’d like to transfer a style onto - ‘ **style\_path** ‘ replace the url + file of the image you’d like to transfer the style from ![This is what the page will look like once you've clicked to run the algorithm in Google Colab, from here you need to scroll down to the 'Setup' section.](https://i2.wp.com/jamesmiller.blog/wp-content/uploads/2021/12/Screenshot-2021-11-21-at-19.07.57.png?resize=640%2C377&ssl=1) _This is what the page will look like once you’ve clicked to run the algorithm in Google Colab, from here you need to scroll down to the ‘Setup’ section._ ![The Setup section of the page, be sure to update the content_path with the image you'd like to change the style of and style_path with the image whose style you'd like to apply to the content.](https://i1.wp.com/jamesmiller.blog/wp-content/uploads/2021/12/Screenshot-2021-12-12-at-12.45.46.png?resize=640%2C303&ssl=1) _The Setup section of the page, be sure to update the content_path with the image you’d like to change the style of and style_path with the image whose style you’d like to apply to the content._ ![](https://i1.wp.com/jamesmiller.blog/wp-content/uploads/2021/12/Screenshot-2021-12-13-at-08.24.34.png?resize=640%2C55&ssl=1) _Here is an example of what the content_path and style_path lines look like when editted._ ## Step 3 Scroll back up to the top and press the arrow button next to the ‘Neural style transfer’ header and then click the play button to run the algorithm ![Scroll back up to the top of the pagea and click on the arrow to the left of the title 'Neural style transfer' to collapse the content and reveal the play button. Click on that play button to start the algorithm.](https://i2.wp.com/jamesmiller.blog/wp-content/uploads/2021/12/Screenshot-2021-11-21-at-19.09.52.png?resize=640%2C73&ssl=1) _Scroll back up to the top of the page and click on the arrow to the left of the title ‘Neural style transfer’ to collapse the content and reveal the play button. Click on that play button to start the algorithm._ ## Results If you click the arrow to the left of ‘Neural style transfer’ to uncollapse the content and scroll down the page, you will see the result of the algorithm. In my case, I used my profile photo as the content image and tried two experiments where I swapped the style image. #### Experiment 1 ![AI Art content and style images for experiment 1.](https://i0.wp.com/jamesmiller.blog/wp-content/uploads/2021/12/Screenshot-2021-11-21-at-19.57.08-1.png?resize=640%2C312&ssl=1) _In experiment 1, I used Vassily Kandinsky’s ‘Composition, VII, 1913’ as the style image._ ![AI Art result from experiment 1.](https://i1.wp.com/jamesmiller.blog/wp-content/uploads/2021/12/image-7.png?resize=404%2C404&ssl=1) _The result here is good, the patterns from the style image were successfully found and replicated onto the content image._ #### Experiment 2 ![AI Art content and style images for experiment 2.](https://i1.wp.com/jamesmiller.blog/wp-content/uploads/2021/12/Screenshot-2021-11-21-at-19.57.08.png?resize=640%2C312&ssl=1) _In experiment 2, I googled a water colour texture as the style image (I couldn’t find the exact one I found for this experiment)_ ![AI Art result from experiment 2.](https://i2.wp.com/jamesmiller.blog/wp-content/uploads/2021/12/Screenshot-2021-11-21-at-19.57.17.png?resize=404%2C398&ssl=1) _The result here was less exciting, this is probably because the patterns that the algorithm found were not as clear as the Kandinsky art piece, and therefore the result is more of a blue blur._ Hopefully this post helps you in understanding how to practically create AI Art, I might create a post about the theory of it another time. In the meantime, have a happy christmas and new years ![😀](https://s.w.org/images/core/emoji/13.1.0/72x72/1f600.png)
jamesmillerblog
931,549
Scrimba: JavaScriptmas 2021 - Issue 3
The JavaScriptmas event continues! I recap Scrimba's Twitter Space "Tricky non-technical...
15,811
2021-12-20T20:02:47
https://selftaughttxg.com/2021/12-21/JavaScriptmas_2021-3/
javascriptmas, javascript, scrimba, programming
#### The JavaScriptmas event continues! I recap Scrimba's Twitter Space "Tricky non-technical interview questions and answers," I document my solutions and highlight more fellow coders from the community! --- ![TXG-Issue 55](https://selftaughttxg.com/static/ea9f9cfde50d61c03c134d49d40b5d5b/1cfc2/TXG-Issue55-Thumbnail.png) --- ### Scrimba's Twitter Space What is a Twitter Space? Twitter Spaces are events held on Twitter where the host of the space conducts live conversations with the speakers assigned to a panel and with audience members invited up to the panel. Scrimba's most recent Twitter Space was a conversation on the topic, "**Tricky non-technical interview questions and answers**." Hosts: [Alex](https://twitter.com/bookercodes) and [Leanne](https://twitter.com/RybaLeanne) **Speakers:** * [@TechRally](https://twitter.com/TechRally) * [@willjohnsonio](https://twitter.com/willjohnsonio) * [@TechSquidTV](https://twitter.com/TechSquidTV) * [@sahanarajasekar](https://twitter.com/sahanarajasekar) * [@xDeniTech](https://twitter.com/xDeniTech) --- ### Tell me about yourself. The first question covered during Scrimba's Twitter Space was "**Tell me about yourself**." **To handle this question, we are advised to keep our answer succinct.** Keep your answer on the topic of the position you are applying for, show enthusiasm for the technologies you are using, and lead your enthusiasm back to the company you are interviewing for. ***Notes:*** *Keep it succinct, show enthusiasm, lead your enthusiasm back to why you want to work there.* --- ### Why do you want to work here? **To best answer the question, "Why do you want to work here" is to have first thoroughly researched the company you are applying for.** You can learn about the company you are applying for by researching their website. Go over their about page and create a relevant bullet point list of essential aspects of the company. ***Notes:*** *Do your research on the company you are applying for.* --- ### Questions to ask at the end of the interview We are encouraged to ask questions at the end of the interview. Not doing so may lead to the impression that we are not that interested in the position we are applying for. **Questions to ask at the end of the interview:** 1. What will be my responsibility for the first 30 days? 2. Do you have tips for me? 3. Your expectations of me for my first full year? ***Notes:*** *Ask questions (it's a 2-way street). Not asking questions may reflect that you are uninterested.* --- ### What can you bring to the table/company? When asked, "**What can you bring to the table/company?**" describe what you are passionate about, and lead it into how your skills will help their company. **describe what you are passionate about:** * You are self-motivated * You are a coding enthusiast * You enjoy solving problems * You're concerned about helping customers' needs * You will hold your tech team to high standards ***Notes:*** *You are self-motivated, love to code, solve problems, help customers' needs, hold the tech team to high standards.* --- ### Tell me about a difficult work relationship. **Tell me about a difficult work relationship with a co-worker and how you resolved it.** To handle this delicate question, we are advised to keep our skills as a coder separate from ourselves and our soft skills, or we will take everything personally. Also, share a story where you actually resolved the issue with your co-worker. [@TechRally](https://twitter.com/TechRally), during the Twitter Space, explained that he failed an interview because he shared an "unresolved" story of a difficult work relationship with a co-worker. ***Notes:*** *Share a "resolved" story of a difficult work relationship with a co-worker. Try to resolve the problem with the co-worker before you bring it up to a manager/management.* --- ### Salary negotiation When it comes to salary negotiation, we are advised to determine the salary range beforehand and make sure we are comfortable with the range. In addition to the offered salary, keep in mind the benefits offered. Healthcare, vacation time, matched contributions to your 401(k) account all together construct your overall compensation. Also, we are told that we will have leverage during salary negotiation if we currently have other job offers at the time of the interview. ***Notes:*** *Know the salary range beforehand, keep in mind the overall compensation offered, and you can gain leverage by having multiple other job offers.* --- ### Why are you leaving your current job? When we are asked why we are leaving our current job, we are encouraged to focus less on why we are leaving and more on why we want to work there. We are to present everything positively, and we are instructed not to bash people at our current or previous jobs. **Reasons for leaving our current job:** * Want to move up professionally * You learned all you can at your current job * Looking to expand your skills ***Notes:*** *Focus less on why you are leaving and more on why you want to work there. Present everything positively, and do not "bad talk" anyone you previously worked with.* --- ### Summary of the Twitter Space The best way to handle "**tricky non-technical interview questions**" is to be well prepared. Research the company you are applying for, keep your answers succinct and on topic, and make sure you are also prepared to ask your own questions. Make sure you always shine a positive light on yourself and do not bad-talk past or current colleagues. Show enthusiasm about working for them, demonstrate how your skill will benefit their company, and tactfully explain why you are leaving your current job. --- ### Community Highlights In this section of the article, I'm showcasing the work of fellow JavaScriptmas coders from the community! --- **Steve** ([@steveWhoCodes](https://twitter.com/steveWhoCodes)) solved [Kevin Powell's](https://twitter.com/KevinJPowell) challenge 18 in style, including the stretch goals of adding corresponding list images. Well done! ![Steve's scrim](https://selftaughttxg.com/static/cb1a466b573a1ba0f59648ffebe02e94/d743b/image1.png) **Link to Steve's scrim:** [scrimba.com/scrim](https://scrimba.com/scrim/coc8d4a639f5f28bf6ed709a0) --- **Lucas** ([@LucasSutter1](https://twitter.com/LucasSutter1)) completed the stretch goal of switching names of people between the Naughty and Nice list by writing a "switchIt" function! Well done! ![Lucas's scrim](https://selftaughttxg.com/static/59f3c19384cbd1800cb9978e0d64ddfd/1cfc2/Lucas.png) **Link to Lucas's scrim:** [scrimba.com/scrim](https://scrimba.com/scrim/coa96497e8543e2adf53efd83) --- **Tim** ([@TimRinkel](https://twitter.com/TimRinkel)) created a Festive Translator with nice message animations. ![Tim's scrim](https://selftaughttxg.com/static/acee354ac986325f131eaf05d4c85210/c483d/Tim.png) **Link to Tim's scrim:** [scrimba.com/scrim](https://scrimba.com/scrim/co35345e7b344131b33377777) --- **Matt** ([@mattemmmmm](https://twitter.com/mattemmmmm)) created a Snow Man Customer that includes a "Random Color" button that lights up the snowman like a Christmas tree! When you are finished customizing the snowman, you can "checkmark" him to the beach and watch him melt! Very creative! ![Matt's scrim](https://selftaughttxg.com/static/64d398874f80330472a78f036a12f961/1cfc2/Matt-new.png) **Link to Matt's scrim:** [scrimba.com/scrim](https://scrimba.com/scrim/co4e5429aa3a5a32e06da2e45) --- **OlehSml** ([@OlehSml](https://twitter.com/OlehSml)) decided to change the Dessert Decider challenge into a Pizza Decider challenge! Click on the "See Delicious Pizzas 😋" button to generate random pizza onto the cutting board background. This challenge was tastefully done! ![OlehSml's scrim](https://selftaughttxg.com/static/05ffd4afcb4557857b9243aa78c34ee1/1cfc2/OlehSml.png) **Link to OlehSml's scrim:** [scrimba.com/scrim](https://scrimba.com/scrim/co22a4ee1ac3a3c0fe18457eb) --- ### Below are my coding solutions to the JavaScriptmas challenges 12 through 18! --- ### Challenge 12 #### Christmas Guest List **Task:** 1. Write the JS to render the Christmas day guest list in the guest list. 2. Add the functionality to add new guests. --- **To style the page, I added:** * Transparent gradient background * Background image (from pixabay.com) * Dotted white border --- ![Challenge 12](https://selftaughttxg.com/static/b41355b4abe6f334711f3ccd01c0eef0/1cfc2/Challenge12.png) --- ### Final code #### Challenge 12 **Link to the solution: [scrimba.com/scrim](https://scrimba.com/scrim/co57849489b5b872f7d95e6c0)** ```javascript function loadGuestList(){ for(let i = 0; i <guests.length; i++) { const listItem = document.createElement("li"); const listItemName = guests[i]; listItem.textContent = listItemName; guestList.appendChild(listItem); } } loadGuestList(); btn.addEventListener("click", addGuest); function addGuest() { const listItem = document.createElement("li"); const listItemName = input.value; listItem.textContent = listItemName; guestList.appendChild(listItem); } ``` --- ### Challenge 13 #### Christmas Dinner Calculator **Task:** *Write the JS to decide the perfect Christmas dinner and render it in the result element. Don't forget to check whether the meal should be vegetarian!* --- **To style the page, I added:** * Transparent gradient background * Background image (from pixabay.com) * Dotted white border --- ![Challenge 13](https://selftaughttxg.com/static/12255f34fe9e6531ab6e1c00dd2f051e/1cfc2/Challenge13.png) --- ### Final code #### Challenge 13 **Link to the solution: [scrimba.com/scrim](https://scrimba.com/scrim/co6fc45678b7d9762466fb26b)** ```javascript function christmasCalculator(){ let guests = document.getElementById("num-input").value; let vegetarianInput = document.getElementById("vegetarian-input"); let vegetarianInputTrue = vegetarianInput.checked; if(vegetarianInputTrue === true) { result.textContent = "Your ideal Christmas dinner is Nut roast" } else { if(guests > 5) { result.textContent = "Your ideal Christmas dinner is Goose" } else { result.textContent = "Your ideal Christmas dinner is turkey" } } } ``` --- ### Challenge 14 #### Lonely Elf **Task:** 1. Write a function to duplicate the elf when the button is clicked. 2. See index.css for optional styling challenges. --- **To style the page, I added:** * Sky background image (from pixabay.com) * Wall background image (from pixabay.com) --- ![Challenge 14](https://selftaughttxg.com/static/e4dc5a741f806b37c8c711252006355a/1cfc2/Challenge14.png) --- ### Final code #### Challenge 14 **Link to the solution: [scrimba.com/scrim](https://scrimba.com/scrim/co4d14c2785de4a5cb7e6b805)** ```javascript function duplicateElf(){ if(counterElf < 100){ counterElf++; const divElf = document.createElement("div"); divElf.classList.add("square-elf"); divElf.innerText = "🧝"; containerElf.appendChild(divElf); title.innerText = `${counterElf} Elves on the wall`; } else { title.innerText = `${counterElf} Elves on the wall!`; } } ``` --- ### Challenge 15 #### Festive Translator **Task:** *Write a function to display the correct greeting when a language is selected.* --- **To style the page, I added:** * Transparent gradient background * Background image (from pixabay.com) --- ![Challenge 15](https://selftaughttxg.com/static/4535782fa673b4849206e4fb82f969f7/1cfc2/Challenge15.png) --- ### Final code #### Challenge 15 **Link to the solution: [scrimba.com/scrim](https://scrimba.com/scrim/co8ae4be3b351f697d2bcf9e1)** ```javascript function translate() { for (let i=0;i<greetingsArr.length;i++) { if (greetingsArr[i].language === languageSelector.value) { greetingDisplay.innerText = greetingsArr[i].greeting; } } } ``` --- ### Challenge 16 #### Christmas Movie Selector **Task:** 1. Write a function to select a suitable movie based on the age group. 2. Display it in the suggested-movie paragraph when the button is clicked. --- **To style the page, I added:** * Background image (from pixabay.com) * Tv png image from Google --- ![Challenge 16](https://selftaughttxg.com/static/3092251bd6b534621ee32f67d4dc4de0/1cfc2/Challenge16.png) --- ### Final code #### Challenge 16 **Link to the solution: [scrimba.com/scrim](https://scrimba.com/scrim/co8ce40b0a12419459e43b603)** ```javascript function selectMovie() { for(let i =0; i <moviesArr.length; i++) { if(ageSelector.value === moviesArr[i].age && genreSelector.value === moviesArr[i].genre){ suggestedMovie.innerText = moviesArr[i].name; } } } ``` --- ### Challenge 17 #### Naughty List, Nice List **Task:** *Write the JavaScript to sort the people in sorteesArr into the naughty and nice lists, according to whether they have been good or not. Then display the names in the relevant place in the DOM.* --- **To style the page, I added:** * Background image (from pixabay.com) * Parchment image (from pixabay.com) --- ![Challenge 17](https://selftaughttxg.com/static/439e1b27166f09c2459bf73db4eba349/1cfc2/Challenge17.png) --- ### Final code #### Challenge 17 **Link to the solution: [scrimba.com/scrim](https://scrimba.com/scrim/co2084003a0b1807b15162873)** ```javascript function sort() { for(let i = 0; i<sorteesArr.length;i++){ if(sorteesArr[i].hasBeenGood) { listNice.push(sorteesArr[i].name); const listItemGood = document.createElement("li"); const listItemGoodName = document.createTextNode(sorteesArr[i].name); listItemGood.appendChild(listItemGoodName); niceList.appendChild(listItemGood); } else { listNaughty.push(sorteesArr[i].name); const listItemBad = document.createElement("li"); const listItemBadName = document.createTextNode(sorteesArr[i].name); listItemBad.appendChild(listItemBadName); naughtyList.appendChild(listItemBad); } btn.disabled = true; } } ``` --- ### Challenge 18 #### Custom Shopping Checkboxes **Task:** *Write the CSS to create custom checkboxes for our shopping list.* --- **To style the page, I added:** * Background image (from pixabay.com) * Google Font --- ![Challenge 18](https://selftaughttxg.com/static/3be5e3f1bcbdda2d42208884006ad00b/1cfc2/Challenge18.png) --- ### Final code #### Challenge 18 **Link to the solution: [scrimba.com/scrim](https://scrimba.com/scrim/co00347cf90b815d5e251d8b5)** ```css [type="checkbox"] { opacity: 0; } [type="checkbox"] + label { position: relative; padding-left: 35px; cursor: pointer; display: inline-block; color: goldenrod; line-height: 30px; } [type="checkbox"] + label::before { content: ""; left: 0; top: 0; position: absolute; width: 30px; height: 25px; outline: 3px dotted darkred; } [type="checkbox"]:checked + label::after { content: "⭐"; left: 0; top: 0; position: absolute; width: 30px; height: 25px; outline: 2px dotted green; } input[type=checkbox]:checked + label.strikethrough span::before { content: "🎄"; } input[type=checkbox]:checked + label.strikethrough span::after { content: "🎄"; } ``` --- ### JavaScriptmas Winners A FREE full-year subscription to Scrimba! * Day 11: [@claircedesign](https://twitter.com/claircedesign) * Day 12: @marleigh (Discord) * Day 13: @Emmanuel (Discord) * Day 14: @Mik (Discord) * Day 15: [@dsabalete](https://twitter.com/dsabalete) * Day 16: [@Arbaaz_77](https://twitter.com/Arbaaz_77) * Day 17: [@evla27](https://twitter.com/evla27) * Day 18: [@graficdoctor](https://twitter.com/graficdoctor) * Day 19: @Daniela (Discord) --- **Be sure to check out my related articles!** * [Review: Scrimba's Weekly Web Dev Challenge](https://selftaughttxg.com/2021/01-21/ReviewScrimbaWebDevChallenge/) * [Scrimba: JavaScriptmas 2020](https://selftaughttxg.com/2020/12-20/Scrimba-JavaScriptmas_2020/) * [The Post-JavaScriptmas 2020 Post](https://selftaughttxg.com/2020/12-20/The_Post-JavaScriptmas_2020_Post/) --- #### **Scrimba has once again impressed and inspired me! You can read my full [Scrimba review](https://selftaughttxg.com/2020/12-20/Review-Scrimba/) on my 12/13/2020 post.** ![Per Harald Borgen Quote](https://selftaughttxg.com/static/85d4b08288b8be565392fd0975170a8e/5fd3e/PerHaraldBorgen-Quote.png) #### *"That&#39;s one of the best Scrimba reviews I&#39;ve ever read, <a href="https://twitter.com/MikeJudeLarocca?ref_src=twsrc%5Etfw">@MikeJudeLarocca</a>. Thank you! 🙏 "* ###### &mdash; Per Harald Borgen, CEO of Scrimba <a href="https://twitter.com/perborgen/status/1338462544143540227?ref_src=twsrc%5Etfw">December 14, 2020</a></blockquote> --- ### Conclusion Scrimba's JavaScriptmas annual FREE event is a wonderful way to commit to coding daily and is a fun and festive event where all participants have an equal opportunity to win prizes, regardless of their skill level. During the JavaScriptmas event, Scrimba offers new students a 20% discount code through a link provided at the end of each day's coding challenge. By completing all 24 coding challenges, you will be awarded a certificate and an exclusive Discord badge, and since each submission acts as a raffle ticket, you will have 24 chances to win prizes! --- ###### *Are you now interested in participating in this year's Scrimba's JavaScriptmas? Have you already participated in last year's Scrimba's JavaScriptmas? Please share the article and comment!* ---
michaellarocca
931,613
My thoughts on learning Web in 2021
Note: this post is originally written in my personal blog. Hello, people! You probably already saw...
0
2021-12-27T23:04:26
https://aibolik.com/blog/my-thoughts-on-learning-web-in-2021
html, web, roadmaps, learningwebdevelopment
--- title: My thoughts on learning Web in 2021 published: true date_time: 27/12/2021 21:06:28 UTC tags: html,web,roadmaps,learningwebdevelopment canonical_url: https://aibolik.com/blog/my-thoughts-on-learning-web-in-2021 --- > Note: this post is originally written in [my personal blog](https://aibolik.github.io/blog/my-thoughts-on-learning-web-in-2021). Hello, people! You probably already saw or read one of those articles like “Web developer roadmap in 2021”, “How to become a web developer”, etc. So, I also wanted to share my perspective on this topic that might be useful to some people who are at the start of their exciting journey or open some discussion with others. ![](https://cdn-images-1.medium.com/max/1024/1*NfqoLP-mVAHW6QBIBHp7BQ.jpeg) _Learning Web in 2021 is not a straight line (Photo by Mark König on Unsplash)_ ### HTML I want to start with the most basic and the important, as well as, sometimes, overlooked part of the Web — HTML. Why overlooked? Thanks to some great JavaScript frameworks, like React, web developers frequently deal with “components” rather than HTML elements. However, it is important to understand **semantic HTML** and **accessibility** and many more topics. I have to admit that I kickstarted my Web Developer work with React and had to catch up with many important concepts of Web later on. Let’s go over some main of the topics here(in my opinion). #### Semantic HTML and Accessibility The [simple idea](https://web.dev/accessible/) is to build a site that works for all of your users. By saying “all of your users” I mean: people with disabilities, people with different internet bandwidth, color blindness issues, device issues, or someone who just doesn’t want to(or can’t) use a mouse/keyboard. Some pretty obvious things to start with are using semantic HTML elements, such as button, input, select, nav, and more. In addition to them, you should be familiar with aria-\* and role attributes, which can add additional context for users with screen readers. And even before starting the development, you can talk with your designer to use contrasting colors and also introduce dark/alternative color schema, if it is worth it. (it is a bit outside of the HTML topic, but still worth mentioning). > When I was around 10, my mouse was broken on Pentium II Windows 98 PC. Guess what I had to use to be able to navigate through my computer? #### Know your “head” tags As the subtitle suggests, you should be familiar with what you put on your head tag. This and using the right semantic HTML elements can also affect the SEO of your website. Some meta tags can provide additional information about your website(like title, description, data for a Twitter card) and some tags can optimize your website. With the link tag, you can hint your browser to do some work before accessing some resources(prefetch, preconnect). Take some time to get familiar with them and feel free to take these low-hanging fruits for your website optimization. #### Know how your elements look and interact Other than knowing your “head” tags you should be quite familiar with your main “body” tags. Especially, what do they imply and how they interact. For example, consider these: - the default styling of elements(margins on paragraph, font size, and margins on h1-h6 tags, styling of anchors) - interactive elements(those are accessible with TAB, like an anchor, button, etc.) and how to make one yourself - other accessibility features, like outlined button - transition when clicking on the anchor These are kinda basic, but you might also want to familiarize yourself with more HTML5 elements, and maybe some new elements like dialog those let you create modals out of the box. I believe there are many topics that I left not mentioning here about HTML, but I wouldn’t be able to put everything in this article. So, if I missed something important, please feel free to leave a comment or mention it tagging me on Twitter([@aibolik\_](https://twitter.com/aibolik_)). ### CSS When it comes to CSS, today, we already have different tools to pre- and post-process our “style code” to make our lives easier. But the essential knowledge of CSS remains the key. These are the basic concepts related to laying out elements and styling of them: box-model, positioning, responsive styles, different laying out strategies(flex, grid), transform and transition of properties, and more. But if we go a bit further, it is worth exploring these topics too. #### Logical properties These might not be relevant to the project you are working on, but if your website supports multiple locales, which include right-to-left and/or vertical top-down layouts, you should be familiar with these properties. Shortly, these properties [adapt to the layout](https://web.dev/logical-property-shorthands/) of the page. You don’t explicitly set right/left/top/bottom spacing, you set start/end spacing and the browser will take care of setting the exact side for you. > Alternatively, if you are working on an open-source (popular) components library, chances are that your design would also be used in websites, where they need [“rtl”](https://developer.mozilla.org/en-US/docs/Web/CSS/direction) support. #### CSS variables When I first heard about CSS variables, the support for them was not good. However, these days all modern browsers support this feature. At first, some might think it is similar to variables in other CSS post-processors(like LESS or SASS), however, they possess more power than you thought. You can easily rewrite them for some selector, media query, or even with JavaScript(because they are still CSS properties). They are quite useful when building (several) [color schemas](https://web.dev/building-a-color-scheme/). But they are also useful for many different things, I saw people using them in very creative ways. It is worth checking out its capabilities. Again here, CSS is another big topic in the Web world. There are also topics like typography and fonts, selector naming conventions, many different CSS frameworks, CSS-in-JS, and more. I can not cover all of them in this article, but case by case, some might be more relevant than others, and for some topics, it is enough to just have a basic understanding of the principles. ### JavaScript Yet another big topic and I believe the one that is more over-hyped than the other 2 pillars of the Web(thanks again to JS frameworks). Since it is a full-blown programming language it is essential to understand how it works. In addition to how JavaScript works, for Web Developer, it is essential to understand how it works in a browser context. Some points to mention: - interaction with DOM API - event handling - browser APIs(history, fetch, IntersectionObserver, storage APIs, and more) - [and many many more topics](https://javascript.info/) Even if popular JavaScript frameworks give a real boost in Web Development, the core JavaScript knowledge is still very important. Even if you start very well with some JavaScript framework, at some point you might end up not understanding how some things function. I was in that shoe, and when I was interviewed for one project where essential JavaScript knowledge was important, I failed that interview. Immediately after that interview, I decided to level up my core JavaScript knowledge and discovered the [“You don’t know JS”](https://github.com/getify/You-Dont-Know-JS) book series. It was a really good time investment and I highly recommend it for people who feel they have gaps in their JavaScript knowledge. This is a small portion of my thoughts regarding the Web topic. I hope to share more of my thoughts and learnings, so if you liked the content, feel free to [follow me on Twitter](https://twitter.com/intent/follow?screen_name=aibolik_), where I will share everything I write. Stay tuned and thanks for reading!
aibolik
934,533
Shop talk
Imagine you’re at a friend’s birthday party, and you bump into someone who works in the same field as...
0
2022-02-02T18:20:46
https://jhall.io/archive/2021/12/23/shop-talk/
hiring, interview
--- title: Shop talk published: true date: 2021-12-23 00:00:00 UTC tags: hiring,interview canonical_url: https://jhall.io/archive/2021/12/23/shop-talk/ --- Imagine you’re at a friend’s birthday party, and you bump into someone who works in the same field as you. Maybe you’re both JavaScript developers. Or maybe you both work with AWS. So you start talking shop. “Have you tried the new version of X?” you ask, with genuine curiosity. Now imagine their response. It’s going to have a serious impact on your professional opinion of this new acquantance. Do they even know what **X** is? Have the heard of it, but dismissed it? If so, is their reason for dismissing it valid? Maybe they’re keenly interested in **X** , but explain why they haven’t tried using it yet. You then dig a bit deeper. “Oh, I see. But had you considered that X can also be used for …?” Through the course of this natural conversation you’ll very quickly form a professional opinion of this person. If you’re at all like me, you’ll put their professional expertise into one of a small number of mental buckets with descriptions like: 1. This person is a genius! I should hang out with him more! 2. She and I could really challenge each other. 3. He’s still fresh, but he’s got a great attitude! 4. We only barely work on similar technology, so I can’t really tell if what he actually does is interesting. 5. This person has no clue, and they like it that way. All bark, no bite. Isn’t this exactly what we’re trying to learn during the job interview process? Companies ask a candidate to spend 8 hours on the weekend writing a REST API, then they ask a technical hiring manager to spend an hour or two reading that code, then they call the candidate in to spend another hour talking about that code. All to determine which of the 5 buckets above the candidate falls into. Why not cut all this crap and just talk shop with the candidate for 15 minutes? There’s nothing like an expert and a poser talking shop to expose the poser in just a few seconds. Don’t believe it’ll work? Next time you meet someone in the same or an adjacent industry in a social setting, try it out. Spend 10-15 minutes talking shop, and see if you can make a clear “no-hire” decision based on what you learn. * * * _If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
jhall
931,676
Building a React Native Filter - Part 1
A couple of weeks ago a client asked us to create an application that displayed all of it's stores....
16,869
2022-02-17T18:08:39
https://dev.to/muvinai/building-a-react-native-filter-part-1-21j7
javascript, webdev, beginners, react
![App Walkthrough](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jxwau6dlwf85sch0wfpj.gif) A couple of weeks ago a client asked us to create an application that displayed all of it's stores. The app had to be built in **React Native** in order to speed up development time and ensure compatibility among Android and IOS and had to include a full list of our client's stores. This list was fetched from a MongoDB collection, and came as an array of objects containing information for each store (such as location, phone number, email, coordinates). Obviously, a plain list of objects doesn't satisfy a customer, as scrolling through a 189 store list to find a specific one might be extremely painful. So with React Native (our choice to build fast compatible apps) we decided to create a filter. The filter we built included features such as **searching, categorizing and ordering according to proximity**. In this article, we will show you how the filter was built by using a <u>mock API</u> to build a filter with search and categorization (in the future we will write another article to show how to handle location based objects, order them and filter them). The tutorial will not cover a step by step of the whole code, but will go through the most important parts when building it. You can find the whole code in **this** [**Expo Snack**](https://snack.expo.dev/@rochi/react-native-filter). You will see this is a **front-end built filter**, and doesn't use backend filtering. Although backend filtering is a good option (particularly to handle long lists), it works smoothly with the data we have. **Bear in mind** if you have millions of elements mapping through them will impact negatively on the app's performance. ![Main view of our application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t1j9ahi8xjcgi6h4vyd6.jpg) So, to start we will be using [Fruityvice's API](https://www.fruityvice.com/) that will bring a response with an array of objects containing different information about fruits. An example for the response we get is: ```json [{ "genus": "Malus", "name": "Apple", "id": 6, "family": "Rosaceae", "order": "Rosales", "nutritions": { "carbohydrates": 11.4, "protein": 0.3, "fat": 0.4, "calories": 52, "sugar": 10.3 } }, ...] ``` ## Project Structure Let's get hands on it to the real code. The structure our project will take is: 1. A main App.js file where most of the work will happen, here we will set the main states and fetch our data. 2. Components folder. 3. Assets folder. 4. Data folder in order to save the initial state some variables will have. ## Fetching the API The first thing we should do, is fetch the API. We fetch it through a simple **fetch function built in a useEffect**, meaning each time the component mounts, the API is fetched and the fruits "refresh". The response is saved as a json and we can now work with it. ```js useEffect(() => { fetch('https://www.fruityvice.com/api/fruit/all') .then((response) => response.json()) .then((json) => setFruits(json)) .catch((error) => console.error(error)) .finally(() => setLoading(false)); }, []); ``` ## Our App.js Component We create a `<SafeAreaView />` for our App.js (so that the content we build is contained within a visible space). Inside the SafeAreaView we will have three components, the **AppBar** (that will hold the modal and a logo for our app), the **modal** itself, and the **Wrapper** (called `<FruitsWrapper />`) where we will render the "card-styled" list of fruits with their information. On the App.js we'll also do two things that will help us handle the Filtering correctly. First we'll set a couple of states: ```js const [fruits, setFruits] = useState([]); const [filter, setFilter] = useState(initialFilter); const [intermediateFilter, setIntermediateFilter] = useState(initialFilter) const [modalVisible, setModalVisible] = useState(false); ``` * _fruits_ holds the array of objects we fetch from the API * _filter_ filter is the real filter that will be applied when the user decides to APPLY the filter within the modal * _intermediateFilter_ is a filter that is setted while the user interacts with the modal, once the apply button is pressed, the intermediateFilter becomes the actual filter * _modalVisible_ will handle modal visibility > **_Why the intermediateFilter?_** the intermediate filter ensures the fields the user clicks while in the modal will be applied correctly. We need to save the user choices as he/she advances through the modal. Both the intermediateFilter and the filter take up an _**initialFilter**_. What is this? The `initialFilter` is a js written in our data folder. initialFilter is an object that hold's the initial state of the fields we are going to filter. ```js export const initialFilter = { query: '', genus: '', carbohydrates: '', } ``` ## The AppBar ![App Bar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5c4sy0vuoolxtg74j6j7.jpg) The App bar is extremely simple. We have a logo, and a button that when pressed will change the state of the `modalVisible` variable to true and show us the modal. ## Displaying the info ![sample of "Apple" card](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shfihowh8uwc2kkcevvn.jpg) Before we filter we want to display multiple cards containing information about the fruits so we can then sort them according to the user's choices. For this we have two components `<FruitsWrapper />` and `<InfoCard/>` * `<FruitsWrapper />` is the wrapper where we map through the fruits and display them. In this Wrapper we will also have the <u>filtering instance</u>. So as long as there no filters it will display the complete object we receive from the fetch. If there filters, we will push fruits to a new variable that will be empty. * `<InfoCard/>` is the UI of the card that will hold the object's info. We build only one object, and then map the fetch response and render each fruit (with it's information in the cards). ### The `<FruitsWrapper />` This component is **SUPER** important. As the logic applied here makes the magic to display the filtered content. You can see that at the beginning of the component I declared two boolean variables: `filterFruits` and `empty` (empty will not be used yet, but will serve us to display that no fruits were fetched). I then set up an **empty filterArray** where the fruits I filter with my modal will be pushed. After doing this I set `filterFruits` equal to `allFruits`, the later one being the whole fruit array we brought on the first place. The following logic is key to filtering: ```js if (filterFruits != undefined && && typeof filterFruits === 'object'){ filterFruits.map((fruit) => { // I have two things, the filter and the fruits genus (in the array) so if I filter I only want to show the ones that match the genus if (filter.genus != '' && !fruit.genus.includes(filter.genus)) { return } filterArray.push(fruit) }) if (filterArray.length > 0) { filterFruits = filterArray; } } else { filterFruits = false empty= true } ``` The filtering happens if `filterFruits` (before known as allFruits) is **not undefined** (meaning it has some content) and the **type of this is an object**. What we do is map through each fruit, if it <u>doesn't match</u> the parameters we want it to, we **return**, else we **push it** to the `filterArray`. If the filter array is bigger than 0 (meaning fruits were pushed) `filterArray` (the one where we pushed) becomes `filterFruits`. ## The Modal ![An image of the App's modal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lcqr48pwfdpktsco7kl5.jpg) The modal is the most important part of this tutorial. For this we will use **React Native's built in modal**. > In the application we built for the client we had two modal instances, the _filtering modal_ (that used the native modal) and an _alert modal_ (where we used [UI Kitten's](https://akveo.github.io/react-native-ui-kitten/) modal). We like the native modal because it offers us the possibility of deciding how it transitions and it's easier to set it up fullscreen. As we mentioned previously we chose to use an **intermediate filter within the modal** so that the state management can be smooth, and we can access the different states (Remember that the `initalFilter` was an object?). Yet, after the user click's the apply button, we want the `intermediateFilter` to become the actual `filter` A key thing we also have in this modal is the list of all the genus. Instead of mapping all the fruits and displaying the genus, in the App.js we created an array with **all the unique genus** (so that we don't get them repeated). The following code creates an array of all the fruit.genus unique values: ``` const genusResult = allFruits.map(item => item.genus) .filter((value, index, self) => self.indexOf(value) === index) ``` We loop through this array that we built to create the radio buttons, as you will see in the `RadioButton.js` file. This file holds custom built Radio Buttons. The good thing about this is that they are fully customizable, and give us more control over the user selection. The thing is, the user can only select one genus, and when the user selects the genus selected is saved in the intermediate filter. Once the user decides which genus he/she wants to see, he applies the filter and because of the logic applied in the `<FruitsWrapper />` only the fruits that have that genus will be shown. ## Closing Remarks This was a quick tutorial over how to build the filter. We hope it was easy to follow and in the second part we will talk about querying filtering. Remember the full code is in our [Expo Snack](https://snack.expo.dev/@rochi/react-native-filter)
rochijacob
931,678
Baloonza IT newsletters weekly digest #16
css, web development, frontend, javascript, react Issue 332 CSS Layout News CSS...
15,791
2021-12-20T22:50:30
https://app.baloonza.com/baloons/1/baloon-issues/16
javascript, webdev, css, startup
### css, web development, frontend, javascript, react - [Issue 332](https://app.baloonza.com/issues/10483?baloon_issue_id=16) `CSS Layout News` - [CSS Animation Weekly #279](https://app.baloonza.com/issues/10500?baloon_issue_id=16) `CSS Animation Weekly` - [📝 [CSS-Tricks] 281: Tabs and Spicy Drama](https://app.baloonza.com/issues/10529?baloon_issue_id=16) `CSS-Tricks` - [Frontend Weekly - Issue 284](https://app.baloonza.com/issues/10600?baloon_issue_id=16) `Frontend Weekly` - [Issue #485: Window Controls Overlay, CSS Relative Colors](https://app.baloonza.com/issues/10604?baloon_issue_id=16) `CSS Weekly` - [The state of CSS in 2021](https://app.baloonza.com/issues/10611?baloon_issue_id=16) `Frontend Focus` - [💻 Issue 209 - 10 Best Websites to become a React.js Developer in 2022](https://app.baloonza.com/issues/10681?baloon_issue_id=16) `Awesome React Newsletter` - [💻 Issue 291 - Tailwind CSS v3.0 is here — bringing incredible performance gains, huge workflow improvements, and a seriously ridiculous number of new features.](https://app.baloonza.com/issues/10678?baloon_issue_id=16) `Awesome Javascript Newsletter` - [Hacker Newsletter #583](https://app.baloonza.com/issues/10703?baloon_issue_id=16) `Hacker Newsletter` ### startup - [Reinventing spreadsheets](https://app.baloonza.com/issues/10510?baloon_issue_id=16) `Product Hunt Daily` - [Shopify for web3](https://app.baloonza.com/issues/10561?baloon_issue_id=16) `Product Hunt Daily` - [Canva vs Adobe](https://app.baloonza.com/issues/10601?baloon_issue_id=16) `Product Hunt Daily` - [Social video threads 🧵](https://app.baloonza.com/issues/10646?baloon_issue_id=16) `Product Hunt Daily` ### marketing - [🎓 Micro-influencers drive more sales (+ a surprise 🔥)](https://app.baloonza.com/issues/10543?baloon_issue_id=16) `Ariyh` ### data science - [Data Science Weekly - Issue 421](https://app.baloonza.com/issues/10694?baloon_issue_id=16) `Data Science Weekly Newsletter ` ***
dimamagunov
931,690
Starting a Prisma + TypeScript Project
With such a rich selection of ORMs out there, choosing which one to use for your JavaScript-based...
15,989
2021-12-21T00:15:30
https://sabinadams.hashnode.dev/starting-a-prisma-typescript-project
javascript, typescript, database
With such a rich selection of ORMs out there, choosing which one to use for your JavaScript-based project can be tough. Depending on your goals or stack you have a ton available: libraries like [TypeORM](https://typeorm.io/#/), [Sequelize](https://sequelize.org/), and [Mongoose](https://mongoosejs.com/), and many more. In this article and throughout the rest of this series we'll be taking a deep dive into another option; One that offers tons of cool features, a unique "ORM" experience, and an active, dedicated team of developers supporting and working on it. That option is [Prisma](https://www.prisma.io/). --- ## What is Prisma? At the most basic level, Prisma provides a set of tools that enable you to access and interact with your database. While offering many of the same features a traditional ORM would, Prisma describes itself as a *next-gen ORM* because of its unique implementation of what is known as the "data-mapper" model of ORM and its careful consideration of Type-Safe interactions. Along with offering a great ORM tool (the Prisma Client), Prisma also offers a database migration tool called `Prisma Migrate` and a nice GUI that allows you to visualize and update data in your connected database called `Prisma Studio`. Our focus in this article and the rest of the series will be on the `Prisma Client` and its rich feature-set. As we learn more about how Prisma works in this series, we will get to play with a lot of the features that make Prisma so powerful and different from the other tools available. > If you'd like to learn more about the different types of ORMs and where Prisma fits in and differs from those, please give [this page](https://www.prisma.io/docs/concepts/overview/prisma-in-your-stack/is-prisma-an-orm#data-mapper) a read. --- ## Jumping In As much as I'd love to start going through all the benefits, downsides, use-cases, and don't-use-cases (that's a phrase right?) of Prisma, I'm sure you're anxious to get to the good stuff. Let's dive right into a super simple setup of Prisma so we can get some context into what Prisma is and take a look at the whats and why’s later on. > This tutorial will assume a basic knowledge of JavaScript and its development ecosystem, TypeScript, and Database Terminology. If you want to brush up on these, check out these pages on [npm](https://nodejs.dev/learn/an-introduction-to-the-npm-package-manager), [TypeScript](https://www.typescriptlang.org/docs/handbook/intro.html), and [SQLite](https://www.tutorialspoint.com/sqlite/index.htm) For the example here we'll connect Prisma to a SQLite database, however Prisma currently also supports Postgres, MySQL, MSSQL, and MongoDB. To start things off, let's create a folder for our project and initialize `npm` inside of it, which we will be using to install various packages. *(For all you yarn-lovers 🐈, feel free to use that instead)* ```sh mkdir <my-project> cd <my-project> npm init -y ``` Next, we'll install our development dependencies for TypeScript and Prisma ```sh npm i -d prisma typescript ts-node @types/node ``` With all of our packages installed, we can now configure TypeScript by adding a `tsconfig.json` file, a simple TypeScript file, and a script to our `package.json` that we can run to start our development server. ```json // tsconfig.json // This is just a basic setup, feel free to tweak as needed { "compilerOptions": { "sourceMap": true, "outDir": "dist", "strict": true, "lib": ["esnext"], "esModuleInterop": true } } ``` ```ts // main.ts console.log("I'm Running!") ``` In `package.json`, add the following to the `"scripts"` section: ```json "dev": "ts-node main", ``` Now, in your terminal at the root of your project run ```sh npm run dev ``` ...and you should see output similar to the following: ![Screen Shot 2021-12-18 at 8.04.32 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639886675636/TNExe_Pet.png) Our project is set up with TypeScript and ready to get fancy! Now we'll move on to setting up Prisma. --- ## Setting up Prisma ### Initializing The steps to get Prisma going are pretty simple. We have the dependency installed already, so to start we'll just run Prisma's `init` command and tell it we're going to use SQLite as our datasource. For a full list of options available to the `init` command, check out these [docs](https://www.prisma.io/docs/reference/api-reference/command-reference#run-prisma-init). ```sh prisma init --datasource-provider sqlite ``` You'll notice a new folder in your project named `prisma` as well as a `.env` file in your project's root. The contents of that folder should just be a file named `schema.prisma`, which is the file where we will define how the `Prisma Client` should get generated and model our data. Then you'll need to tell Prisma where to output the SQLite db file. In the `.env` file let's make sure the `DATASOURCE_URL` env variable specifies a file location that makes sense (I'm outputting it directly into the `prisma` folder): ``` DATABASE_URL="file:dev.db" ``` Prisma allows us to access `.env` variables using the `env()` function in a `.schema` file. You can see its usage by opening up `prisma.schema` and checking out the `url` attribute of the `datasource` block. ### Defining our Data Model There are various different kinds of blocks in a `.schema` file that do different things and have tons of different options. We'll just set up a simple `User` model for the purposes of this tutorial. ```prisma model User { id Int @id @default(autoincrement()) firstName String lastName String email String } ``` > In a future article we'll dive deeper into the contents of this file and how to model out your data This defines a User table for Prisma so it will know how to generate a nice, typed client that allows us to interact with the data. Right now our database is empty though, we'll need to push our schema into the database to actually create that table. *(This command should also generate the `Prisma Client` after pushing the schema)* ``` prisma db push ``` ![Screen Shot 2021-12-20 at 12.38.41 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640032724523/b3Z6Qpt6u.png) After running that, we can make sure our table was created using `Prisma Studio`. Run this command to open up the studio ``` prisma studio ``` This should open up a window at [http://localhost:5555](http://localhost:5555) and look something like this. ![Screen Shot 2021-12-20 at 12.15.42 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640031349057/8ubZjL21f.png) If you click on the `User` model you should see a nice table view of your database table with options to search and add rows to the table. Pretty sweet! This tool definitely comes in handy working with your data. Now that we've got our data modeled, the model available in the database, our datasources set up, AND the client generated, let's put it to use! --- ### Prisma Client The `Prisma Client` is generated by default into your `node_modules` folder under `@prisma/client`. To start, go ahead and modify your `main.ts`. Import and instantiate the Prisma client. ```ts import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() async function main() {} main() .catch( e => { throw e }) .finally( async () => await prisma.$disconnect() ) ``` So what does this do? This imports and creates an instance of the `PrismaClient` class that was generated by Prisma based off of the model definitions you gave it. Right now our `main()` function doesn't do anything, this is where we will add some code to interact with our data. The ending piece is important. Prisma opens up and handles connections automatically, however we need to tell it that when the application closes or reloads it should disconnect. If not, connections would be generated for each time your application starts and stay alive until manually disconnected. If your application gets an error when you try to run it, it is likely the Prisma Client was not generated on the `db push`. Go ahead and run the following command to generate the Prisma Client and try again. ``` prisma generate ``` ### Querying the Database We can now start playing with some data! In your `main()` function, lets try to print out all of the `users` in our database. ```ts async function main() { const users = await prisma.user.findMany(); console.log(JSON.stringify(users)); } ``` As you type that out, check out the awesome IntelliSense! Prisma generated a set of types and definitions for the Client to help make our lives easier. ![Dec-20-2021 23-58-12.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1640073545095/W5jhqe0J0.gif) Pretty awesome! Although you may notice after running this the results are empty... that's because we have no data yet! We can fix that, head back over to the `Prisma Studio` and add a record to your User table. ![Dec-20-2021 13-04-01.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1640034269631/fUx3tHPGh.gif) Now if you run your code again, you should see your user outputted in the console! ![Screen Shot 2021-12-20 at 1.05.40 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640034343027/Chj02ASpV.png) --- ## Wrapping Up This is just the beginning, Prisma has such a rich set of features and potential for so much more. In the coming series we will be taking a deep look at everything Prisma has to offer, design patterns, custom extensions, and more! So if you enjoyed this and Prisma is piqueing your interest, keep an eye out for the coming articles. We managed to set up Prisma with TypeScript, a SQLite database, and an entire database client to connect to that database in this article with very little effort. That's pretty awesome to me. If you want to dig deeper and expand on what we talked about, check out the [`Prisma Client`](https://www.prisma.io/docs/concepts/components/prisma-client) docs. Thanks for reading, and happy coding!
sabinthedev
931,716
Criando um CRUD em Go com persistência em arquivos
Construindo um CRUD em Go com persistência em Arquivos Introdução O objetivo...
0
2021-12-21T01:36:31
https://brenoasrm.com/2021/12/19/crud-em-go-pesistencia-arquivos.html
go
## Construindo um CRUD em Go com persistência em Arquivos ### Introdução O objetivo desse artigo é mostrar o passo a passo necessário para construir uma API de um CRUD (Create, Read, Update, Delete). Ou seja, nossa API permitirá criar, ler, atualizar e deletar pessoas. Antes de começar de fato a fazer o código, vou mostrar aqui de maneira visual o que pretendo ter contruído no final desse post. ![rotas-api-crud](https://brenoassp.github.io/assets/img/crud-persistencia-arquivo/crud-persistencia-arquivo.png) A gente pode ver na figura que teremos 4 rotas: - Rota de POST para criação de pessoas. - Rota GET para leitura das pessoas. No caso podemos ler todas as pessoas armazenadas ou apenas uma pessoa com base no ID fornecido na URL. - Rota PUT para atualização de uma pessoa já existente. - Rota DELETE para remover uma pessoa. Todas essas rotas vão utilizar a mesma fonte de dados que será um arquivo de nome `person.json`, ou seja, nessa API nós não vamos utilizar banco de dados como forma de armazenamento. Futuramente pretendo fazer um post onde eu modifico esse código atual para utilizar banco de dados ao invés de arquivo, mas nesse caso aqui vou fazer com arquivos para mostrar algumas funções de manipulação de arquivo com Go. Com isso em mente, a gente já consegue ir para a parte de implementação do código. ### Rota de criação de pessoas (POST /person/) O primeiro passo é criar o projeto. Para isso, vou abrir um terminal, criar uma pasta com o nome do projeto, no nosso caso vai ser api-crud-persistencia-arquivo. Em seguida, vou inicializar um novo módulo nessa pasta que a gente acabou de criar utilizando o `go mod init github.com/brenoassp/api-crud-persistencia-arquivo`. Agora que nosso módulo já está inicializado, vamos criar aqui um arquivo `main.go` que vai ser a nossa API. ```go package main func main(){ http.HandleFunc("/person/", func(w http.ResponseWriter, r *http.Request){ http.Error(w, "Not implemented", http.StatusInternalServerError) }) http.ListenAndServe(":8080", nil) } ``` A primeira coisa que estamos fazendo aqui é criando uma função que será executada quando chegar requisições que começam com `/person/`. Note que nesse caso aqui não estamos escolhendo qual o método HTTP utilizado, ou seja, todas as requisições que se encaixarem no padrão de URL executarão essa mesma função. Podemos executar o código para ver que independente do método, o retorno será o mesmo. Para isso faça: `go run main.go` `curl -XPOST localhost:8080/person/` `curl -XGET localhost:8080/person/` Ambos os resultados são iguais pois não há distinção de método e teremos que ter isso em mente durante a implementação da API. Vou começar primeiramente com a implementação da operação de criação de uma pessoa. ```go package main func main(){ http.HandleFunc("/person/", func(w http.ResponseWriter, r *http.Request){ if r.Method == "POST" { type Person struct { ID int `json:"id"` Name string `json:"name"` Age int `json:"age"` } var person Person err := json.NewDecoder(r.Body).Decode(&person) if err != nil { fmt.Printf("Error trying to decode body. Body should be a json. Error: %s\n", err.Error()) http.Error(w, "Error trying to create person", http.StatusBadRequest) return } if person.ID <= 0 { http.Error(w, "person ID should be a positive integer", http.StatusBadRequest) return } // criar pessoa // montar resposta w.WriteHeader(http.StatusCreated) return } http.Error(w, "Not implemented", http.StatusInternalServerError) }) http.ListenAndServe(":8080", nil) } ``` Primeiro eu vou verificar se o método da requisição é POST, se sim então podemos continuar. A primeira operação que devemos fazer é decodificar o corpo da requisição, que no nosso caso deverá ser um JSON com os campos `ID`, `Name` e `Age`. Para isso é preciso criar uma variável de uma struct nesse formato para receber o resultado da decodificação. Com essa variável criada, basta decodificar o JSON recebido da seguinte forma: `json.NewDecoder(r.Body).Decode(&person)`. Esse código tá criando um decodificador com base no corpo da requisição e chamando a função de decodificar passando o endereço de memória da variável que foi criada acima do tipo Person. Esse método retorna um erro que se for diferente de `nil` significa que algo deu errado durante a decodificação. Faremos um tratamento usando esse erro para retornar um erro para o usuário com o status de BadRequest que indica que o erro ocorreu por conta de valor inválido fornecido pelo próprio usuário. Caso dê tudo certo a resposta será o status http OK (200). `curl -XPOST localhost:8080/person/ -d '{"id": 1, "name": "joao}'` **(Faltando fechar as aspas duplas no nome, dá erro na decodificação do JSON)** `curl -XPOST localhost:8080/person/ -d '{"id": 1, "name": "joao"}'` **(Tudo ok)** Se não tiver dado erro nenhum na decodificação, vou verificar se o ID fornecido é maior do que zero, pois o ID tem que ser positivo. Se deu tudo certo, agora vou tentar adicionar essa pessoa, persistindo em um arquivo. A princípio vou só deixar um comentário aqui indicando que essa parte da implementação tá faltando e retornar uma resposta com status de criado. Antes de implementar essa etapa final da rota, vou extrair a struct que foi criada aqui que representa a pessoa para um arquivo separado. Vou criar uma pasta `domain` e dentro dela o arquivo `entities.go` que terá as entidades. No nosso caso aqui, vou mover a struct Person pra esse arquivo. ```go // Arquivo: api-crud-salvando-arquivo/domain/entities.go package domain type Person struct { ID int `json:"id"` Name string `json:"name"` Age int `json:"age"` } ``` Pronto, agora eu já vou conseguir usar essa struct no nosso serviço sem precisar duplicar código. O próximo passo agora é criar o nosso serviço. Dentro de domínio, vou criar a pasta `person` e dentro dela o arquivo `person.go` ```go // Arquivo: api-crud-salvando-arquivo/domain/person/person.go package person type Service struct { dbFilePath string people domain.People } ``` A primeira coisa que vou fazer é criar uma struct que armazenará as informações utilizadas pelo serviço, essas informações serão: 1 - o caminho do arquivo onde serão armazenadas as pessoas. 2 - as pessoas que estão armazenadas nesse arquivo. No arquivo de entidades vou criar um tipo chamado `People` que será a representação do nosso arquivo de persistência. ```go type People struct { People []Person `json:"people"` } ``` Voltando pra criação do serviço responsável pela lógica de negócio de pessoas, eu vou receber o caminho completo do arquivo como parâmetro. Se o arquivo não existir, então eu crio um arquivo vazio. Se ele existir então eu vou pegar todas as pessoas armazenadas nele e colocar na variável people. Essa abordagem tá longe de ser a ideal porque vamos gastar bastante memória se o arquivo for grande, mas como no nosso caso aqui o objetivo é mostrar como manipular arquivos e construir uma API, eu não estou preocupado com essa otimização. Até porque, num caso real a gente provavelmente utilizaria um banco de dados ao invés de um arquivo como forma de persistência. O primeiro passo é verificar se o arquivo passado já existe. O método `Stat` do pacote `os` nos dá informações sobre o arquivo e caso o arquivo não exista é retornado um erro. Esse erro pode ser usado no método IsNotExist para ver se o arquivo não existe. Se for esse o caso a gente cria o arquivo. Se o erro não for desse tipo então aconteceu algo inesperado que não sabemos como tratar, nesse caso vamos apenas retornar esse erro na criação do serviço. ```go package person type Service struct { dbFilePath string people domain.People } func NewService(dbFilePath string) (Service, error) { _, err := os.Stat(dbFilePath) if err != nil { if os.IsNotExist(err) { err = createEmptyFile(dbFilePath) if err != nil { return Service{}, err } return Service{ dbFilePath: dbFilePath, people: domain.People{}, }, nil } else { return Service{}, err } } jsonFile, err := os.Open(dbFilePath) if err != nil { return Service{}, fmt.Errorf("Error trying to open file that contains all people: %s", err.Error()) } jsonFileContentByte, err := ioutil.ReadAll(jsonFile) if err != nil { return Service{}, fmt.Errorf("Error trying to read people file: %s", err.Error()) } var allPeople domain.People json.Unmarshal(jsonFileContentByte, &allPeople) return Service{ dbFilePath: dbFilePath, people: allPeople, }, nil } ``` A parte de criação de um arquivo vazio eu vou mover para um método separado, nesse método o primeiro passo será criar uma variável do tipo People que vai ter uma slice vazia de pessoas, já que o arquivo não terá nenhuma pessoa inicialmente. Eu vou codificar essa variável para json utilizando o método `Marshal` do pacote `json`. Se der algum erro na codificação um erro será retornado. Se der tudo certo eu vou salvar esse JSON no arquivo, pra isso vou utilizar a função `WriteFile` do pacote `ioutil`. Aqui eu vou passar as permissões do arquivo como 0755, mas na prática acho que poderia ter um pouco menos de permissão nesse caso. Se der erro eu vou retornar erro e se der tudo certo eu retorno `nil`. ```go func createEmptyFile(dbFilePath string) error { var people domain.People = domain.People{ People: []domain.Person{}, } peopleJSON, err := json.Marshal(people) if err != nil { return fmt.Errorf("Error trying to encode people as JSON: %s", err.Error()) } err = ioutil.WriteFile(dbFilePath, peopleJSON, 0755) if err != nil { return fmt.Errorf("Error trying to writing people file: %s", err.Error()) } return nil } ``` O que tá faltando agora é abrir o arquivo caso ele exista e colocar todas as pessoas que tem nesse arquivo dentro da variável people da nossa struct. Primeiro é preciso abrir o arquivo com a função `Open` do pacote `os`. Em seguida ler o conteúdo desse arquivo com o método `ReadAll` do pacote `ioutil` e jogá-lo pra uma nova variável. E por fim decodificar esse JSON para uma variável da struct people com o `json.Unmarshal`. Agora só retornar o serviço criado. ```go jsonFile, err := os.Open(dbFilePath) if err != nil { return Service{}, fmt.Errorf("Error trying to open file that contains all people: %s", err.Error()) } jsonFileContentByte, err := ioutil.ReadAll(jsonFile) if err != nil { return Service{}, fmt.Errorf("Error trying to read people file: %s", err.Error()) } var allPeople domain.People json.Unmarshal(jsonFileContentByte, &allPeople) return Service{ dbFilePath: dbFilePath, people: allPeople, }, nil ``` Pronto, agora o construtor do serviço já está implementado e podemos partir pra implementação do método de criação de pessoa. ```go func (s *Service) Create(person domain.Person) error { // verifica se ja a pessoa ja existe, se já existe retorna erro s.people.People = append(s.people.People, person) // salvo o arquivo return nil } ``` Para verificar se a pessoa já existe eu vou criar uma função que vai receber uma pessoa e com base no ID dela eu procuro na nossa slice de pessoas. ```go func (s Service) exists(person domain.Person) bool { for _, currentPerson := range s.people.People { if currentPerson.ID == person.ID { return true } } return false } ``` Pronto, agora eu já posso substituir na função de criação de pessoa a parte que tá com comentário fazendo essa verificação. ```go func (s *Service) Create(person domain.Person) error { if s.exists(person) { return fmt.Errorf("There is already a person with this ID registered") } s.people.People = append(s.people.People, person) // salvar arquivo return nil } ``` Por fim, basta criar uma função pra salvar o arquivo e chamar ela no lugar do comentário. Essa parte de salvar eu vou extrair pra uma função porque vou precisar na hora de implementar os outros métodos do CRUD. ```go func (s *Service) Create(person domain.Person) error { if s.exists(person) { return fmt.Errorf("There is already a person with this ID registered") } s.people.People = append(s.people.People, person) err := s.saveFile() if err != nil { return fmt.Errorf("Error trying to add Person to file: %s", err.Error()) } return nil } func (s Service) saveFile() error { allPeopleJSON, err := json.Marshal(s.people) if err != nil { return fmt.Errorf("Error trying to encode people as JSON: %s", err.Error()) } return ioutil.WriteFile(s.dbFilePath, allPeopleJSON, 0755) } ``` Pronto. A parte do serviço agora tá pronta. Agora falta apenas criar esse serviço na função `main` e utilizar na nossa função que é chamada na rota de criação de pessoa. ```go package main import ( "encoding/json" "fmt" "net/http" "github.com/brenoassp/api-crud-salvando-arquivo/domain" "github.com/brenoassp/api-crud-salvando-arquivo/domain/person" ) func main() { personService, err := person.NewService("person.json") if err != nil { fmt.Printf("Error trying to creating personService: %s\n", err.Error()) } http.HandleFunc("/person/", func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { var person domain.Person err := json.NewDecoder(r.Body).Decode(&person) if err != nil { fmt.Printf("Error trying to decode body. Body should be a json. Error: %s\n", err.Error()) http.Error(w, "Error trying to create person", http.StatusBadRequest) return } if person.ID <= 0 { http.Error(w, "person ID should be a positive integer", http.StatusBadRequest) return } err = personService.Create(person) if err != nil { fmt.Printf("Error trying to create person: %s\n", err.Error()) http.Error(w, "Error trying to create person", http.StatusInternalServerError) return } w.WriteHeader(http.StatusCreated) return } }) http.ListenAndServe(":8080", nil) } ``` ### Rota de atualização de pessoas (PUT /person/) A rota de atualização de pessoas é, de certa forma, similar à rota de criação de pessoas. Ela também receberá como payload as mesmas informações da pessoa, com a única diferença de que ao invés de criar a pessoa, ela utilizará o ID fornecido para buscar a pessoa que precisa ser atualizada no nosso arquivo. Caso não exista nenhuma pessoa com o ID fornecido, é preciso retornar um erro. O primeiro passo é criar o código para tratar o método PUT no arquivo `main.go` que ficará quase igual ao código de criação de pessoa, como pode ser visto abaixo: ```go if r.Method == "PUT" { var person domain.Person err := json.NewDecoder(r.Body).Decode(&person) if err != nil { fmt.Printf("Error trying to decode body. Body should be a json. Error: %s\n", err.Error()) http.Error(w, "Error trying to update person", http.StatusBadRequest) return } if person.ID <= 0 { http.Error(w, "person ID should be a positive integer", http.StatusBadRequest) return } err = personService.Update(person) if err != nil { fmt.Printf("Error trying to update person: %s\n", err.Error()) http.Error(w, "Error trying to update person", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) return } ``` Em seguida, é preciso criar o método responsável pela atualizar da pessoa no serviço. Antes de fazer a atualização é preciso verificar se existe uma pessoa com o ID fornecido para fazer a atualização, caso contrário um erro é gerado. Se o registro foi encontrado, basta atualizar a slice de pessoas e salvar o arquivo. Um ponto importante aqui é a necessidade de utilizar ponteiro na assinatura do método pois estamos alterando a slice, caso contrário iríamos estar alterando a cópia e as futuras chamadas de métodos do serviço utilizaria dados desatualizados com a realidade do nosso arquivo. ```go func (s *Service) Update(person domain.Person) error { var indexToUpdate int = -1 for index, currentPerson := range s.people.People { if currentPerson.ID == person.ID { indexToUpdate = index break } } if indexToUpdate < 0 { return fmt.Errorf("There is no person with the given ID to be updated") } s.people.People[indexToUpdate] = person return s.saveFile() } ``` ### Rota de listagem de pessoas (GET /person/ e GET /person/{id}) O primeiro passo a fazer na rota de listagem de pessoas é a distinção entre a rota de listagem de uma única pessoa e a rota de listagem de todas as pessoas do nosso arquivo. Para isso, vamos utilizar o método `TrimPrefix` passando o que veio no PATH da URL e o prefixo que queremos excluir `/person/`, com isso teremos dois possíveis resultados: 1 - a string vazia `""` se não tiver nada após o prefixo. 2 - uma string com o conteúdo contido após a string `/person/`. No primeiro caso significa que precisamos retornar todas as pessoas. Já no segundo precisamos verificar se o conteúdo é um ID válido e, caso for, buscar a pessoa que possui esse ID no nosso arquivo. Primeiro tentamos converter para inteiro essa string com o método `Atoi` do pacote `strconv`, se der errado então já sabemos que não é um ID válido e podemos responder com um erro. Caso a conversão aconteça com sucesso, fazemos a validação se o ID fornecido é um número inteiro positivo. Por fim, se passar em todas as validações, estamos aptos a buscar a pessoa com o ID fornecido. ```go if r.Method == "GET" { path := strings.TrimPrefix(r.URL.Path, "/person/") if path == "" { // list all people w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(personService.List()) if err != nil { http.Error(w, "Error trying to list people", http.StatusInternalServerError) return } } else { personID, err := strconv.Atoi(path) if err != nil { http.Error(w, "Invalid id given. person ID must be an integer", http.StatusBadRequest) return } person, err := personService.GetByID(personID) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(person) if err != nil { http.Error(w, "Error trying to get person", http.StatusInternalServerError) return } } return } ``` No nosso serviço nós teremos duas funções diferentes, uma para cada um dos cenários acima. No caso de não ser passado nenhum ID, iremos listar todas as pessoas do nosso arquivo. Como o código que fizemos foi feito de tal forma a deixar sempre a slice do serviço atualizada com o nosso arquivo, basta retornar o conteúdo dessa slice quando quisermos saber quais são as pessoas presentes no arquivo. Já no caso de retornar uma pessoa com base no ID, é preciso buscar na slice se existe alguma pessoa com o ID fornecido e retorná-la caso a encontre. Se não for o caso, basta retornar um erro de `Pessoa não encontrada`. ```go func (s Service) List() domain.People { return s.people } func (s Service) GetByID(personID int) (domain.Person, error) { for _, currentPerson := range s.people.People { if currentPerson.ID == personID { return currentPerson, nil } } return domain.Person{}, fmt.Errorf("Person not found") } ``` ### Rota de deleção de pessoas (DELETE /person/{id}) Para a rota de deleção de pessoas iremos exigir que um ID seja passado na URL para identificar qual a pessoa que precisará ser deletada. Com base nesse ID, iremos procurar a pessoa no nosso arquivo para deletá-la caso exista. A validação do ID é feita da mesma forma que foi feita na rota de listagem de pessoas. ```go if r.Method == "DELETE" { path := strings.TrimPrefix(r.URL.Path, "/person/") if path == "" { http.Error(w, "ID is required to delete a person", http.StatusBadRequest) return } else { personID, err := strconv.Atoi(path) if err != nil { http.Error(w, "Invalid id given. person ID must be an integer", http.StatusBadRequest) return } err = personService.DeleteByID(personID) if err != nil { fmt.Printf("Error trying to delete person: %s\n", err.Error()) http.Error(w, "Error trying to delete person", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } return } ``` Será necessário criar o método `DeleteByID` no serviço para deletar a pessoa com o ID passado. Assim como no método de `Update`, é necessário utilizar o ponteiro na assinatura do método para realizar a alteração da slice original. O primeiro passo é pesquisar na slice se existe uma pessoa com o ID fornecido, caso não exista, um erro de pessoa não encontrada deve ser retornado. Caso a pessoa seja encontrada, criamos uma nova slice que não contenha a pessoa que deve ser deletada e a armazenamos na variável people do nosso serviço. Por fim, atualizamos nosso arquivo com o conteúdo novo dessa variável com o método `saveFile()`. ```go func (s *Service) DeleteByID(personID int) error { var indexToRemove int = -1 for index, currentPerson := range s.people.People { if currentPerson.ID == personID { indexToRemove = index break } } if indexToRemove < 0 { return fmt.Errorf("There is no person with the provided ID") } s.people.People = append( s.people.People[:indexToRemove], s.people.People[indexToRemove+1:]..., ) return s.saveFile() } ```
brenoassp
931,724
Red Hat is looking for feedback
Hi, everybody! Red Hat User Experience Design (UXD) is on a mission to deliver quality user...
0
2021-12-21T02:42:58
https://dev.to/wluttrell/red-hat-is-looking-for-feedback-ed6
cloud, productivity, tooling
Hi, everybody! Red Hat User Experience Design (UXD) is on a mission to deliver quality user experiences inspired by and tailored to you — and for that, we need your input. We are looking for application developers with a variety of experience with cloud technologies. Does this sound like you? We’d love to hear from you! Join us in our effort to elevate Red Hat user experiences the open source way — fill out this [5-minute screener survey](https://redhatdg.co1.qualtrics.com/jfe/form/SV_1B8dET7l1Ln7yXI) to get started. After you complete the screener, if you are a good fit for our research, we will send you a link to the follow-up survey. After completing that survey, we will send you a thank-you from our team, a $50 (USD or equivalent) gift card choice from several options. Questions about privacy? Here is [Red Hat’s privacy statement](https://www.redhat.com/en/about/privacy-policy). To learn more about Red Hat UXD, check out our [team website](https://www.redhat.com/en/about/product-design). Have any questions? Reach out on this post, or at wluttrell@redhat.com We look forward to hearing from you!
wluttrell
932,854
How to Indent a Paragraph in Word in Java
Indent a Paragraph in word, left indent, right indent, first line indent, hanging indent
0
2021-12-22T04:00:25
https://dev.to/eiceblue/how-to-indent-a-paragraph-in-word-in-java-549d
free, java, word, indent
--- title: How to Indent a Paragraph in Word in Java published: true description: Indent a Paragraph in word, left indent, right indent, first line indent, hanging indent tags: free, java, word, indent //cover_image: https://direct_url_to_image.jpg --- In this article, we will demonstrate how to indent paragraphs in Word in Java applications using [Spire.Doc for Java](https://www.e-iceblue.com/Introduce/doc-for-java.html). Spire.Doc for Java offers **ParagraphFormat.setLeftIndent(float value)** method to set the paragraph left indents and **ParagraphFormat.setRightIndent(float value)** for right indents. The **ParagraphFormat.setFirstLineIndent(float value)** method can be used to set both hanging and first line indents. Negative value for this property is for the hanging indent and positive value for the first line indent of the paragraph. ##Install Spire.Doc for Java First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded [from this link](https://www.e-iceblue.com/Download/doc-for-java.html). If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file. ```java <repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>4.12.7</version> </dependency> </dependencies> ``` ##Using the code The following are the steps to set paragraph indents in Word: * Create a Document instance. * Load a Word document using **Document.loadFromFile()** method. * Get the desired section by its index using **Document.getSections.get()** method. * Get the desired paragraph by index using **Section.getParagraphs.get()** method. * Get the ParagraphFormat object using **Paragraph.getFormat()** method. * Call the methods to set paragraph indents with the object. * Save the result document using **Document.saveToFile()** method. ```java import com.spire.doc.Document; import com.spire.doc.FileFormat; import com.spire.doc.Section; import com.spire.doc.documents.Paragraph; import com.spire.doc.formatting.ParagraphFormat; public class Test { public static void main(String[] args) throws Exception { //Create a Document instance Document document= new Document(); //Load a Word document document.loadFromFile("Sample.docx"); //Get the first section Section section = document.getSections().get(0); //Get the first paragraph and set left indent, right indent Paragraph para = section.getParagraphs().get(0); ParagraphFormat format = para.getFormat(); format.setLeftIndent(30); format.setRightIndent(50); //Get the second paragraph and set first line indent para = section.getParagraphs().get(1); format = para.getFormat(); format.setFirstLineIndent(30); //Get the third paragraph and set hanging indent para = section.getParagraphs().get(2); format = para.getFormat(); format.setFirstLineIndent(-30); //Save the result document document.saveToFile("SetParagraphIndents.docx", FileFormat.Docx_2013); } } ``` ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hlf93v882d40olf3ogz9.png)
eiceblue
931,787
100 things I learned writing my first technical book.
Writing a technical book is much harder than writing blog posts. Writing a blog post is like...
0
2021-12-21T04:24:09
https://dev.to/redditupvote/a-hundred-things-i-learned-writing-my-first-technical-book-data-oriented-programming-11cp
programming
<li>Writing a technical book is much harder than writing blog posts.</li> <li>Writing a blog post is like running a sprint while writing a book is like running a marathon.</li> <li>Writing my first technical book without a publisher would have been a MISSION: IMPOSSIBLE!</li> <li>Each piece of the book content must be clear and interesting. Each part, each chapter, each section, each paragraph, each sentence.</li> <li>“Clear” is more important that “interesting”. If something is not clear to your reader, it cannot be interesting for for them.</li> <li>A possible way to make things clear is go from concrete to abstract.</li> <li>A possible way to make things interesting is to teach the material as a story with fiction characters and a bit of drama.</li> <li>The “why” is more important than the “what”.</li> <li>The “what” is more important than the “how”.</li> <li>An average writer makes the reader think the author is smart. A good writer makes the reader think the reader is smart.</li> <li>A technical book is written for MQRs (Minimal Qualified Readers).</li> <li>Figuring out what are the qualifications of your MQRs (Minimal Qualified Readers) is important as it allows you to assume what knowledge your readers already have.</li> <li>It’s hard to figure out what are the qualifications of your MQRs (Minimal Qualified Readers).</li> <li>Checking book sales could be addictive.</li> <li>Making a good Table of Contents is crucial as it is the first part of the book potential readers will encounter.</li> <li>Making a good Table of Contents is hard as you need to figure out what you really want to talk about.</li> <li>The Table of Contents might evolve a bit as you write your book.</li> <li>You should resist the temptation to write the first chapter before the Table of Contents is ready.</li> <li>It’s not necessary to write chapters in order. But it’s easier.</li> <li>Never assume that your readers will read the next chapter only because they have enjoyed the previous chapter.</li> <li>You should always convince your readers why what you are teaching is important and relevant for them.</li> <li>Before writing a chapter, you should formulate to yourself what is the main objective of the chapter.</li> <li>If a chapter has two main objectives, it’s a sign that you should split it into two chapters.</li> <li>A chapter should be treated like a piece of software. You should resist the temptation of writing the chapter contents without a plan.</li> <li>A possible way to make things interesting is to use concrete examples.</li> <li>A possible way to make things clear inside a chapter is to start with the easy stuff and increase the level of difficulty as the chapter goes.</li> <li>Do not hesitate to highlight sentences that convey an important message.</li> <li>It’s OK to engage in writing a technical book without mastering every topic you want to cover in your book.</li> <li>Writing technical book involves a descent amount of research even if you consider yourself as an expert in the field.</li> <li>Finding attractive but accurate titles to book chapters is an art.</li> <li>You can learn a lot from a failed attempt to write a book, provided that you put your ago aside.</li> <li>If you try to write a Wikipedia article about the topic of your book before it is mentioned by other sources, it will be rejected.</li> <li>It’s possible to write a technical book while keeping your day job as a programmer, provided that you are willing to wake up early or sleep late.</li> <li>Writing a technical book takes between a year and two.</li> <li>Don’t rush! Enjoy the journey…</li> <li>It makes lot of sense to use a source control software for your manuscript.</li> <li>AsciiDoc rocks!</li> <li>PlantUML rocks!</li> <li>NeoVim rocks!</li> <li>Using a tool - like PlantUML - that generates diagrams from text makes it easy to refactor multiple diagrams at once (e.g rename a label, change a color).</li> <li>People on Reddit could feel hurt by opinions that take them out of their comfort zone.</li> <li>On Reddit, when people feel hurt, they could become violent.</li> <li>Being mentored by an experienced writer is a blessing.</li> <li>If you are lucky enough to be mentored by an experienced writer, ask them to be hard with you. That’s how you are going to improve your book!</li> <li>A good technical reviewer is a representative of your MQRs (Minimal Qualified Readers). They can tell you upfront is something is going to be unclear to your readers.</li> <li>You should make sure your readers will never frown while reading your book.</li> <li>A project manager that pays attention to the details is important.</li> <li>Your publisher is your partner.</li> <li>You could make more dollars per copy by self-publishing but you’d probably sell much less copies.</li> <li>Asking early feedback from external reviewers is a great source of improvement.</li> <li>Releasing an early version of the book (approx. when the first third is ready) allows you to find out if the topic of your book is interesting.</li> <li>Finding a good book title is hard.</li> <li>Finding a good book subtitle is even harder.</li> <li>You need to be very careful not to hurt the sensitivity of any of your readers.</li> <li>Having your book featured on HackerNews home page do not mean selling lots of copies.</li> <li>Twitter is a great medium to share ideas from your book.</li> <li>Writing a book could sometimes take you to flow.</li> <li>My real motivation for writing a book was neither to be famous nor to be rich. It only wanted to accomplish a child’s dream.</li> <li>It’s hard to find your voice.</li> <li>Once you have found the your voice, the writing flows much better.</li> <li>Usually readers stop reading after reading the middle of the book. If you want them to read the second half of your book, you need to find a way to hook them.</li> <li>A possible way to hook your readers is to tell a story.</li> <li>Inspiration is not linear. It’s OK to stop writing for a couple of hours.</li> <li>Motivation is not linear. It’s OK to stop writing for a couple of weeks.</li> <li>Be open to critics - even when they hurt your ego.</li> <li>The more you write, the more you like it.</li> <li>It’s safe to assume that every developer can read JavaScript.</li> <li>It’s a great feeling to mention the work of other authors.</li> <li>You should make sure that each and every code snippet - that appears in your book - runs as expected.</li> <li>Invoking “it’s so obvious I don’t need to explain it” is not an acceptable argument.</li> <li>Writing your teaching materials as a dialogue between an imaginary expert and a imaginary novice is a very useful process in order to figure out what questions your materials might raise in your reader’s mind.</li> <li>Sometimes the questions that an imaginary novice would ask about the stuff you teach would be tough. Don’t ignore them. It’s an opportunity to make your book better.</li> <li>Rewriting a chapter from scratch because you forgot to save your work could be a blessing as writing from scratch might lead to a material of higher quality.</li> <li>Writing in a coffee shop makes me feel like a famous author, but in fact I am much more productive at home.</li> <li>Writing a preface - after the whole manuscript is ready - is really a pleasure!</li> <li>You should think about the way your contents is going to appear on the paper. Use headlines, highlights, call outs and diagrams to make sure it doesn’t look boring.</li> <li>Resist the temptation to impress your readers with “cool stuff” if you think it might confuse them.</li> <li>Working on your book is a good reason to wake up early. Sometimes, before sunrise (even in summer!).</li> <li>Include at least 2 or 3 diagrams in every chapter. It makes the material fun to read and easier to grasp.</li> <li>Draw your diagrams on a sheet of paper before using a drawing software.</li> <li>It’s OK to use colors in diagrams for the online version of the book. But remember that the print version of the book will be not be in color.</li> <li>Mind maps are a great visualization tool. Use them smartly.</li> <li>When a section is more difficult to read that the others, let your readers know about it.</li> <li>When a section is more difficult to read that the others, make it skippable.</li> <li>It’s OK - from times to times - to copy-paste a diagram in order to save from your readers the need to flip back.</li> <li>Asking a friend or a colleague to read your work in progress is not a productive idea. The best feedback come from people you don’t know.</li> <li>Brainstorming with a friend or a colleague about a difficulty you encounter might be a productive idea.</li> <li>Throwing away some (good) ideas is sometimes necessary. Not easy but necessary.</li> <li>When you are blocked in the middle of a chapter, it might be a sign that you need to rethink the chapter.</li> <li>When you are blocked in the middle of a chapter, it might be a sign that you need to rest and come back later.</li> <li>Adapting parts of your book to blog posts could be a good idea. But you need to resist the temptation of copy-pasting verbatim as the blog posts will be without the context of the book.</li> <li>If feels great when someone with lots of followers tweets about the fun they had reading your book.</li> <li>Don’t worry if your English is not perfect. Your manuscript will be proofread later.</li> <li>“Not being an native English speaker” is not an excuse for your lack of clarity.</li> <li>Writing an appendix is much easier than writing a chapter.</li> <li>Using humour in a technical book is possible. Hopefully, it’s well appreciated.</li> <li>You should write the chapter introduction after all the other parts of the chapter are written.</li> <li>Getting positive feedback - even from people who are easily enthusiastic - feels good.</li> <li>Front matter is the last part an author writes.</li> <li>Writing a hundred things you learned from writing a technical book is not as difficult as it may seem.</li> </ol>
redditupvote
931,797
Self-Taught Developer Journal, Day 21: TOP JavaScript Fundamentals Part 1 - Variables
Today I learned.... JavaScript Variables To create a variable in JavaScript use the let...
16,004
2021-12-21T04:57:38
https://dev.to/jennifertieu/self-taught-developer-journal-day-21-javascript-fundamentals-part-1-2668
webdev, beginners, codenewbie, devjournal
Today I learned.... ## JavaScript Variables To create a variable in JavaScript use the **let** keyword. let message = Hello; **var** is an old school way of declaring a variable. This declaration exists in older scripts. Declaring a variable twice will trigger an error. There are two variable naming limitations: 1. *The name must contain only letters, digits, or the symbols $ and _.* 2. *The first character must not be a digit.* camelCase is commonly used naming convention, for example, *newToy*. ### Constants Constants is an unchanging variable meaning the value cannot be reassigned. The keyword to use is **const**. When declaring a variables, its a general rule to use **const** unless you know the value will change. I'm guessing this is to prevent any accidental reassignment of a value. #### Uppercase Constants It is a common practice *to use constants as aliases for difficult-to-remember values that are known prior to execution.* They are named using capital letters and underscores. #### Capitol Constant vs Not A capitol constant name is used when the value is known prior and is hard-coded in. A lower case constant is calculated run time and doesn't change after initial assignment. ### Constant Objects and Arrays *const* does define a constant value, but a read-only reference to a value. For this reason, the value cannot be reassigned or redeclared, but you can change the elements of constant array and change the properties of constant object ## Resources [The Odin Project](https://www.theodinproject.com/paths/foundations/courses/foundations/) https://www.w3schools.com/js/js_const.asp https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const Day 20: https://dev.to/jennifer_tieu/self-taught-developer-journal-day-20-top-landing-page-cont-the-fourth-section-and-footer-57b Please refer to [Starting My Self-Taught Developer Journey]( https://dev.to/jennifer_tieu/starting-my-self-taught-developer-journey-2dga) for context.
jennifertieu
931,801
Neon Nav
A post by SebastianDreyer
0
2021-12-21T05:16:05
https://dev.to/linoleumdevelop/neon-nav-c9f
beginners, css, design, codepen
{% codepen https://codepen.io/linoleum-develop/pen/dyVzpdz %}
linoleumdevelop
931,862
When to use Call Apply Bind methods in JavaScript
Explained when to use Call Apply &amp; Bind methods in JavaScript with practical examples and...
16,016
2021-12-21T07:49:00
https://dev.to/dasaradhanimmala/when-to-use-call-apply-bind-methods-in-javascript-3o8
javascript, programming, beginners
Explained when to use Call Apply & Bind methods in JavaScript with practical examples and explained how to answer in Interview. {%youtube -P0kKSxalLI%}
dasaradhanimmala
931,897
The Complete Python Masterclass: My Journey Towards Learning Python
Python is my favorite programming language since the beginning of my programming journey. However, I...
15,990
2021-12-21T08:37:06
https://fullstackstage.com/python-masterclass
python, programming, codenewbie
Python is my favorite programming language since the beginning of my programming journey. However, I didn't spend enough time learning it properly. My journey took me from HTML, CSS, and JavaScript route. However, I am restarting the Python course called **The Complete Python Masterclass** I bought 3 years ago on Udemy but never finished :) Here's the [link](https://www.udemy.com/course/python-masterclass-course/) to the course, in case you're curious to know. It's the best Python course I've found online, so if you wish you can certainly enroll in it. **The course covers the core Python concepts like -** - Basic Python Concepts(variables, strings, user input, maths, etc) - Control Structures in Python - Functions and Modules in Python - Exception Handling and File Handling in Python - Some More types in Python - Functional Programming in Python - Object Oriented Programming in Python - Regular Expressions in Python **Apart from that, the course also touches -** - Tkinter - Database apps with Python and PostgreSQL - File Compression - Data Analysis - Django - Flask - Web Scraping - Image Processing - Automation etc. Not to forget this is a project based course and to validate your learning you'll build projects like **Calculator, Password Manager, QR Code Generator, Video Downloader, Expense Manager, Facebook Autoposter, etc.** while following the course and you'll also be challenged to build certain advanced projects on your own. Currently, there are 9 projects in the challenge which you've to build on your own. So if you completed the whole course sincerely, you'll build a total of 23 awesome projects enough for you to become a Python ninja. I'll document my whole learning journey in a series of posts and share what I learn here on my blog. So if it sounds interesting follow me to not miss any post in the series. *Happy Coding!*
ashutoshmishra
931,973
More JS Concepts
Truthy and Falsy values A truthy value is a value which is true in any boolean context. We can say...
0
2021-12-21T09:08:03
https://dev.to/chayti/more-js-concepts-44il
javascript, truthy, null, implicit
**Truthy and Falsy values** A truthy value is a value which is true in any boolean context. We can say all values as truthy unless they are falsy. Falsy values are: 1. false 2. 0 (zero) 3. -0 (minus zero) 4. 0n (BigInt zero) 5. '', "", `` (empty string) 6. null 7. undefined 8. NaN Truthy values are: 1. '0' (a string containing a single zero) 2. 'false' (a string containing the text “false”) 3. {} (an empty object) 4. an empty array 5. function(){} (an “empty” function) By writing if condition or passing value to the boolean constructor function, we can check if a value is truthy or falsy. **Null Vs Undefined** 1. Null is an object where undefined is a type. 2. Null is a declared and assigned value where undefined is just a declared variable. `var example; alert(example); // output -> undefined` `var example = null; alert(example); // output -> null` Moreover, we can check if null & undefined are the same or not. `null === undefined // false null == undefined // true` **Double equal (==) vs triple equal (===)** Both do the comparison between variables. But the difference between them is that (==) checks for value equality by doing type coercion. That means, if we are performing (==) operation between ‘6’ (string) & 6 (number), the output is true, which is false for (===) operation, because (===) does not allow type coercion. So, we can say, (===) is superior to (==). (==) is also known as a loose, abstract or type converting equality operator. **Implicit conversion** It is also known as automatic type conversion or implicit coercion. JS converts an unexpected value type to an expected value type for performing operations. We can find implicit conversion to number, to string, implicit boolean conversion to number, null conversion to number. **Implicit conversion to number:** `let result;` `result = '3' - '2'; alert(result); // 1` `result = '3' - 2; alert(result); // 1` ` result = '3' * 2; alert(result); // 6` `result = '3' / 2; alert(result); // 1` When we perform -, /, * operations between a number and string or between two strings, the string is automatically converted to a number before performing the operation. **Implicit conversion to string:** `let result;` `result = '2' + 2; console.log(result) // "22"` `result = '2' + false; console.log(result); // "2false"` When we add a number to a string in JS, the number is automatically converted to a string before performing the operation. **Implicit boolean conversion to number:** `let result;` `result = '3' - true; alert(result); // 2` `result = 3 + false; alert(result); // 3` JS converts false as 0 and true as 1 in type conversion. **Null conversion to number:** `let result;` `result = 3 + null; alert(result); // 3` JS converts null as 0 in type conversion. But for undefined, JS converts it as NaN.
chayti
931,975
Things I’ve learned being a Junior Dev
Picture by Gelgas Airlangga So often we only realize how far we’ve come only when things come to an...
0
2021-12-21T09:52:37
https://dev.to/studio_m_song/things-ive-learned-being-a-junior-dev-22kj
juniordev, beginners, todayilearned, codenewbie
*Picture by [Gelgas Airlangga](https://www.instagram.com/gelgasairlangga/)* So often we only realize how far we’ve come only when things come to an end - it took being shifted to our next career level for me to realize how much had happened in the last years. In two years of being a Junior Developer, I feel safe to say I’ve learned a lot - of course in terms of technical skills, but also as a person. Some things certainly did not come easy to me, I won’t lie - there was definitely some sweat and tears on the journey. But I made it. And I want to share with you lessons I have learned being a Junior Dev - I’d love to hear what your take away was from your time as a Junior (or whatever the ‘bottom of the food chain’ is called at our workplace) - please let us know in the comments! **You don’t have to know it all.** Despite the perceived pressure you might feel to have all the answers, to solve every problem alone and to stay on top of the latest technology trend - nobody expects you to know it all. Simply because it’s not possible - nobody does. There is way too much information out there and our time is far too precious to care about everything at once. Everybody googles all the time and that is perfectly fine. Stay curious and continue to dare asking questions even though you might feel like the answer is obvious (more often than not, people will be relieved you asked cause they didn’t dare themselves). Learn what you are passionate or curious about, but by no means feel pressured to continue studying because you feel like you have too. Because… **…You will keep learning (probably forever).** Let’s face it: you will never be done learning. For some time I was sure I would be more comfortable calling myself a developer if I just understood that one concept or fixed that one bug confidently. No no, my friend, the journey is the reward - You will most certainly get quicker and tackle more complex problems with confidence, but there will always be something you will just see for the first time. So brace yourself for the long run, it’s a marathon - not a sprint. And it’s likely a good idea to stay humble despite your progress. **You will find your people. Or they will find you.** Especially in the beginning I felt like there was no way I would fit into this community. I felt like other developers must surely smell that I was too different from them. Many of the people I met had been in the industry for ages or had been interested in computers and technology from a young age, loved video games and had a bunch of side projects and were overall very intimidating to me. I don’t mean to play on stereotypes at all, I just felt like I couldn’t join in many conversations and was scared I would have to force myself to be something I’m not to fit in. If this sounds anything like you, be sure: you don’t. You are great, just the way you are and you will be accepted as such. Maybe not by anybody, but by your crowd. And they will find you - or vice versa. Just stay true to yourself and be open-minded when meeting new people - this community is very accepting. **Human connections over - well - everything.** For some, their job is just a job and they aren’t out to make friends. That’s perfectly fine, it’s just not me. I found that what (to me) mattered most as a Junior Dev was not the technological progress I made but the people I met along the way. Mentors, colleagues, managers, people from other disciplines, who shaped the way I worked, what I learned and how I grew as a person. Especially in odd times working remotely with what felt like little connection to the outside world. It’s great to be focused and productive - but make sure you take time to have a (virtual) coffee with your fellows, check in and talk about something else than code for a couple of minutes. **Your voice matters.** You might feel from time to time that your idea doesn’t matter as a Junior - that your solution might be less worthy than somebody else's or that your question is redundant. It’s not. Your input matters and is highly valuable. And whoever makes you feel otherwise likely didn’t get the memo yet. Often, less experienced people bring in a new perspective, fresh ideas and dare to challenge the status quo. Sure, if decisions need to be made and someone has to take responsibility, it’s great to have very experienced people on the team to take charge for a team - but that doesn’t make your contribution less valuable. Mentors can learn from Mentees, bosses from their employees - knowledge isn’t a one way street. It’s good to listen and learn, but don’t let anyone convince you to stop asking questions and make your voice heard.
josefine
932,027
Become a chameleon thanks to introversion and shyness
How did it all start? The title of this article might intrigue you, especially if you are...
0
2021-12-21T13:35:33
https://dev.to/one-beyond/become-a-chameleon-thanks-to-introversion-and-shyness-268p
psychology, empathy, interview, selfconfidence
## How did it all start? The title of this article might intrigue you, especially if you are shy or you are not quite good at handling uncomfortable situations. My interest in this subject came from distinct times in my life, the most recent one might sound familiar to you, starting in DCSL GuideSmiths. I consider myself quite reserved, sometimes the vision that people have of me is similar to a wall when they don’t know me or I’ve not given them the opportunity to know me better. When I jumped into DCSL GuideSmiths obviously I should not have provided this appearance. Here's something to consider: how could I have joined DCSL GuideSmiths with this attribute? Well, I became a chameleon. Human relationships are quite difficult and really tough. People who don’t know each other have to interact despite their current sentiment. For instance, sometimes a worker might be pushed by his job position, his role or the feeling of making money or he can be in an undesirable moment either. Usually when you are inside a group of new people you will find a lot of new personalities, most of which you will have interacted with in the past. For example, the person who always tries to help you, the person who needs to talk about themself, the one who always forgets something… Make the exercise about finding distinct types. However, depending on the situation you can be with people who don’t know anybody there or they’ve already met. I’m going to touch on both situations in the next paragraphs but you have to keep in mind one thing: At the beginning of this article I started telling you that I had put up a wall, if you became familiar with it too, **It’s important to break down the wall and make a difference by being accessible when you must be**. That’s the secret, you don’t have to be always open or talking all the time with the new teammate or feeling the obligation about interacting with someone, **you have to time it right**, you must become a chameleon. ## Case 1: people you haven’t met before Let’s step into a situation where nobody knows each other. It usually happens when you are entering a new group or you are talking to someone for a specific purpose. The best way to make an approach **is thinking about the other/others**, trying to figure out what they are thinking or what they are expecting from you. Empathy here is your best ally, you can feel the emotions and adapt yourself to the situation. You could have in front of you a shy person or an extrovert and you should know it. A common case is a job interview, you don’t know the interviewer at all but you have to know as much as you can to earn the opportunity to continue in the selection process. Their mission it’s to get to know your personality, to get to know your skills and you have to adapt yourself to the questions that they will ask, obviously without lying. Sometimes recruiters can seem uninterested in getting to know you as a person you should notice that and not waste energy and false hopes. But in the case you feel the interviewer is doing the best they can, open the door and show yourself. The interviewer's mission is to emit their judgement based on the things they are looking for. For that reason you should be prepared to answer. Anticipate them, try to figure out the answers that they want from you. That’s the main point, **to know their motivation** and consequently change the chameleon’s color to overcome the situation. ## Case 2: people you have already met Now, let’s move forward to case number two where people have already met before. There are a lot of situations here actually, but in the end you should keep one in mind. People always offer their best self. People want to show a facade, especially in job environments; always kind, some people are more open, some are more closed but they are trying to protect themselves from appearing weak. You can detect this, you must stay focused and be safe about yourself. Don’t show anything you would regret, **you are you**. When you find the right teammate there to show the best of yourself to, do it. You will feel better doing it rather than trying to be “the perfect teammate” with all the people. As I said at the beginning of the article, **human interactions are really complex** therefore you need to show your best when it’s the right moment. > I always like to observe people and it’s really easy to find a common personality. This personality can be described as extroverted, talkative, with a lot of friends (is something said by them), always open, agitated... I’ve to say, not all the people with these attributes are equal. Some of these kinds of personality really need to do that. Usually, they don’t have self confidence, they have feelings of which they regret and at the end, they show the opposite characteristics that I’ve told you before, so it’s quite easy to take them as a mirror to not look at. ## Putting everything together To summarize, the key concepts here in both cases are: empathy, self-confidence, adaptability, open-mindedness, emotional intelligence and yourself. And with all the previous concepts, I would like the last one: the layers (or the onion). Imagine you are in any of the previous situations: you would like to show your chameleon form and you could change between these states. That’s perfect, **but you can not switch from one personality to another**, you should take away layers like when an onion is being cut. This will provide you the flexibility which you were looking for, it will give you **the chameleon spirit** to stay calm and focussed in the moments where you probably don’t feel comfortable. For instance, in case 1 you wouldn’t like to switch instantly between states. If you do that the person in front of you wouldn’t know what was going on. Therefore, when the situation advances ahead of you, you will take out the layers from the onion. As we come to the end of this article I would like to mention how much time these tips take to apply to somebody. Obviously, nobody really knows, it’s something that depends on the person. Being able to scan the situation, adapting to them, choosing the right layer is an error-proof thing. Don’t be scared to try different approaches, when you’re in a new situation, try to show something new or something different, **explore inside you** to know which chameleon part fits better in each environment.
albertoturegano
932,066
Programação Orientada a Objetos
Para se entender programação orientada a objetos, primeiramente é necessário entender o que é um...
0
2021-12-21T11:53:31
https://dev.to/pabloferrari013/programacao-orientada-a-objetos-818
programming, oop, braziliandevs
Para se entender programação orientada a objetos, primeiramente é necessário entender o que é um objeto. Um objeto é uma coisa material ou abstrata que pode ser percebida pelos sentidos e descrita por meio de suas características, comportamentos e estado atual. Partindo dessa definição, pode-se afirmar que objetos semelhantes possuem uma mesma classificação, tendo como exemplo de objeto um cachorro que é classificado como animal. Em programação orientada a objetos essa classificação é denominada classe. Ao se criar uma nova classe, é preciso que a mesma responda a três perguntas: - Quais as características do objeto? - Quais ações esse objeto realiza? - Qual o estado desse objeto? Realizando uma analogia com uma caneta obtém-se as seguintes respostas acerca das perguntas a cima: - Uma caneta possui: modelo, cor, ponta, carga, tamanho, etc. - Uma caneta pode: escrever, pintar, rabiscar, tampar, destampar, etc. - Uma caneta está em estado de: 50% de carga, ponta fina, cor azul, destampada, escrevendo, etc. Nessa linha, segundo a teoria de Programação Orientado a Objetos, as perguntas podem ser entendidas como: - As características do objeto são chamados atributos - As ações realizadas pelo objeto são chamadas métodos - A maneira que o objeto está nesse momento é chamado estado Contudo, pode-se concluir que uma classe age como sendo uma forma na criação dos objetos, onde todo novo objeto irá possuir um padrão predefinido na classe. Para criar um novo objeto é preciso instanciar a classe, na qual irá criar um novo objeto a partir do molde da classe. ## Vantagens - Confiabilidade, o isolamento entre as partes gera software seguro. Ao alterar uma parte, nenhuma outra é afetada. - Oportuno, ao dividir tudo em partes, várias delas podem ser desenvolvidas em paralelos. - Manutenível, atualizar um software é mais fácil. Uma pequena modificação vai beneficiar todas as partes que usarem o objeto. - Extensível, o software não é estático, ele deve crescer para ser útil. - Reutilizável, podemos usar objetos de um sistema que criamos em um outro projeto futuro. - Natural, mais fácil de entender. Você se preocupa mais na funcionalidade do que nos detalhes de implementação. ## Classes vs Objetos Podemos entender classes e objetos como sendo conceitos interligados, onde um é depende do outro. A respeito das classes, podemos dizer que elas definem os atributos e métodos comuns dos objetos, que por sua vez, um objeto é uma instancia de uma classe. O exemplo a seguir ilustrará bem esses conceitos: Imagine que tenhamos em mão uma forma de biscoitos. Essa forma não é um biscoito, no entanto, ela pode ser utilizada para gerar biscoitos. O objetivo dessa forma que assume o papel da classe é gerar biscoitos exatamente iguais, a partir dessa forma, é possível a criação de biscoitos, ou seja, objetos. ## Abstração de Objetos Pode ser entendida como a simplificação de conceito, ou seja, abstrair apenas o essencial. Abstração é o ato de observar a realidade e dela abstrair ações e características consideras essenciais para uma determinada coisa. Objetos semelhantes possuem atributos semelhantes, no entanto, estados diferentes. O exemplo a seguir ilustrará bem esse conceito: Suponhamos que em determinado momento um cliente requeira uma aplicação, onde serão vendidos apenas celulares na web. Tendo em mente que toda a lógica do seu sistema irá girar em torno da venda de celulares, podemos abstrair esse contexto, de modo que retiremos apenas o essencial, tais como o tamanho da tela, o fabricante, o modelo, o preço, entre outros atributos. Perceba que não é necessário abstrair dados como quantos transistores o processador do celular possui, pôs essa informação não é relevante para o cliente. Ademais, podemos abstrair métodos desses celulares, como por exemplo, calcular o frete ou a quantidade em estoque. Abstrações não perduram em contextos diferentes, ou seja, a abstração de um e-commerce de celulares difere de um catálogo de celulares. Quando utilizamos programação orientada a objetos, devemos observar as características e os comportamentos de uma determinada entidade, para que possamos absorver essas informações e transforma-las em código. Em alguns livros, a abstração é considerada como o primeiro pilar da Programação Orientada a Objetos. ## Modificadores de Visibilidade Os modificadores de visibilidade indicam o nível de acesso aos componentes internos de uma classe, que são: atributos e métodos. A visibilidade irá informar qual o nível de acesso que se tem sobre eles. O exemplo a seguir ilustrará bem esse conceito: Imagine um telefone. Podemos ter telefones públicos(popularmente conhecido como orelhão), telefones privados, e telefones protegidos. O que caracteriza um telefone público? Um telefone público é caracterizado como sendo algo que qualquer um pode usar. O que caracteriza um telefone privado? Um telefone privado é caracterizado como sendo algo que apenas o dono pode usar. E por fim, o que seria um telefone protegido? Imagine o telefone fixo da sua residência, apenas os membros da sua família poderão usar o telefone. Definição de público, privado e protegido, segundo a Programação Orientada a Objetos: - **Público:** todo atributo ou método definido como público ira definir que a classe atual e todas as outras classes possam ter acesso a elas. - **Privado:** Apenas a classe atual terá acesso aos atributos e métodos. - **Protegido:** Da acesso aos seus atributos e métodos a sua classe e todas as suas sub-classes. ## Pilares da Programação Orientada a Objetos Para se entender os pilares da Programação Orientada a objetos, primeiramente é preciso entender o que é um pilar. Pilar é algo que dá sustentação a determinada coisa. Na Programação Orientada a Objetos existem três pilares: ### Encapsulamento Encapsular é o ato de ocultar partes da implementação, permitindo construir partes invisíveis ao mundo exterior. Um software encapsulado possui um mesmo padrão. A capsula age como uma proteção de dois lados, onde ela protege o código do usuário, e o usuário do código. O usuário não deve ter acesso ao funcionamento de uma classe, mas sim de sua capsula, que por sua vez, uma classe não dever ter acesso ao usuário. Exemplificando a teoria: Observe uma pilha qualquer. Perceba que a pilha é uma capsula. No interior dessa pilha, estão contidas substâncias químicas que são prejudiciais a saúde. Graças a sua capsula não temos acesso a essas substâncias, mas sim, a energia por ela transmitida. Ademais, não poderíamos ter acesso as substâncias presentes em nessa pilha, devido elas serem prejudiciais, e a possibilidade de nós corrompermos seu funcionamento. #### Relacionamento entre classes O relacionamento entre classes como próprio nome propriamente diz, consiste em relacionar uma classe com outra. Exemplo de relacionamento: Suponhamos que tenhamos uma classe caneta. Agora imagine que tenhamos várias canetas resultantes dessa classe caneta, ou seja, vários objetos que foram criados a partir dessa classe. Esse montante de objetos criados pode formar outra classe, onde tenham atributos como: quantidade, cor e preço; E os métodos: vender, comprar e pegarQuantidadeNoEstoque. Perceba que no exemplo acima, uma nova classe foi criada a partir dos objetos gerados por uma outra classe, isso é relacionamento entre classes. Podemos ter os seguintes relacionamentos: - **Relacionamento de Agregação:** É um tipo especial de associação onde tenta-se demonstrar que as informações de um objeto (chamado objeto-todo) precisam ser complementados pelas informações contidas em um ou mais objetos de outra classe (chamados objetos-parte); conhecemos como todo/parte. - **Relacionamento de Associação:** é o relacionamento entre duas classes independentes que em determinado momento se relacionam, ou seja, as classes se relacionam porém não depende umas das outras para existir. - **Relacionamento de Composição:** é o relacionamento onde há dependência entre as classes, onde se uma classe progenitora deixar de existir, o filho também deixara de existir. - **Relacionamento de Generalização:** é o relacionamento onde classes compartilham estados e comportamentos, ou seja, métodos e atributos. Define uma hierarquia de abstrações em que uma subclasse herda classes de uma ou mais classes. #### Vantagens do Encapsulamento - Torna mudanças invisíveis. - Facilita a reutilização de código. - Reduz efeitos colaterais. #### Interface no Encapsulamento No que diz respeito a visibilidade, pode-se afirmar que ela possui uma ligação com o encapsulamento, onde para que o encapsulamento funcione de maneira eficaz e correta, é preciso que aja um canal de comunicação. Esse canal de comunicação no encapsulamento é chamado interface. Sendo assim, um bom objeto encapsulado possui uma interface bem definida. Em outras palavras, interface, é uma lista de serviços fornecidos por um componente. É o contato com o mundo exterior, que permite o que pode ser feito com um objeto dessa classe. Nessa linha, segundo a teoria de encapsulamento, na Programação Orientado a Objetos e o exemplo citado no tópico de encapsulamento, seus conceitos podem ser entendidos como: A pilha sendo a capsula e os polos da pilha sendo a interface Estão presentes na composição de uma interface: - **Métodos abstratos ou sobrescritos:** Qualquer classe que herda um método de uma superclasse tem a oportunidade de sobrescrever o método. O benefício de sobrepor é a capacidade de definir um comportamento que é específico para um tipo de subclasse particular. - **Método construtor:** Tem a função de preparar o objeto para o usuário usar depois, ou seja são métodos especiais chamados pelo sistema no momento da criação de um objeto. - **Métodos Get e Set:** Responsáveis pelo gerenciamento sobre o acesso aos atributos. Esse método determina quando será alterado um atributo e o acesso ao mesmo. - **Métodos de Usuário:** Dentro da classe, declaramos o que cada objeto faz e como é feito. Irei usar como exemplo a classe Conta, onde simulamos uma conta de banco. Os métodos de usuário definem como um depósito ou um saque serão feitos. As funções que realizam isso, são chamadas de Métodos de Usuário. Quando encapsulamos um objeto, em seu princípio, é de suma importância que aderimos a um conceito muito importante: torne todos os atributos privados, para que haja uma proteção da parte interna do objeto, fazendo com que, meios externos não possam interagir com seus atributos. Para se utilizar a interface, é preciso que a mesma esteja implementada na classe. Para implementar, baste que na criação da classe, após seu nome, adicione a palavra implements e o nome da interface. Caso em sua interface estejam declarados métodos estáticos, é obrigatório que sobrescreva-os na classe. ### Herança A herança permite basear uma nova classe na definição de uma outra classe previamente existente, podendo basear-se tanto nas características quanto nos comportamentos. Existem definições para essa situação: - A classe que se baseia em uma outra classe é conhecida como classe filha, ou subclasse. - A classe que se é baseada é conhecida como classe mãe, superclasse, ou progenitora. Exemplificando a teoria: Utilizando novamente a analogia da caneta, imagine que se tenha uma classe de criação de canetas. Em determinado momento, se faz necessário a criação de uma nova caneta com características e ações semelhantes a primeira, no entanto, com algumas melhorias. É nesse contexto que a herança se encaixa. Basta que a classe de criação da caneta melhorada herde os atributos e métodos da caneta simples e após isso defina novos atributos e métodos conforme sua necessidade. Agora imagine que em uma escola qualquer tenham alunos, professores e funcionários, e é preciso criar uma classe para cada um. Eles irão possuir as seguintes características e comportamentos: - Aluno: - Características: - nome - idade - sexo - matrícula - sexo - Comportamentos: - fazer aniversário - cancelar matrícula - Professor: - Características: - nome - idade - sexo - especialidade - salário - Comportamentos: - fazer aniversário - receber aumento - Funcionário - Características - nome - idade - sexo - setor - trabalhando - Comportamentos - fazer aniversário - mudar de emprego Perceba que algumas características e comportamentos se repetem entre eles, então basta que se crie uma quarta classe chamada pessoa, que irá possuir todas as características e comportamentos comuns entre eles. A partir daqui, as classes aluno, professor e funcionário irão herdar as características e comportamento da classe pessoa. #### Navegação Hierárquica A navegação hierárquica consiste na representação das hierarquias das classes, onde uma classe independente que não seja herdeira é herdada por outras classes, que por sua vez, podem ser herdadas por outras classes. Esse processo se repete conforme a necessidade do projeto, podendo haver inúmeras classes mães e filhas. Quando a navegação é feita de de cima para baixo ela é chamada especificação, quando ela é feita de baixo para cima ela é chamada de generalização. Essa navegação hierárquica pode ser entendi da seguinte forma: - A base dessa hierarquia será a classe independente que não é herdeira. - Haverão sempre classes filhas, ou seja, classes que herdem de outra classe. - Haverão sempre classes mães, ou seja, classes que são herdadas por outras classes. - Podem haver classes descendentes, que são classes duas hierarquias abaixo de outra classe, sendo assim, neta. - Podem haver classes ancestrais, que são classes duas hierarquias acima de outra classe, sendo assim, avó. #### Tipos de Herança - **Herança de implementação:** herda atributos e métodos de outra classe, no entanto ela não possui seus próprios atributos e métodos. - **Herança para diferença:** herda atributos e métodos de outra classe, além de possuir seus próprios atributos e métodos. ### Polimorfismo A noção de polimorfismo refere-se àquilo que dispõe ou que pode adoptar múltiplas formas. O termo também faz referência a uma propriedade capaz de atravessar numerosos estados. #### Tipos de Polimorfismo - **Sobreposição:** quando um método da classe mãe é sobreposto nas classes filhas, ou seja, substituído ou modificada. Para se obter a sobreposição de um método, é preciso que ele tenha a mesma assinatura(quantidade de atributos e os tipos dos atributos que serão passados no parâmetro do método) e estejam em classes diferentes. Para que a sobreposição seja realizada é preciso que um método abstrato seja criado na classe mãe e o mesmo seja sobreposto nas classes filhas. A sobreposição só pode ocorrer uma vez em cada classe filha. - **Sobrecarga:** consiste em modificar um método da classe mãe através da classe filha, buscando se obter vários resultados diferentes a partir de suas assinaturas(quantidade de atributos e os tipos dos atributos que serão passados no parâmetro do método). A modificação do método deve ocorrer mais de uma vez em uma única classe filha, desde que suas assinaturas estejam diferentes umas das outras. ## Abstrato e Afim - **Classe abstrata:** não pode ser instanciada. Só pode servir como progenitora. - **Método abstrato:** declarado, mas não implementado na progenitora. - **Classe final:** não pode ser herdada por outra classe. - **Método final:** não pode ser sobrescrito por suas subclasses. Obrigatoriamente herdado. --- Obrigado pela leitura ❤️ Linkedin: https://www.linkedin.com/in/pablo-caliari-ferrari-32bb7a1a8/ Github: https://github.com/PabloFerrari013
pabloferrari013
932,081
What technologies should you know to become a Front-End Developer in 2022.
In this article, I will show you everything you need to know to start a career as a Front-end...
0
2022-01-15T13:43:57
https://dev.to/nourdinedev/what-technologies-should-you-know-to-become-a-front-end-developer-in-2022-hci
webdev, beginners, programming, javascript
In this article, I will show you everything you need to know to start a career as a Front-end developers in 2022, from the common tools to the advance technologies you will need to learn if you are considering becoming a Front-end developers. #The fundamentals. There are three technologies that every web developer should know, **HTML**, **CSS** and **JavaScript**, and these technologies are the three building blocks that you'll find in any website. ##HTML. ![HTML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29tnnbrzjz95yynjmzcu.jpg) The **Hyper Text Markup Language**, or **HTML** is the standard markup language for documents designed to be displayed in a web browser, **HTML** is essentially the “skeleton” for your website. **HTML** is how you structure your website. ##CSS. ![CSS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rh1umtpqpvjakc6ocf71.png) **Cascading Style Sheets**, or **CSS** is a style sheet language used for describing the presentation of a document written in a markup language such as **HTML**, **CSS** is responsible for giving **HTML** documents and webpages a face. In other words, it describes how an **HTML** page should look. ##JavaScript. ![JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xtzpcep2nru3mv6vrxgu.jpg) **JavaScript**, often abbreviated **JS**, is a programming language that is one of the core technologies of the World Wide Web, alongside **HTML** and **CSS**. Over **97%** of websites use **JavaScript** on the client side for web page behavior. #Dive into front-end development. ##Git and GitHub. ![Git and GitHub](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kfz3w0nubem1ndc6ya26.png) **[Git](https://git-scm.com)** is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. **[GitHub](https://github.com)** is a provider of internet hosting for software development and version control using Git. It offers the distributed version control and source code management functionality of Git, plus its own features. ##npm ![npm](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h6i1ci8o3yeqqk87iwl6.jpg) **[npm](https://www.npmjs.com)** is a package manager for the JavaScript programming language maintained by npm, Inc. npm is the default package manager for the JavaScript runtime environment Node.js. ##Sass ![Sass](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hop7ytfavbu52466kdfz.png) **[Sass](https://sass-lang.com)** is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets. It lets you write maintainable CSS and provides features like variable, nesting, mixins, extension, functions, loops, conditionals and so on. ##Tailwind CSS ![Tailwind CSS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b5drejxxbo7sxjkmz3gd.png) **[Tailwind CSS](Tailwind CSS)** is a CSS Framework that provides atomic CSS classes to help you style components e.g. flex, pt-4, text-center and rotate-90 that can be composed to build any design, directly in your markup. ##React ![React](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zvrvbyiat76p1idx0j02.jpg) **[React](https://reactjs.org)** is the most popular front-end JavaScript library for building user interfaces. React can also render on the server using Node and power mobile apps using React Native. ##Chakra UI ![Chakra UI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4biol65vigty70z739ha.png) **[Chakra UI](https://chakra-ui.com)** is a simple, modular and accessible component library that gives you the building blocks you need to build your React applications. ##Redux ![Redux](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u4khilxo0q9cw9bwr6nv.png) **[Redux](https://redux.js.org)** is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. ##Next.js ![Next.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ba6eks8ybauab09oxhmj.jpeg) **[Next.js](Next.js)** is an open-source development framework built on top of Node.js enabling React based web applications functionalities such as server-side rendering and generating static websites. ##Typescript ![Typescript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tw3xhib6y8x0qdm7fmof.png) [TypeScript](https://www.typescriptlang.org) is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale. #Conclusion There are more and more technologies out there, and you will use some of them based on your projects needs. Based on my opinion the best skill you should have is the ability to read documentations, because technologies change and gets updated day by day, so as a developer, you never going to stop learning. If you want a more detailed roadmaps check out **[roadmap.sh](https://roadmap.sh)**
nourdinedev
932,096
Minimum Marketable Feature in Agile - What is it?
What is 'Minimum Marketable Feature'? Minimum marketable feature (MMF) is a small feature...
15,006
2021-12-21T12:53:19
https://buildd.co/product/minimum-marketable-feature
agile, beginners, todayilearned
## What is &#39;Minimum Marketable Feature&#39;? Minimum marketable feature (MMF) is a small feature which is delivered fast and gives significant value to the user. The term, MMF, isn&#39;t very widely used. However, the first agile principle and the MMF are in alignment. The first agile principle states that the highest priority of the agile team is to satisfy the user. This is through early and continuous delivery of valuable software to the customer. Both the first agile principle as well as MMF talk about delivering value to the customer. They try to give value that the customer hadn&#39;t had before, even if this is done frequently. The term &#39;marketable&#39; defines this. Now, value can have a lot of definitions based on where you&#39;re looking. It could increase the revenue of the company or reduce customer cost. So, the MMF concept applies to both internal and external products. Products used within an organization as well as ones which are sold outside can make use of MMF. ## Origin As we have mentioned above, the MMF concept isn&#39;t much used. However, it&#39;s been around for a few years now. Mark Denne Dr. JaneCleland-Huang wrote about the concept in 2004. Their 2004 book, Software by Numbers: Low-Risk, High-Return Development, spoke about MMF for the first time. The concept has been in use since. ## MMF vs MVP You may know of the concept of the[Minimum Viable Product](https://buildd.co/product/mvp-minimum-viable-product) (MVP) and wondering if the MVP and MMF differ in any way. Well, they are different in practice. Let&#39;s understand the difference here. ### The MVP Firstly, let&#39;s look at the definition of the MVP as defined by Eric Reiss in the Lean Startup methodology. The Minimum Viable Product is a version of a new product which requires the least effort but allows maximum learning. This learning is in the form of customer feedback, when the MVP is adopted by early customers of the product. The MVP tries to check whether the team is building the right thing in the first place. For this sake, they try to use a minimum amount of time and money when making it. The early adopters then give valuable feedback about their experience with the MVP. This allows the team to determine if it&#39;s worth going ahead and building the complete product. MVPs need not necessarily be a product. Anything which explains to the user what the product would do can also be considered as an MVP. For example, Dropbox only made a video to show their customers what they could expect out of the end product. Only after they saw that there was demand did they put in effort into creating it. ### The MMF Now, we&#39;ve already defined an MMF at the start of this blog. The exact textbook definition, as given in &#39;Software by Numbers&#39;, is &#39;&quot;The Minimum Marketable Feature is the smallest unit of functionality with intrinsic market value.&#39; It is a real feature, which solves the customer&#39;s need in some way. The MMF can be marketed and sold. It&#39;s all about releasing products that have a high value, and doing so fast. Building an initial product with the main features and later making incremental, high value changes is an example of an MMF. ### Minimum Marketable Feature vs Minimum Viable Product So, from the above two you can see that while the MVP focuses on learning, the MMF&#39;s focus is on providing value to the user. The MVP may or may not have an MMF, or it could have more than one MMF built into it. Your use of either concept would depend on your context and need. ## The MMP - Minimum Marketable Product So now you know about the MMF and the MVP. However, there&#39;s yet another term, the MMP, which may lead to some confusion. Let&#39;s understand what the Minimum Marketable Product is. After the MVP, the MMP can be considered as the next practical step in the product building process. The MMP is the very core version of the product which has just the basic features needed by it. In other words, only the &#39;must-have&#39; functionalities are incorporated into the MMP. The &#39;good-to-haves&#39; aren&#39;t added in this stage. Like the MMF, the MMP tries to market a product at a fast pace and with the necessary features. The MMF, focusing on a feature, then becomes a subset of the MMF. ## Example of Minimum Marketable Feature After an initial product with some solid, core features has been released, there may be a progressive addition of new features. One very stark example is the operating systems of cell phones or computers. The smartphone would of course work right out of the box. But, over the course of using it, users would see that there are more updates added regularly. These are features that add value to the product, but aren&#39;t required at the very start. Hence, they can be added incrementally. Originally published here. Also check out: 1. [Incumbency Certificate](https://buildd.co/funding/incumbency-certificate) 2. [4 Ds of Time Management](https://buildd.co/product/four-ds-of-time-management) 3. [Kano Prioritization Model](https://buildd.co/product/kano-prioritization-model) 4. [Pure Competition](https://buildd.co/marketing/pure-competition) 5. [Working Capital Turnover](https://buildd.co/marketing/working-capital-turnover) 6. [RICE Model](https://buildd.co/product/rice-scoring-model)
rebecca
932,099
Top React Native UI Component Libraries
In this article we take a look at the best UI component libraries and explain what makes them so great.
0
2021-12-21T14:38:31
https://flatlogic.com/blog/top-react-native-ui-components-libraries/
--- title: Top React Native UI Component Libraries published: true description: In this article we take a look at the best UI component libraries and explain what makes them so great. tags: //cover_image: https://direct_url_to_image.jpg canonical_url: https://flatlogic.com/blog/top-react-native-ui-components-libraries/ --- React Native was created by Facebook to accelerate and reduce the cost of developing mobile applications. It is clear that React Native is currently the best solution for creating cross-platform mobile applications. Under the hood React Native uses the Javascript bridge to interpret the UI components for rendering and then calls Objective-C or Java API to display the corresponding iOS or Android component. This bridge is an extra layer of abstraction that may cause a more extended and laborious development process. The React Native solution was used in the development of Facebook Ads, Instagram, Pinterest, Skype, Airbnb, Yeti Smart Home, Uber Eats, and many more. The projects speak for themselves. With the development of React Native technology and gaining more and more trust from the community, tools began to appear to facilitate and accelerate development based on the technology – such as ready-made React Native libraries and UI components. In this article, we will share a list of the best free React Native UI components, which designers and developers can use to jumpstart the design & development of their next mobile project. ###What is a React Native UI component? React Native UI Component is a mobile application element that is isolated from other elements and can be reused several times. For example, it can be a button to buy a product or a subscription. ###Why use React Native UI component library? Much like React itself, React Native encourages you to build your UI using isolated components. React Native UI Component libraries and UI toolkits help you save time and build your applications faster using a pre-made set of components. React Native UI Kit is a very useful thing. It’s basically a set of ready-made interface elements (and sometimes APIs) you can use when creating your application. Thus, you can release an MVP project in a matter of weeks, saving time on the development of interface components and concentrating on the business logic itself. Of course, there are a lot fewer UI Kits for React Native than there are for React.js, but all of these existing are made by professionals, each in the same style. ###How to choose a React Native UI component? In order to choose a library or an already written application with ready-made React Native UI components, you can use the following decision-making criteria: - Price - Easy to start - Popularity (stars on GitHub) - Quality and support speed - Performance - Design - Easy to use - Documentation ###Top React Native UI components Let’s move on to our React Native UI components list. While choosing the following tools we have kept in mind things like trustworthiness, price, documentation, and other important factors one uses for evaluating software. ####React Native Elements Web-site: https://react-native-elements.github.io/react-native-elements/ GitHub stars: 18.9k Price: Free License: MIT Demo: https://expo.io/@monte9/react-native-elements-app Type of support: Community support via GitHub issues Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vzvbppcsbspubggcbyh5.png) React Native Elements is a cross-platform React Native UI toolkit that puts together a number of great open-source UI components made by developers. Here’s what the library’s authors state: “The idea with React Native Elements is more about component structure than actual design, meaning less boilerplate in setting up certain elements but full control over their design”. This seems appealing for both new developers and seasoned veterans. The package includes a whole basket of components such as pricing, badge, overlay, divider, and platform-specific search bars. They are easy to use and quite customizable. The props for all the components are defined in one central location, which makes it possible to easily update or modify components. Additionally, it can serve as a platform connecting small teams developing commercial React Native apps with open source contributions. If you’re going to design an application that looks universal across platforms, this is a perfect option. The documentation clearly explains how to customize the available components with simplicity, and comes with a set of beautiful icons. #####Key facts: - All-in-one UI kit - Supports iOS and Android - Supports Expo - Comprehensive documentation - A decent list of small components like avatar, buttons, form elements, icons, typography, sliders - Complex elements like pricing, rating, card, search bar, checkbox, list items ####React Native Starter Kit by Flatlogic Web-site: https://flatlogic.com/templates/react-native GitHub stars: 1k Price: Free, $99.95, $449.95 License: Mozilla Public License 2.0 Demo: https://play.google.com/store/apps/details?id=com.reactnativestarter.app Type of support: Dedicated support via email Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jiqy9mtcfx7kdho910ou.png) React Native Starter is a mobile application template that contains many ready-to-use components and pages, including theme support. The product is actually a mobile application template with lots of built-in components like sidebar, navigation, form elements, etc – all you need to start building your mobile app faster. You won’t spend lots of time building your app from scratch. This starter kit is perfect for eCommerce applications, offering lifetime updates and support. The design itself is clean, modern and eye-catching. Trends like color gradients and simple curves are also there. #####Key features: - Supports iOS and Android; - 16 pre-built components; - Chat application; - Multiple colors schemes; - Selection of UI elements; - Modular architecture; - Easy analytics integration (GA, Firebase, etc); - Sign in/signup screens; - 6 Color Themes; - Simple customization (using themes and plop generator); - Built without Expo. ####NativeBase Web-site: https://nativebase.io/ GitHub stars: 13.9k Price: Free License: Apache License 2.0 Demo: https://expo.io/@geekyants/nativebasekitchensink Type of support: Community support via GitHub issues Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ge5sr5n0md9bwl9fpi2k.png) NativeBase is a collection of essential cross-platform React Native components: a good place to start building your app. The components are built with React Native combined with some JavaScript functionality with customizable properties. NativeBase is fully open-source and has 12,000+ stars on GitHub. When using NativeBase, you can use any native third-party libraries out of the box. The project itself comes with a rich ecosystem around it, from useful starter kits to customizable theme templates. Here’s a nice starter kit: the template acts as a wrapper on most of the native React components (such as buttons, text fields, views, keyboard views, list views, etc), and enriches them by adding extra functionality (e.g. rounded corners, shadows, etc). #####What it offers: - Easy component styling - Wide range of component options - Use any native third-party libraries - Import custom components - Intuitive component structure - 3 preset themes (Platform, Material, and CommonColor) ####Lottie Wrapper for React Native Web-site: https://github.com/react-native-community/lottie-react-native GitHub stars: 13.1k Price: Free License: Apache License 2.0 Demo: – Type of support: Community support via GitHub issues Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/13c4ar545z1mgwpmm5ap.png) Lottie is a mobile library that parses Adobe After Effects animations natively on mobile. It works by exporting animation data in JSON format from an After Effects extension, BodyMovin. This extension is bundled with a JS player to render animations on the web. Lottie libraries and plugins are available for free. You can also use the curated collection of animation files to make your apps attractive and interesting. The animation files are small in size and are in vector format, meaning that you won’t experience any impact on your app performance. At the same time, it can spice up your UI and make it more visually appealing. ####React Native Vector Icons Web-site: https://oblador.github.io/react-native-vector-icons/ GitHub stars: 13.5k Price: Free License: Apache License 2.0 Demo: – Type of support: Community support via GitHub issues Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nqhgjr4i1tjkxfnz8dv2.png) This library is basically a set of customizable icons for React Native with support for NavBar/TabBar/ToolbarAndroid, image source, and full styling. The library provides pre-made bundled icon sets out of the box, and here are full examples of all the icons in the library. The package supports TabBar and Toolbar Android, as well as the image source and multi-style font. It draws on React Native’s animated library combining it with an icon to create an animated component. ####React Native Gifted Chat Web-site: https://github.com/FaridSafi/react-native-gifted-chat GitHub stars: 9.4k Price: Free License: MIT License Demo: – Type of support: Community support via GitHub issues Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uqxi0n8uocrlb2dfgcii.png) React-native-gifted-chat offers fully customizable components, multiline text input, avatars, copying messages to the clipboard, attachment options etc. Written with TypeScript, it includes fully customizable components that help load earlier messages or copy messages to clipboard and more. There’s an InputToolbar too, helping users skip the keyboard. To enhance user experience, it enables Avatar as user’s initials, localized dates, multi-line TextInput, quick reply messages (bot) and system message. There’s support for Redux too. ####React Native Mapview Web-site: https://github.com/react-native-community/react-native-maps GitHub stars: 11.2k Price: Free License: MIT License Demo: – Type of support: Community support via GitHub issues Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4oxxdhb9wcw35x9ok9sd.png) One of the React Native component libraries that offers map components for Android and iOS is React Native Mapview. Here, common features on any map (such as markers and polygons) are specified as children of the Mapview component. There’s a lot you can do to customize the map style. You’ll be able to change map view position, track region/location, and make points of interest clickable on Google Maps. You can enable zooming in to specified markers or coordinates, or even animate them. If you assign an animated region value to the prop, Mapview can utilize the Animated API to control the map’s center and zoom. Unless you specify custom markers, default markers will be rendered. ####React Native UI Kitten Web-site: https://akveo.github.io/react-native-ui-kitten/ GitHub stars: 6.7k Price: Free License: MIT License Demo: https://play.google.com/store/apps/details?id=com.akveo.kittenTricks Type of support: Dedicated support for the paid version Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vxgtji49z0f3d7psaegt.png) Image source: https://akveo.github.io/react-native-ui-kitten/ React Native UI Kitten – a React Native implementation of the Eva Design system. It offers a set of about 20 general-purpose components styled in the same way to take care of visual appearance. There are a lot of standalone components available as well. The library is based on Eva Design System, containing a set of general-purpose UI components styled in a similar way. UI Kitten stores style definitions separately from business logic. UI elements are styled in the same manner. This concept is similar to CSS, where style classes are separate from the code. ####Shoutem Web-site: https://shoutem.github.io/ GitHub stars: 4.5k Price: Free License: MIT License Demo: – Type of support: Community support via GitHub issues Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uhuuupicu6uvlsrpyzzj.png) Shoutem is an app-building platform that works by using extensions or modular building blocks, somewhat like building a website with plugins on WordPress. Extensions include galleries for photos and videos, products, events, restaurant menus, and more. Shoutem offers many mobile back-end services such as analytics, user authentication, layouts, push notifications, and more. Also, there are many well-coded themes for you to use and customize. This open-source UI toolkit helps you design professional-looking solutions. Each component has a predefined style and can be composed with others. These predefined components are elegant but seem a bit more biased towards iOS style guidelines. Along with components, it comes with basic Animation that is suitable for using its own UI toolkit and themes to build amazing React Native applications. Key features: - 20+ UI components - Variety of app themes - Parallax effects - Transition animations - Large extension library ####React Native Paper Web-site: https://reactnativepaper.com/ GitHub stars: 6k Price: Free License: MIT License Demo: – Type of support: Community support via GitHub issues Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0du5vvn6xmeecwlpo31c.png) React Native Paper is a cross-platform UI component library that follows the Material Design guidelines. Global theming support and an optional babel plugin to reduce bundle size are also there. Paper is cross-platform and works on both web and mobile. There are components and interactions to suit almost every use-case scenario. Most details, including animations, accessibility, and UI logic are taken care of. Here are the main features of Paper: it follows material design guidelines, it works on both iOS and Android following platform-specific guidelines and it also has full theming support. ####React Native Material Kit Web-site: http://xinthink.github.io/react-native-material-kit/ GitHub stars: 4.7k Price: Free License: MIT License Demo: – Type of support: Community support via GitHub issues Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/orydauwn42gpw4j49yyh.png) Inside React Native Material Kit there are buttons, cards, range sliders, and text fields. You’ll also see spinners and progress bars to display loading, as well as toggles for switches, radio buttons, and checkboxes. It provides a complete Material Design solution for the UI and is better maintained than other UI kits available for React Native. It works great even on an iOS device by giving an accurate Android UI feel. It does provide an API to develop your own customized components. #####Key facts: - Material Design-based components - Dynamic components that are not available on some frameworks - Advanced API for building custom components ####Nachos UI Kit Web-site: https://avocode.com/nachos-ui GitHub stars: 2k Price: From 15$ per month License: MIT License Demo: – Type of support: Community support via GitHub issues Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/62gzyw2ir1dw9vr8h1dd.png) Nachos UI provides over 30 UI components that are available in plug-n-play mode. It does provide some nice-looking components that can be customized. The product facilitates customizable UI components that work on the web. It also provides Jest Snapshot testing and uses a prettier. The components were coded using Avocode, which is a fully-featured platform for sharing, hands-off, and inspecting Photoshop and Sketch designs. #####Key features: - 30+ pre-coded UI components including typography, radio, spinner, slider, card, etc. - React Native Web support ####Material Kit React Native Web-site: https://www.creative-tim.com/product/material-kit-pro-react- native/ GitHub stars: <1k Price: Free, $149 License: MIT License Demo: https://demos.creative-tim.com/material-kit-pro-react-native/ Type of support: Dedicated support for paid version Documentation: Full documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5cpc7if808hvddmqi4u5.png) Material Kit React Native offers a free native app template with Material Design built with the Galio framework. It’s easy to use, including 100+ handcrafted elements like buttons, cards, navigation, and inputs. All components can take on color variations by making changes to the theme. Additionally, there are five customized plugins and five example pages. #####Features: - Built over Galio.io - 200 handcrafted elements - Five customized plugins - Five example pages ####React Native Material UI Web-site: https://github.com/xotahal/react-native-material-ui GitHub stars: 3.5k Price: Free License: MIT License Demo: https://github.com/xotahal/react-native-material-ui/blob/master/docs/Demo.md Type of support: Community support via GitHub issues Documentation: Limited documentation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3b4a1kzwza9u7sgbijah.png) The React Native Material UI offers about 20 components for React Native. The components include action buttons, avatars, subheaders, drawers, dividers, toolbars, and more. These components are highly customizable and use Material Design in their construct. The components are self-supporting and will integrate (and only integrate) the styles they need to display. They are independent of any global stylesheets. Material-UI is developed for mobile-first application UI design. ##Conclusion These are the best React Native UI Kits on the market we’ve selected for you. The most advanced solutions, such as the React Native Starter Kit or NativeBase, are presented in the first part. In the second part, we have collected projects you can integrate into your existing project as a good addition. All of these tools make your development much faster and more convenient. We recommend you do your own analysis before choosing the best library for your project. This way you will know for sure what suits your project and needs better. If you’d like to integrate a library into your existing React Native project, or if you plan to create a cross-platform app from scratch, be sure to contact us. ###Flatlogic At Flatlogic we have built a development platform that simplifies the creation of web applications – we call it Web App Generator. The tool allows you to create a fully working full-stack CRUD app in minutes, you just need to choose the stack, design, and define the database model with help of an online interface and that is all. Moreover, you can preview generated code, push it to your GitHub repo and get the automatically generated REST API docs. Try it for free! Please see the guide below on how to do the full-stack web app based on React with help of Flatlogic Generator. ####Step №1. Choose your projects name Any good story starts with a title, any good React App starts with a name. So, summon all of your wit and creativity and write your project’s name into the fill-in bar in Flatlogic’s Full Stack Web App Generator. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ms28eim8kpv5calcbmd.png) ####Step №2. Select your React App Stack At this step, you will need to choose the frontend, backend, and database stack of your app. And, to correlate with our illustrative React App, we will choose here React for the frontend, Node.js for the back-end, and MySQL for the database. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jcmsfqlni3q1qws3m45b.png) ####Step №3. Choose your React App Design As we’ve already mentioned, design is quite important. Choose any from a number of colorful, visually pleasing, and, most importantly, extremely convenient designs Flatlogic’s Full Stack Web App Generator presents. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wwp2wv3mmy6aftj06n0t.png) ####Step №4. Create your React App Database Schema You can create a database model with a UI editor. There are options to create custom tables, columns, and relationships between them. So, basically, you can create any type of content. Moreover, you will receive automatically generated REST API docs for your application. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d8k5bah04zbafuhlu5ra.png) ####Step №5. Review and Generate your React App In the final step, just to make sure everything is as you want it to be, you can review all of the previously made decisions and click the “Create Project” button. After a short time to generate, you will have at your fingertips a beautiful and fully functional React Node.js App. Voila! Nice and easy! ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bodxbxmhnlav6wmvpzsh.png) [Try it for free!](https://flatlogic.com/generator) #####You might also like these articles: - [Top 10 Angular Material Admin Dashboard Templates](https://flatlogic.com/blog/top-10-angular-material-admin-dashboard-templates/) - [Top 15 React App Ideas for Web Developers in 2022](https://flatlogic.com/blog/top-15-react-app-ideas-for-web-developer-in-2022/) - [10 Best IDEs for React.JS in 2021](https://flatlogic.com/blog/best-10-ides-for-react-js-for-2021/) - [Bootstrap vs. Material-UI. Which One to Use for the Next Web App?](https://flatlogic.com/blog/bootstrap-vs-material-ui-which-one-to-use-for-the-next-web-app/) - [Top JavaScript Datepicker Plugins and Libraries](https://flatlogic.com/blog/best-javascript-datepicker-libraries/)
anaflatlogic
932,277
I am excited to share that I have received my Hactoberfest 2021 Badge
It was kinda nice experience to take part in hactoberfest this year.
0
2021-12-21T13:49:13
https://dev.to/datalogmindhack/i-am-excited-to-share-that-i-have-received-my-hactoberfest-2021-badge-c8j
hacktoberfest
It was kinda nice experience to take part in hactoberfest this year.
datalogmindhack
932,379
Towards Perfecting Code Organization
Environment and Well-Being Your environment impacts your well-being. If you've ever...
0
2021-12-21T16:28:23
https://dev.to/michaelmangial1/towards-perfecting-code-organization-m8e
javascript, react, webdev, productivity
## Environment and Well-Being Your environment impacts your well-being. If you've ever gathered motivation to clean, organize, and decorate your workspace, opened your laptop with a fresh cup of hot coffee, and then carried on with your work for the day, you'll know that this is a proven fact. Your environment impacts your well-being. Your coding environment is no exception. Just like a physical workspace, if a coding workspace is routinely kept organized and neat, it will have a positive impact on your well-being. So, how can we organize our coding workspaces? Again, just like with a physical workspace, organization is probably the most significant factor. A physical workspace may not look neat and tidy, but if things are organized, and a clear pattern for staying organized, then a sense of being overwhelmed is avoided and a productive environment is maintained. In a codebase, there may be a variety of different patterns of organization. However, the most important thing is to have it organized via a consistent pattern. It's simple math. 1% is better than 0%. **An organized but less-than-ideal workspace is better than an unorganized and definitely-less-than-ideal workspace.** > _If you take away nothing else from this article, at least take away this:_ If you want to improve your developer experience, organize your workspace. It doesn't haven't to be perfect, it just has to be consistent and intelligible. The first step to perfecting code organization is to organize your codebase. Later on, you can fine tune it to be closer to ideal. It's a simple fact. It's much easier to reorganize an already-organized workspace. ## Perfecting Code Organization As for the fine-tuning of a codebase, let's compare and contrast some common approached to code organization (using a React app as our example). ### Grouping Files by Type One common approach in React applications is to group files by their types/groups: ``` /src /components /hooks /pages /functions ``` The benefit of this approach is that it's pretty clear where to look for a `Button` component (let's say) versus where to look for a `Products` page. The difficulty with this approach is that it doesn't allow for an association between various files and a common experience in the application (sometimes called a "domain"). Or, you have nest a folder named after a domain across all the various top-level directories: ``` /src /components /product-listing /hooks /product-listing /pages /product-listing /functions /product-listing ``` Then, it can get confusing as to what is a component that it tightly coupled with a domain versus a component that is generic enough to be shared across any domain (for example). Of course, you could nest `shared` directories to distinguish: ``` /src /components /shared /product-listing /hooks /shared /product-listing /pages /product-listing /functions /shared /product-listing ``` However, as you can catch with the glance of your eye, there is an obvious problem of duplication. ### Grouping Files by Domain What if we reverse the hierarchy? Instead of grouping first by file _type_ and then by _domain_, look what happens when we group by domain and then type: ``` /src /shared /components /hooks /functions /pages /product-listing /components /hooks /functions /pages ``` We still have repetition of directories for the various file types, but the domain concepts are centralized to one part of the code. You can also easily see if a file is scoped to a domain or if it is shared. There is one development off of this that we will want to make, however. The `shared` directory is still a bit ambiguous with this domain-driven organization. There are two main types of shared files: 1. Files that contain project-specific concepts but are used across multiple domains (i.e. `ShoppingCart`, not found in a design system, etc.). 2. Files that contain generic files that could theoretically be consumed in any application (i.e. `Button`, could be found in a design system, etc.). For this reason, we can distinguish between `common` (product-specific) and `shared` (generic) files: ``` /src /shared /components /hooks /functions /pages /common /components /hooks /functions /pages /product-listing /components /hooks /functions /pages ``` ? **Note:** You can use whatever verbiage you prefer to make the distinction. The important thing is to make a distinction. Also, what constitutes `common` versus `shared` can vary based on context. ### Treating Shared Files As External Packages A final suggestion to perfect our code organization is to treat the `shared` directory as an external package. You can achieve this by using [an alias](https://webpack.js.org/configuration/resolve/#resolvealias): ```jsx // some-component.js import { Button } from '@shared/components'; ``` The advantage of this is that 1) you don't have to deal with long relative imports, 2) you can clearly see the distinction between generic and project-specific files as you would if using an external library, and 3) you can find and replace if you do move the files to an external library. Once these files are being treated as a separate package, you may want to group the directory by potential external library names as opposed to file types: ``` /src /shared /design /data-visualization ``` > This is a great way to keep shared, generic files in the project for convenience and experimentation before they become an external library. You can treat this section of the codebase as a "lab" or "staging" for external libraries. ## Conclusion Remember that 1% is better than 0%. Your environment impacts your well-being. Organize your codebase, and then find ways to improve the organization incremental. The big thing is to have consistency in organization and clarity in where to put what and when. What do you do to organize your codebase?
michaelmangial1
932,418
Stylify. Dynamic CSS Generator for fluent and rapid development.
Stylify is a library that generates CSS dynamically based on what you write. Write HTML. Get CSS....
16,075
2021-12-21T18:48:26
https://stylifycss.com/blog/stylify-dynamic-utlity-first-css-generator/
webdev, css, javascript, productivity
[Stylify](https://stylifycss.com) is a library that generates CSS dynamically based on what you write. Write HTML. Get CSS. 🚀 ## Let me tell you a story Recently, I have been working on multiple projects. One project uses Bootstrap, second one Tailwind and some other vanilla CSS with own utility and components classes. Even though those tools are great and approaches not "bad", **learning and remembering the classes, configurations, selectors all over again is just simply anoying and time consuming**. IDE plugins for whispering classes sometimes come to me as pure despair. I asked myself many times, **why there is no framework or a library that uses natural CSS properties and their values as selectors**, that developers already knows. Yes, the selectors will maybe be a bit longer but there would be nothing to study in order to use it. Because I have could not find any, I have created my own. ## From Idea to Project It took me a year of development and I have finally released the first version 🎉. [Stylify](https://stylifycss.com) is a library that comes with a [Native Preset](https://stylifycss.com/docs/stylify/native-preset) that can match **678 (probably all)** CSS properties from `Chrome, Mozilla, Opera, Safari and Edge`. The size is less than **28 kB**. The syntax is simple: `cssProperty:value` and in case you need screens and pseudo classes `screen:pseudoClass:property:value`. In practice, the usage of the Stylify looks like this: ```html <div class="font-size:24px hover:color:red md:font-size:48px"> Hello World! </div> <script src="https://cdn.jsdelivr.net/npm/@stylify/stylify@latest/dist/stylify.native.min.js"></script> ``` Because some values can contain a space and a quote, I have decided to add a special syntax. When writting a selector its value should contain a space, you can use `__`(two underscores) and for a quote `^` (hat). This allows you to write selectors like this: ```html <div class=" border:12px__solid__steelblue font-family:^Arial^,__sans-serif "> Hello World! </div> ``` When compiled and mangled, it generates the following CSS: ```css ._nmed{ border:12px solid steelblue } ._l4hja{ font-family:'Arial', sans-serif } ``` ### Another Features - **[Dynamic selectors](https://stylifycss.com/docs/stylify/compiler#macros)**: Define a macro and use it however you want `width:240px`, `width:10%`, `width:30rem`. - **[Dynamic screens](https://stylifycss.com/docs/stylify/compiler#logical-operands-in-screens)**: You can combine screens using logical operands like `||` and `&&` => `sm&&tolg:font-size:48px xl&&dark:color:rgba(200,200,200,0.5)` and use any value you want `minw123px:font-size:24px`. - **Selectors mangling**: Stylify can convert long selectors `transition:color__0.3s__ease-in-out` to `_abc123`. - **Spliting CSS**: CSS can be generated for each file separately. Thanks to that you can split CSS for example for a page and layout. - **[Components](https://stylifycss.com/docs/stylify/compiler#components)**: Define for example a `button` with dependencies like `background:#000 color:#fff padding:24px` and use it in a whole project. - **[Variables](https://stylifycss.com/docs/stylify/compiler#variables)**: Define variables for repetetative values. They can be injected into code as CSS variables. - **[Plain selectors](https://stylifycss.com/docs/stylify/compiler#plainselectors)**: Allows you to style selectors like `article > h1`. - **[Helpers](https://stylifycss.com/docs/stylify/compiler#helpers)**: Can be used when the CSS is generated for example for recalculating units and etc. ## Seamless Integration Stylify can be integrated easily into frameworks like [Next.js](https://stylifycss.com/docs/integrations/nextjs), [Nuxt.js](https://stylifycss.com/docs/integrations/nuxtjs), [Vite.js](https://stylifycss.com/docs/integrations/vitejs), [Symfony Framework](https://stylifycss.com/docs/integrations/symfony), [Nette Framework](https://stylifycss.com/docs/integrations/nette), [Laravel](https://stylifycss.com/docs/integrations/laravel) and etc. Also it works great along with [Webpack](https://stylifycss.com/docs/integrations/webpack) and [Rollup.js](https://stylifycss.com/docs/integrations/rollupjs). For easier integration there is a [@stylify/nuxt-module](https://stylifycss.com/docs/nuxt-module/installation-and-usage) for Nuxt.js and a [@stylify/bundler](https://stylifycss.com/docs/bundler/installation-and-usage) that can be used with already mentioned Rollup.js and Webpack or in any other tool. When integrating into an existing project, it is possible to generate CSS for each page separately (even for small components) and [slowly rewrite the website](https://stylifycss.com/docs/get-started/migrating-to-stylify) without increasing it's size or breaking anything. ## Let me know what you think! If you like the idea, let me know that by [starring Stylify repo](https://github.com/stylify/packages) ❤️. I will also be happy for any feedback! The [Stylify](https://stylifycss.com) is still a new Library and there is a lot of space for improvement 🙂.
machy8
932,564
Optimize Mongodb aggregates
TL;DR tips for mongodb aggregate optimization
0
2021-12-21T19:53:51
https://dev.to/satansly/optimize-mongodb-aggregates-13g8
mongodb, aggregate, pipeline, optimization
--- title: Optimize Mongodb aggregates published: true description: TL;DR tips for mongodb aggregate optimization tags: mongodb, aggregate, pipeline, optimization --- NoSql queries can quickly become time consuming if queries rely on relating data across collections with large datasets. You may be running into query time outs trying to generate a report on data. In order to minimize the data query has to look through(hence time) do these two steps(if applicable) on every stage ## $project `$project` only fields that will be needed in proceeding stages. ## $match Narrow down data before `$lookup` and `$group` or after `$unwind` using `$match` Yep thats it. If there is anything you do to optimize your aggregate piplines or know of a better way. Teach me!
satansly
932,619
#005 | Tool Talk: Hello, Command Line
Explore the @playwrightweb command line and learn 8 tools that simplify your testing workflow!
15,755
2021-12-22T02:04:19
https://nitya.github.io/learn-playwright/005-command-line/
playwright, tools, beginners, testing
--- title: #005 | Tool Talk: Hello, Command Line published: true date: 2021-12-20 14:56:45 UTC description: Explore the @playwrightweb command line and learn 8 tools that simplify your testing workflow! tags: playwright, tools, beginners, testing series: End to End Testing with 30DaysOfPlaywright canonical_url: https://nitya.github.io/learn-playwright/005-command-line/ cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j7dhzl991a7gb940hc5n.png --- > This post was originally published on the [Learn Playwright](https://bit.ly/learn-playwright?WT.mc_id=javascript-51408-ninarasi) blog. Reference the [original post](https://nitya.github.io/learn-playwright/003-aswa-demo-app/) to get the most updated version of this content. Don't forget to follow the #playwright tag on dev.to for more community-authored articles on Playwright! {% tag playwright %} --- ### 🔖 | Today's Resources * [Command line tools](https://playwright.dev/docs/cli) - Playwright documentation. * [Visual Cheatsheet For Playwright CLI](https://cloud-skills.dev/gallery/Playwright-01-CommandLine.png) - download for reference * [Follow #playwright on dev.to](https://dev.to/t/playwright) - contribute posts! * [Device descriptors](https://github.com/microsoft/playwright/blob/16ae0af0fd2932efc9cc0e12e86a1b209be62da7/packages/playwright-core/src/server/deviceDescriptorsSource.json) - for emulated devices * [Trace Viewer](https://playwright.dev/docs/trace-viewer) - post-mortem analysis of test run * [Codegen](https://playwright.dev/docs/codegen) - generate tests from user actions * [Playwright Test](https://playwright.dev/docs/test-cli) - test runner for modern web apps * [Playwright Inspector](https://playwright.dev/docs/inspector) - debugging a test run --- ### 🗺 | Article Roadmap I'm back after a week away - let's continue the #30DaysOfPlaywright journey with more Tool Talk!! Here's what today's post covers: * 1️⃣ | Follow #playwright on dev.to * 2️⃣ | Today's Objectives * 3️⃣ | A Visual Cheatsheet * 4️⃣ | Playwright CLI: Usage * 5️⃣ | Playwright CLI: Basic Commands * 6️⃣ | Playwright CLI: Try Examples * 7️⃣ | Playwright CLI: Command Options * 8️⃣ | Next Steps --- ### 1️⃣ &nbsp; Follow #playwright on dev.to I've been publishing the [#30DaysofPlaywright](https://dev.to/nitya/series/15755) series on the dev.to platform. And I'm excited to say that I am now also moderating the [#playwright tag](https://dev.to/t/playwright) there. Follow it for new posts from me and the community! {% twitter 1471223653383782400 %} _And I have an ask for you!!_ Are you a beginner learning Playwright? Or an experienced tester with insights into Playwright usage with existing web frameworks or application scenarios? If so, do consider [writing a dev.to post](https://dev.to/new) and tagging it with `playwright`! I'm monitoring that tag and want to read / amplify your posts! --- ### 2️⃣ &nbsp; Today's Objectives In my [last post](https://nitya.github.io/learn-playwright/004-trace-viewer/) I continued my learning journey by exploring [Trace Viewer](https://playwright.dev/docs/trace-viewer) - a Playwright tool for _post-mortem analysis_ of tracing-enabled test runs. Today, I want to step back and look at the full spectrum of [Command Line](https://playwright.dev/docs/cli) tools and options available to us for authoring, debugging, and analyzing, our testing runs. Some of these capabilities can also be configured and used from [the Playwright API](https://playwright.dev/docs/api/class-playwright) - something we'll explore in future posts. For today, I'll focus on three things: * CLI _commands_ - what tools can we launch from command line? * CLI _options_ - how can we customize tool behaviors for our needs? * CLI _examples_ - let's see how these work with practical use cases --- ### 3️⃣ &nbsp; A Visual Cheatsheet You can browse the [Command Line Tools](https://playwright.dev/docs/cli) documentation in depth - but if you're a visual-spatial learner like me, you might benefit from seeing a big picture before diving into the details. So here's my visual cheatsheet to the various tools and options provided by Playwright CLI. I created this from the `--help` screens for Playwright `v1.17.1`. Start exploration at the yellow rectangle, then follow arrows pointing to deep-dives into individual commands. Run highlighted commands (per area) in your terminal for usage updates related to _your_ installed Playwright version. Consider [downloading the hi-res image](https://cloud-skills.dev/gallery/Playwright-01-CommandLine.png) and using it - as a printout or as desktop wallpaper - to give yourself a handy reference to guide our CLI exploration! ![Visual Guide to Playwright Command Line](https://cloud-skills.dev/gallery/Playwright-01-CommandLine.png) --- ### 4️⃣ &nbsp; Playwright CLI: Usage The [Command Line Tools](https://playwright.dev/docs/cli) documentation page has a great reference with examples, but the best way explore the CLI is interactively. Try this: ``` // Check your installed version of Playwright $ npx playwright -V Version 1.17.1 // Get help on Playwright CLI commands available $npx playwright --help Usage: npx playwright [options] [command] ... <truncated for clarity> // Get help on usage + options for specific CLI command // Ex: for `open` command $ npx playwright open --help Usage: npx playwright open [options] [url] open page in browser specified via -b, --browser Options: ... <truncated for clarity> ``` Check out the visual cheatsheet to see the `--help` outputs for all commands to get a sense of the extent of supported options for each. --- ### 5️⃣ &nbsp; Playwright CLI: Basic Commands For convenience, here is a simplified table of the main Playwright CLI commands available now (v1.17.1) with links to relevant documentation pages. | Commands | Description | |:---|:---| | `install` | **installs browsers** needed for this Playwright version | | `install-deps` | **installs system dependencies** for supported browsers | | `open` | **opens the specified page in the default browser** (_cr_ = chromium) | | `cr` = `open` in chromium <br/> `fr` = `open` in firefox <br/> `wk` = `open` in webkit | **opens the specified page in the specified browser** <br/> (same `open` options) | | `screenshot` | opens specified page, then <br/> **captures page screenshot** | | `pdf` | opens specified page, then <br/> **saves page as pdf** | | `codegen` | opens specified page, then <br/> **launches [Test Generator](https://playwright.dev/docs/codegen)**, creating test code (script) from user actions. | | `test` | **launches [Playwright Test runner](https://playwright.dev/docs/test-cli)** using default configuration file (CLI options take priority, if specified) | | `show-trace` | **launches [Trace Viewer](https://playwright.dev/docs/trace-viewer) (PWA)** for interactive analysis of _trace zipfiles_. | | `show-report` | **launches [HTML Reporter](https://playwright.dev/docs/test-reporters#html-reporter) webpage** on local server, for test run analysis. | The final four commands in this list are likely to find the most use - so I'll explore each in a separate post. Ex: check out the [Trace Viewer](https://nitya.github.io/learn-playwright/004-trace-viewer/) post to learn about `show-trace` and it's usage for post-mortem analysis of test runs. --- ### 6️⃣ &nbsp; Playwright CLI: Try Examples Let's do a quick run through of a subset of the [command-line examples](https://playwright.dev/docs/cli#open-pages) and use these to understand the Playwright CLI options with a real world context. In the video below, I walk through the examples using [this script](https://nitya.github.io/learn-playwright/files/005-examples-script.txt) - try it out yourself in your local environment. {% youtube bWYWyUiQykI %} --- ### 7️⃣ &nbsp; Playwright CLI: Command Options For convenience, here's a recap of key options defined for use in the Playwright CLI. Use `--help` with a specific command (or refer to the [visual cheatsheet](https://cloud-skills.dev/gallery/Playwright-01-CommandLine.png)), to learn which options are applicable to each command. | Option | Description | |:--- | :--- | | `--browser <browserType>` | use a specific browser (options are cr=chromium, ff=firefox, wk=webkit) with default=cr | | `--channel <distribution>` | for chromium-based browsers - see [channel options](https://playwright.dev/docs/api/class-testoptions#test-options-channel) for chrome, msedge| | `--device <name>` <br/> `--user-agent <ua-string>` <br/> `--viewport-size <size>`| emulate mobile browser contexts using [supported parameters](https://playwright.dev/docs/emulation) -- see [device descriptors](https://github.com/microsoft/playwright/blob/16ae0af0fd2932efc9cc0e12e86a1b209be62da7/packages/playwright-core/src/server/deviceDescriptorsSource.json) for valid values.| | `--timezone <time-zone>`<br/> `--lang <lang>`<br/> `--geolocation <lat,long>`<br/>| emulate browser context for [these parameters](https://playwright.dev/docs/emulation) - see [Locale/Timezone](https://playwright.dev/docs/emulation#locale--timezone), [Language tags](https://en.wikipedia.org/wiki/Language_localisation#Language_tags_and_codes), [Geolocation](https://playwright.dev/docs/cli#emulate-geolocation-language-and-timezone) values. | | `--color-scheme <dark,light>` | emulate context with [dark or light mode](https://playwright.dev/docs/emulation#color-scheme-and-media) | | `--timeout <timeout>` | set [timeout](https://playwright.dev/docs/test-timeouts) for Playwright test actions to complete, in ms (default "10000")| | `--save-storage <filename>` <br/> `--load-storage <filename>`| preserve state (e.g., cookies, localStorage) for reuse across sessions e.g., [for authentication](https://playwright.dev/docs/cli#preserve-authenticated-state) | | `--ignore-https-errors` | ignore HTTPS errors on network requests | | `--proxy-server <proxy>` | specify URL of proxy server to use | | `--wait-for-selector <selector>` | (**use with `screenshot` and `pdf`**) - wait for selector to take action | | `--wait-for-timeout <timeout>` | (**use with `screenshot` and `pdf`**) - wait for timeout (in ms) to take action | | `--full-page` | (**use with `screenshot`**) - capture full page (entire scrollable area) | | `--output <filename>` | (**use with `codegen`**) save the generated script to this filename | | `--debug` | (**use with `test`**) runs Playwright Test with Inspector for debugging | The `playwright test` command has a much richer [set of options](https://playwright.dev/docs/test-cli#reference) that we will revisit in a separate post about Playwright Test runner. --- ### 8️⃣ &nbsp; Next Steps We explored [Command Line Tools](https://playwright.dev/docs/cli) at a high level, and tried out examples for a subset of CLI commands. But there are four commands that will get a lot more usage so we'll explore these in separate posts coming up next. * `show-trace` - explore [Trace Viewer](https://playwright.dev/docs/trace-viewer) | previously [done]() ✅ * `show-report` - explore [Test Reporters](https://playwright.dev/docs/test-reporters) * `codegen` - explore [Test Generator](https://playwright.dev/docs/codegen) * `test` - explore [Playwright Test](https://playwright.dev/docs/test-cli) * `test --debug` - explore [Playwright Inspector](https://playwright.dev/docs/inspector) + [Debugging Tools](https://playwright.dev/docs/debug)
nitya
932,789
Writing Prometheus exporters - the Lazy Dev way
This article is part of the&nbsp;C# Advent Series. Christmas has a special place in our hearts and this event is also a wonderful way to help build up the C# &hellip; Continue reading &#8220;Writing Prometheus exporters &#8211; the Lazy Dev way&#8221;
0
2021-12-22T00:19:36
https://blog.wiseowls.co.nz/index.php/2021/12/17/writing-prometheus-exporters-the-lazy-dev-way/
csharp, monitoring, webapi, prometheus
--- title: Writing Prometheus exporters - the Lazy Dev way published: true description: This article is part of the&nbsp;C# Advent Series. Christmas has a special place in our hearts and this event is also a wonderful way to help build up the C# &hellip; Continue reading &#8220;Writing Prometheus exporters &#8211; the Lazy Dev way&#8221; tags: csharp, monitoring, webapi, prometheus canonical_url: https://blog.wiseowls.co.nz/index.php/2021/12/17/writing-prometheus-exporters-the-lazy-dev-way/ cover_image: https://blog.wiseowls.co.nz/wp-content/uploads/2021/12/monitoring-stock.jpg --- This article is part of the [C# Advent Series](https://www.csadvent.christmas/). Christmas has a special place in our hearts and this event is also a wonderful way to help build up the C# community. Do check out awesome content from other authors! There’s a couple of things about Christmas in Southern Hemisphere that tends to hit us pretty hard each year: first, the fact that it is summer and it’s scorching hot outside. And second – is a customary closedown of almost all businesses (which probably started as response to the first point). Some businesses, however, keep boxing on. One of our clients is into cryptocurrency mining and they could not care less about staff wanting time off to spend with family. Their only workforce are GPUs, and these devices can work 24/7. However, with temperatures creeping up, efficiency takes a hit. Also, other sad things can happen: ![santa frying GPU laser eyes](https://blog.wiseowls.co.nz/wp-content/uploads/2021/11/t-rex-miner-burnt-GPU-1024x611.jpg)Solution design --------------- Our first suggestion was to use our trusty [ELK+G](https://blog.wiseowls.co.nz/index.php/2019/09/13/monitoring-sql-server-setting-up-elkg/) and poll extra data from [NVIDIA SMI](https://developer.nvidia.com/nvidia-system-management-interface) tool, but we soon figured out that this problem has already been solved for us. Mining software nowadays got extremely sophisticated (and obfuscated) – it now comes with own webserver and [API](https://github.com/trexminer/T-Rex/wiki/API). So, we simplified a bit: ![solution diagram](https://blog.wiseowls.co.nz/wp-content/uploads/2021/11/t-rex-miner-solution-design.drawio-1024x571.png)All we have to do here would be to stand up an exporter and set up a few dashboards. Easy. Hosted Services We essentially need to run two services: poll underlying API and expose metrics in Prometheus-friendly format. We felt [.NET Core Generic host](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.1) infrastructure would fit very well here. It allows us to bootstrap an app, add Hosted Services and leave plumbing to Docker. The program ended up looking like so: ```csharp class Program { private static async Task Main(string[] args) { using IHost host = CreatHostBuilder(args).Build(); await host.RunAsync(); } static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((configuration) => { configuration.AddEnvironmentVariables("TREX") ; // can add more sources such as command line }) .ConfigureServices(c => { c.AddSingleton<MetricCollection>(); // This is where we will keep all metrics state. hence singleton c.AddHostedService<PrometheusExporter>(); // exposes MetricCollection c.AddHostedService<TRexPoller>(); // periodically GETs status and updates MetricCollection }); } ``` Defining services ----------------- The two parts of our applicatgion are `TRexPoller` and `PrometheusExporter`. Writing both is trivial and we won’t spend much time on the code there. Feel free to [check it out](https://github.com/tkhadimullin/trex-exporter) on GitHub. The point to make here is it has never been easier to focus on business logic and leave heavy lifting to respective NuGet packages. Crafting the models ------------------- The most important part of our application is of course telemetry. We grabbed a sample json response from the API and used an online tool to convert that into C# classes: ```csharp // generated code looks like this. A set of POCOs with each property decorated with JsonProperty that maps to api response public partial class Gpu { [JsonProperty("device_id")] public int DeviceId { get; set; } [JsonProperty("hashrate")] public int Hashrate { get; set; } [JsonProperty("hashrate_day")] public int HashrateDay { get; set; } [JsonProperty("hashrate_hour")] public int HashrateHour { get; set; } ... } ``` Now we need to define metrics that [Prometheus.Net](https://github.com/prometheus-net/prometheus-net#quick-start) can later discover and serve up: ```csharp // example taken from https://github.com/prometheus-net/prometheus-net#quick-start private static readonly Counter ProcessedJobCount = Metrics .CreateCounter("myapp_jobs_processed_total", "Number of processed jobs."); ... ProcessJob(); ProcessedJobCount.Inc(); ``` Turning on lazy mode -------------------- This is where we’ve got so inspired by our “low code” solution that we didn’t want to get down to hand-crafting a bunch of class fields to describe every single value the API serves. Luckily, C#9 has a new feature just for us: [Source Code Generators](https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#support-for-code-generators) to the rescue! We’ve [covered the basic setup](https://blog.wiseowls.co.nz/index.php/2021/03/22/calling-wcf-services-from-net-core-clients/) before, so we’ll skip this part here and move on the Christmas magic part. Let Code Generators do the work for us -------------------------------------- Before we hand everything over to robots, we need to set some basic rules to control the process. Custom attributes looked like a sensible way to keep all configuration local with the model POCOs: ```csharp [AddInstrumentation("gpus")] // the first attribute prompts the generator to loop through the properties and search for metrics public partial class Gpu { [JsonProperty("device_id")] public int DeviceId { get; set; } [JsonProperty("hashrate")] /* * the second attribute controls which type the metric will have as well as what labels we want to store with it. * In this example, it's a Gauge with gpu_id, vendor and name being labels for grouping in Prometheus */ [Metric("Gauge", "gpu_id", "vendor", "name")] public int Hashrate { get; set; } [JsonProperty("hashrate_day")] [Metric("Gauge", "gpu_id", "vendor", "name")] public int HashrateDay { get; set; } [JsonProperty("hashrate_hour")] [Metric("Gauge", "gpu_id", "vendor", "name")] public int HashrateHour { get; set; } ``` Finally, the generator itself hooks into `ClassDeclarationSyntax` and looks for well-known attributes: ```csharp public void OnVisitSyntaxNode(SyntaxNode syntaxNode) { if (syntaxNode is ClassDeclarationSyntax cds && cds.AttributeLists .SelectMany(al => al.Attributes) .Any(a => (a.Name as IdentifierNameSyntax)?.Identifier.ValueText == "AddInstrumentation")) { ClassesToProcess.Add(cds); } } ``` Once we’ve got our list, we loop through each property and generate a dictionary of `Collector` objects. ```csharp var text = new StringBuilder(@"public static Dictionary<string, Collector> GetMetrics(string prefix) { var result = new Dictionary<string, Collector> {").AppendLine(); foreach (PropertyDeclarationSyntax p in properties) { var jsonPropertyAttr = p.GetAttr("JsonProperty"); var metricAttr = p.GetAttr("Metric"); if (metricAttr == null) continue; var propName = jsonPropertyAttr.GetFirstParameterValue(); var metricName = metricAttr.GetFirstParameterValue(); // determine metric type if (metricAttr.ArgumentList.Arguments.Count > 1) { var labels = metricAttr.GetTailParameterValues(); // if we have extra labels to process - here's our chance text.AppendLine( $"{{$\"{{prefix}}{attrPrefix}_{propName}\", Metrics.Create{metricName}($\"{{prefix}}{attrPrefix}_{propName}\", \"{propName}\", {commonLabels}, {labels}) }},"); } else { text.AppendLine( $"{{$\"{{prefix}}{attrPrefix}_{propName}\", Metrics.Create{metricName}($\"{{prefix}}{attrPrefix}_{propName}\", \"{propName}\", {commonLabels}) }},"); } } text.AppendLine(@"}; return result; }"); ``` In parallel to defining storage for metrics, we also need to generate code that will update values as soon as we’ve heard back from the API: ```csharp private StringBuilder UpdateMetrics(List<MemberDeclarationSyntax> properties, SyntaxToken classToProcess, string attrPrefix) { var text = new StringBuilder($"public static void UpdateMetrics(string prefix, Dictionary<string, Collector> metrics, {classToProcess} data, string host, string slot, string algo, List<string> extraLabels = null) {{"); text.AppendLine(); text.AppendLine(@"if(extraLabels == null) { extraLabels = new List<string> {host, slot, algo}; } else { extraLabels.Insert(0, algo); extraLabels.Insert(0, slot); extraLabels.Insert(0, host); }"); foreach (PropertyDeclarationSyntax p in properties) { var jsonPropertyAttr = p.GetAttr("JsonProperty"); var metricAttr = p.GetAttr("Metric"); if (metricAttr == null) continue; var propName = jsonPropertyAttr.GetFirstParameterValue(); var metricName = metricAttr.GetFirstParameterValue(); var newValue = $"data.{p.Identifier.ValueText}"; text.Append( $"(metrics[$\"{{prefix}}{attrPrefix}_{propName}\"] as {metricName}).WithLabels(extraLabels.ToArray())"); switch (metricName) { case "Counter": text.AppendLine($".IncTo({newValue});"); break; case "Gauge": text.AppendLine($".Set({newValue});"); break; } } text.AppendLine("}").AppendLine(); return text; } ``` Bringing it all together with MetricCollection ----------------------------------------------- Finally, we can use the generated code to bootstrap metrics on per-model basis and ensure we correctly handle updates: ```csharp internal class MetricCollection { private readonly Dictionary<string, Collector> _metrics; private readonly string _prefix; private readonly string _host; public MetricCollection(IConfiguration configuration) { _prefix = configuration.GetValue<string>("exporterPrefix", "trex"); _metrics = new Dictionary<string, Collector>(); // this is where declaring particl classes and generating extra methods makes for seamless development experience foreach (var (key, value) in TRexResponse.GetMetrics(_prefix)) _metrics.Add(key, value); foreach (var (key, value) in DualStat.GetMetrics(_prefix)) _metrics.Add(key, value); foreach (var (key, value) in Gpu.GetMetrics(_prefix)) _metrics.Add(key, value); foreach (var (key, value) in Shares.GetMetrics(_prefix)) _metrics.Add(key, value); } public void Update(TRexResponse data) { TRexResponse.UpdateMetrics(_prefix, _metrics, data, _host, "main", data.Algorithm); DualStat.UpdateMetrics(_prefix, _metrics, data.DualStat, _host, "dual", data.DualStat.Algorithm); foreach (var dataGpu in data.Gpus) { Gpu.UpdateMetrics(_prefix, _metrics, dataGpu, _host, "main", data.Algorithm, new List<string> { dataGpu.DeviceId.ToString(), dataGpu.Vendor, dataGpu.Name }); Shares.UpdateMetrics(_prefix, _metrics, dataGpu.Shares, _host, "main", data.Algorithm, new List<string> { dataGpu.GpuId.ToString(), dataGpu.Vendor, dataGpu.Name }); } } } ``` Peeking into generated code --------------------------- Just to make sure we’re on the right track, we looked at generated code. It ain’t pretty but it’s honest work: ``` public partial class Shares { public static Dictionary<string, Collector> GetMetrics(string prefix) { var result = new Dictionary<string, Collector> { {$"{prefix}_shares_accepted_count", Metrics.CreateCounter($"{prefix}_shares_accepted_count", "accepted_count", "host", "slot", "algo", "gpu_id", "vendor", "name") }, {$"{prefix}_shares_invalid_count", Metrics.CreateCounter($"{prefix}_shares_invalid_count", "invalid_count", "host", "slot", "algo", "gpu_id", "vendor", "name") }, {$"{prefix}_shares_last_share_diff", Metrics.CreateGauge($"{prefix}_shares_last_share_diff", "last_share_diff", "host", "slot", "algo", "gpu_id", "vendor", "name") }, ... }; return result; } public static void UpdateMetrics(string prefix, Dictionary<string, Collector> metrics, Shares data, string host, string slot, string algo, List<string> extraLabels = null) { if(extraLabels == null) { extraLabels = new List<string> {host, slot, algo}; } else { extraLabels.Insert(0, algo); extraLabels.Insert(0, slot); extraLabels.Insert(0, host); } (metrics[$"{prefix}_shares_accepted_count"] as Counter).WithLabels(extraLabels.ToArray()).IncTo(data.AcceptedCount); (metrics[$"{prefix}_shares_invalid_count"] as Counter).WithLabels(extraLabels.ToArray()).IncTo(data.InvalidCount); (metrics[$"{prefix}_shares_last_share_diff"] as Gauge).WithLabels(extraLabels.ToArray()).Set(data.LastShareDiff); ... } } ``` Conclusion ---------- This example barely scratches the surface of what’s possible with this feature. Source code generators are extremely helpful when we deal with tedious and repetitive development tasks. It also helps reduce maintenance overheads by enabling us to switch to declarative approach. I’m sure we will see more project coming up where this feature will become. If not already, do check out [the source code in GitHub](https://github.com/tkhadimullin/trex-exporter). And as for us, we would like to sign off with warmest greetings of this festive season and best wishes for happiness in the New Year.
timur_kh
932,801
Tutorial Android Studio: Agregar Notificaciones de firebase
Bienvenidos a un nuevo tutorial En esta ocasión les enseñare a agregar notificaciones...
16,002
2021-12-22T01:11:16
https://dev.to/fynio/tutorial-android-studio-agregar-notificaciones-de-firebase-4klb
firebase, android, minitutorial, espanol
#Bienvenidos a un nuevo tutorial En esta ocasión les enseñare a agregar notificaciones utilizando firebase en android studio paso a paso: --- --- --- #firebase Primero necesitamos un proyecto en firebase para eso iremos a su página web llamada firebase console [click aquí](https://console.firebase.google.com/u/0/) y creamos un nuevo proyecto y le asignamos un nombre ![Creando proyecto](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3egfvd2d56w0azdnunfw.jpg) Después agregaremos una app a nuestro proyecto creado tipo android ![Android](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qxoi2817j2sjjg04x9mg.png ) Después de seleccionar la opción Android debemos de agregar el nombre de nuestro proyecto y si desean pueden poner un nombre a tu proyecto. ![Ingresando un nombre](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9w4bcogwys2ltqp02v61.png) Descargamos el archivo google.service.json y lo agregamos en nuestra aplicacion en la carpeta app para eso debemos seleccionar la opcion de ver Project ![googlse service json](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ln4l965zrfh6se6z1os.png) En la misma carpeta App en el archivo build.gradle agregamos dos apply ``` apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' ``` Quedando de la siguiente manera ![Agregando Apply Apply](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1blumjg9spr66qanctte.png) En la sección de dependencias del mismo archivo build_gradle agregamos lo siguiente: ``` implementation platform('com.google.firebase:firebase-bom:29.0.1') implementation 'com.google.firebase:firebase-bom:29.0.1' implementation 'com.google.firebase:firebase-messaging:23.0.0' implementation 'com.google.firebase:firebase-analytics' ``` Quedando de la siguiente manera ![implements](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nfo9l9ywf8r49pl9u2qd.png) Y le damos en sincronizar. --- ---- #MyFirebaseMessagingService Cambiaremos de vista de **Project** a **Android** y creamos una Java Class llamada **MyFirebaseMessagingService** e ingresamos el siguiente código. ``` package com.example.administracionsedecohidalgo; import com.google.firebase.messaging.FirebaseMessagingService; public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "MyFirebaseMsgService"; } ``` Quedando de la siguiente manera: ![MyFirebaseMessagingService](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wqaoti745j7cuvayjnr0.png) --- --- #AndroidManifest.xml En este archivo **AndroidManifest.xml** agregaremos permisos de Internet debajo de donde aparece la etiqueta **package** ``` <uses-permission android:name="android.permission.INTERNET" /> ``` Quedando el código de la siguiente manera: ![8](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yycjrp7c8hs14dzgl8ar.png) En la etiqueta **<application** agregamos 2 etiquetas Meta-data ``` <meta-data android:name="firebase_messaging_auto_init_enabled" android:value="false" /> <meta-data android:name="firebase_analytics_collection_enabled" android:value="false" /> ``` Quedando de la siguiente manera: ![9](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ymq9gpq7lf9g49vid0d0.png) Antes de cerrar la etiqueta **</application>** agregamos el siguiente código el cual manda llamar la clase MyFirebaseMessagingService que creamos anteriormente: ``` <service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> ``` ![10](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/at1xd4gkd7hzmy95rzsw.png) Eso es todo lo que tenemos que agregar en nuestra aplicación de Android studio. Solo nos resta ir a firabase en la sección Cloud Messaging y en la opción **Send your first message** ![11](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p1l1gns9cny2e367nc9r.png) Al darle clic nos mostrará una ventana para redactar la notificación ![12](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8wnbyw3s5src7upo27r0.png) Entonces escribimos un titulo y texto que queramos agregar y le damos en siguiente. Posteriormente selecciona la aplicación que hemos creado en firabase y le damos en siguiente ![13](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9cg2dxd3uibf0eweye4.png) Todos los demás campos de los siguientes pasos los dejaremos como están solo daremos siguiente, siguiente, hasta llegar al ultimo paso ![14](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g6pbl3agqomlxaib55gc.png) Damos clic en revisar ![15](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/487kblequgtrtuo84aau.png) Y en publicar ![16](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x6w77d00i87dzthn96gh.png) #ESO ES TODO!! Nos tiene que llegar una notificación en nuestro celular. ![17](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d233agpexu45ze1quqwg.png) ## Si todo te salió bien regálame un like
fynio
932,818
Self-made animation comedy series for programmers: Learning databases from scratch to crash~~
Just uploaded the first episode on YouTube Self-made animation series for programmers. Hello,...
0
2021-12-22T01:38:29
https://dev.to/ambermoe/self-made-animation-comedy-series-for-programmers-learning-databases-from-scratch-to-crash-41k9
beginners, tutorial, programming, database
Just uploaded the first episode on [YouTube](https://www.youtube.com/watch?v=yzggvHKRMe4) Self-made animation series for programmers. Hello, everyone. My name is Amber Moe and I'm a technical writer, a database lover. This video shows why I quit learning databases. It seems I have a lot of trouble installing a database. Learning databases from scratch to crash~~ Just can't make it. Forget it. Did you ever learn something from scratch to crash? What did you quit learning? And what makes you crash? Tell me by leaving your comments. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d5hqem5ntkooxgw4tog8.jpg)
ambermoe
932,856
Master Frontend by doing Frontendmentor challenges
If you are looking for projects to practice your Front-end skills like CSS, JavaScript, and React,...
0
2021-12-22T05:08:30
https://coderamrin.hashnode.dev/master-frontend-by-doing-frontendmentor-challenges
beginners, tutorial, css, webdev
If you are looking for projects to practice your Front-end skills like CSS, JavaScript, and React, then you are in the right place. In this series, I’m going to build projects from the frontendmentor. ![Frontendmentor image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2hxagko78zrpgk03ri97.png) . ## [Frontendmentor] (https://www.frontendmentor.io/) . Frontendmentor is a place where you can find projects to practice your frontend-related skills like CSS, JavaScript, and React. They got hundreds of free and paid challenges. So, I decided to do the challenges and share them as tutorials with you. I’ll write articles and make videos of the challenges as I complete them. Cause learning together is much more fun than learning alone. If that sounds Interesting you can ### subscribe to my [YouTube channel ](https://www.youtube.com/channel/UCiHUi4wJ6rkPSQ5n4bxKU1A) and follow me here to get the articles and videos as I post them. . {% youtube VIqOujcceIE %} ### Conclusion Thanks for reading. You can also connect with me on twitter at [coderamrin](https://twitter.com/CoderAmrin) Have a good one :D
coderamrin
932,938
Event Driven Approach in Node js real time example Like : Cricket , AC etc.,
can you please say Event Driven Approach in Node js real time example Like : Cricket , AC etc.,
0
2021-12-22T05:56:22
https://dev.to/sindhuja1999/event-driven-approach-in-node-js-real-time-example-like-cricket-ac-etc-h0c
node, javascript, eventdriven
can you please say Event Driven Approach in Node js real time example Like : Cricket , AC etc.,
sindhuja1999
933,016
Code Coverage, Java Debugger API and Full Integration in Building DDJT - Day 3
Yesterday we got the first PR through and now I'm on the second PR. We almost have an open source...
15,971
2021-12-22T12:18:49
https://dev.to/codenameone/code-coverage-java-debugger-api-and-full-integration-in-building-ddjt-day-3-1i20
testing, java, startup, opensource
Yesterday [we got the first PR through](https://dev.to/codenameone/scaffolding-spring-boot-freemarker-and-jdi-building-ddtj-day-2-7od) and now I'm on the second PR. We almost have an [open source project](https://github.com/ddtj/ddtj/). Well, technically we already have the source code and a few lines of code, but it still isn't exactly a "project". Not in the sense of "it needs to do something useful". But it compiles, runs unit tests and even has 80% code coverage. That last one was painful. I'm not a fan of arbitrary metrics to qualify the quality of code. The 80% code coverage is a good example of this. Case in point, this code. Currently, the source code looks like this: ```java MonitoredSession monitoredSession = connectSession.create(System.getProperty("java.home"), "-Dhello=true", HelloWorld.class.getName(), "*"); ``` But originally it looked like: ```java MonitoredSession monitoredSession = connectSession.create(null, null, HelloWorld.class.getName(),null); ``` Changing this increased code coverage noticeably because code down the road I have special case conditions for variables that aren't null. For good test coverage, I would also want to test the null situation, but it doesn't affect test coverage. Now obviously, you don't write tests just to satisfy a code coverage tool... But if we rely on metrics like that as a benchmark of code quality and reliability. We should probably stop. Another problem I have with this approach is the amount of work required to get that last 10-20% of code coverage to pass the 80% requirement. That's insanely hard. If you work on a project with 100% code coverage requirement, you have my condolences. I think an arbitrary percentage of code for coverage is a problematic metric. I like the statement coverage stats better, but they still suffer from similar problems. On the plus side, I love the code coverage report; I feel it gives some sense of where the project stands and helps make sense of it all. In that sense, Sonar Cloud is pretty great. Keen observers of the code will notice I didn't add any coverage to the common code. It has very little business logic at the moment and in fact I removed even that piece of code in the upcoming PR. ## Writing Tests I spent a lot of time writing tests and mocking, which is good preparation for building a tool that will generate mocked unit tests. As a result, I feel the secondary goal of generating tests based on code coverage report; is more interesting than ever before. I can't wait to dogfood the code to see if I can bring up the statistics easily. One thing I find very painful in tests is the error log file. For the life of me, I do not know why Maven tests target shows a stack trace that points at the line in the test instead of the full stack trace by default. IntelliJ/IDEA improved on this, but it's still not ideal. Especially when combing through CI logs. Right now, all of my tests are unit tests because I don't have full integration in place yet. But this will change soon. I'm still not sure what form I will pick for integration tests since the initial version of the application won't have a web front-end. I've yet to test the CLI. It conflicted me a bit when I started writing this code. As I mentioned before, integrating the Java debug API into the Spring Boot backend was a pretty big shift in direction for me. But it makes sense and solves a lot of problems. The main point of contention for me was supporting other languages/platforms. But I hope I'll be able to integrate with the respective platforms native debug APIs as we add them. This will make the debugging process for other platforms similar to the Java debug sessions. I'll try to write the code in a modular way so we can inject support for additional platforms. I'm pretty sure program execution for python, node etc. will allow similar capabilities as JDI on Java SE. So if the code is modular enough, I could just add packages to match every supported platform. At least, that's the plan right now. If that won't work, we can always refactor or just add an agent option for those platforms. Our requirements are relatively simple, we don't need expression evaluation, etc. only the current stack frame data and simple step over results. When I thought about using a debugger session, I thought about setting breakpoints for every method. This is obviously problematic since there are limits on the number of breakpoints we can set. Instead, I'm using method entry callbacks to track the application. Within every method, I use step over to review the elements within. This isn't implemented yet mostly because it's pretty darn hard to test this from unit tests. That's why I paused the work on the debugger session and moved down the stack to the CLI. I want to use the actual product to debug this functionality. ## Integrating CLI through Web Service I created a CLI project and defined the dependencies, but until now I didn't really write any CLI code. The plan is that the CLI will communicate with the backend code via REST. Initially, I thought of using Swagger (Open API) which is pretty great. If you're unfamiliar with it, it essentially generates the documentation and even application code for all the networking you need. Just by inspecting your API, pretty sweet! It generates a lot of boilerplate that's sometimes verbose and less intuitive. It also blocks some code reuse. If I had an extensive project or a public facing API, I might have used it. But for something intended for internal use, it seems like an overkill. So I ended up using Gson, which I used in the past, and the new [Java 11 HttpClient](https://github.com/ddtj/ddtj/pull/2/files#diff-806d340badbe3c5f02113a15b0a9d8b6c4242ce155f36c3a0cc595b106c2f0bfR86) API. The API is pretty nice and pretty easy to work with. ### Over Eager PicoCLI I really like [PicoCLI](https://picocli.info/), I think that if you [look at this source file](https://github.com/ddtj/ddtj/blob/cf316d9f4c0c361686dbee48f68c4e9b2c7f2636/CLI/src/main/java/dev/ddtj/cli/Main.java), you can easily see why. It makes coding a command line app trivial. You get gorgeous CLI APIs with highlighting, completion, smart grouping and so much more. It even has a preprocessor, which makes it easy to compile it with GraalVM. Unfortunately, I ran into a use case that PicoCLI was probably a bit too "clever". My initial design was to provide a command like this: ``` java -jar ddtj.jar -run [-javahome:<path-to-java-home] [-whitelist:regex-whitelist classes] [-arg=<app argument>...] mainClass ``` Notice that `-arg` would essentially allow us to take all the arguments we want to pass to the target JVM. E.g. if we want to pass an environment variable to the JVM we can do something like: ``` -arg "-Denv=x" ``` The problem is that PicoCLI thinks that -D is another argument and tries to parse it. I spent a lot of time trying to find a way to do this. I don't think it's possible with PicoCLI, but I might have missed something. The problem is, I don't want to replicate all the JVM arguments with PicoCLI arguments, e.g. classpath parameters, etc. Unfortunately, this is the only option I can see right now. I'll have to re-think this approach after I get the MVP off the ground, but for now I changed the CLI specification to this: ``` java -jar ddtj.jar -run mainClass [-javahome:<path-to-java-home] [-whitelist:regex-whitelist classes] [-classpath...] [-jar...] ``` In fact, here's what the help command passed to PicoCLI generated for that code: ![Command Line Help from PicoCLI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t8vgvdkkdzcgyvfj33uo.png) ### Completely Redid the Common When I implemented the common project, I did so based on guesses. Which were totally wrong. I had to move every source file from my original implementation into the backend project. Then I had to reimplement classes for the common code. The reason for this is the web interface. It made me realize I stuck the data model in common instead of the data that needs to move to the client (which is far smaller). Implementing the web interface was trivial. I just went over the commands I listed in the documentation and added a web service method for each command. Then added a DTO (Data Transfer Object) for each one. The DTOs are all in the common project, which is how it should be. Initially, I thought I'd just write all the logic within the web service rest class, but I eventually separated the logic to a generic service class. I'd like to add a web UI in the future so it makes sense to have common logic in a [service class](https://github.com/ddtj/ddtj/blob/cf316d9f4c0c361686dbee48f68c4e9b2c7f2636/Backend/src/main/java/dev/ddtj/backend/service/MainService.java). ### Handling State State is a tough call for this type of application. I don't want a database and everything is "in memory". But even then, do we use session management? What if we have multiple apps running on the backend? So currently I just punted this problem from the MVP. If you run more than one app, it will fail. I just store data in one local field on the session object. I don't need static variables here since spring defaults to singletons for session beans and there's no clustering involved. After the MVP, we should look into running multiple applications. This might require changing the CLI to determine the app we're working on right now. I think we'll still keep state in a field, but we should have a way to flush the state to reduce RAM usage. ## Snyk Integration Yesterday I had some issues with Snyk. If you're unfamiliar with it, it's a tool that seamlessly scans your code for vulnerabilities and helps you fix them. Pretty cool. The integration was super easy to do, and I was pretty pleased with it. Then I tried to add a badge to the project... Apparently, Snyk badges don't work well with a mono-repo. They expect the pom file to be at the top level of the project. So I gave up on the badge for that. The scanning worked, so it's weird to me that the badge would fail. I'll try to monitor that one and see if there's a solution for that. I discussed this with their support, which was reasonably responsive but didn't seem to have a decent answer for that. It's a shame, I like the idea of a badge that authenticates the security status of the project. ## Tomorrow This has been a busy day, but it felt unproductive in the end because all the time I wasted on the CLI and trying to get things like the Snyk badge working. This is something to be weary of. Always look for the shortcut when doing an MVP and if you can't get something working, just cut it out for now. We can always get back to that later. Tomorrow I hope to get the current PR up to function coverage standards and start wiring in the command line API so I can start debugging the debugger process in real-world conditions. There are still some commented out code fragments and some smells I need to improve.
codenameone
933,056
Reinforcement learning with Q-learning
Like other machine learning algorithms, a reinforcement learning model needs to be trained before it...
0
2021-12-22T09:27:21
https://dev.to/rishalhurbans/reinforcement-learning-with-q-learning-59dn
watercooler
Like other machine learning algorithms, a reinforcement learning model needs to be trained before it can be used. The training phase centers on exploring the environment and receiving feedback, given specific actions performed in specific circumstances or states. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8azgawh4wkyi6u5or7l1.png) The life cycle of training a reinforcement learning model is based on the Markov Decision Process, which provides a mathematical framework for modeling decisions. Let's use an autonomous car parking as an example. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2c500tg6sto9cxht4b1d.png) A simulator needs to model the environment, the actions of the agent, and the rewards received after each action. A reinforcement learning algorithm will use the simulator to learn through practice by taking actions in the simulated environment and measuring the outcome. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/inc2n55bmruld6515zn7.png) Initialize the environment: This function involves resetting the environment, including the agent, to the starting state. Get the current state of the environment: This function provides the current state of the environment, which will change after each action is performed. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wofdu6woegl2a4vjc7bm.png) Apply an action to the environment: This function involves having the agent apply an action to the environment - the environment is affected by the action, which may result in a reward. Calculate the reward of the action: This function is related to applying the action to the environment. The reward for the action and effect on the environment need to be calculated. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3z5tzmpbs89d3goco0z3.png) Determine whether the goal is achieved: This function determines whether the agent has achieved the goal. In an environment in which the goal cannot be achieved, the simulator needs to signal completion when it deems necessary. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zokoy2tocbqck35lcpw0.png) After many cycles of simulation, and the agent taking actions, the Q-table will be trained with sequences of actions that are favourable to get to the destination. Note: Without varying environment data, the model will be overfitted and perform poorly in real-world situations. Learn more about reinforcement learning in Grokking AI Algorithms with Manning Publications: [http://bit.ly/gaia-book](http://bit.ly/gaia-book), consider following me - [@RishalHurbans](https://twitter.com/RishalHurbans), or join my mailing list for infrequent knowledge drops: [https://rhurbans.com/subscribe](https://rhurbans.com/subscribe).
rishalhurbans
933,185
Free Code Camp: Build a Tribute Page
A post by HARUN PEHLİVAN
0
2021-12-22T11:35:28
https://dev.to/harunpehlivan/free-code-camp-build-a-tribute-page-4aie
codepen
{% codepen https://codepen.io/harunpehlivan/pen/eXZJeM %}
harunpehlivan
933,193
We opened a lightweight Web IDE UI framework!
A lightweight Web IDE UI Framework Introduction The Molecule is a lightweight Web IDE...
0
2021-12-22T11:44:34
https://dev.to/wewoor/we-opened-a-lightweight-web-ide-ui-framework-2ank
javascript, react, webdev, typescript
![Molecule Logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u0bx0o181g1ji25cn0q4.png) > A lightweight Web IDE UI Framework ## Introduction The [Molecule](https://github.com/DTStack/molecule) is a lightweight Web IDE UI framework built with React.js and inspired by VS Code. We designed the Extension APIs similar to the VS Code to help developers develop the Web IDE System more efficiently. Molecule built-in the Monaco Editor, we provided extract APIs of the Keybinding and QuickAccess. Due to the Extension mechanism, the developers can decouple the business code from the IDE UI, but to focus on the business iteration, part of IDE UI almost move to the isolated iteration. It is a better way to make the product can keep moving. ![Workbench](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pwrucf61gv2bsxj5kd99.png) ## Motivation In [DTSTack](https://www.dtstack.com/dtinsight/), we have many Web applications, like Batch/Stream Task Development, Analysis, Data Source Management, Algorithm Development. The developers need to code, debugging in our platform, so the IDE is a frequent scene in our product. ![Early Web IDE Product Version](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jlhpjybgbxrrt7a23wk4.png) *Early Web IDE Product Version* This screenshot shows the early version of the IDE, and the product is simple yet. The IDE UI is based on React.js, Ant Design, and Codemirror so on technologies. Besides, due to the IDE Workbench applied in our multiple products, we have to abstract a simple IDE UI React component to share with the other products. ![Current Web IDE Product Version](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1hpg39c60jex0llvb79.png) *Current Web IDE Product Version* With the business growing and product iteration, the features in Workbench are more and more complex. As all you know, the product of interactive and visual upgrade every year, but the early Front end structure is so fat, extensible badly, can't support new incoming features and designs. UI designers are always confused why the cost of upgrading the frontend is so high. In the past two years, We researched the [Cloud9 IDE](https://github.com/c9), [VS Code](https://github.com/microsoft/vscode), [Eclipse Theia](https://github.com/eclipse-theia/theia) solutions. These products have good UI abstraction, extensibility, and full features for IDE. But, so many features are useless for our product, and it's too hard to customize for our team. Another reason is our React.js code is also hard to integrate with these solutions. So, We want a solution, which has good UI abstraction, easy-to-customize UI, Color Theme, friendly for React.js applications. Finally, VS Code inspired us. The team tried to make the [Molecule](https://github.com/DTStack/molecule). ## Core Features The Molecule wrote in Typescript and applied the React.js, Monaco Editor so on technologies, and the main features are: - Built-in VS Code Workbench UI - Compatible with the VS Code ColorTheme - Customize the Workbench via React Component easily - Built-in Monaco-Editor Command Palette, Keybinding features - Support the i18n, built-in zhCN, and English - Built-in Settings, support to edit and extend via the Extension - Built-in basic Explorer, Search components and support extending via the Extension - Typescript Ready ![Workbench Parts](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6mj5uvr442q858e57u3x.png) This picture is the default IDE Workbench of Molecule, basically, like Workbench, ColorTheme, QuickAccess, Keybinding, i18n, Settings, and so on features are easy to extend via the Extension API. ## What are the differences of Molecule with other Web IDE Solutions? - React.js application friendly - Built on React.js component and More powerful UI custom ability - Compatible the VS Code so many ColorTheme extensions - Only focusing on UI, it's easy to understand to Front-end developers. - Support to extend like File System, Version Control, LSP, DAP, Terminal, and so on features if you want ## How to use it? Read the [QuickStart](https://dtstack.github.io/molecule/docs/quick-start), please. ## TODO Molecule only released a Beta version currently. The APIs are not stable enough. Some concepts referred to from VS Code are over-designed. We are going to make the Extension API is more powerful. Keep optimizing the details of UI and ColorTheme, developing a more rich layout system. ## Finally Hoping our experience is helpful to you. - GitHub: https://github.com/DTStack/molecule - Website: https://dtstack.github.io/molecule/en/ - Preview: https://dtstack.github.io/molecule-examples/#/
wewoor
933,261
https://docs.google.com/document/d/1nqSFwWGe8E8C1nvDxU2Z9_o8MN_Ubw1ObYG7iWLc0zg/edit?usp=sharing
A post by Ananna14
0
2021-12-22T12:44:02
https://dev.to/ananna14/httpsdocsgooglecomdocumentd1nqsfwwge8e8c1nvdxu2z9o8mnubw1obyg7iwlc0zgedituspsharing-3f3b
ananna14
933,524
Cleanup Azure DevOps pipelines retained by releases
One situation I've come across a while ago was not being able to remove some deprecated pipelines due...
0
2021-12-22T15:55:38
https://www.nunobarreiro.com/posts/cleanup-devops-pipelines-retained
azure, devops
One situation I've come across a while ago was not being able to remove some deprecated pipelines due to the following error: ![One or more builds associated with the requested pipeline(s) are retained by a release. The pipeline(s) and builds will not be deleted.](https://nunobarreiro.com/images/devops-pipeline-retention-lease-error-onremoval.png) Going through the [builds REST documentation](https://docs.microsoft.com/en-us/rest/api/azure/devops/build/builds/get?view=azure-devops-rest-6.0), I was able to check that Builds do have a property "retainedByRelease". Not only that, but digging further and looking at the [leases REST documentation](https://docs.microsoft.com/en-us/rest/api/azure/devops/build/leases?view=azure-devops-rest-6.1) I also noticed a boolean property named "protectPipeline" that, according to its very relevant description states that: > If set, this lease will also prevent the pipeline from being deleted while the lease is still valid. Now I was finally getting somewhere, and I've attempted to patch the lease and set that property to false. Surprised, or maybe not, when you set that property to false for all the leases associated with the build, then the build own property "retainedByRelease" also turns out to false, allowing you to finally delete it permanently! To automate things, since I had multiple builds with the same state, I've created the below python script, that you are invited to read and use. At the time I was using [Fiddler](https://www.telerik.com/fiddler) to check the requests, but you can remove the "fiddler_proxies" related stuff from there if you don't need that. Please follow the [instructions](https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&tabs=preview-page#create-a-pat) on how to create a Personal Access Token and encode it using a base64 encoding tool like [this](https://www.base64encode.org) one. Make sure to fill in the "project_url", the "encoded_pat" and the "build_definition_ids" variables, before running the script. You can get the build IDs from the URL when you enter a build definition using the DevOps portal The project url can also be get from the address bar, and for this script it needs to be in the format: `https://dev.azure.com/{org name}/{project name}`. {% gist https://gist.github.com/nuno-barreiro/b14ec7ee58c718400dbb14a8860716c6 %}
nuno_barreiro
933,526
Props & PropsTypes
PropTypes [Prop Types are a mechanism to ensure that components use the correct data type...
0
2021-12-22T15:52:06
https://dev.to/mdabusufian/react-props-propstypes-139c
## PropTypes [Prop Types are a mechanism to ensure that components use the correct data type and pass the right data, and that components use the right type of props, and that receiving components receive the right type of props. It is a very important mechanism for passing information between react components. JavaScript is not a strongly typed language. JavaScript Function to accept data of different types when this data is declaration the function. If you can pass a number to a function that expects a string. JavaScript will try to convert the number into a string and go on to the next operation. Prop Types is a library and it helps minimize this problem by checking types passed in the props object against a specification you set beforehand and to raise a warning if the types passed do not match the types expected. This section above, you saw how to pass information to any component using props. You passed props directly as an attribute to the component, and we also passed props from outside of the component and used them in that component. But we didn’t check what type of values we are getting in our component through props or that everything still works. ### React Props React is a component based library. React Component Props are used from one component to another component to pass or share any data or object. Props makes use of directional data flow parent component to child component.it is works unidirectional data passing root component to child or under component. Props is the very important to data passing or information shearing way. However, with a callback function, it’s possible to pass props back from a child to a parent component. This data can come in different types to passing: numbers, strings, arrays, functions, objects, etc. if you pass props to any component. **This example to following: ** `const parentAssets=[ {id:1,assetLocation:”Dhaka”,assetPrice:20,00,000}, {id:2,assetLocation:”Narayanganj”,assetPrice:30,00,000}, {id:3,assetLocation:”Dhanmondi32”,assetPrice:50,00,000}, {id:4,assetLocation:”Uttara”,assetPrice:70,00,000}] Data Pass Parent Component to Child Component <ParentComponent> parentAssets.map(parentAsset=><ChildComponent asset={parentAsset}/>) </ParentComponent> ` ####Data Received and used Child Component *Received props* `const ChildComponent=({parentAsset})=>{ const{assetLocation,assetPrice,id)=parentAsset;` ## Used Props `<div>` `<h3>Parent All Asset Details</h1>` `<h4>{id}</h1>` `<h4>{assetLocation}</h1>` `<h4>{assetPrice}</h1>` `</div>}` ####Result: Parent All Asset Details 1,Dhaka,20,00,000; 2,Narayanganj,30,00,000; 3,Dhanmondi 32, 50,00,000; 4,Uttara,70,00,000; ####Real Life Example: Your Grandfather, your Father and You. This three man are most powerfully and respectfully man at first your Grandfather then your Father. All of time your Grandfather also order following your father and you. Because Your Grandfather is Old Man and Your Family First and Respectfully people.so that your family also decision make your Grandfather .He manage your family also Situation .The same role play your father also order following You step by step. Because he is your parent. So that you can not replay order your parent. Programming Example: React is a component based library . This Component any data or information sharing parent component to child component. It is unidirectional data pass method. It is props dialing method up to down data pass or data shearing method. This up to down drilling method is parent to child data pass or Shearing. This props drilling data passed method some time not working child to data pass her parents or down to up data pass or share .This problem solved for react Adding some hooks and Context ,reduce .This Context use for any where data passed or data shearing easily .The Context used react any child component shear his data her up level parent component. #####<span>Hablu Programmer ABUSUFIAN(cH@MoK)</span>
mdabusufian
933,853
Reasons to Have an Employee Portal in Your Company
More and more companies are implementing new ways to optimize communication between employees and the...
0
2021-12-22T16:48:14
https://dev.to/upsers/reasons-to-have-an-employee-portal-in-your-company-4ll2
More and more companies are implementing new ways to optimize communication between employees and the Human Resources department. The portals of the employee are one of them. And not only that, this type of software, tool or application implies incorporating a new mentality, more adapted to the latest trends in administrative, information management and internal organization. Still not convinced about the importance of enabling an employee portal? Here are some reasons to change your mind. [Upsers Login](https://upserscomlogin.xyz/upsers-login-upsers-employee-login-portal/) What is an Employee Portal? An employee portal is a tool that allows small and medium-sized companies to establish communication channels with the employee. Through an online platform, the company can give workers prominence and automate their data and other internal processes. Here is an Example [Upsers Com Login](https://upsersemp.online/) for UPS Employees. In the market, there are many services that allow you to create employee portals and each one with different functionalities. Document manager, payroll, vacation ... depending on the service you use you will have more or fewer functionalities, and the tool will be more or less adapted to your company. What is an Employee Portal for? Before going into the advantages that an employee portal can bring to a company, let's review what functions can or usually have employee portals. An employee portal is nothing more than a personal space for someone who is part of a company's staff. What does this mean? That said employee will have access to all his information, he will be able to take steps from there instead of having to go through different filters or supervisors that would take him some time that he will not be dedicating to other tasks. And the same happens with the Human Resources departments; the employee portal becomes a database whose information is managed and added automatically, is stored online and securely. Reasons to have an employee portal For both small and medium or large companies (especially the latter two), having a tool that helps automate processes is something that can revolutionize the Human Resources department, change its mentality and make its number one priority not It is to manage the paperwork but to the talent of the company. Let's see the reasons why your company could benefit from this resource: 1. IT IS A TWO-WAY COMMUNICATION CHANNEL Much of the labor conflict is caused by a lack of internal communication between the company and the employee or by poor management of the internal communication processes. The main reason for implementing an employee portal in your company is to establish procedures and agile communication channels between company and worker. 2. REDUCE THE ADMINISTRATIVE BURDEN FOR THE HR DEPARTMENT. The vast majority of employee portals have mechanisms that simplify the management of the Human Resources department. Depending on the tool you choose, you will have the possibility to reduce the administrative burden of the department and save time month by month. 3. AUTOMATE TEDIOUS PROCESSES There is no reason why you should continue to manually perform tedious and repetitive processes that can be done faster and better thanks to intuitive technology like this. 4. STANDARDIZE PROCESSES AND EVERYTHING WILL BE UNDER CONTROL In most companies and SMEs there are several completely different processes to do the same thing, for example, request a vacation. The result of this is chaos. Standardizing a simple process for each task is the best way to ensure optimization of everyone's time. What's the point of sending an email to the Human Resources department to ask how many days do you have on vacation? The employee portal can solve this without having to respond one by one to the 50 employees of your company when they have doubts. 5. REDUCES THE RISK OF DATA LOSS If you have had the bad luck of having lost your computer or it has been damaged, you will know that nowhere near a device with a password is the best place to store all the vital information of your company. The employee portal is in the cloud, and it is the solution. Relying on a secure and cloud-backed tool can help you minimize the risk of data loss or exposure to eyes outside the organization. How to choose the best employee portal for your company Each company is a world and choosing the employee portal service that best suits each one is a matter of understanding what the needs are trying to cover. Are you looking for something basic that allows you to share documents internally and solve more general aspects such as absences and vacations or rather something that goes further and allows you to create payrolls, send them and track candidates for a vacant position? Depending on the objective of the company you will find several options on the market, our advice is to choose the tool that allows you a higher level of personalization and that adapts perfectly to the structure of your company. However, there are certain requirements that the option you choose should have: USABILITY It has to be easy to use. You don't want to have to waste time training employees so they can do simple processes. The objective is to get rid of you, not the other way around. MOBILE APP The best thing is that the employee can access their personal space both on the company computer and on their own mobile device. This will be beneficial especially if you have workers who are not always present in the office or perform their duties remotely. PERMISSIONS If your employee portal has a permit system, it will be easier for you to manage each of the workers according to their manager. Do you want the organization chart to be effective? Your employee portal has to allow certain workers to approve and supervise the tasks of others, or to request them digitally and automatically. REPORTS If you want to store the information in the cloud provided by an employee portal, you may want to do something with it. The software you end up using should allow you to extract and download documents, as well as upload and report the data you have generated.
upsers
933,869
Become A Great Solution Architect – Chapter 2 – The Requirements
1 - Vision A great solution architect can draw the big picture of a solution in a...
0
2021-12-22T17:10:45
https://dev.to/iotcloudarchitect/become-a-great-solution-architect-chapter-2-the-requirements-29c2
architecture, career, tutorial
## 1 - Vision ![Vision](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9goyrkf6xd42lxefs183.jpg) A great solution architect can draw the big picture of a solution in a fashion all stakeholders can read and understand. And he can present it, including all the objectives and how every stakeholder can contribute. A common understanding of the solution is essential for the success of the entire project. Because, if some stakeholders have a different opinion or interpretation of the solution, this could cause a problem. **Transparency is a crucial success factor.** So, if everyone in the project team, from the product owner over the business analysts to every developer and operational staff, can tell you the same story about the solution, the solution architect did a great job. --- ## 2 - Communication & Presentation Skills ![Communication & Presentation Skills](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wyaza9thwmizo7bg5ixx.jpg) A great solution architect is a great communicator since this ability is a vital part of his competence. Along the entire road to successfully realize the defined solution, there is a lot to discuss, negotiate, and specify with every single stakeholder. Therefore, the solution architect listens carefully, explains properly, gives valuable advice, and understands the stakeholders’ intentions. **Being present on the project – even virtually – gives stakeholders confidence in your work.** Presenting the architecture, results of proofs-of-concept, and sharing insights about the progress of the implementation process and the quality of deliverables is an essential part of his work. **Do good things, and tell about it.** --- ## 3 - Organizational and Leadership Skills ![Organizational and Leadership Skills](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7bcqpbot8zbm6ljp7wc9.jpg) Of course, the solution architect does not play the role of a project manager on top of his work. But, since he gets directly involved due to his essential position inside the project, he has to deal with deadlines, given resources, and must be focused on the project’s results. His objective is to succeed in achieving the milestones. **Go the extra mile – it’s more than merely writing a concept and test implementation.** Besides this more visual part of work, a great solution architect mentors the lead developer and, if necessary, parts of the development team. His objective is to get an impression of how the development team implements the architecture. In case there is a mismatch, you better know about it in an early stage. **Mentor the team which implements your ideas.** --- ## 4 - Modelling Methods, Frameworks, and Best Practises ![Modelling Methods, Frameworks, and Best Practises](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v214rvvqz19rnwwyobly.jpg) A vital part of a solution architect’s work is to document the architectural approach in a standardized way. Here, architecture design patterns can scaffold the fundaments of the solution architecture. Modeling methods like the Unified Modelling Language (UML) depict the solution architecture in a fashion the development team understands and uses it as the basis for their implementation. **Standards are your friend.** Since more and more software projects go the agile way, the solution architect is familiar with frameworks like Scrum and Kanban, which help to organize the development and delivery process but also found the planning of product features. The solution architect is continuously looking for best-practice approaches and game-changing tools and technologies. **Stay open to new impressions.** --- ## 5 - Knowledge of Software Development ![Knowledge of Software Development](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hvangfsblbv8qv292867.jpg) At the end of the day, the development team will implement the architected solution. It is, of course, not part of the solution architect’s job. But, it is beneficial to understand how developers think, how they act, and what things they do not know in detail. **Software developer experience helps to assess the developers’ progress and quality and offers the possibility to support the team.** Besides, a solution architect shall be able to code on its own – at least for technical evaluations or entire proofs-of-concept. Therefore, the knowledge of at least one of the top three popular programming languages will boost his possibilities. We are currently (2020) talking about JavaScript (EcmaScript 6, TypeScript, NodeJS), Python, Java, and C#. **Coding skills are helpful, but you don’t need to write production-ready code.** In case there is a need to assess code quality, the solution architect could dive in, but then his knowledge of the particular programming language must be excellent. --- ## 6 - DevOps ![DevOps](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jeq21a0h81qn3w69d2de.jpg) It defines an approach to shorten the software development life cycle and provides continuous delivery of high-quality software with the help of a dedicated toolchain. Since the solution must finally run in the production environment, the solution architect, the development team, and the operations team shall work together to find an excellent process and to select the vital supporting technologies. To ensure that, the solution architect helps with the setup of DevOps processes, like the planning of the building, automatic testing, packaging, releasing, configuring, and monitoring. **The objective is to define an (automated) process to build, test, and deploy properly working software.** The solution architect considers the DevOps approach during his architectural work by examining the staging environments, e.g., development, testing, acceptance/reference, and production. --- ## 7 - Analytical Skills ![Analytical Skills](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ayagjyg7lawrb4zhuz2.jpg) A great solution architect is an excellent listener and structures the insights he gets accordingly. Collecting data, interviewing stakeholders, and reflecting the gained information will help get a holistic picture of the problem. Based on this treasure, he can focus on details to fully understand the business needs and processes. Another essential attitude of a great solution architect is always to reflect and question the information he gets. --- ## 8 - Tech Domain and Industry Knowledge ![Tech Domain and Industry Knowledge](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wr43pyfwrcwlwfh6783g.jpg) An experienced solution architect has a lot of expertise in different types of projects enabled by various technologies. Furthermore, he specializes in some way towards key tech domains, e.g., IoT, Cloud, AI, Big Data, etc. There usually are a lot of best-practice approaches, architecture design patterns, and out-of-the-box examples well known in these tech domains. Furthermore, an experienced solution architect gained a lot of knowledge from proofs-of-concept and knows about the pitfalls of key technology implementations. **Experience with technology stacks is significant.** Besides the knowledge of specific technologies, it is beneficial to know about the processes, methodologies, and do’s and don’ts of particular industries. Industries like finance, healthcare, energy, automotive, etc., have their own rules and restrictions. Especially in the phase of interviewing or reviewing the business (functional) requirements, domain knowledge can help identify mistakes in specifications. **Industry know-how is beneficial but not crucial.** --- ## Summary All the requirements mentioned here are the essence of my personal experience and opinion and reflect the demands of companies hiring solution architects. Of course, it can’t be a collectively exhaustive line-up, but I deem it touches the most prominent topics. In case you believe this article can help others sharpen their focus, or reflect themselves, feel free to share it. Hope to see you again in the next chapter! Photos on [Unsplash](https://unsplash.com)
iotcloudarchitect
933,909
Explore API
Today we will learn What is an API? And The purpose of API &amp; CRUD Operations. What's an...
16,006
2021-12-22T17:48:55
https://dev.to/iftakher_hossen/learn-about-api-1cae
javascript, tutorial, beginners, codenewbie
**Today we will learn What is an API? And The purpose of API & CRUD Operations.** ### What's an API **API** stands for **Application Programming Interface**. It’s a way to connect two applications for talking with each other. It helps you to embed content on your website from any website in a more efficient way. API is simple, flexible, and easier to use. The main purpose of the API is to create communication between two applications. API lets you call to send or receive information. The communication is done by **JSON**. We fetch data with API requests in applications. API request has 4 components. They are Endpoint, Header, Method & Data. After calling those individually we can build an API request. ###CRUD Operations **CRUD** Operations stands for **Create**, **Read**, **Update** & **Delete** operations. The fours basics and important methods in database operations. The purpose of CRUD operations is to modify the data in an application. Let’s explore CRUD Operations: - **GET** - GET method allows you to get information from the source/database. - **POST** - POST method allows you to add some information to the source/database. - **PUT** - PUT method allows you to update the existing information to the source/database. - **DELETE** - DELETE method allows you to delete existing information from the source/database. ###JSON **JSON** stands for **JavaScript Object Notation**. It’s used to represent data on the server. It’s easy to read for humans and computers. Let’s see an example: ![JSON Example Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/36lys18lfkyj9ytkkdqk.png) ###Types of API There are three types of API: - **Open API** - Open API means an API that is free to use and everyone can use it. - **Partner API** - Partner API means an API that makes a connection between the server and the clients. - **Private API** - Private API means a secure API that can only be used for internal uses like payments. API is a powerful tool for making connections between client and server applications. API provides more benefits like security, speed, & scalability for eCommerce applications. API helps developers send data to clients and is used every day in today’s world. Thank you for reading this!
iftakher_hossen
933,942
Mini-tutorial Android Studio: Revisar conexión a internet
Hola de nuevo a un mini-tutorial de Android Studio. En esta ocasión les enseñare a revisar...
0
2021-12-22T18:38:25
https://dev.to/fynio/mini-tutorial-android-studio-revisar-conexion-a-internet-3id7
android, espanol, minitutorial, spanish
## Hola de nuevo a un mini-tutorial de Android Studio. En esta ocasión les enseñare a revisar si en su dispositivo hay conexión a internet ### ¡¡¡Vamos al código!!! ------ ## AndroidManifest.xml En nuestro **AndroidManifest.xml** agregaremos los permisos para eso tendremos que agregar arriba de nuestro **application** ``` <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> .... <application android:allowBackup="false" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" ``` ## MainActivity.java En nuestro MainActivity utilizaremos el objeto **ConnectivityManager** y creamos un objeto **Networkinfo** ``` ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = con.getActiveNetworkInfo(); ``` Ya teniendo el objeto **networkInfo** podremos revisar la conexión. Ahora con un simple **if** revisamos si hay conexión a internet ``` if(networkInfo!=null && networkInfo.isConnected()) { Toast.makeText(getApplicationContext(), "Si hay conexión a internet", Toast.LENGTH_LONG).show(); }else { Toast.makeText(context, "Necesitas conectarte a internet", Toast.LENGTH_LONG).show(); } ``` ## Fin
fynio
933,945
Understanding Built In Angular Directives - Part 4
Today we will continue our journey in understanding the other built in Angular directives mainly the...
0
2021-12-23T21:40:00
https://dev.to/anubhab5/understanding-built-in-angular-directives-part-4-49ch
angular, beginners, directives, tutorial
**T**oday we will continue our journey in understanding the other built in Angular directives mainly the **Structural Directives**. The directives which are used to change the structure of the DOM are called <u>structural directives</u>. On a high level a structural directive adds or removes element in the DOM. The first directive which we will understand is the `ngIf` directive. The structural directives always starts with an asterisk `*` `*ngIf` ngIf directive is used to show or hide an element on which it is added conditionally. If the condition executes to true the element will be shown else the element will be hidden. **A point to note** _The element is completely removed from the DOM if the condition executes to false. It will not occupy any space in the DOM._ Now lets see in practice- Lets create a fresh component. Name it `structural-directive-demo`. If you are not aware of what is a component or how to create and use it I would highly recommend to read through the [post](https://dev.to/anubhab5/creating-angular-component-129e). Once the component is created our project would look like - ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d21yt1dn3t2t8jmcv86f.PNG) Lets open the component.ts file and write the below code- To be precise add the variable `myAge` and assign the value `18` to it. ``` export class StructuralDirectiveDemoComponent implements OnInit { myAge = 18; constructor() { } ngOnInit(): void { } } ``` Now open the corresponding html template file and paste in the below code- ``` <p *ngIf="myAge >= 18">I am an Adult!</p> <p *ngIf="myAge < 18">I am a CHILD</p> ``` Now lets start the application and open the browser and open localhost:4200. You should see an output like below - ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xtoi9ols5j94utxxih2m.PNG) Lets understand what is happening under the hood. The variable `myAge` is holding the value 18 (the model). In the template when we write the below code say- `<p *ngIf="myAge >= 18">I am an Adult!</p>` the variable myAge points to the model or we can say it holds the value present in the model. The condition `myAge >= 18` returns `true` which is assigned to the directive ngIf. Since true is assigned to the directive `ngIf` the `p` tag is visible. Now lets change the `myAge` variable value to say 17 so that the above condition is false but the second line of code `<p *ngIf="myAge < 18">I am a CHILD</p>` returns true. Now if you open the browser you will see that the output changes. The first `p` tag is not shown/ hidden while the second `p` tag is shown which was hidden when the model value was 18. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gt4q94dsxny477fp83gt.PNG) So that's the power of ngIf directive. If you have to conditionally show/ hide some data in the template you can easily use it. Also to add to the above stuff you can also assign a function to the ngIf directive which returns a Boolean value. Something like below - In component.ts file you have a function like below - ``` checkAge() { if (this.myAge >= 18) { return true; } else { return false; } } ``` and in html template file you can call the function inside ngIf like below - ``` <p *ngIf="checkAge()">I am an Adult!</p> ``` **Note** _Any values like `false`, `null`, `undefined`, `empty string` when assigned to `ngIf` will result in hiding the element._ Hope you enjoyed the post. Do like comment and share the post. **Cheers**!!! _Happy Coding_
anubhab5
933,995
Apama Advent Calendar - 22 Dec 2021 - The MemoryStore plugin
This is Day #22 of a short series of brief tips, tricks, hints, and reminders of information relating...
0
2021-12-23T13:04:13
https://tech.forums.softwareag.com/t/apama-advent-calendar-22-dec-2021-the-memorystore-plugin/254021
apama, iot, cumulocity, streaminganalytics
--- title: Apama Advent Calendar - 22 Dec 2021 - The MemoryStore plugin published: true date: 2021-12-22 16:56:44 UTC tags: apama, iot, cumulocity, streaminganalytics canonical_url: https://tech.forums.softwareag.com/t/apama-advent-calendar-22-dec-2021-the-memorystore-plugin/254021 --- _This is Day #22_ _of a short series of brief tips, tricks, hints, and reminders of information relating to the Apama Streaming Analytics platform, both from Software AG as well as from the community._ Check out some typical use cases for the Memory Store, and learn to set up the store and describe the tables before you can use them in the original post in the [Software AG Tech Community](https://tech.forums.softwareag.com/t/apama-advent-calendar-22-dec-2021-the-memorystore-plugin/254021). _Note that some posts may be published a day or two early or late (e.g. Mon-Fri) so you may find you have bonus days with more than one post!_
techcomm_sag
934,086
Number Methods JavaScript
The toString() Method: The toString() method retunes a number as a string The toExponential()...
0
2021-12-22T20:24:13
https://dev.to/abpz3r0/number-methods-javascript-3j61
javascript
**<u>The toString() Method:</u>** The toString() method retunes a number as a string ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uukmannj7xtgyux0dboy.png) **<u>The toExponential() Method</u>** toExponential() provides a string containing a number that has been rounded and expressed in exponential notation. The number of characters after the decimal point is determined by a parameter. The parameter is not required. JavaScript will not round the number if you don't provide it. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w2oveeemnhoxgk07ccuj.png) **<u>The toFixed() Method </u>** toFixed() produces a string containing a number with a given number of decimals put in it. The toFixed() function reduces the number of digits in an integer to a specified number. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/47bml2qxp7iz4zjy6zd2.png) **<u>Converting Variables to Numbers</u>** Number() Returns a number, converted from its argument. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xx6d96h4jsfaabd2e5v8.png) parseInt() Parses its argument and returns an intege ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ey75en92ktxqteyqzjos.png) parseFloat() Parses its argument and returns a floating point number ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1r4wkk40tws5uotu053n.png)
abpz3r0
935,123
SIMPLE CSS ANIMTATION
*CSS ANIMATIONS : * CSS Animation is which is helps to change one style to another style. We can use...
0
2021-12-23T20:34:02
https://dev.to/thuising/simple-css-animtation-41h6
**CSS ANIMATIONS : ** CSS Animation is which is helps to change one style to another style. We can use animation without using javascript. If we want to use animation on CSS we have to use @keyframes. There have some advantages to using CSS animations: This is easy to use and you can create animation without using javascript. This animation’s performances are so smooth for their rendering engine use frame0skipping and some other techniques. Letting the browser control the animation sequence lets the browser optimize performance and efficiency @keyframes helps to use animation on CSS. @keyframes take a name and curly bracket. On curly bracket, you have to use from and to or 0% and 100%, percentage to changing styles. 0% means the beginning of the animations and 100% means the end of the animation and the from means from where animation start and to means where the animation will end. **Example of defining: **—from to— ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/43xmnyeopq1zraf88a74.png) –percentage— ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7zbvcje558eox4ei0su2.png) These two images are showing that how to use from to and percentage in keyframes. Now we will see an example of animation. Example of animation : First, you have write an HTML code to make a structure for your animations. Like I had written some HTML code in below. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gya2iwu2097dd8k0d7ox.png) After writing some HTML code and we have to add some styles for positions items and looking beautiful. Styles ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cqoowu8wblfoy3jjry1j.png) After adding styles on elements we need to take which element you want to make animation. On that element’s CSS you have to write the animation property name on that CSS element’s CSS. you can add delay, how many time loops and etc more options. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wkwnb44gz9scxcsf3h61.png) After defining the name on that CSS you have to @keyframes Name { } in CSS. inside the curly bracket, you will write code which animation you want to make. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pxmf7s9l7w67jhtvu66f.png) **Animation Project and code : ** ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zj3akw69klbh89y9qy4r.gif) You can check this simple animation on CodePen. [Click here to see](https://codepen.io/pen/?template=QWqqzBJ)
thuising
934,089
How to get old LinkedIn app in China
TLDR -- The China-localised LinkedIn app has been replaced with InJobs app. If you are unfortunate...
0
2021-12-22T20:41:34
https://dev.to/emmanuelnk/how-to-get-old-linkedin-app-in-china-3ac8
android, samsung, linkedin, adb
TLDR -- The China-localised LinkedIn app has been replaced with InJobs app. If you are unfortunate like me, that localised LinkedIn app is not easily replaceable with a non-China-localised version on your phone (e.g. on most Samsung phones) -- which means you simply cannot use the LinkedIn app on your phone anymore because if you open it, you are prompted to download InJobs app instead. Scroll to 'The solution' section to see how to fix this. ## The Problem Recently, the LinkedIn mobile app [exited the China market](https://www.nytimes.com/2021/10/14/technology/linkedin-china-microsoft.html) -- more specifically, [they sunsetted the normal LinkedIn app and replaced it with a new application called InJobs specifically for China region](https://blog.linkedin.com/2021/october/14/china-sunset-of-localized-version-of-linkedin-and-launch-of-new-injobs-app). So as the new InJob app rollout is underway, users of the old China-localised LinkedIn app are now blocked from logging in and are instead prompted to download the new InJobs app. This happened to me yesterday. This would usually be fine because it means all you have to do is uninstall the China-localised LinkedIn application and install a non-China-localised LinkedIn application from the Google Playstore to continue using the LinkedIn app you are used to. But... What happens when you cannot remove it? Unfortunately for most Samsung users, apps like Facebook (HK, TW, Rest of the world), LinkedIn (Mainland, HK, TW, Rest of the world) and many Microsoft apps are in most cases pre-installed bloatware. This means they cannot be uninstalled easily -- only disabled. These are apps I use (or at least did not mind being bloatware) so this hasn't been an issue for me -- until now. Unfortunately for users who got their Samsung (and probably other phones) from China region (Mainland, HK, Taiwan) the uninstallable LinkedIn app is the now discontinued China-localised version. Since I'm no longer in the China region (where I bought my phone), the InJobs app is useless to me. And even if I wasn't I would probably still want to use the regular LinkedIn app and not a stripped down version. ## The Solution Fortunately, there is a work-around. It is quite technical so I hope you know how to use the terminal. **NOTE:** Don't attempt this if you don't know what you are doing or have never used the terminal. I am not responsible for you bricking yor phone. ### Pre-requisites - Computer - Data wire - Your mobile phone - Internet ### Initial Steps 1. Enable USB debugging on your Phone - https://www.verizon.com/support/knowledge-base-223020/ 2. Download Android SDK platform tools for your operating system (I use Linux and it is what I will show from now on) - https://developer.android.com/studio/releases/platform-tools 3. Unzip platform tools you just downloaded 4. Enter the platform tools folder and open your terminal there ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywekqqletke3vnzui43u.png) 5. Connect your phone to computer and allow it to share data if prompted 6. Download the latest version of LinkedIn APK from APKPure. Download [here](https://m.apkpure.com/linkedin-jobs-business-news/com.linkedin.android/download). We need this non-China-localised version to overwrite the existing China localised version -- Don't worry its safe to install. Also, we only need it for a few minutes and all future versions will be from your trusted Google Playstore. Copy the location of the downloaded LinkedIn APK 7. Prepare your phone -- Set the screen timeout to be at least 10 minutes. You don't want your screen going odd during this process. Make sure you do not disconnect the wire during any of the following steps. ### Next steps 1. Open your terminal and do the following ``` ./adb devices ``` You should see your device connected. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lez29pk11q4ma0g8jy4m.png) 2. Run the following command to ensure you grant permissions to run commands on your device ```bash ./adb shell pm list packages | grep linkedin ``` ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vciuuitv42l8rfrhf0kq.png) You should see that `linkedin` is installed 3. Install the LinkedIn apk you just downloaded ```bash ./adb install -r -d ~/Downloads/LinkedIn\ Jobs\ Business\ News_v4.1.649.1_apkpure.com.apk ``` In this command, `-r` will force the APK to update with the new APK and `-d` will force the phone to ignore the possibly lower LinkedIn version you want to install 8. If prompted to grant permission on your phone, ensure you grant it. If the command fails because of this, just run it again. 4. When it is done (may take a while -- give it up to 3 min) -- You should see `success` ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3mvyyargoshjpp9v5x6t.png) That's it. You can now disconnect your phone from your computer and now you should have the correct non-China localised LinkedIn application installed on your phone. If the version you downloaded from APKPure is lower than the latest version on Google Play, you will see a prompt to update the app in Google Play. Update it. That's all. ------- Hi I'm [Emmanuel](https://emmanuelnk.com)! I write about software, devOps and other random technical stuff. If you liked this article and want to see more, add me on [LinkedIn](https://www.linkedin.com/in/emmanuel-nsubuga-kyeyune/) or follow me on [Twitter](https://twitter.com/emmanuel_n_k)
emmanuelnk
934,119
The best extensions, tips, and themes for VS Code!
Best extensions and themes for Visual Studio Code! This post is a list of extensions and themes for...
0
2021-12-22T22:39:16
https://dev.to/jlgjosue/the-best-extensions-tips-and-themes-for-vs-code-49k9
vscode, python, theme, extensions
Best extensions and themes for Visual Studio Code! This post is a list of extensions and themes for Microsoft Visual Studio Code that I’ve used and recommend. **About VS Code** Visual Studio Code is an open-source editor developed and maintained by Microsoft, one of the most used and popular editors at the moment. Its popularity is mainly: For the abundant amount of “IntelliSenses” (solutions to autocomplete your code). * Possibility of “debug” by the editor. * Integration with GIT. * Lots of cloud integrations like Azure and GCP. * Possible to use with DevOps solutions such as Terraform, Ansible, and Kubernetes. * Having supported Windows, Linux, and Mac. * It supports the possibility of development for several languages like C++, C#, Java, Python, PHP, Go, and runtimes like .NET and Unity. https://code.visualstudio.com/ There is a large community helping Microsoft to maintain and evolve this editor daily, but before you go out customizing and installing extensions and themes, check the documentation available. **Extensions and Tips** This is a short list of extensions, integrations, and tips for everyday use. * Support for Jupyter Notebooks(*.ipynb) within VS Code: ![0_tV22CP21UugJLt6z.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1640185115659/O5G9xrpRo.gif) To enable support for Jupyter Notebooks, you will need to have Python installed, install the support, and create a test file (ex: test.ipynb). https://code.visualstudio.com/learn/educators/notebooks >IntelliSense is a general term for various code editing features, including: code completion, parameter information, quick info, and member lists. IntelliSense features are sometimes referred to by other names, such as “code completion”, “content assistant” and “code hints”. ![0_8JgU_T4n-DSKdSbj.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1640185181888/Bnhklx5Vd.gif) As time went by, several intelligent “wizards” began to appear to assist and complement the VS Code, one of the most promising is “Kite”, a solution with support for 16 languages, using several machine learning models to improve the auto-complete, reducing the keys used during its use by 47%, in addition, to easily accessing the documentation for each new library used and tools to search for repeated code. https://medium.com/kitepython There are several alternatives to kiting, one of them is the [Tabnine](https://www.tabnine.com/). * [GitLens](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens) A set of solutions that will make your day-to-day, driving code versioning with Git much easier. ![0_49Omw1hEjyVlscuU.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1640185423187/rDsGT5Dc_.gif) * [TODO Highlight](https://marketplace.visualstudio.com/items?itemName=wayou.vscode-todo-highlight) A way to remember some “TODO” that are always to be done… ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640185481965/3GS8oO-MQ.png) * [Path Intellisense](https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense) An extension to auto-complete the path and filenames. ![0__1UzDnDS0A1Jh4PV.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1640185742050/ecsrS7bhA.gif) * [Pylance](https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance) Pylance is an extension that works alongside Python in Visual Studio Code to provide high-performance language support. Behind the scenes, Pylance is powered by Pyright, Microsoft’s static type checking tool. Using Pyright, Pylance has the ability to turbo-charge your Python IntelliSense experience with rich type information, helping you write better code faster. ![0_-QxL7MGMUUQMh6gr.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1640185834890/SUv7ebGsi.gif) * [Visual Studio IntelliCode](https://visualstudio.microsoft.com/services/intellicode/) An “Assisted IntelliSense”, ie an assistant with artificial intelligence to improve the autocomplete. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640186132180/aDssxjzOy.png) * [Material Theme Icons](https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme) A gigantic catalog of icons that customize your editor and make your navigation a little easier visually. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640186206693/XJvKvBPEs.png) *[VSCode Great Icons](https://marketplace.visualstudio.com/items?itemName=emmanuelbeziat.vscode-great-icons) Another set of icons to customize the environment. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640186338052/K1vBQD6f3.png) * [One Monokai Theme](https://marketplace.visualstudio.com/items?itemName=azemoh.one-monokai) A simple and practical theme. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640186381502/TDBmOhidvqE.png) * [Noctis](https://marketplace.visualstudio.com/items?itemName=liviuschera.noctis) A theme created to rest your eyes. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1640186449790/ga9cQTL9p.png) * [Remote WSL](https://code.visualstudio.com/docs/remote/wsl?WT.mc_id=javascript-36257-gllemos) This extension allows the use of the VS Code on the Windows Linux subsystem, the WSL: ![0_iuCuSxPfLwwPN6Kz.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1640186511372/DEPWwgrws.gif) This publication is a presentation of a set of extensions, themes, and tips to use with VS Code, but before you go madly installing everything that was presented, read the documentation and remember that as new extensions are being installed, know this can make your editor “heavy” and increase RAM consumption. **References:** https://medium.com/free-code-camp/here-are-some-super-secret-vs-code-hacks-to-boost-your-productivity-20d30197ac76 https://medium.com/hackernoon/vs-code-extensions-for-happier-javascript-coding-e258f72dd9c1 https://levelup.gitconnected.com/15-vs-code-extension-to-save-your-time-and-make-you-a-better-developer-506f79baec53 https://medium.com/swlh/best-4-vs-code-extensions-in-2020-d629f37a034 https://towardsdatascience.com/pylance-the-best-python-extension-for-vs-code-ae299f35548c https://medium.com/for-self-taught-developers/10-best-themes-for-visual-studio-code-2020-87885ec1576a https://glaucia86.medium.com/14-dicas-para-turbinar-o-seu-vs-code-341cf5f8a353 <a href="https://www.buymeacoffee.com/jlgjosue" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a> Follow me on [Medium](https://jlgjosue.medium.com/) :)
jlgjosue
934,175
Why I use aqua
aqua is a declarative CLI Version Manager written in Go. https://aquaproj.github.io/ In this...
0
2021-12-23T00:32:46
https://dev.to/suzukishunsuke/why-i-use-aqua-230
aqua is a declarative CLI Version Manager written in Go. https://aquaproj.github.io/ [![asciicast](https://asciinema.org/a/457021.svg)](https://asciinema.org/a/457021) In this post, I describe why I use aqua. ## Why I use aqua * Align tool versions in team and CI * Solve the problem due to the difference of tool versions * Manage tools and their versions for projects as code declaratively, and provide an unified way to install tools * aqua supports changing tool versions per project * Stop developing shell scripts and GitHub Actions to install tools per tool and per project * Update tools with Renovate easily * Install tools hosted in private repositories ## Why not asdf? asdf is used for the similar purpose, but I use aqua. Why? * Some tools don't have asdf plugins for them * Good Experience * You don't have to install plugins * Tools are installed automatically * Search tools by `aqua g` is useful * aqua doesn't force to use aqua in other projects and globally * Easy to support new tools * It is easier to contribute to aqua-registry than to develop asdf plugin * Easy to introduce aqua to teams and projects because aqua is easy and doesn't force to use aqua in other projects and globally * Easy to update tools with Renovate * aqua supports splitting configuration files, so it is easy to filter builds in CI by changed file paths About the difference between aqua and asf, please see [Comparison - asdf](https://aquaproj.github.io/docs/comparison/asdf) too.
suzukishunsuke
934,391
Create Stopwatch using javascript
In this tutorial, we will discuss, how to construct a simple javascript stopwatch. A stopwatch is...
0
2021-12-23T07:07:40
https://dev.to/codewith_random/create-stopwatch-using-javascript-m2h
stopwatch, javascript, html, webdev
In this tutorial, we will discuss, how to construct a simple javascript stopwatch. A stopwatch is used on many websites to track time. Moreover, it is also a good standalone project as well. The stopwatch we are creating is similar to a regular stopwatch that is used to keep track of time. Albeit, it is unique for its ability to track hours, minutes, seconds, and milliseconds. Prerequisites for this project: This article requires a basic understanding of HTML, CSS, and a little bit of Javascript. I'll explain the project in a manner that makes it easy to follow even for complete beginners with a basic understanding of the listed technologies. Live Demo: Before we start the programming, let's discuss the UI of the project. First, we are creating a stopwatch container that will have a screen to display the current stopwatch time. The stopwatch also has three buttons — Pause, Start, Reset — to control the stopwatch.[read more](https://www.codewithrandom.com/2021/12/create-stopwatch-using-javascript.html)
codewith_random
934,428
Advance Laravel 8 Interview Questions and Answers 2022
Q. 1: What is Serialization in Laravel? It's similar to turning an object into JSON, but...
0
2021-12-23T08:49:26
https://dev.to/expoashish/advance-laravel-8-interview-questions-and-answers-2022-4p66
laravel, computerscience, programming, tutorial
#Q. 1: What is Serialization in Laravel? It's similar to turning an object into JSON, but with the advantage that PHP will remember the native data type of each serialized item (string, array, integer, float, boolean). PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript? The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format: **echo json_encode($array) [Read Full Blog Here....](https://codexashish.blogspot.com/2021/12/advance-laravel-8-interview-questions.html)
expoashish
934,434
Swagger To Typescript
Swagger To Typescript is a plug-in used to convert the types provided by Swagger documents to...
0
2021-12-23T09:03:19
https://dev.to/akclown/swagger-to-typescript-3c2h
Swagger To Typescript is a plug-in used to convert the types provided by Swagger documents to typescript types automatically. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wu9s7aftxd0idxe1dkby.png) usage ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8pil1q1u3xp9avav3tbr.gif) Keyboard shortcuts configuration. - Default button configuration (window & mac) 1. Conversion operation `ctrl+shift+k` (Right-click panel also has options) - You can also make customize settings in the shortcut key setting interface. PS: [File Teleport](https://github.com/AKclown/file-teleport)File will be updated synchronously together with plug-in.
akclown
934,448
User profile page
A post by HARUN PEHLİVAN
0
2021-12-23T09:16:00
https://dev.to/harunpehlivan/user-profile-page-198h
codepen
{% codepen https://codepen.io/harunpehlivan/pen/VwMazJM %}
harunpehlivan
934,465
What is the longest name in C++?
Find the longest identifier in C++20 Standard Library.
0
2021-12-23T09:33:01
https://dev.to/yohhoy/what-is-the-longest-name-in-c-32n
cpp, api, fun
--- title: What is the longest name in C++? published: true description: Find the longest identifier in C++20 Standard Library. tags: cpp, api, fun --- Question: What is the longest identifier in C++20 Standard Library? Answer: https://github.com/yohhoy/cpp-longest-identifier |identifier|len|since| |:---|--:|:--| |[`atomic_compare_exchange_strong_explicit`][acx]|39|C++11| |[`hardware_constructive_interference_size`][hdis]|39|C++17| |[`get_return_object_on_allocation_failure`][coro]|39|C++20| |[`uninitialized_construct_using_allocator`][ucua]|39|C++20| |[`propagate_on_container_copy_assignment`][pocca]|38|C++11| |[`propagate_on_container_move_assignment`][pocca]|38|C++11| |[`hardware_destructive_interference_size`][hdis]|38|C++17| |[`is_pointer_interconvertible_with_class`][ipiwc]|38|C++20| |[`atomic_compare_exchange_weak_explicit`][acx]|37|C++11| |[`select_on_container_copy_construction`][sococ]|37|C++11| |[`is_pointer_interconvertible_base_of_v`][ipibo]|37|C++20| |[`is_trivially_default_constructible_v`][idc]|36|C++17| |[`has_unique_object_representations_v`][huor]|35|C++17| |[`is_pointer_interconvertible_base_of`][ipibo]|35|C++20| |[`inappropriate_io_control_operation`][errc]|34|C++11| |[`is_trivially_default_constructible`][idc]|34|C++11| |[`is_nothrow_default_constructible_v`][idc]|34|C++17| |[`indirectly_regular_unary_invocable`][iui]|34|C++20| |[`atomic_flag_test_and_set_explicit`][aftas]|33|C++11| |[`has_unique_object_representations`][huor]|33|C++17| |[`is_trivially_copy_constructible_v`][icc]|33|C++17| |[`is_trivially_move_constructible_v`][imc]|33|C++17| |[`uninitialized_default_construct_n`][udcn]|33|C++17| |[`lexicographical_compare_three_way`][lctw]|33|C++20| |[`is_nothrow_default_constructible`][idc]|32|C++11| |[`uses_allocator_construction_args`][uaca]|32|C++20| [errc]:https://en.cppreference.com/w/cpp/error/errc [hdis]:https://en.cppreference.com/w/cpp/thread/hardware_destructive_interference_size [pocca]:https://en.cppreference.com/w/cpp/memory/allocator_traits [sococ]:https://en.cppreference.com/w/cpp/memory/allocator_traits/select_on_container_copy_construction [idc]:https://en.cppreference.com/w/cpp/types/is_default_constructible [icc]:https://en.cppreference.com/w/cpp/types/is_copy_constructible [imc]:https://en.cppreference.com/w/cpp/types/is_move_constructible [huor]:https://en.cppreference.com/w/cpp/types/has_unique_object_representations [udcn]:https://en.cppreference.com/w/cpp/memory/uninitialized_default_construct_n [udc]:https://en.cppreference.com/w/cpp/memory/uninitialized_default_construct [acx]:https://en.cppreference.com/w/cpp/atomic/atomic_compare_exchange [aftas]:https://en.cppreference.com/w/cpp/atomic/atomic_flag_test_and_set [coro]:https://en.cppreference.com/w/cpp/language/coroutines [ucua]:https://en.cppreference.com/w/cpp/memory/uninitialized_construct_using_allocator [ipiwc]:https://en.cppreference.com/w/cpp/types/is_pointer_interconvertible_with_class [ipibo]:https://en.cppreference.com/w/cpp/types/is_pointer_interconvertible_base_of [iui]:https://en.cppreference.com/w/cpp/iterator/indirectly_unary_invocable [lctw]:https://en.cppreference.com/w/cpp/algorithm/lexicographical_compare_three_way [uaca]:https://en.cppreference.com/w/cpp/memory/uses_allocator_construction_args
yohhoy
934,474
The Mythical Fullstack Developer
I have been thinking about the so-called Fullstack Developer role lately, and I wanted to get some...
0
2021-12-23T11:12:07
https://dev.to/peibolsang/the-mythical-fullstack-developer-2i5e
javascript, programming, webdev, career
--- title: The Mythical Fullstack Developer published: true description: tags: javascript, programming, webdev, career cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9qx4p8ovgbjv44ftikur.jpeg --- I have been thinking about the so-called *Fullstack Developer* role lately, and I wanted to get some things off my chest. I don't like the term. It is misleading, and more importantly, dangerous for entry-level developers who are joining our industry. The thing is that the term means different things for different people. On the one hand, it is used to describe the work of those backend developers who could move up the tech stack and do frontend work with HTML, CSS, and Javascript. But, *doing frontend work* or feeling comfortable with it is way different from being *good at it*. I am not saying that these individuals do not exist, I am sure they do, but they are rather exceptions who were presented with unique projects and opportunities to expand their skill spectra. In any case, I am still skeptical that someone is good at writing multi-thread management applications and CSS. In this context, the term *Fullstack Developer* by definition encloses some seniority and comes with a payload of discredit and underestimation of the frontend work. It is diminishing the relevance, importance, and careful thought needed to complete professional frontends in 2021. No matter what framework or architecture you use (SSG, SSR, SPA) ... you need **specialists** to take care of frontend work. On the other hand, the term's meaning started to shift recently due to the surge of serverless and infrastructure as a utility. Let me put it this way: > All architecture is design, but not all design is architecture. Architecture is when we make significant design decisions, where significance is measured by the cost of change. Where am I going with this? With serverless and the modern cloud, developers can make significant design decisions at a lower cost of change. In the past, with physical infrastructure and even IaaS, reverting a lousy design decision meant a complete refurbish of the servers and even contacting vendors to supply new material. Now instead, if you screw up your design by using AWS DocumentsDB because it is too costly, you can switch to AWS DynamoDB with way less cost of change. Also, if you decide to write an AWS Lambda function for some piece of work and find out that it does not scale well, moving it to AWS Fargate or ECS with auto-scaling is relatively more straightforward. What does this mean? It means that it is now way more accessible for frontend developers to step into the *structural design* work (aka Architecture). Does this make them fullstack developers, as many suggest? **No, it does not**. Similarly to my point above, if a given developer is good at CSS and NextJS and can decide how to deploy their stuff with serverless components, this does not make them a *Fullstack Developer*. I refuse to think that someone is still skilled at CSS, NextJS, and NoSQL database optimizations or event broking at a professional-grade level. The term here also comes with a payload of underestimating the importance and relevance of backend work. Again, I am not saying that these profiles do not exist as individuals in particular cases. However, I am skeptical about companies who use the term extensively in their job title architecture, especially when it comes preceded with the label *junior*. It just does not make sense. Since the term was originally coupled to the use of the MEAN/MERN stack, maybe what the community meant was just *JavaScript Developers*? Why didn't we use it? There is nothing wrong with that. If that is the case then, the term also denotes a bit of underestimation of the language as if it was a toy not ready for prime time. In any case, the fact that we could use the same programming language across the stack does not mean that one can be good at every stack layer. Even within the context of the same programming language, the term fullstack developer is not very accurate.
peibolsang
934,492
The many methods for using SVG icons
Recently at work, I ran into a situation where we had to revisit how SVG icons were being implemented...
0
2021-12-24T02:13:19
https://chenhuijing.com/blog/the-many-methods-for-using-svg-icons/
css, svg, webdev
--- title: The many methods for using SVG icons published: true date: 2021-12-23 05:53:22 UTC tags: css, svg, webdev canonical_url: https://chenhuijing.com/blog/the-many-methods-for-using-svg-icons/ --- Recently at work, I ran into a situation where we had to revisit how SVG icons were being implemented on our pages. And that gave me the opportunity to dig into the myriad of options we have for doing so. I thought this was worth documenting for future me (and maybe some of you who actually read this blog), because there are a LOT of options. ## As a pseudo-element via CSS ```css .a-cleverly-named-css-class { /* bunch of pretty styles, oh wow */ &::after { content: url('./some_icon.svg'); display: block; height: 1.5em; width: 1.5em; } } ``` This is good for icons that do not require modifications to the SVG itself (i.e. different colour?). If you look at the styles in the example above, we can modify the icon’s positioning and sizing but we will not be able to change the icon itself. The FAQ accordion uses this method at the moment. ## As a background-image on pseudo-element via CSS This is almost exactly the same thing as option 1 except that instead of using the SVG directly as the `content`, we attach it using `background-image` to the pseudo-element instead. ```css .a-cleverly-named-css-class { /* bunch of pretty styles, oh wow */ &::after { content: ''; display: block; height: 1.5em; width: 1.5em; background-image: url('./some_icon.svg'); background-position: initial; background-size: initial; background-repeat: initial; } } ``` This does allow slightly more control over the image because then you would have access to `background-position`, `background-size` etc. This approach does allow you to do what was usually done for sprite sheets, where all the icons were in a single image file. Developers then specified the “coordinates” of each icon based on the `background-position` and maybe `background-size` depending on the icon being specified. The main issue with both CSS approaches is that you cannot change the colour of the icon via CSS. There might be cases where your icons need to appear in different contexts, where they need to match different colours of content for example. If you are using monochrome icons, there is a solution to this. Some people might think this is hacky but I think it’s kinda smart. The trick here is using CSS filters to get just the right shade you want. And no, I cannot write the filters by hand, but there’s this filter calculator by [Barrett Sonntag](https://twitter.com/bsonntag) that can do it for us. {% codepen https://codepen.io/twhite96/pen/Pjoqqp default-tab=result %} You may or may not get the exact shade that you’re looking for, but odds are if you run the thing enough times, you can get something that’s close enough. ## Inline SVG rendered on the page itself ```html <a href="https://namu.wiki/w/Redd"> 음색 요정 휘인의 첫 번째 미니앨범 [Redd] <svg viewBox="0 0 24 24"><path d="M21 12.424V11a9 9 0 0 0-18 0v1.424A5 5 0 0 0 5 22a2 2 0 0 0 2-2v-6a2 2 0 0 0-2-2v-1a7 7 0 0 1 14 0v1a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 5 5 0 0 0 2-9.576ZM5 20a3 3 0 0 1 0-6Zm14 0v-6a3 3 0 0 1 0 6Z"/></svg> </a> ``` This approach allows us to modify the icon itself via CSS because `svg` and `path` are accessible to us via this inline approach. This might be fine for SVG files that have reasonably short path data but would litter the markup if more complicated SVGs are required. But it does allow very granular control with CSS classes. If you needed to animate the SVG, this is a pretty good option. But if you really don’t want to have the markup be so messy, another approach to inline SVG is via the `use` attribute, which allows you to reference an SVG shape from elsewhere in the file. You can also choose to place the SVG file somewhere else in your document and just reference the identifier. For multiple SVG icons, they can each be symbols without the main SVG element, and referenced with the hash symbol. This makes the markup much neater. ```html <!-- This is rendered but hidden with CSS --> <svg xmlns="http://www.w3.org/2000/svg"> <symbol id="icon-headphones" viewBox="0 0 24 24"> <path d="M21 12.424V11a9 9 0 0 0-18 0v1.424A5 5 0 0 0 5 22a2 2 0 0 0 2-2v-6a2 2 0 0 0-2-2v-1a7 7 0 0 1 14 0v1a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 5 5 0 0 0 2-9.576ZM5 20a3 3 0 0 1 0-6Zm14 0v-6a3 3 0 0 1 0 6Z"/> </symbol> </svg> <!-- Totally invisible, you're not supposed to know it's here… --> <a href="https://namu.wiki/w/Redd"> 음색 요정 휘인의 첫 번째 미니앨범 [Redd] <svg class="icon__headphones" aria-hidden="true" focusable="false"> <use href="#icon-headphones"></use> </svg> </a> ``` Regardless of how the inline SVG is implemented, this seems to be the preferred approach because it gives us full control over the styling of the icon. ## As an externally referenced image file The last option is to reference the SVG from an external file altogether. You might be thinking, isn’t this the same as the first option where you won’t be able to change anything on the SVG? Well, turns out there are _some_ things that are possible. Let’s say the icons are all in an SVG file named _icons.svg_. ```xml <svg xmlns="http://www.w3.org/2000/svg"> <symbol id="icon-headphones" viewBox="0 0 24 24"> <path d="M21 12.424V11a9 9 0 0 0-18 0v1.424A5 5 0 0 0 5 22a2 2 0 0 0 2-2v-6a2 2 0 0 0-2-2v-1a7 7 0 0 1 14 0v1a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 5 5 0 0 0 2-9.576ZM5 20a3 3 0 0 1 0-6Zm14 0v-6a3 3 0 0 1 0 6Z"/> </symbol> </svg> ``` It is possible to reference this external SVG file like so: ```html <a href="https://namu.wiki/w/Redd"> 음색 요정 휘인의 첫 번째 미니앨범 [Redd] <svg class="icon__headphones" aria-hidden="true" focusable="false"> <use href="icons.svg#icon-headphones"></use> </svg> </a> ``` Changing the colour of the icon via CSS is do-able because the fill property cascades in through the shadow DOM boundary as long as there is no existing fill attribute on the paths in the file, but you wouldn’t be able to modify individual paths like in the second option. The benefit of this approach is that the external file can be cached for performance gains, and if your use case only requires mono-coloured icons, this is a pretty good approach. But if you have multi-coloured icons, then you’re out of luck, and would probably have to use the second option. Learned about this approach from [SVG `use` with External Reference, Take 2](https://css-tricks.com/svg-use-with-external-reference-take-2/) by [Chris Coyier](https://chriscoyier.net/) and ended up going for this approach in my project. One thing to note is there might be CORS issues if you are serving assets from a different URL from your web page: [Understanding CORS and SVG](https://oreillymedia.github.io/Using_SVG/extras/ch10-cors.html). This is a problem I’m going to be facing, so we’ll see how that goes. ## As a mask layer with `mask-image` After I wrote up these methods, I read [Which SVG technique performs best for way too many icons?](https://cloudfour.com/thinks/svg-icon-stress-test/) by [Tyler Sticka](https://tylersticka.com/) and learned about the [mask-image](https://developer.mozilla.org/en-US/docs/Web/CSS/mask-image) approach. This is the CSS property that allows us to set an image as the mask layer for an element. So I guess this kind of falls into the first 2 categories of using CSS to do it, because I would most likely do this with pseudo-elements as well. ```css .a-cleverly-named-css-class { /* bunch of pretty styles, oh wow */ &::before { -webkit-mask-image: url('./some_icon.svg'); mask-image: url('./some_icon.svg'); background-color: forestgreen; height: 1.5em; width: 1.5em; } } ``` ## Wrapping up Given there are so many methods to implement the same thing, hopefully there is a technique available that suits your particular situation and use-case. Anywayz, stay safe, my friends! 😷
huijing
934,570
What is the difference between Node.js and React?
These two JavaScript frameworks are both popular, but they’re not quite the same thing. So what’s the...
0
2021-12-23T10:43:13
https://dev.to/deveshchauhan04/what-is-the-difference-between-nodejs-and-react-360l
node, react, programming
These two JavaScript frameworks are both popular, but they’re not quite the same thing. So what’s the difference between them? And how can you use each to your advantage? In this article, we’ll compare Node and React and explain when to use each one in order to create an awesome website or application. Let’s get started! **Why Node.js was created? ** Node.js was originally created by Ryan Dahl in 2009, with a goal of creating a platform that could enable developers to create real-time applications using JavaScript on both server and client sides. Since Node’s inception, it has been widely used for backend development (most notably for single page applications) because of its lightweight nature and asynchronous processing model as well as for its versatility in handling concurrent operations. Currently, Node has over 170K stars on GitHub! **How Node.js works?** Node.js makes it possible to build server-side applications using JavaScript outside of a browser environment, which is advantageous because browsers don’t support some of the more advanced JavaScript features like asynchronous callbacks and highly dynamic code execution. With Node, an application uses a library called Node Package Manager (npm) to install other packages from its community repository – npm currently hosts over half a million open source packages for use in applications built with Node. **About ReactJS** The library exposes a set of components and APIs that allow you to build applications using a declarative programming paradigm. As such, it enables you to separate your application's logic from its rendering, making it possible to test components in isolation of one another and thus easily reuse them within different contexts, which increases code maintainability while simultaneously reducing complexity by minimizing inter-component dependencies as well as runtime exceptions [source]. **Comparison of NodeJS and ReactJS** [Node.js vs react](https://devdojo.com/pixelcrayon2021/a-battle-of-nodejs-vs-react-which-is-better): One of these things is not like the other... but which one, you ask? Well, it depends on your needs, really. While they are both Javascript frameworks used for building apps and websites, each have different strengths that lend themselves to specific types of applications – so it’s best to take a look at how they compare before deciding on what framework might be best for your project! Also Read: [Node.js vs Python](https://www.pixelcrayons.com/blog/node-js-vs-python-which-is-better/)
deveshchauhan04
934,599
Roxait
Roxait Inc. is a software solution provider company that is focused on delivering high-quality...
0
2021-12-23T11:05:09
https://dev.to/roxait/roxait-2maa
Roxait Inc. is a software solution provider company that is focused on delivering high-quality experiences in Software Consulting, Cloud Uplifting, DevOps, DevSecOps, etc.
totochan
934,630
Top Salesforce Partners in 2022 for Successful CRM Implementation
The key to successful Salesforce implementation is meticulous planning, commitment, and in-depth...
0
2021-12-31T14:30:01
https://dev.to/naveenc65628676/top-salesforce-partners-in-2022-for-successful-crm-implementation-35e6
salesforcepartners, digitalcrm, crmimplementation
The key to successful Salesforce implementation is meticulous planning, commitment, and in-depth expertise about how business process affects customer experience. According to CIO, about one third of all CRM projects fail due to the absence of a robust project management framework. Salesforce has a comprehensive partner program that enables partners to build and grow successful businesses while delivering customer success. Hence, businesses must work with reliable Salesforce partners to derive value from their CRM implementations and maximize the return on their investment. With over 150,000 registered Salesforce partners in the ecosystem, choosing the right vendor can be a daunting task. In this article, we have outlined some steps to follow while selecting the right Salesforce consulting partner along with a top salesforce partners list, their capabilities and unique selling propositions. ## Who is a Salesforce Partner? Salesforce is a multinational software company offering easy to use, cloud-based CRM and business applications on a subscription basis. A Salesforce consulting partner is an enterprise authorized by Salesforce to develop and implement tailor-made solutions for their applications. Salesforce consulting partners are thoroughly trained to lead innovation, expand capabilities, and connect with their customers in new ways to meet their current and future needs. ### Salesforce categories its partners into three types: **Consulting partners or system integrators (SI)**: They use their experience and expertise to enable business growth and increase process efficiency. **AppExchange partners (ISV):** They are Independent Software Vendors (ISV) who research and develop innovative applications in AppExchange. **Resellers:** They sell Salesforce licenses but are not necessarily involved in the implementation process. The Salesforce consulting and AppExchange partners can be Base, Ridge, Crest, or Summit based on their trailblazer score across customer success, innovation, and engagement. <h2>List of the top Salesforce consulting partners in 2022</h2> **1. [Prodapt](https://www.prodapt.com/service/salesforce/)** Prodapt is a leading global technology consulting and managed services provider to the connectedness vertical. To meet the fast-growing demands of today’s telco customers, Communication Service Providers (CSPs) need to unify and simplify their processes. Prodapt enables next-gen technologies that help CSPs in their digital acceleration journey. Prodapt is a trusted Salesforce Crest Partner with 450+ certified professionals spread across 10 countries. As a strategic Salesforce partner, Prodapt helps global telcos to transform their customer engagement process. Prodapt’s team of 100% certified Salesforce consultants bring years of experience in successfully implementing digital transformations and co-creating innovation at scale. They offer end-to-end Salesforce consulting services for the cloud that involves developing applications, collaborating cloud applications, and supporting cloud solutions for the end-users. Prodapt’s expertise includes telco-specific Salesforce solutions, Salesforce Industries, Salesforce Integration (mulesoft) and Prodapt Solution Accelerators. **2. [10Pearls LLC](https://10pearls.com/salesforce-development/)** 10Pearls is a global digital development company, helping businesses with product design, development, and technology acceleration. They design and develop mobile and web applications for SME's and serve customers worldwide. Founded in 2004, 10Pearls is today a 1000+ workforce organization with offices in DC, New York, San Jose, Toronto, Dubai, Karachi, Lahore, Islamabad, and Medellin. 10Pearls is a leading Salesforce service provider helping businesses of all sizes build, customize, integrate with Salesforce applications. They offer Salesforce consulting, design, support, integration, and implementation services for businesses. Their team of technologists, developers, and consultants provide the resources to meet the specific needs of an enterprise and deliver Salesforce solutions that are right for a business. **3. [Deloitte](https://www2.deloitte.com/global/en/pages/technology/topics/salesforce-com.html)** With consultants in over 35 countries, Deloitte offers deep industry insight, proven customer experience solutions and Salesforce know-how. Deloitte’s industry-specific solutions and accelerators, powered by Salesforce, help businesses to be future ready. Deloitte offers custom Salesforce solutions through simplified market strategies, sales processes, and operating models that deliver optimal results. Deloitte’s deep industry knowledge and technical experience helps them to create assets that can quickly solve challenges and generate business value. They operate across sectors and industries, from human capital to life sciences, industrial products to consumer business, and financial services to media and telecommunications. They also offer government-specific Salesforce solutions through their Digital Government practice. **4. [Zensar](https://www.zensar.com/services/application-services/salesforce-services)** With over 10 years of experience, Zensar is a Salesforce Silver Consulting Partner with 250+ Salesforce certified consultants. They cater to clients in retail, financial services, insurance, manufacturing and hi-tech, transforming their CRM outcomes and driving business growth. Zensar’s expertise in CRM has helped them to design a comprehensive range of technology solutions to modernize legacy applications. Their extensive development experience on the Salesforce platform ensures pre-defined data models for solutions, reusable assets & accelerators, and rapid implementation for the clients. **5. [Accenture](https://www.accenture.com/us-en/services/accenture-salesforce-index)** Accenture is a multinational services company specializing in IT services and consulting with capabilities in digital, cloud and security. They have a strong workforce of more than 500,000 people worldwide across 50 countries. They operate more than 100 “innovation hubs,” for developing digital and cloud-based solutions for a broad range of industries. Accenture was among the early movers to form a strategic alliance with Salesforce and continues to strengthen its position as a leading Salesforce partner. The team of 10000+ Salesforce professionals, provide the full gamut of services from ideation to implementation to ongoing support. They are particularly suitable for large and more complex projects where business transformation is the primary goal. <h3>Tips to choose the right Salesforce consulting partner</h3> <h4>i) Select a Salesforce partner with relevant industry experience</h4> The Salesforce ecosystem is huge with several Salesforce consultants. Therefore, finding a partner that is the right fit for your business is a crucial step. The consulting partner with industry knowledge and experience of working on a similar project will be time as well as cost-effective. Proof of Concept (PoC), case studies, demos etc can help you understand the consultant’s domain experience. Large companies with complex IT structures must consider partnering with big consulting firms capable of handling tasks of such magnitude. Similarly, speciality partners with a good track record may be a good fit for smaller companies. <h4>ii) Look for Salesforce partner certification</h4> Salesforce certification is a critical aspect while selecting the salesforce implementation partner. Salesforce has an impressive certification program for Salesforce administrators, developers, consultants, and architectures. The certification is a great way to verify a partner’s credentials. <h4>iii) Assess business value, not just the costs</h4> Selecting the most economical partner will not necessarily save you money. Instead, consider looking for the most comprehensive partner who can provide the best value for your budget. Avoiding implementation delays is very important and, a time-efficient partner can provide a better return on investment. <h4>iv) Look for a long-term partner and continuous support</h4> Salesforce platform is constantly evolving and hence, it is important to have a consulting partner who can provide ongoing support even after the project period, both on-site and off-site. Similarly, seek a long-term alliance who are capable of proactively identifying potential risks and keeping up with evolving needs of the business. A continuous engagement will help save you costs and efforts. <h4>v) Use research to make informed decisions</h4> Do thorough research for understanding the different Salesforce services, comparing potential partners, identifying different implementation frameworks etc. These resources are extensively available on the internet as case studies, industry reports, blogs, reviews and more. You can also explore Salesforce forums and seek peer advice. Proper research will help you to chart realistic expectations and business goals for your Salesforce implementation project. <h3>Conclusion</h3> In order to improve the customer journey and provide superior business performance, one needs a unified salesforce ecosystem. An experienced Salesforce consulting partner can create an ideal pathway for organizational success be it for updating an existing system or implementing a new one.
naveenc65628676
934,731
Piano Chords
A post by HARUN PEHLİVAN
0
2021-12-23T14:31:29
https://dev.to/harunpehlivan/piano-chords-23fp
codepen
{% codepen https://codepen.io/harunpehlivan/pen/BaRZOXM %}
harunpehlivan
934,741
Piano example
A post by HARUN PEHLİVAN
0
2021-12-23T14:44:47
https://dev.to/harunpehlivan/piano-example-2hkj
codepen
{% codepen https://codepen.io/harunpehlivan/pen/VwbWGoQ %}
harunpehlivan
934,774
Countdown to New Year - [ Updated ]
Updated: - Improvement to view complete spin around the sun. - Earth Solar System sector centered...
0
2021-12-23T15:19:36
https://dev.to/harunpehlivan/countdown-to-new-year-updated--3460
codepen
<p>Updated: - Improvement to view complete spin around the sun. - Earth Solar System sector centered auto in screen. - Dates of all equinoxes and solstices. - Added leap year calculation.</p> {% codepen https://codepen.io/harunpehlivan/pen/NWjxmdy %}
harunpehlivan
934,946
Angular for Newbies III
glad to post the third post of angular newbies series to day we are going to talk about how to...
0
2021-12-23T16:08:56
https://dev.to/mhbaando/angular-for-newbies-iii-23o7
angular, javascript, beginners, webdev
glad to post the third post of angular newbies series to day we are going to talk about how to initialize angular project, along the way i will cover a lot of topics that i cant cover in one post like release cycle of the angular and so on. ## Installing Angular CLI to create new angular project you need to install globally on angular cli ! 🤔 But wait what is Angular CLI ?? **Angular CLI** : Angular command-line interface is where we put / write commands that executes our command, and don't worry i will cover Angular CLI in another series Promise ! 😀 **SO HOW DO WE INSTALL ANGULAR CLI ON OUR MACHINE** to install angular CLI you need to have - Node installed on you machine if go to this link and [download node](https://nodejs.org/en/) - And Code Editor, i will use [vscode](https://code.visualstudio.com/) choose your favorite editor after you successfully installed open your CMD / terminal / power shell depends on your operating system then type the following command ``` npm install -g @angular/cli ``` it will installed angular CLI Globally and **npm** is a package manager for the JavaScript programming language maintained by npm after successfully installed now we are ready to rock and roll 🙋‍♂️ Yeeeeey ! now let's setup our Angular Project, go to your desired destination / folder and open with terminal then type the following command ``` ng new your-Porject-Name ``` that simple commnad genertes the angular project for us ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2mbhwgdn6fg05hgq23vy.png) then asks you if you would like to add angular routing just choose no! will add it manually later, ![Terminal Screenshot for choosing the style](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/evkowcgulg7x9r5xxvrm.png) then asks you your preferred sylesheet just choose what ever you like css or other option i personlly like SCSS wlaaaaah ! you made you first Angular Project Congratulations 🎊 🎊 🎊 then let's See He Generates for Us ![vscode screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1870421kwh5cojccsvr9.png) as you see that simple command generated for a bunch of files DON'T BE AFRAID 😰 it is simple let see what each one is and what is do okay ... ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t5gj8l2687n0s24202gz.png) here are the folders and files inside our project **1. node_modules** : is where all our libraries and their libraries store and please don't edit them manually **2.src** this is our main folder where we edit delete and all the magic here like creating components, services , modules and so on this is where 99.99% work happens **3. browsersliststrc** this files holds the list of browser that our application support and is used by the build system to adjust javascript and css output to support our listed browsers there **again you dont need to edit this file** **4. editorconfig** this file holds the editor configuration it helps maintain consistent coding styles for multiple developers working on the same project across various editors and IDEs **5. gitignore** this file holds the list of items,files,folders that wont upload/save to the GIT **6. angular.json ** provides workspace-wide and project-specific configuration defaults for build and development tools provided by the [Angular CLI](https://angular.io/guide/workspace-config). **7. karma.conf.js** it holds the karma configurations and it is used for testing , to test it you app **8. package.json & package-lock.json** these files are provides us a starter set of packages, some of which are required by Angular and others that support common application scenarios. **9. the other three files** are files that configure the typescript since angular uses typescript Heeey you see easy isn't it so dont worry you will adapt these files and you will be expert soon enough Promise. hey that is it today you did an amazing job see you buddy 🖐 and stay health and please if you find this useful please share it to the others thanks
mhbaando
935,004
Let's know about Mongoose
Mongoose: MongoDB is a nosql, document oriented database program. It stores JSON-like documents with...
0
2021-12-23T16:56:12
https://dev.to/chayti/lets-know-about-mongoose-4p4i
database, mongoose, nosql, backend
**Mongoose:** MongoDB is a nosql, document oriented database program. It stores JSON-like documents with optional schema. But, Mongoose is an Object Data Modelling (ODM) for mongodb and nodejs. It manages relationships between data. It defines a schema for collections. **MongoDB VS Mongoose:** 1. DBMS VS Object Document Mapper 2. Stores data VS Manages relationship between data 3. Supports multiple languages VS Only mondoDB 4. Aim - Storing collection in DB VS Defining schema for collections. Mongoose defines schema and also validates it. It helps to structure the document for better presentation. It enables users to add/ edit properties easily. To use this, at first we have to install mongoose, like, ``` npm install mongoose --save ``` Once we define a schema, we can create a Model based on a specific schema in Mongoose. After creation of the model, a Mongoose Model is then mapped to a MongoDB Document and it is done via the Model's schema definition. The permitted schema types are: 1. Array 2. Boolean 3. Buffer 4. Date 5. Mixed (A generic / flexible data type) 6. Number 7. ObjectId 8. String **We can create a mongoose model by following 3 steps as:** **1. Referencing mongoose:** ``` let mongoose = require('mongoose') ``` **2. Defining the schema** ``` let newSchema = new mongoose.Schema({ variable_name: variable_type }) ``` **3. Exporting a model** ``` module.exports = mongoose.model(collection_name, schema_name) ``` **Basic operations of Mongoose are:** 1. Create record 2. Fetch record 3. Update record 4. Delete record **References:** 1. [Introduction to mongoose for mongodb](https://www.freecodecamp.org/news/introduction-to-mongoose-for-mongodb-d2a7aa593c57/) 2. [Mongoose crash course](https://www.youtube.com/watch?v=DZBGEVgL2eE) 3. [Reasons to use mongoose](https://www.stackchief.com/blog/Top%204%20Reasons%20to%20Use%20Mongoose%20with%20MongoDB) 4. [Mongoose tutorial playlist for beginner](https://www.youtube.com/playlist?list=PLNHw_0qv1zy_UEXiWaqSXiLSwwE8mjuj7) Mongoose documentation can be followed for detailed implementation.
chayti
935,083
AWS Lambda 101: How To Create an Endpoint for a Lambda Function Using API Gateway
In my previous articles in this series, I looked at setting up an AWS Lambda function and setting it...
16,113
2022-01-01T19:47:31
https://frankcorso.dev/aws-lambda-function-endpoint-api-gateway.html
python, datascience, aws
In my previous articles in this series, I looked at setting up an AWS Lambda function and setting it up on a recurring schedule. Another common use of a serverless function is connecting it to an endpoint to be able to send data to it or receive data from it. For example, maybe your server needs to fire off a request to a Lambda to trigger a new calculation. Or, maybe your web app needs to pull in data that is processed by a Lambda. In this article, I will set up a basic Lambda function that accepts two numbers, multiplies them together, and then returns the results. We will then connect this to an endpoint that we can send some JSON data to. If a user sends JSON with keys of `a` and `b` with both being a number, they will get back the result of the two multiplied. To do this, we will be using AWS's API Gateway to handle the endpoints. Let's get started! ## Writing the Code for our Lambda function To get started, let's write a very basic lambda handler: ```python def lambda_handler(event, context): return 'Something' ``` In order to use the numbers being sent to our Lambda function, we will need to use the `event` parameter. This parameter contains any data sent to the Lambda function. If we were triggering the Lambda function manually, we would use the `event` variable as an exact representation of the data. For example, if we had passed only the number 16 to the Lambda function, `event` would be equal to `16`. However, with the API Gateway endpoint, the event variable will include a variety of other data with the JSON sent being included within the body key. If we were to print our the `event` variable for a Lambda triggered by an endpoint, it would look like: ```json { "version": "2.0", "routeKey": "GET /testFunction", "rawPath": "/testFunction", "rawQueryString": "", "headers": {}, "requestContext": {}, "body": "{\"exampleJSONKey\": \"Random text\"}", "isBase64Encoded": false } ``` So, in order to get the JSON sent with the request, we will use `event['body']` but we will need to decode the JSON. This will look like this: ```python import json def lambda_handler(event, context): body = json.loads(event['body']) return 'Something' ``` For this example project, the Lambda function will be expecting the user to send in JSON with keys of `a` and `b` to be multiplied together. So, we can add then use these in the return like this: ```python import json def lambda_handler(event, context): body = json.loads(event['body']) return body['a'] * body['b'] ``` However, if someone sends in values that are not numbers, this will result in an error or unexpected results. So, we should create a small conditional to ensure both are valid numbers. ```python import json def lambda_handler(event, context): body = json.loads(event['body']) if not is_numerical(body['a']) or not is_numerical(body['b']): return 'One or both of the values are not a number' return body['a'] * body['b'] def is_numerical(value): """"Checks if value is an int or float.""" return isinstance(value, int) or isinstance(value, float) ``` Since the user is sending JSON to the endpoint, they would probably expect JSON as the response. Luckily, Lambda will automatically take care of this process if we return Python objects. So, we can update our returns: ```python import json def lambda_handler(event, context): body = json.loads(event['body']) if not is_numerical(body['a']) or not is_numerical(body['b']): return { 'error': 'One or both of the values are not a number' } return { 'result': body['a'] * body['b'] } def is_numerical(value): """"Checks if value is an int or float.""" return isinstance(value, int) or isinstance(value, float) ``` Lastly, the user would encounter a Lambda error if they are not submitting both `a` and `b`. So, let's add one last conditional to check that: ```python import json def lambda_handler(event, context): body = json.loads(event['body']) if 'a' not in body or 'b' not in body: return { 'error': 'You must provide keys for both "a" and "b"' } if not is_numerical(body['a']) or not is_numerical(body['b']): return { 'error': 'One or both of the values are not a number' } return { 'result': body['a'] * body['b'] } def is_numerical(value): """"Checks if value is an int or float.""" return isinstance(value, int) or isinstance(value, float) ``` Great! Our code is looking good so let's get this into a Lambda function. ## Setting Up Our Lambda Function First, let's go ahead and create a new Lambda function. If you've never set up one before, [check out my "How To Create Your First Python AWS Lambda Function" article](https://frankcorso.dev/python-aws-lambda-function.html). Inside the Lambda function admin area, paste the code above into the "Code" tab as shown below: ![Example AWS Lambda function with our sample code above entered into the code tab.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/scpvjeuhtud85dsl4haa.png) Click the white "Deploy" button right above the code to finish setting it up. Great, our Lambda function is now ready! ## Setting Up Our API Gateway Endpoint In API Gateway, there are many different types of APIs that you can create. Since we are creating a single endpoint, we will use HTTP API. However, there are many other types you could consider such as REST and WebSocket. Additionally, you can have each endpoint accept different HTTP request types, such as GET and POST, and you can also use "stages" to have different versions of each for development. To keep our endpoint simple, we will only use the default "stage" and accept all HTTP request types. To get started, in your AWS console, you can either click on "Services" to go to "Networking & Content Delivery"->"API Gateway" or use their search bar to search for it. ![The search bar in AWS showing "api gateway" in the search bar with a result of "API Gateway".](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ml1poex8dkcfi76rew6p.png) If you have not created any APIs yet in API Gateway, you will be directed to the page to select which type of API you want to build. If you already have created APIs click the APIs link in the left navigation menu and then click "build". In either case, select the "HTTP API" option. ![The API Gateway new API page. It shows an area to "Choose an API type" with several listed including HTTP API, each with a "Build" button.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ywvfeat229t9k46lr8f.png) Once on the "Create an API" page, add an integration and select Lambda. Once selected, you will be prompted to select which Lambda function. Underneath, name your API. I like to use something descriptive that is similar to the Lambda function's name. ![The first step to creating an API. This API has a "Lambda" integration with a Lambda function set as example endpoint function. The API name field is also filled in.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u4mhf1orn4lkdr0cq4ix.png) If you wanted to limit the HTTP request types allowed on this endpoint, the path for the endpoint, or the "stages" you can click "Next" to set those up. For this endpoint, I'll keep the defaults and click "Review and Create". On this page, we can verify the name, integrations, routes, and stages. ![The last step for creating an API. This API has example endpoint as the name with a Lambda integration.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/071by7gexx3v63k81qan.png) Click the "Create" button to finish creating this endpoint. Now, you will see the domain of this new API. ![A recap screen showing the API ID, stage, and invoke URL. There are links along the left for routes, throttling, authorization, and more.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dbug4plmhbn96ddonrjq.png) We can use this domain with our route to craft our final endpoint. For example, for the endpoint I created, the full URL is https://j485uzw9v0.execute-api.us-east-1.amazonaws.com/exampleEndpointFunction. If you do not remember what the route was, you can click the "Routes" link in the left navigation to see all routes on the API. Great, our endpoint is set up! ## Testing Our Endpoint Now, let's see it in action. Open your favorite API tester, such as [Postman](https://www.postman.com/). Create a new request with any HTTP method and paste in the full URL to your API route. Then, inside the body, create a new JSON object with keys of "a" and "b" and click send. You should see something like this: ![A Postman window showing a POST request to our URL with JSON in the body with a set to 12 and b set to 3. The result shows a JSON response with result set to 36.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7fmzlwnsgooz6x5a43ky.png) Then, try passing something instead of numbers or omit one of the fields to see one of the error messages like this: ![A Postman window showing a POST request to our URL with JSON in the body with a set to "Not a number" and b set to 3. The JSON response has an error key set to "One or both of the values are not a number."](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l3vs8o8t7nr8vrv4bq48.png) Great! Everything looks like it's working correctly. We have now successfully created a Lambda function that is accessible from a URL. ## Next Steps Now that you have set up a Lambda function and connected it to an API, you are on your way to creating new serverless endpoints that can accept and return data. In future articles, I'll look at safely passing credentials to it and adding other Python libraries to it. Be sure to follow to get notified when my next article is published!
fpcorso
935,084
Basic About React jS
1.What is JSX is React Ans:Full form of JSX is JavaScript XML. It allows us to write HTML in...
0
2021-12-23T18:49:53
https://dev.to/alaminhossain01052000/basic-about-react-js-651
1.What is JSX is React Ans:Full form of JSX is JavaScript XML. It allows us to write HTML in JavaScript without using the methods like appendChild(), createElement(). It is syntactic sugar of function calls. A browser can not understand a JSX syntax. So we need a transpiler to make it browser compatible. Babel works as a transpiler and converts the JSX to an object tree. The browser just receives the object tree and compiled it. 2. Describe Component Lifecycle in React Ans: There are three phases in react component life. Mount: Birth of component Update: Growth of a component Unmount: Delete or death of a component A react component has to pass through these phases. We need some methods to mount, update or unmount a react component. Mount: render(), componentDidMount(), constructor() Update: render, componentDidUpdate Unmount: componentWillUnmount 3.Tell me about differences of State-props in React Scope: Props are passed in components like function’s parameter. State only works in a component like a variable. Immutable: Props are immutable. It means it is only read-only. States are mutable. Use in class components: props is used like this.props and state is used like this.state in class component. Use in functional components: props are used as props and state is used like useState in functional component. 4.What do you know about Virtual DOM and diffing- algorithm Ans: Whenever a React Js web application is executed a virtual dom is created in primary phase of its execution. New dom check the changes with previous dom.When changes is detected two virtual dom is compared using diff algorithm and finally it allows changes in real dom. 5. What is Prop Drilling Ans: Passing parameters between components in react is possible in one way. A parent component can only pass a parameter to its immediate child component. But sometimes we need to pass parameters or props to many components. So here the word comes props drilling. Props drilling means not only passing data to a child component but also to other components. In react using context API we can easily pass data. There is a hook called useContext and method createContext and many other terms are used to props drilling 6.What do you mean by render() method Ans: render() method is used in every component of React Js. It returns the HTML which has to display in the UI. We only render a single element. If we want to render multiple elements we have to contain them in one parent tag. 7.What will you do to Prevent unnecessary component re-render Ans:Avoid changes in DOM tree structure. Using keys to prevent re-renders. Make sure that values are must not be changed. Using React.memo or React.PureComponent Use object as props 8. What is PropTypes Ans: Generally we use props for passing data between one component to another.But sometime because of wrong props and error is occurred and we can handle it by using proptypes.
alaminhossain01052000
935,238
283. Move Zeroes [Leetcode][C++]
All suggestions are welcome. Please upvote if you like it. Thank you. Leetcode Problem Link: 283....
0
2021-12-24T01:36:02
https://dev.to/mayankdv/283-move-zeroes-leetcodec-3n66
cpp, algorithms, leetcode, programming
**_All suggestions are welcome. Please upvote if you like it. Thank you._** --- [Leetcode Problem Link: 283. Move Zeroes](https://leetcode.com/problems/move-zeroes/) --- **_Brute Force Solution:_** ```javascript class Solution { public: void moveZeroes(vector<int>& nums) { // Brute Force Solution Time O(N) & Auxiliary Space O(N) vector<int> a; int count=0; for(int i=0;i<nums.size();i++){ if(nums[i]==0) count++; else a.push_back(nums[i]); } while(count--) a.push_back(0); for(int i=0;i<nums.size();i++){ nums[i]=a[i]; } } }; ``` **_Efficient Solution:_** ```javascript class Solution { public: void moveZeroes(vector<int>& nums) { // Efficient Solution Time O(N) & Auxiliary Space O(1) int lt=0,rt=0,n=nums.size(); while(rt<n){ if(nums[rt]==0) rt++; else{ int temp=nums[lt]; nums[lt]=nums[rt]; nums[rt]=temp; lt++; rt++; } } } }; ``` **_All suggestions are welcome. Please upvote if you like it. Thank you._**
mayankdv
935,340
Bảng giá sàn gỗ công nghiệp Malaysia mới nhất 2022
Sàn gỗ công nghiệp Malaysia luôn là sự lựa chọn của nhiều người bởi sự phù hợp với các loại không...
0
2021-12-24T04:12:45
https://dev.to/sangocongnghiep/bang-gia-san-go-cong-nghiep-malaysia-moi-nhat-2022-49ld
Sàn gỗ công nghiệp Malaysia luôn là sự lựa chọn của nhiều người bởi sự phù hợp với các loại không gian khác nhau như nhà ở hay văn phòng công ty. Chúng sẽ khiến không gian của bạn trở nên sang trọng và hiện đại hơn. Trên thị trường hiện nay có nhiều loại sàn gỗ công nghiệp Malaysia, với đặc tính và giá cả khác nhau. Để dễ dàng lựa chọn loại sàn gỗ Malaysia phù hợp, chúng tôi gửi đến khách hàng **[bảng giá sàn gỗ công nghiệp Malaysia](https://sangocongnghiepcaocap.com/tu-van/bang-gia-san-go-cong-nghiep-malaysia-moi-nhat.html)** mới nhất hiên nay và luôn được cập nhật liên tục. ## Đôi nét vế sàn gỗ công nghiệp Malaysia Cấu tạo của sàn gỗ công nghiệp Malaysia Sàn gỗ công nghiệp Malaysia được cấu tạo từ 4 lớp: Lớp trên cùng – Lớp phủ bảo vệ chống mài mòn: Có độ bóng cao nhất, có khả năng chống hơi ẩm với chỉ số IP trên mức trung bình Lớp thứ 2 – Phim trang trí: Sàn gỗ công nghiệp Malaysia được thiết kế hiện đại, đa dạng về màu sắc và phong cách. Các vân gỗ được thiết kế tự nhiên nhất, không bị giả. Lớp thứ 3 – Lõi (HDF): Sàn gỗ công nghiệp Malaysia có độ bền cao và thân thiện với môi trường, độ trương nở của sàn gỗ thấp dưới 8% Lớp 4 – Lớp dưới cùng: Độ co dãn ổn định và chống ẩm tốt. Sàn gỗ công nghiệp Malaysia có bền không ? Trên thực tế, sàn gỗ công nghiệp Malaysia có độ cứng tương đương (cứng hơn) sàn gỗ thật. Bởi vì lõi bên trong sàn gỗ được làm từ ván sợi có mật độ cao và được nén dưới áp suất cực lớp. Bên cạnh đó, lớp trên cùng của sàn gỗ công nghiệp Malaysia còn dược phù bằng axit nhôm, một trong những lớp phủ cứng nhất hiện nay. Sàn gỗ công nghiệp Malaysia có bền không ? Sàn gỗ công nghiệp Malaysia rất được ưa chuộng hơn trong các khu dân cư hoặc khu thương mại có đông người qua lại. Chúng sẽ không bị xước hoặc phát ra tiếng nếu bạn thường xuyên đi lại. Bên cạnh đó, giá sàn gỗ công nghiệp Malaysia cũng khá rẻ nên được nhiều gia chủ tin dùng. Sàn gỗ công nghiệp Malaysia có dễ bám bẩn không ? Sàn gỗ công nghiệp Malaysia không bị phai, ố và có khả năng chống mài mòn cao. Màu sắc của sàn sẽ giữ nguyên qua thời gian dài. Lớp bề mặt của nó cũng miễn nhiễm với vết cháy của thuốc lá trong khi các vết bẩn vĩnh viễn có thể dễ dàng làm sạch bằng nước lau sàn thông thường. Sàn gỗ Malaysia có đắt không ? Đây là một vấn đề được rất nhiều gia chủ quan tâm. Trên thực tế, sàn gỗ công nghiệp Malaysia có mức giá tầm trung, ngang bằng với giá sàn gỗ công nghiệp Việt Nam, ở vào khoảng 200.000 VNĐ – 300.000 VNĐ trên 1m2, tuỳ thuộc vào các thương hiệu khác nhau. ## Cách chọn sàn gỗ công nghiệp Malaysia phù hợp với bạn Để lựa chọn được sàn gỗ công nghiệp Malaysia phù hợp với không gian của bạn, bạn cần phải lưu ý các đặc tính sau: Độ dày của sàn gỗ công nghiệp Độ dày của sàn gỗ công nghiệp được chia làm 2 loại là 8mm và 12mm. Độ dày của ván sàn gỗ quyết định độ bền tổng thể của sàn nhà. Sàn dày 8mm phù hợp cho các ngôi nhà, trong khi sàn dày 12mm rất lý tưởng cho những nơi có nhiều người qua lại như văn phòng công ty, quá ăn,…vì chúng có AC5 Tiêu chuẩn AC AC (Abrasion Criteria) hiểu một cách đơn giản là tiêu chuẩn đo khả năng chống mòn của sàn gỗ. Thang đo AC có từ AC1 đến AC6: Đối với sàn nhà bạn nên chọn AC3 Đối với nơi có đông người đi lại nên chọn: AC4, AC5 Không nên lựa chọn AC1 hay AC2 vì chất lượng sàn gỗ loại này không đảm bảo, dễ bị hỏng, tuổi thọ trung bình rất kém bang gia san go cong nghiep malaysia moi nhat 2 Tiêu chuẩn AC của sàn gỗ công nghiệp Malaysia Bề mặt sàn gỗ công nghiệp Có rất nhiều loại bề mặt sàn gỗ công nghiệp Malaysia khác nhau. Do đó, khi lắp đặt sàn gỗ công nghiệp cho không gian của bạn nên lưu ý đến màu sắc và hoa văn có phù hợp với không gian của bạn hay không ? Tránh việc sàn gỗ đối lập với thiết kế nội thất trong không gian của bạn. Đặc tính sàn Mỗi loại sàn gỗ công nghiệp Malaysia đều có những đặc tính khác nhau. Các đặc tính chủ yếu nhất mà bạn có thể thấy là chống va đập, chống thấm nước, chống ố. Tuỳ theo không gian của bạn mà chọn sàn gỗ có đặc tính phù hợp Bảng giá sàn gỗ công nghiệp Malaysia Sàn gỗ công nghiệp Malaysia có mức giá tầm trung với nhiều loại khác nhau. Dưới đây là bảng giá sàn gỗ công nghiệp Malaysia Nhìn chung, sàn gỗ Malaysia có mức giá tầm trung, phù hợp với điều kiện của các gia đình nhỏ. Khi so sánh giá các thương hiệu sàn gỗ khác nhau thì sàn gỗ Malaysia là một lựa chọn không tồi. Trên đây là báo giá các loại sàn gỗ công nghiệp Malaysia, nếu có bất kỳ thắc mắc nào về sàn gỗ công nghiệp Malaysia, hãy liên hệ với ngay với chúng tôi, Sangocongnghiepcaocap.com sẽ tư vấn cho bạn.
sangocongnghiep
935,402
I have completed my Advent of UI Components
This year I decided to make my own version of Advent of code. So I thought it would be nice to share...
0
2021-12-24T06:26:50
https://dev.to/starbist/i-have-completed-my-advent-of-ui-components-39kg
html, css, showdev, webdev
This year I decided to make my own version of Advent of code. So I thought it would be nice to share one UI component a day. {% twitter 1474263655118168065 %} Every day I shared one component and how I built it. I used a lot of shiny new stuff from the CSS world. Here's the project: https://www.silvestar.codes/side-projects/. Happy holidays!
starbist
935,457
I created my first portfolio website using webflow
Info ! How are you all? Welcome back to another post, actually this is not a post I am...
0
2021-12-24T06:54:40
https://dev.to/sehgalspandan/i-created-my-first-portfolio-website-using-webflow-2957
webdev, beginners, programming
#Info ! How are you all? Welcome back to another post, actually this is not a post I am posting it to give a info to you all. I have created my portfolio website using WebFlow so be sure to check it out [Website]("https://spandyboss-portfolio.webflow.io/") and do tell me how was it . That's it for today, thanks for reading. Bye bye Stay safe and do take very good care of yourselves.
sehgalspandan
935,484
What kinds of companies hire freelance Java developers?
Hiring a freelance java developer is a good option for companies with a significant number of...
0
2021-12-24T07:46:05
https://dev.to/vikas044/what-kinds-of-companies-hire-freelance-java-developers-1hcj
javascript, java, development
Hiring a freelance [java developer](https://eiliana.com/blogitem/how-to-embrace-java-at-low-cost-by-hiring-dedicated-java-developers) is a good option for companies with a significant number of projects and need support. Freelancers are also great for companies that do not need full-time employees, as they can work remotely when needed. Companies tend to hire freelancers because they don't provide the same benefits as employees and often lack some of the stability and longevity offered by full-time hires. Companies looking for Java developers include: Businesses that rely on technology to bring in revenue Businesses that social media managers or marketing professionals run. These professionals need Java developers to help them create and maintain the website. Associations and organizations that want to use social media platforms like Facebook and tools used by online marketers such as email marketing services. Java developers freelancers are in high demand these days as many companies are looking to outsource their projects to save on costs and offload the management aspect too. Companies that hire Java freelancers include technology giants like Microsoft, Amazon, and Oracle to large enterprises in different industries. Many companies are hiring java developers because they need to develop digital products like mobile apps and websites. These companies need the flexibility that freelancers offer and the ability to take on multiple projects simultaneously. Project-based companies such as e-commerce websites, technology startups, and mobile apps could use Java software development skills for their projects. For example, a tech startup may use Java to develop its web application. They may also use Java as a platform language to build web games or mobile applications. Non-project-based companies such as marketing agencies and law firms may need Java skills to develop new content or campaigns for their core business activities. Eiliana can help you connect with quality clients and companies and get you hired!
vikas044
935,620
How to promote your software projects efficiently?
Put it on developer platforms and share it on Social Media If you have an open source project, get...
0
2021-12-24T10:50:29
https://dev.to/trystancocolatte/how-to-promote-your-software-projects-efficiently-4o2o
webdev, programming, tooling, productivity
Put it on developer platforms and share it on Social Media If you have an open source project, get yourself on services like GitHub and Open Hub. Be creative and get an entry on all well-known developer platforms. Put the website in your signature of forums, and remember don’t spam. Here are some recommended social media platforms: Facebook, Twitter, Linkedin, Reddit, Dev.to, Lobsters, Hacker News, Product Hunt, Beta page, Human Coders. Make your projects easy to use Do you like software that is difficult to use and install? No way, because that would waste time. But, in most cases, you'll need to read the documentation and install it locally according to the prompts, which often takes a few dozen minutes or even more time. If It's very difficult to read, or missing some key information, it may waste a lot of time and fail to install. So my suggestion would be to test your software from the beginning, and take user experience into consideration. Advanced usage of the tool Visitors will want to know what your project is for, how it works, and how to use it right away. The common practice is to provide a demonstrating GIF or video demo. More importantly, you can also use development tools like [Tin](https://www.teamcode.com/docs/tin/what-is-tin/), so that other people can try your projects with one click. Create clean and well structured documentation Creating a good documentation is probably the most important step. If you have a small documentation, you can include it within your README. Otherwise, you should probably host it in a separate website. Some open source projects like vuepress can help you creating clean documentation in a simple way. Keep your projects up-to-date People don’t like to use outdated projects. A project that was updated more than 1 year ago, will lose new users. It shows that it is not maintained. Determine a release schedule in advance and update your projects and user manuals accordingly. Try to regularly release new versions of your project. Show people that the software is maintained and be careful with the usage of dates.
trystancocolatte
940,351
2nd part MBS.works — The Year of Living Brilliantly
2nd part MBS.works — The Year of Living Brilliantly This is the second article about...
0
2021-12-30T13:21:01
https://medium.com/swlh/2nd-part-mbs-works-the-year-of-living-brilliantly-cf1429bb760e
leadership
--- title: 2nd part MBS.works — The Year of Living Brilliantly published: true date: 2021-12-23 07:30:00 UTC tags: leadership canonical_url: https://medium.com/swlh/2nd-part-mbs-works-the-year-of-living-brilliantly-cf1429bb760e --- ### 2nd part MBS.works — The Year of Living Brilliantly This is the second article about [**_MBS.works — The Year of Living Brilliantly_**](https://www.mbs.works/products/the-year-of-living-brilliantly) that contains the next 17 lessons of the program. Just like in [the first one](https://magdamiu.com/2021/05/14/mbs-works-the-year-of-living-brilliantly/), I added my notes for each session, plus references to learn more about the person who is talking about that topic. ![](https://cdn-images-1.medium.com/max/1024/0*DLiQ_ifv4hjalirn) ### 18. How to Start Your Day **Neil Pasricha** => You can learn more about Neil and his work at [https://www.neil.blog/about-neil#](https://www.neil.blog/about-neil#) or by following him on Instagram, Facebook, or Twitter [@neilpasricha](https://www.instagram.com/neilpasricha). Neil shares with us the idea to have a notebook and write down one thing you want to get done every day. And at the end of the day check if you managed to finish that thing. Also use the same notebook to write 5 tiny specific things that you are grateful for, plus 5 things that make you angry and anxious. He recommends us a two-minute exercise called “Two-minute Mornings” and it is about starting your day by asking yourself 3 questions: 1. **I will let go of**. This is the anxiety thing. 2. **I am grateful for**. These are the few little things I can be happy about, specific gratitudes from my day. 3. **I will focus on**. Remember that’s how my cue card started first. It was just one thing I was going to do every day. ### 19. How to Notice Your Advice Monster **Mark Bowden** => Find out more about Mark and his work at [truthplane.com/home/people/mark-bowden/](https://truthplane.com/home/people/mark-bowden/) or by following him on Twitter [@truthplane](https://twitter.com/truthplane). Notice when you get triggered by the environment to give advice and be aware of your feelings, behavior, non-verbal. When you notice that you are tense and you are prepared to give advice, work to moderate yourself. Moderate your gestures and focus on listening to the person in front of you and asking helpful questions. interlace your fingers, place them over your navel, stand up straight, tilting your head to one side, have a gentle smile, and listen. Try to have this posture every time you feel the need to give advice and it is not the case. ### 20. How to See Other Perspectives **Dr. Elizabeth Kiss** => Find out more about Dr. Kiss’ work at [www.rhodeshouse.ox.ac.uk](https://www.rhodeshouse.ox.ac.uk/) or on Twitter [@rhodes\_trust](https://www.twitter.com/rhodes_trust). Stop, breathe and listen. The research shows that diverse teams, teams of people with different backgrounds and perspectives, teams that have men and women, so gender diversity, teams that have racial diversity, are more effective at solving problems. When you get a different perspective than yours for sure it is not comfortable but you should stop, breathe and listen. Try to understand if that perspective will lead to wiser, richer, fuller decision-making. ### 21. How to Discover the Rules **Kevin Kruse** => Find out more about Kevin and his work at [www.leadx.org](https://www.leadx.org/) and follow him on Twitter [@LEADxLife](https://twitter.com/leadxlife) and [@Kruse](https://twitter.com/kruse). Be curious about the rules of your life. Great leaders have no rules. It is not about being a rebel, it is about having as few rules as possible. You want a few rules because it will allow you to make your choice. Work to understand why some rules exist, be curious about them, have conversations about them with your team, and see if they are still relevant. ### 22. How to Allow Innovation to Blossom **Dr. Simone Bhan Ahuja** => Find out more about Simone and her work at [www.blood-orange.com](https://www.blood-orange.com/) and follow her on Twitter [@simoneahuja](https://www.twitter.com/simoneahuja). Dr. Simone Bhan Ahuja talks about how to support more innovation by becoming a learning organization, and doing this by encouraging humility, empathy, and curiosity. The foundation of innovation is learning about your customers, about their needs, about what’s working and what’s not, having to know all the answers is going to make the possibility of meaningful innovation take a dive. There are 3 steps that could be followed to build a learning organization and more innovation: 1. Making learning a priority 2. When in doubt test it out 3. Measure the new ROI, return on intelligence. ### 23. How to Have an Idea that Works **Alexander Osterwalder** => Find out more about Alex and his work at [strategyzer.com](https://strategyzer.com/) and follow Alex on Twitter at [@alexosterwalder](https://www.twitter.com/alexosterwalder). There are 2 worlds inside of an organization: managing the existing and inventing the new and as a leader, you should be aware of them to apply the right mechanisms. Managing existing is about predictability. When you create something new, what is hard is to get that idea and create value for your organization and customers through it. Test your idea as soon as possible and make sure you do not apply the rules available for managing existing work. ### 24. How to Be Grateful **Darryl Slim** => You can learn more about Darryl and his work by visiting [darrylslim.com](https://darrylslim.com/) Touch and listen. The core of his teaching is “listen and touch” to our hearts. He calls the heart the natural spring water. ### 25. How to Be Empathetic **Dan Pontefract** => Find out more about Dan and his work at [danpontefract.com](http://www.danpontefract.com/) and by following Dan on Twitter at [@dpontefract](http://www.twitter.com/dpontefract). Empathy comes in three forms: - Cognitive empathy (head) — Where’s their headspace? How are they thinking about that? - Emotional empathy (heart) — How are they feeling? - Sympathetic empathy (hands) — you can sympathize with them and then take action. “Hey, is there anything I can do to take that off your plate?” ### 26. How to Understand the Context **Dave Stachowiak** => Find out more about Dave and his work at [coachingforleaders.com](https://coachingforleaders.com/) or on LinkedIn [@davestachowiak](https://www.linkedin.com/davestachowiak). When people complain about some things or try to describe a situation a good question to understand the context of the situation is “What’s a time that happened, recently?” If you try to understand, to coach them, it is important to understand the context to know how to lead the conversation and if it is the case to offer the right possibilities or ideas. ### 27. How to Be More Influential **Dorie Clark** => You can learn more about Dorie at [dorieclark.com](https://www.dorieclark.com/) and follow her on Twitter [@dorieclark](https://www.twitter.com/dorieclark). How you can grow your influence by positioning yourself as an expert: **Willing to share your ideas publicly:** - Speak up more in meetings and make sure that people know what you’re thinking, what’s on your mind - Do a lunch-and-learn and share those experiences so that others can benefit from them - Stepping up and raising your hand and volunteering to speak at a conference or a convention **Social proof:** - Volunteer as a leader in your local professional association - Volunteer as a committee on cross-departmental initiative - Be part of alumni associations **Your network:** - Can you even just once a week, have a coffee, have a phone call, have lunch with someone who is outside your company or outside of your industry? ### 28. How to Know Exactly What to Say **Phil Jones** => You can find out more about Phil and his work [philmjones.com](https://www.philmjones.com/) and by following him on social [@philmjonesuk](https://www.instagram.com/philmjonesuk/). The person in control of every conversation is the one who’s asking the questions. Questions create conversations, conversations lead to relationships, relationships create opportunities, and only opportunities lead to action. Think about the regular questions that are asked of you, plan your words out ahead of time, respond to those questions with questions that create more clarity. With clarity comes certainty, with certainty comes growth. ### 29. How to Say No **Sanyin Siang** => Find out more about Sanyin and her work at [coachsanyin.com](https://www.coachsanyin.com/) and follow her on LinkedIn [/sanyin](https://www.linkedin.com/in/sanyin/). We don’t like to say no because we want to help people. Being able to say no in the right way and in an intentional way can be precisely what’s needed for us to be able to help others. How to do that: - Respond with “not yet” — it is important, but I will help you later when I will have the necessary time to bring the best from that situation/task/activity - “Can I bring someone else along?” or “Can I bring someone else, can I do it with someone else?” - “I may not be the best person for this because the expertise you’re looking for, I’m not the best fit for that, but let me recommend someone who’ll be a perfect fit”. ### 30. How to be a Host **Marshall Goldsmith** => Find out more about Marshall and his work at [marshallgoldsmith.com](https://www.marshallgoldsmith.com/) and by following him on LinkedIn [/marshallgoldsmith](https://www.linkedin.com/in/marshallgoldsmith/). Marshall Goldsmith shares that his coaching process is about teaching and connecting people with similar responsibilities. He allows his clients to help each other, to be empathetic, and share knowledge and ideas in a safe environment. He facilitates all of these. ### 31. How to Scale **Fiona Macaulay** => You can find out more about Fiona and her work at [WILDleadershipforum.org](http://www.wildleadershipforum.org/) or by following her on Twitter [@F\_macaulay](https://www.twitter.com/f_macaulay). Fiona talks about the fundamentals of leadership for founders so that you can take your idea to scale and not burn out in the process. When you feel overwhelmed about the things you should do, remember to ask yourself: _“What’s most important now?”_. This question will help you to prioritize your work and will keep you focused. Your goal is to ensure that you’re leading yourself from the very beginning with compassion and honesty and self-care. ### 32. How to Forgive **Desiree Adaway** => Find out more about Desiree and her work at [desireeadaway.com](http://desireeadaway.com/) and follow Desiree on Instagram or Twitter [@desireeadaway](https://www.instagram.com/desireeadaway/). Forgiveness and reconciliation are essential for creating cultures because they build safer, braver, and more peaceful organizations. Forgiveness needs to be practiced in combination with accountability, governance, transparency, with truth-telling. Forgiveness always has to be intentional, it always has to be voluntary, and it always has to be a deliberate decision that we make. Forgiveness is really about individual healing. Reconciliation is about restoring relationships. Reconciliation is the social process to acknowledge the past hurts and suffering. Forgiveness is possible without reconciliation, but reconciliation is not possible without forgiveness. We have to do both. Forgiveness is that individual healing and reconciliation is that social healing that has to happen before you can move on. ### 33. How to Access Curiosity **Liz Wiseman & Shawn V** => You can find out more about Liz and her work at [thewisemangroup.com/](https://thewisemangroup.com/) or by following her on [Twitter](https://twitter.com/lizwiseman). Good leaders should ask questions and not give answers. The art of asking questions is an important skill of a leader. How to build your own set of back pocket questions: 1. **Brainstorm your favorite questions:** - Write down five of your favorite questions that you tend to use when you want to engage people in solving problems, think through challenges, tap into new thinking and open up innovation and creativity, or just gain commitment. - After the list is done, review them and select your best three. **2. Inspire yourself from the questions presented by Liz and Shawn:** - Sample of go-to questions - “What does this look like from your perspective?” - “What am I not seeing that’s important for me to understand?” - “What are the risks or the downsides?” - “What are we assuming that just might not be true?” - “Are there any reasons why we shouldn’t proceed?” **3. Inspire yourself from the questions addressed by your colleagues** - Listen for questions that you like or questions that you noticed to bring results and great ideas or answers **4. Use the collected set of questions** - Make sure you have added the questions in a known place and use them because they will help you tell less and ask more. And when you as a leader ask more, you’re going to get more from others, more insight, more capability, more ownership. ### 34. How to Find the Story **Pat Flynn** => You can find out more about Pat and his work at [smartpassiveincome.com/about/](https://www.smartpassiveincome.com/about/) or by following him on Twitter or Instagram [@patflynn](https://twitter.com/PatFlynn). Every time you speak with somebody, especially if there’s a problem that arises or even a suggestion or feedback, you should find the story. Ask that person: “Well, tell me the story behind that.” By knowing the story you can understand better the context, you could empathize with that person and allow you to understand what they are looking for, versus what they might be just asking for. Happy reading! 🤓 _Originally published at_ [_http://magdamiu.com_](https://magdamiu.com/2021/12/23/2nd-part-mbs-works-the-year-of-living-brilliantly/) _on December 23, 2021._ * * *
magdamiu
940,499
Scalable CRON job executor for AWS Lambda
Running scheduled jobs at scale in the cloud is an interesting problem to solve. In this post I will...
0
2021-12-30T14:41:02
https://dev.to/chrismore/scalable-cron-job-executor-for-aws-lambda-3p98
aws, devops, cloud, serverless
Running scheduled jobs at scale in the cloud is an interesting problem to solve. In this post I will describe an architecture we came up with at [Fusebit](https://fusebit.io/) that allows us to execute a large number of arbitrarily scheduled CRON jobs in AWS using Lambda, SQS, and CloudWatch. ## The problem Say you are building a large-scale, multi-tenant system where tenants define programmatic jobs to be executed in the cloud on a given schedule. You have a large number of such jobs, each with a potentially different execution schedule. In the context of [Fusebit](https://fusebot.io/), we needed a solution to this problem to enable customers of our integration platform to implement and run integration logic on a given schedule. For example, to export new leads from HubSpot to MailChimp every night, or to send a status report based on Jira tickets to Slack every hour. The non-scalable CRON solution We have decided to use AWS Lambda to run the customer-provided logic. While Lambda is not an ideal compute layer for all types of integration workloads, in our case it satisfied the functional requirements while providing a convenient way of scaling and isolating workloads of multiple tenants. Once the infrastructure was in place to run the customer code, the next step was to trigger it on a customer-defined schedule. There are many ways to trigger execution of a Lambda function in AWS. One of them uses [scheduled CloudWatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html). On the surface, CloudWatch Events meet all the requirements. You can define an arbitrary CRON schedule following which a CloudWatch Event will be triggered, and attach a specific Lambda function to execute in response. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmpwroo7swzepf5s8l5n.png) ## Non-scalable CRON executor for AWS Lambda The problem with using CloudWatch Events in a highly scalable system is the limits. Per AWS region and account, one can only support up to 100 scheduled events (as of this writing), which was not sufficient to support the needs of a highly scalable multi-tenant system. We clearly needed a different approach. The scalable CRON solution After looking around for the right building blocks, a lesser known feature of Amazon SQS drew our attention: [SQS delay queues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-delay-queues.html). The feature enables a message published to an SQS queue to remain invisible to consumers for a configurable time, up to 15 minutes. Equipped with this new tool, we have split our CRON processing pipeline by adding SQS delay queues in the middle, and using two additional Lambda functions: a scheduler and an executor. First, we defined a single scheduled CloudWatch Event that triggered the scheduler Lambda function every 10 minutes, starting at minute 8 of an hour. So the scheduler Lambda was running at minute 8, 18, 28, 38 etc. of every hour. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hm018j3np174hzywtd27.png) ## Scalable CRON executor for AWS Lambda The purpose of the scheduler Lambda was to consider all scheduled jobs in the system (possibly millions), and select those that were due for execution in the subsequent whole-10-minute interval. For example, if the scheduler Lambda was running at 3:18, it would determine all scheduled job executions that need to occur in the 3:20-3:30 time span. The scheduler Lambda would then enqueue those job definitions to the SQS queue, setting the delayed delivery for each to correspond to the exact intended moment of execution of that job. For example, if a job was to run at 3:24, the scheduler Lambda running at 3:18 would enqueue that job to SQS setting the delayed execution to 6 minutes. The granularity of delayed execution allows the execution time to be set with 1 second precision. Lastly, the executor Lambda would consume messages from SQS as they are released following their delayed delivery settings. The executor Lambda would then invoke the appropriate customer-defined Lambda function to execute the intended logic. With this architecture, we were able to use a single CloudWatch Event to schedule a very large number of jobs and support our scheduled integration needs. ## Shameless plug This is just one of many interesting technical problems we are continuously solving when building the integration platform at [Fusebit](https://fusebit.io/). If you enjoy working on developer-centric products and cracking this type of technical problems on a daily basis and in a good company, we are hiring. Also, if you need code-first integrations and connectors to 3rd-party SaaS platforms, check out our [integrations](https://fusebit.io/integrations/).
chrismore
940,525
How to Add User Authentication in Magento
How to Add User Authentication in Magento Before using the API, the system will ask you to...
0
2021-12-30T15:22:51
https://dev.to/alexhusar/how-to-add-user-authentication-in-magento-55p6
programming, react
# **How to Add User Authentication in Magento** Before using the API, the system will ask you to authenticate. Why do you need user authentication in Magento? It helps to protect data from unwanted third-party users. Authentication allows Magento to determine the caller’s user type and the rights to access API requests. We make sure that the user has the required privileges, for example, to edit the product catalog or configure any other feature on your website or [Magento headless commerce solution](https://onilab.com/blog/magento-headless-commerce-explained/). In this post, I’ll go through the Magento 2 API [authentication process](https://dev.to/propelauth/understanding-user-authentication-from-scratch-3pl2). I will talk about Token, OAuth, and Session Authentication. But before we start, I’ll introduce you to Magento. ## **Short Introduction to Magento** Magento is an eCommerce engine aiding medium-sized and large online businesses in the creation of a distinctive shopping experience. Magento is a PHP-based open-source platform currently owned by Adobe. It means you can change and customize it to meet your specific requirements. This platform stands out because of its flexibility in terms of custom development and idea feasibility. However, it lacks a built-in visual editor, making it difficult for newbies. Because Magento is a platform for expert users, you’ll almost certainly need to employ a Magento development service provider to get a store up and operating. Managing a store isn’t difficult. When you put everything up, you can add new categories, pages, and products, as well as change them directly in the admin panel. You may use it to manage add-ons, create templates, and much more. You can download and configure Magento’s Open Source edition for free, which is the choice for [83% of Magento stores](https://litextension.com/blog/magento-2-review/). However, if you require more advanced features, you can upgrade to paid Magento Commerce edition or Magento Commerce Cloud. Magento is a powerful solution for large businesses with a high volume of visitors and a high turnover. For example, Magento Commerce can handle 350 million catalog views and 487,000 orders daily. Ahmad Tea, Nestle Nespresso, Land Rover, and other well-known and high-traffic online Magento stores are just a few examples. ## **Defining XML Elements and Attributes** Where can you establish web API resources and associated permissions in Magento? There is the `webapi.xml` configuration file. This file is used to register our API routes and specify the rights, such as: * indicating the URL; * the method (`GET`, `POST`, `SAVE`, and so on); * interface, where our processes are registered; * resources, i.e., who has access to the API (`anonymous`, `self`); * etc. The table below shows the resources each user type can reach: <table> <tr> <td><strong>Type of User</strong> </td> <td><strong>Available Resources</strong> </td> </tr> <tr> <td>Administrator or Integration </td> <td>Resources with admin or integrator authorization. Suppose administrators are entitled to the <code>Magento_Customer::manage</code> resource. It means they can make a <code>PUT /V1/customers/:customerId</code> call. </td> </tr> <tr> <td>Customer </td> <td>Access to resources with <code>anonymous</code> or <code>self </code>permission </td> </tr> <tr> <td>Guest user </td> <td><code>anonymous </code>permission </td> </tr> </table> ## **Steps to Add User Authentication in Magento** There are three types of authentication in Magento: Token, OAuth, and Session authentication. Token and OAuth are roughly the same things. But for OAuth, you need to log in first and receive an access token for your account. Or you can simply create a token that will have certain rights and doesn’t [require authorization](https://dev.to/ubahthebuilder/user-authentication-vs-user-authorization-what-do-they-mean-in-back-end-web-development-18bb) with Token Authentication. Each subsection below will tell you how to configure them in steps. ### **1. Token Authentication** Token-based authentication is preferable for registered users making web API calls using a **mobile application**. What is a token? It’s an electronic key for accessing API(s). 1. A registered user requests** a token** from the token service at the endpoint. Note that this endpoint should be defined for your user type. 2. Once the token service receives a Magento account username and password, it returns a unique **authentication token**. 3. Insert this token in the `Authorization` request header as proof of your identity on web API calls. There are three types of access tokens by Magento, which differ in terms of longevity: 1. **Integration \ **It** **doesn’t have time restrictions, and the access granted by the merchant lasts forever **until it is manually revoked**. \ 2. **Admin** \ The merchant determines an admin user’s access to Magento resources, lasting **four hours**. \ 3. **Customer \ **Such** **tokens are valid for **one hour**. Users with `anonymous `or `self `authorization get access to resources from Magento. These options are not editable by merchants. Since the token is only valid for a while, we need to ask for it again when it expires. #### **Step 1. Integration Tokens** What happens when a merchant creates and activates an integration? Magento generates the following credentials: * consumer key; * consumer secret; * access token; * access token secret. All of them are also relevant for OAuth-based authentication, but **Token-based authentication** simply requires the **access token**, and that’s how you can create it: 1. Access the Integrations page. Log in to Admin and go to **System **> **Extensions **> **Integrations**. \ 2. To access the New Integration page, click **Add New Integration**. \ 3. Proceed to the **Name **field and give the integration a unique name. Type your admin password in the **Your Password** section. Don’t fill in other fields. \ 4. Navigate to the **API tab**, where you can choose the access to Magento resources for the integration (all resources or a custom list). \ 5. After saving your modifications by clicking the **Save **button, return to the Integrations page. \ 6. Find the grid of the newly-created integration, click the **Activate **link, and select **Allow**. You will see a dialogue like this: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qbnqegoy7xknoex805bo.png) ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1pc0i231rzt9xdcgbmb0.png) The access token can be used for any calls performed by the integration. #### **Step 2. Admin and Customer Access Tokens** Administrators and customers each have their own token service in Magento. When you ask one of these services for a token, you’ll receive a unique access token in exchange for your Magento account’s username and password. Guest users can access resources defined with the `anonymous `permission level using the Magento web API architecture. Who are guest users? These are users who can’t be authenticated using the framework’s existing authentication procedures. They don’t need to specify a token in a web [API call](https://dev.to/endymion1818/how-to-test-javascript-api-calls-187k) for a resource with anonymous authorization, but they can. Magento admins must be sure to authenticate using **two-factor authentication**. General users don’t need it, so they have a different authorization API. You can realize your APIs for authorization or enable authorization through a third-party service, such as: * Duo Security; * Google Authenticator; * U2F; * Authy. Customer calls for REST and SOAP will look the following way: * REST: `POST /V1/integration/customer/token` * SOAP: `integrationCustomerTokenServiceV1` Include this token in the `Authorization` request header with the `Bearer `HTTP authorization scheme to establish your identity. As I’ve mentioned, an admin token is valid for four hours by default, while a customer token remains operative for one hour. You can change the default settings from the Admin menu like this: Select **Stores **> **Settings **> **Configuration **> **Services **> **OAuth **> **Access Token Expiration** All expired tokens are removed by a cron job that runs every hour. #### **Step 3. Inquire a Token** A request for an access token has three essential components: * **Endpoint** \ It combines the server making the request, the web service, and the `resource `to which the request is addressed. \ \ Let’s take this endpoint as an example: \ `POST &lt;host>/rest/&lt;store_code>/V1/integration/customer/token`. \ Here, the server is `magento.host/index.php/`, the web service is `rest`, and the resource is `/V1/integration/customer/token`.` \ ` * **Content type** It concerns the request body. There are two options to set this value: `"Content-Type:application/json"` or `"Content-Type:application/xml"`. \ * **Credentials** \ This is a Magento account’s username and password. Include code in the call to specify these credentials in a JSON request body: `{"username":"&lt;USER-NAME>;", "password":"&lt;PASSWORD>"}`. \ \ If you need to indicate these credentials in XML, use this code in the call: `&lt;login>&lt;username>customer1&lt;/username>&lt;password>customer1pw&lt;/password>&lt;/login>`. Here’s an example of the `curl `command to request a token for an admin account: ``` curl -H "Content-Type: application/json" \ --request "POST" \ --data '{"username":"<username>","password":"<password>"}' \ https://<magento_host>/index.php/rest/V1/integration/admin/token ``` #### **Step 4. Authentication Token Response** The response body with the token will look like this, provided the request is successful: ``` 6yivz6jrmo147x4skq0xt1ights6siob ``` ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h7uiwbgxok9f6gdsu3t0.png) #### **Step 5. Utilizing the Token in a Web API Call** You need the authentication token when you access the resource that requires a permission level higher than “anonymous”. Include it in the header of any web API call, using the following HTTP header format: ``` Authorization: Bearer <authentication token> ``` **a) Admin Access** Admins have full access to all resources for which they received permission. Here is how you perform a web API call with an admin token: ``` curl -X GET https://<magento_host>/index.php/rest/V1/customers/29171 \ -H "Authorization: Bearer 6yivz6jrmo147x4skq0xt1ights6siob" ``` ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ytm0nfy4qhwk6pb3ery8.png) **b) Customer Access** Unlike admins, customers can’t access all resources other than with `self` permissions. The following code explains how to use a customer token to make a web API call: ``` curl -X GET https://<magento_host>/index.php/rest/V1/customers/me \ -H "Authorization: Bearer 6yivz6jrmo147x4skq0xt1ights6siob" ``` ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/akqjqnlsjl41e2leyror.png) ### **2. OAuth Authentication** Let’s talk about the Magento OAuth authentication process. This type of authentication is based on OAuth 1.0a, a secure API authentication open standard. OAuth is a token-passing technique to specify access for **third-party applications** to internal data. It’s done without revealing or storing user IDs or passwords. Such a third-party application using OAuth for authentication is known as **integration **in Magento. OAuth authentication determines the resources that the application can access. For example, you can enable all resources or restrict the list. To illustrate my point, suppose you use Mailchimp to notify your store visitors about the abandoned carts. When a visitor leaves your website with an unpaid order, Mailchimp needs to obtain a list of such clients, the contents of their carts, and email addresses. As a store owner, you specify the Mailchimp rights with the help of OAuth authentication. That’s how Magento generates the tokens needed for authentication: 1. It starts by generating a **request token**. \ 2. This token is usable for a short time and must be exchanged for an **access token**. Access tokens have a lengthy lifespan and expire only when the merchant revokes the application access. #### **Step 1. OAuth Overview** The OAuth authentication process takes ten steps: 1. **Creating an integration** from Admin. The merchant builds an integration, while Magento generates a **consumer key** and a **consumer secret**. \ 2. The next step is **activating the integration**, which starts the OAuth process. Magento uses HTTPS post to transmit the following attributes to the external application: \ 1. OAuth consumer key and secret; 2. OAuth verifier; 3. the store URL. These credentials go to the page indicated in the Callback Link field in Admin. 3. The integrator **receives the activation information** and saves it to ask for tokens. \ 4. Magento **accesses the application login page** specified in the Admin Identity Link field. \ 5. The merchant **logs in to the third-party application**, which will integrate with Magento. The application returns to the call location in case of a successful login. The login page doesn’t participate in this process. \ 6. The application **asks for a request token**. It uses the REST API `POST /oauth/token/request`. The consumer key and other details are included in the `Authorization `header. \ 7. The application** receives a request token and a request token secret** from Magento. \ 8. The application **asks for an access token** using the REST API `POST /oauth/token/access`. The request token and other details are included in the `Authorization `header. \ 9. Magento **delivers an access token and an** **access token secret **if the request is successful. \ 10. The application **can operate the store resources**. All requests submitted to Magento must include the entire set of request parameters in the `Authorization `header. #### **Step 2. Activating Integration** How can you configure integration? Go to the Admin **System** > **Extensions **> **Integrations**. The process also involves a callback URL and an identity link URL. What is a **callback URL**? This link specifies where OAuth credentials can be transmitted during OAuth token exchange. On the other hand, the identity link takes you to the login page of the external application, which will integrate with Magento. When merchants create an integration, they can select **Save and Activate**. Or the merchant can use the **Activate **button to activate a previously saved integration from the Integration grid. Magento creates a consumer key and a consumer secret after initiating the integration. When you activate an integration, it sends the [credentials to the endpoint](https://dev.to/ebereplenty/react-authentication-protecting-and-accessing-routes-endpoints-96h) you specified when you created it. The following attributes will be in an HTTP POST from Magento to the Integration endpoint: * `store_base_url` (for example, http://magento-store-example.com); * `oauth_verifier`; * `oauth_consumer_key`; * `oauth_consumer_secret`. To receive a request token, integrations utilize the key: `oauth_consumer_key`. And to get an access token, they use the `oauth_verifier`. #### **Step 3. OAuth Handshake Details** To complete a two-legged OAuth handshake, you must obtain: * a request token; * an access token. **a) Getting a Request Token** A request token is a one-time usage token needed to exchange for an access token. This API allows you to obtain a request token from Magento: ``` POST /oauth/token/request ``` These request parameters must be included in the `Authorization `header of the call: * `oauth_consumer_key`; * `oauth_signature_method`; * `oauth_signature`; * `oauth_nonce`; * `oauth_timestamp`; * `oauth_version`. Fields in the response include: * `oauth_token`, the token to request an access token; * `oauth_token_secret`, a secret value that identifies who owns the token. An example of a valid response may look: ``` oauth_token=6rq0x917xdzkhjlru0n4m2r6z2vvj66r&oauth_token_secret=4d85786q9yxisfjoh0d2xgvsard8j0zj ``` **b) Acquiring an Access Token** Integrators obtain an access token in exchange for the request token, using the following API: ``` POST /oauth/token/access ``` The call `Authorization` header contains the same request parameters as for the request token, plus: * `oauth_token`, or the request token; * `oauth_verifier`, a verification code transmitted as part of the initial POST transaction. Here’s an example of a valid response: ``` oauth_token=6rdpi1d4qypjpcdxcktef35kmmqxw6b1&oauth_token_secret=fcufgnt83chiljiftg2uj7nty6vvfzgo ``` It includes the following fields: * `oauth_token`, which enables third-party applications to access protected resources; * `oauth_token_secret`. #### **Step 4. Access Web APIs** Third-party applications, or integrators, can use the access token to make Magento web APIs, such as: ``` GET /rest/V1/addresses/3112 ``` The request parameters in the `Authorization` request header in the call must be: * `oauth_consumer_key`; * `oauth_nonce`; * `oauth_signature_method`; * `oauth_signature`; * `oauth_timestamp`; * `oauth_token`. #### **Step 5. The OAuth Signature** `Authorization `header includes the signature of every OAuth handshake and Web API requests. How do you generate the OAuth signature? The signature base string is created by connecting the following set of URL-encoded attributes and parameters with the ampersand (&) character: * HTTP method; * URL; * `oauth_nonce`; * `oauth_signature_method`; * `oauth_timestamp`; * `oauth_version`; * `oauth_consumer_key`; * `oauth_token`. The signature generation requires the HMAC-SHA1 signature method. Even if the consumer secret and token secret are both empty, the signing key is the sequence of their values separated by the ampersand (&) character (ASCII code 38). Each value must be encoded using parameter encoding. ### **3. Session Authentication** Users may be required to confirm their identity every time they want to make a call. Sessions let them avoid this repetitive task. When a person logs in, their temporary session is created, which stores data. And then, the data for verification is taken from the session where authorization is required. The **JavaScript widget on the Magento storefront or Admin** is the preferred client for session-based authentication. How does this authentication work? A cookie identifies a session of a registered user, which expires after a period of inactivity. You can also use the system as a guest user without logging in. Depending on the type of user, you log in to the Magento store with customer or administrator credentials. The Magento web API framework recognizes you and controls what resources you’re trying to access. Suppose a customer logs in, and the JavaScript widget calls the `self `API, the following method retrieves the details: `GET /rest/V1/customers/me`. Note that API endpoints don’t support admin session-based authentication at this time. AJAX calls are the only way to use session-based authentication. Due to security flaws, direct browser requests are not possible. A developer can make a custom Magento widget to send requests without requiring any further authentication. ## **To Sum Up** This article covered three types of Magento authentication: * Token; * OAuth; * Session. Each one has a preferred type of user, so you need to know how to add them in steps. If you want to give access to the resources for customers, admins (integrations), or guest users, you configure permission in the `webapi.xml` file. Why do you need it all? It is needed for security so that no user can access your data or make changes in the online store without your permission.
alexhusar
940,689
Learn Mongoose
Mongoose is like a wrapper around MongoDB. With mongoose we do not need to wait to get mongoDB...
0
2021-12-30T18:29:18
https://dev.to/foysalbn/learn-mongoose-10j2
mongoose, mongodb
Mongoose is like a wrapper around MongoDB. With mongoose we do not need to wait to get mongoDB connected. Mongoose will queue up all the command you make and only make those command after it connect to mongoDB . for mongoose you need to know 3 basic concept. Inside mongoose, there are 3 main concepts we need to understand first 1. schema - it defines , what the structure of your data look like. 2. Model - It is the actual form of a schema. A model is a class with which we construct documents. 3. Query - A query is just a query we make against mongoDB database. we can write all schema in one file. But it is good to use different file for each schema. Schema takes an object with key value pairs , where key is the name of the key in your mongoDB object. so if we want the user have a name , we give it a key of a name. And then the value will be the datatype of ***name** ,* that is ***String***. ```jsx const mongoose = require('mongoose') const userSchema = new mongoose.Schema({ name: String, age : Number }) ``` We now have a user schema that defines a name field and a age field. And the name going to be a string and age is going to be a number. Now we have to create a model for this schema. we have to user *mongoose.model()* function for this. This function takes a name of the model, in our case, this is going to ‘User’’. And we have to pass a schema as the second parameter. ```jsx mongoose.model('User', userSchema) ``` If we create the schema in another file, we have to export the model. ```jsx module.exports= mongoose.model('User', userSchema) ``` **Now, let’s create a user**. As we created the schema in another file , we have to require it on the main script. ```jsx const User = require('./user'); ``` we can create user by instantiate User class as new user object and pass a object. ```jsx new User({ name: 'abir', age: 6 }) ``` It just create a local copy of a user in our script. it won’t save to database. We have to use save() function for this. [ It give use a promise. But it is more cleaner to use ***async await*** instant of promise. ]\ ```jsx run(); async function run() { const user = await new User({ name: 'abir', age: 6 }) await user.save(); console.log(user); //return // { // name: 'abir', // age: 6, // _id: new ObjectId("61ccb948e35a787b6ad2b812"), // __v: 0 // } } ``` We can also create a user using the create() method on the actual ***User*** class. ```jsx run(); async function run() { const user = await User.create({ name: 'abir', age: 21 }) console.log(user) } ``` ### Schema type we can use many types like String, Number, Date , ObjectId etc. We can use nested object in schema like what we did for ***address —***— ```jsx const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, age: Number, cratedAt: Date, updatedAt: Date, bestFriend: mongoose.SchemaTypes.ObjectId, hobbies: [String], address: { street: String, city: String, } }); module.exports = mongoose.model('User', userSchema); ``` We can create whole asperated schema for “**address”** like this ```jsx const addressSchema = new mongoose.Schema({ street: String, city: String, }); const userSchema = new mongoose.Schema({ name: String, age: Number, cratedAt: Date, updatedAt: Date, bestFriend: mongoose.SchemaTypes.ObjectId, hobbies: [String], address: addressSchema, }); ``` This is much useful for complex schema. ### Validation—————————— We should use try catch for error handling ```jsx const mongoose = require('mongoose'); const User = require('./user'); mongoose.connect('mongodb://localhost/test', () => { console.log('connected'); }) run(); async function run() { try { const user = await User.create({ name: 'abir', age: 'ab' }) user.name = 'rafi' user.save(); console.log(user) } catch (e) { console.log(e.message) } } ``` we can add additional properties to field in our schema in object format. we can set a field “*require*” in a schema like this— ```jsx const userSchema = new mongoose.Schema({ name: String, email:{ type: String, required: true, }, age: Number, }); ``` some additional properties we can use in our schema- 1. required - it is like require attribute of html form . That’s means we must include the filed 2. lowercase - it will automatically convert the given email to lowercase. 3. uppercase - it will automatically convert the given email to uppercase. 4. default - set a default value. 5. immutable - make a field immutable or unchangeable.
foysalbn
940,953
What is Facebook Jail? How to Avoid it?
Facebook is the most used platform by the users and has been loved by the users too. There are many...
0
2021-12-31T05:03:23
https://dev.to/worldzo_net/what-is-facebook-jail-how-to-avoid-it-1e6g
howtogetoutoffacebookjail, facebookjail, facebookjailreport, outoffacebookjail
Facebook is the most used platform by the users and has been loved by the users too. There are many users who are not aware of Facebook jail and those who do not know what it is then you must not think that it is original jail with bars and etc but it is a virtual jail where people are locked and banned from using Facebook and this situation is considered as being put in a Facebook jail and when they are in such situation they look for ways for **[how to get out of Facebook jail](https://worldzo.net/what-is-facebook-jail-and-how-to-get-out-of-it/)**. Here in this blog we will tell you the ways to get out of Facebook jail so let us look for the ways of the same. **Ways to Get Out of Facebook Jail –** **Serving your Sentence** If you are aware of the reason why your Facebook was locked and how can you get out of Facebook jail then you must file in your sentence to Facebook telling that your account was locked without your knowledge and without reason. **Appealing to Facebook** You can file in an appeal to Facebook to bring your account of Facebook jail which was put their because of **[Facebook jail report](https://worldzo.hpage.com/how-to-stay-out-of-facebook-jail.html)**. **Creating a New Account** If you are not able to get your account then you have no other option left than to create a new account on Facebook and avoid doing things which will lead to your account getting locked in Facebook jail. And you can send requests to your friends again and set up your account again. If you are a user looking for some extra information on Facebook and issues related to it then you need to visit the site **[worldzo.net](https://worldzo.net/)** and this site is a good one that is why you will like the site once you have used it.
worldzo_net
940,991
Things I asked the DevAd hiring manager before verbally accepting the intern offer
As I prepare for my third and last internship before graduation, I thought it would help to...
0
2022-01-02T04:24:21
https://dev.to/dianasoyster/things-i-asked-the-devad-hiring-manager-before-verbally-accepting-the-intern-offer-1b5h
intern, devrel, firstpost
As I prepare for my third and last internship before graduation, I thought it would help to articulate details I needed to know about a role before signing my soul away. I had the luxury of meeting with my future manager a few times before making my decision, so I made sure each call was productive and insightful since I only had those moments to decide if vibes check out. ## What is the intern project? I've learned to run for the hills when a hiring manager is extremely vague or even unsure about what they want me to work on. First, it comes off open-minded and flexible which is really intriguing. But then I find myself gaslit and working on something I absolutely did not want to do. I'd love to know: - What product I'll be working with - What specific topics I'll be covering - What my final project will be I've narrowed my choices of employers based on (1) products that interest me and (2) projects assigned. I learned I don't make a good sellout, and there was no way I'd make a decent devad if I wasn't working on something I enjoyed. ## Why are you hiring an intern specifically on this team? I was once brought onto a team as an impromptu intern (ie. they made my role because I was referred). During my first week, I approached my manager with a list of clarifying questions including "What are your expectations of me in order to get a return offer on this team?" _(Something I was taught to ask early on and a previous internship had addressed on my first day)_ Had I not asked this, I probably wouldn't have ever learned that **this team wasn't even hiring**. That conversation turned into a real sh!t show, but my point is: Please don't bring an intern on without intent to keep them. ## Is mentorship offered? If yes, what's your style? When hearing about my classmates who interned at Amazon, I envied the kind of mentorship they received. It was very organized and systematic, and expectations of the mentor were crystal clear. I never felt like I really had that. It's not their fault; none of my assigned mentors were given instructions on how to contribute to my internships. Some of them didn't even know what being a mentor entailed. Ideally I would like an empathetic mentor(s) who can: - willingly take on questions - train me but understand I'm likely unable to perform at their level in the time I'm interning - help unblock me after I've tried to solve a problem - offer constructive feedback (I don't want to think I'm doing fine then get blindsided) - offer the amount of guidance I need - carve out time to have involved 1:1's; if they're busy, we can move it (I don't want a mentor who is constantly working on other things every time we meet while I'm trying to talk to them) ## What are the expectations to get a return offer? I was once told it was "extremely off-putting" that I had asked about _what is expected of me in order to get a return offer_ because it came off "entitled that I even thought it was a possibility to return to the team." I hated that I tip-toed around this question for countless talks every since, but I've spoken to enough people now to confirm that **that isn't an offensive question and it's completely normal to want to know this information**. I asked if we could establish some metrics we can refer to (e.g. How many videos am I expected to make?), so I have some level of self-awareness. I get that solely reaching a count isn't all it takes, but I just want some way of knowing how much I've done and how much I have left to do. ## Are you crazy? (Please don't ask this verbatim) _"I just wanted to make sure you're not crazy."_ Lacks context but yes...I did actually say the above sentence verbatim. Admittedly, it was unnecessarily vulnerable to share my story about being expected to work normally after 3 deaths in my family during a past internship. I'm sure there were other ways to find out whether my next boss understands that "life happens" and I'm a human-being before I'm an employee. My point is: this was important to me, and I needed some reasurrance that I was going to work for a reasonable person. ## Wrap up When I got the offer, I had already chosen the company based on their size, pay, benefits, etc. The only thing left was choosing my manager. My key determining factors when deciding on a manager were their: - assigned project - purpose for hiring an intern - mentorship style - expectations - response to emergencies Can't wait to share my journey as a DevAd intern at Snowflake starting in February!
dianasoyster