From cab822c68947b76bfa14289dfc6a68ce2f7cbb39 Mon Sep 17 00:00:00 2001 From: Bill D <355438+vegetabill@users.noreply.github.com> Date: Sun, 13 Dec 2020 18:56:52 -0800 Subject: [PATCH] [automated changes] run prettier on entire repo after simplifying config --- .prettierrc | 11 - _templates/lesson-v2.md | 6 +- algorithms/sorting.md | 12 +- api/REST-API.md | 353 ++++++------ career/interviewing/README.md | 7 +- .../non-technical-interviewing.md | 2 +- career/roles-in-tech/data-science.md | 1 + career/working-and-collaborating-remotely.md | 88 +-- databases/relational-databases.md | 8 +- deploying/deploying-to-heroku.md | 155 +++--- deploying/deploying.md | 12 +- dev-tools/command-line-advanced.md | 86 +-- dev-tools/command-line-interface.md | 28 +- dev-tools/dot-profile.md | 49 +- electives/databases/mongoose.md | 18 +- electives/mocha-testing.md | 14 +- git/git-version-control.md | 5 +- javascript/JavaScript-React-Modularity.md | 58 +- javascript/React_JavaScript.md | 33 +- javascript/common-functions-cheatsheet.md | 526 +++++++++++------- javascript/first-js-oop-project.md | 4 +- javascript/javascript-7-oop.md | 1 - javascript/require-and-import-mini-lesson.md | 42 +- javascript/spread-operator.md | 87 +-- node-js/node-lab-exercise-part-1.md | 5 +- objectives/week-6-assessment.md | 4 +- onboarding/ergonomics.md | 1 - onboarding/professionalism.md | 105 ++-- prework/2_ConditionalsExercise.js | 14 +- prework/4_FunctionsExercise.js | 38 +- prework/5_ArraysObjectsExercise.js | 28 +- prework/6_DomExercise.html | 101 ++-- prework/codeSamples.js | 30 +- projects/Eventful-API-test-page/app.js | 98 ++-- projects/Eventful-API-test-page/connection.js | 11 +- .../Eventful-API-test-page/eventfulAPI.js | 49 +- projects/Eventful-API-test-page/index.js | 10 +- projects/Eventful-API-test-page/package.json | 2 +- .../eventonica/eventonica-part6-postgres.md | 32 +- .../starter-code/eventRecommenderSpec.js | 4 +- projects/mongo-assessment.md | 3 +- .../node-http-exercise/node-http-exercise.md | 7 +- ...-server-assignment.postman_collection.json | 354 ++++++------ projects/utils-js.md | 4 + runtime-complexity/index.html | 36 +- runtime-complexity/runtime.js | 135 +++-- runtime-complexity/runtime1-analyzing.js | 33 +- runtime-complexity/runtime2-comparisions.js | 24 +- testing-and-tdd/integration-testing.md | 3 +- testing-and-tdd/jasmine-pair-activity.js | 4 +- testing-and-tdd/jasmine-testing.md | 24 +- testing-and-tdd/mocking-and-abstraction.md | 10 +- web/html-forms.md | 48 +- .../index.html | 38 +- .../static/js/myScript.js | 18 +- web/js-dom-methods-walkthrough/index.html | 32 +- .../static/script.js | 21 +- web/js-dom-methods.md | 10 +- 58 files changed, 1552 insertions(+), 1390 deletions(-) diff --git a/.prettierrc b/.prettierrc index 83821224c..79c9a44e7 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,19 +1,8 @@ { - "arrowParens": "always", - "bracketSpacing": true, - "jsxBracketSameLine": false, - "jsxSingleQuote": false, - "semi": true, - "singleQuote": true, "tabWidth": 2, "useTabs": false, - "quoteProps": "as-needed", "trailingComma": "none", - "requirePragma": false, - "insertPragma": false, "proseWrap": "preserve", - "vueIndentScriptAndStyle": false, - "endOfLine": "auto", "overrides": [ { "files": "*.md", diff --git a/_templates/lesson-v2.md b/_templates/lesson-v2.md index 2228a21af..5293eb9e9 100644 --- a/_templates/lesson-v2.md +++ b/_templates/lesson-v2.md @@ -1,4 +1,5 @@ # Your Topic Name + _Should match the filename, but filename should be `kebab-case`_ **Note: all content should follow the [Style Guide](./README.md#style-guide)** @@ -6,6 +7,7 @@ _Should match the filename, but filename should be `kebab-case`_ ## Projected Time 1.5 hours + - Lesson: 30min - Guided Practice: 30min - Independent Practice: 30min @@ -42,7 +44,6 @@ It can contain links to external materials but you should summarize here in your ### - ### Common Mistakes & Misconceptions This section is optional, but if there are common misunderstandings, please enumerate them here. List things that apprentices might not realize, might assume at first, or should avoid. @@ -51,12 +52,10 @@ This section is optional, but if there are common misunderstandings, please enum - `for (let x of obj)` loops and `for (let elem in obj)` loops are different - `const` variables are not immutable; they just can't be reassigned - ### Guided Practice Have the apprentices work with you as you do something step-by-step. This should be inlined here as original content, not just linked to an external tutorials. - ### Independent Practice Class does this thing themselves with specific additional items. This could be alone, with a partner, or small group; but the idea is that it's less guided, more independent. @@ -68,5 +67,6 @@ Building on the independent practice, here are some challenging optional add-ons ### Supplemental Materials Here you can link in external tutorials, official or unofficial documentation pages, blogs, videos, etc. + - [example website](https://google.com) - short description (approximate duration to watch/read) - [Other example website](https://google.com) - description diff --git a/algorithms/sorting.md b/algorithms/sorting.md index ed01c4d3a..65b8c2c40 100644 --- a/algorithms/sorting.md +++ b/algorithms/sorting.md @@ -61,7 +61,7 @@ Say we want to sort a deck of cards: Let's talk about the Complexity of BogoSort. Here's the pseudocode: ```JavaScript -while not Sorted(a) +while not Sorted(a) Shuffle(a) ``` @@ -114,8 +114,8 @@ function bubble_sort(a) } n--; } while (swap); - return x; -} + return x; +} ``` We have nested loops: the while-loop and the for-loop! The outer loop passes until there are no more swaps. Thus the runtime is O(n^2). @@ -195,8 +195,8 @@ function merge (a, left, right, middle){ for(let j=0;j { - res.status(200).send(customers); - } - ) +app.route('/customers').get((req, res) => { + res.status(200).send(customers); +}); ``` Now, if you test your route with Postman or by opening a browser and going to `http://localhost:3000/customers`, you should see: ```json -[{"id":1,"first_name":"Fremont","last_name":"Broader","email":"fbroader0@bloglines.com","gender":"Male","ip_address":"23.27.246.1"},{"id":2,"first_name":"Georgetta","last_name":"Blamey","email":"gblamey1@wisc.edu","gender":"Female","ip_address":"17.110.6.159"},{"id":3,"first_name":"Meghann","last_name":"Quillinane","email":"mquillinane2@surveymonkey.com","gender":"Female","ip_address":"237.88.226.148"},{"id":4,"first_name":"Kerby","last_name":"Mate","email":"kmate3@si.edu","gender":"Male","ip_address":"81.44.87.187"},{"id":5,"first_name":"Loren","last_name":"Brabon","email":"lbrabon4@umich.edu","gender":"Female","ip_address":"47.137.187.14"}] +[ + { + "id": 1, + "first_name": "Fremont", + "last_name": "Broader", + "email": "fbroader0@bloglines.com", + "gender": "Male", + "ip_address": "23.27.246.1" + }, + { + "id": 2, + "first_name": "Georgetta", + "last_name": "Blamey", + "email": "gblamey1@wisc.edu", + "gender": "Female", + "ip_address": "17.110.6.159" + }, + { + "id": 3, + "first_name": "Meghann", + "last_name": "Quillinane", + "email": "mquillinane2@surveymonkey.com", + "gender": "Female", + "ip_address": "237.88.226.148" + }, + { + "id": 4, + "first_name": "Kerby", + "last_name": "Mate", + "email": "kmate3@si.edu", + "gender": "Male", + "ip_address": "81.44.87.187" + }, + { + "id": 5, + "first_name": "Loren", + "last_name": "Brabon", + "email": "lbrabon4@umich.edu", + "gender": "Female", + "ip_address": "47.137.187.14" + } +] ``` So, the same way, you can setup the second GET method, as planned: -|Route|HTTP Method| -|-|-| -|`/invoices`|`GET`| +| Route | HTTP Method | +| ----------- | ----------- | +| `/invoices` | `GET` | With Express, routing is as easy as chaining the HTTP method to the `route()` method, taking care of putting the route you want to lookup inside of the `route()` method parenthesis. ```javascript -app - .route('/invoices') - .get( - (req, res) => { - res.status(200).send(invoices); - } - ) +app.route('/invoices').get((req, res) => { + res.status(200).send(invoices); +}); ``` + This time, if you test, you will get the entire invoices collection. However, the beauty of a RESTful API is that we want to use the possibility to fetch a particular customer or invoice. To do so, we need to create another set of routing that includes the ID of the record we wish to inquire about. For example, if we look at our data, we know that there is a customer with id 1 and an invoice with id 6. If we go back to our plan, we can see that we already had planned the route for these: -|Route|HTTP Method| -|-|-| -|`/customers/{id}`|`GET`| -|`/invoices/{id}`|`GET`| +| Route | HTTP Method | +| ----------------- | ----------- | +| `/customers/{id}` | `GET` | +| `/invoices/{id}` | `GET` | So, to create these, simply add another routing to the `app`, but this time we need to fetch the ID that's included in the parameters. If you recall your server lessons, this can be done by accessing the `req.params` object. We then should iterate through all records until we find the record that has the same `id` because that is the property that we are looking for. Of course, you could use any of the object's properties, here. You would just need to adjust the route appropriately, but we will not cover this for now. ```javascript -app - .route('/customers/:id') - .get((req, res) => { - let customer_id = req.params.id; - let status = 400; - let response = "Unable to fetch data!"; - customers.forEach((customer) => { - if (customer["id"] == customer_id) { - res.status(200).send(customer); - } - }); - res.status(status).send(response); - }) - -app - .route('/invoices/:id') - .get((req, res) => { - let invoice_id = req.params.id; - let status = 400; - let response = "Unable to fetch data!"; - invoices.forEach((invoice) => { - if (invoice["id"] == invoice_id) { - res.status(200).send(invoice); - } - }); - res.status(status).send(response); - }) +app.route('/customers/:id').get((req, res) => { + let customer_id = req.params.id; + let status = 400; + let response = 'Unable to fetch data!'; + customers.forEach((customer) => { + if (customer['id'] == customer_id) { + res.status(200).send(customer); + } + }); + res.status(status).send(response); +}); +app.route('/invoices/:id').get((req, res) => { + let invoice_id = req.params.id; + let status = 400; + let response = 'Unable to fetch data!'; + invoices.forEach((invoice) => { + if (invoice['id'] == invoice_id) { + res.status(200).send(invoice); + } + }); + res.status(status).send(response); +}); ``` + If you test your routes with Postman or by opening a browser and going to `http://localhost:3000/customers/1` and to `http://localhost:3000/invoices/6`, you should see these 2 records being returned. Now, in order to have a full-out API, we need more routes. So, we will now create the remaining routes, mainly the `POST`, `PUT` and `DELETE` ones. First, let's take care of the `POST` routes, like planned: -|Route|HTTP Method| -|-|-| -|`/customers`|`GET` and `POST`| -|`/invoices`|`GET` and `POST`| +| Route | HTTP Method | +| ------------ | ---------------- | +| `/customers` | `GET` and `POST` | +| `/invoices` | `GET` and `POST` | For that, you can simply chain the `.post()` Express method after the `.get()` one: @@ -435,7 +463,7 @@ For that, you can simply chain the `.post()` Express method after the `.get()` o */ let newCustomer = req.body; customers.push(newCustomer); - /* + /* * Here, we choose to return the customer object, but you could respond with anything such as a * generic message, etc. * When testing, you could console.log the complete customers array to see the added customer. @@ -448,17 +476,17 @@ For that, you can simply chain the `.post()` Express method after the `.get()` o let newInvoice = req.body; invoices.push(newInvoice); res.status(200).send(invoices); - }) + }) ``` If we look at what's left in our plan, we are just missing the `PUT`, and the `DELETE` methods: -|Route|HTTP Method| -|-|-| -|`/customers/{id}`|`PUT` and `DELETE`| -|`/invoices/{id}`|`PUT`| +| Route | HTTP Method | +| ----------------- | ------------------ | +| `/customers/{id}` | `PUT` and `DELETE` | +| `/invoices/{id}` | `PUT` | -Although this seems like a lot, in reality, they are quite easy to implement. +Although this seems like a lot, in reality, they are quite easy to implement. ```javascript // PUT in the /customers/:id route @@ -495,6 +523,7 @@ Although this seems like a lot, in reality, they are quite easy to implement. res.status(status).send(response); }) ``` + Finally, for the `DELETE` method: ```javascript diff --git a/career/interviewing/README.md b/career/interviewing/README.md index a4bef2fc9..83178caf7 100644 --- a/career/interviewing/README.md +++ b/career/interviewing/README.md @@ -5,6 +5,7 @@ Preparing for technical interviews is the subject of countless guides. This is Techtonica's guide, which is tailored to the audience of intensive training (or "bootcamp") graduates but should be applicable generally. ### Submit your own! + We value all contributions, but especially to this doc, where there are always new resources being created. Open an Issue or Pull Request with your suggestion. ## TL;DR Resource Link Dump @@ -32,8 +33,7 @@ Why is interview prep so important, even for grads who just spent 4 years learni Some argue that prep is so important because becoming a more effective engineer at building real production code does not make you better at interview questions. -*The only thing that reliably makes you better at interview questions is interview questions.* - +_The only thing that reliably makes you better at interview questions is interview questions._ ## Organization @@ -44,10 +44,9 @@ Interview prep and job searches in general reward Type A personality types. Give - This is really helpful because tasks beget other tasks. For example, if you're sprucing up the CSS on your portfolio page and notice it could use some more open-source contributions, you'd want to a place to capture those TODO's without derailing your styling efforts - No matter how much time you can devote, there will always be more tasks than time. Use your list to capture ideas but be intentional and thoughtful about how you spend your time - ## Typical Interview Process -Unfortunately, *there is no typical interview process*. Every company follows a different methodology and it often reflects the company culture. Some companies emulate the Big Tech style which weighs Computer Science and abstract analytical skills highly; other companies disagree that this selects for success and as a reaction try to create more a more "realistic" process and use take-home code challenges, pair programming, or other ways to assess +Unfortunately, _there is no typical interview process_. Every company follows a different methodology and it often reflects the company culture. Some companies emulate the Big Tech style which weighs Computer Science and abstract analytical skills highly; other companies disagree that this selects for success and as a reaction try to create more a more "realistic" process and use take-home code challenges, pair programming, or other ways to assess ### Big Tech Interviews diff --git a/career/interviewing/non-technical-interviewing.md b/career/interviewing/non-technical-interviewing.md index 5a66efc79..6fc849290 100644 --- a/career/interviewing/non-technical-interviewing.md +++ b/career/interviewing/non-technical-interviewing.md @@ -74,7 +74,7 @@ Use this format to help focus your responses and ensure you answer the question. - What are your goals for your career? (frame as how this role will help you get there) - Every junior person wants a place to learn and grow their skills, so try to be more specific - Mention if you have interest in exploring other roles in the future based on career week (e.g. PM) -- When did you need to give someone difficult feedback? +- When did you need to give someone difficult feedback? - How did you approach the conversation? How did you prepare? - How did the conversation go? What was the outcome? - The flip side of this is describe a time when you were given feedback that was difficult to hear diff --git a/career/roles-in-tech/data-science.md b/career/roles-in-tech/data-science.md index 151fc5b53..0ac39c97a 100644 --- a/career/roles-in-tech/data-science.md +++ b/career/roles-in-tech/data-science.md @@ -95,6 +95,7 @@ A data scientist will: - [EDA with Pandas on Google-Colab](https://colab.research.google.com/drive/1LQzSDISFudcL6meC3NXFOIaCYqXjNH04) ### Supplemental Materials + - [Python](../electives/python.md) - [Pandas Complete (1 hour video)](https://www.youtube.com/watch?v=vmEHCJofslg) - [Amazing Resources](https://github.com/frontbench-open-source/Data-Science-Free) diff --git a/career/working-and-collaborating-remotely.md b/career/working-and-collaborating-remotely.md index 0826bd4ed..647c58784 100644 --- a/career/working-and-collaborating-remotely.md +++ b/career/working-and-collaborating-remotely.md @@ -1,7 +1,9 @@ # Working and Collaborating Remotely ### Projected Time + About 1.5 hrs + - 12 min for Survey of Remote Workers blog post - 13 min for 10 tips for Productive Remote Work video - 20 min to Read over Lesson @@ -12,12 +14,14 @@ About 1.5 hrs ### Prerequisites Here are some topics that should be reviewed before this topic: + - [General Professionalism](professionalism.md) - [Workspace Ergonomics](../onboarding/ergonomics.md) ### Motivation The term "working remotely" simply means that an employee is working outside of a traditional office environment, and the number of companies that are allowing remote work has been steadily increasing. In some cases, remote work is done full-time, and in others the work is done offsite, often just one to a few days a week. Similarly, collaborating remotely means working with others who may or not be from the same company without meeting face to face. + - Both working and collaborating remotely is a mainstay in software development - Remote work sometimes presents unanticipated personal challenges - Remote work and collaboration comes with a set of tools that a new developer might have to learn quickly @@ -35,6 +39,7 @@ The term "working remotely" simply means that an employee is working outside of - Take home tips on how to stay productive and be professional ### Specific Things To Learn + - Myths vs. reality about the remote lifestyle - Ergonomics at home - Communicating online @@ -47,10 +52,12 @@ The term "working remotely" simply means that an employee is working outside of - Asking questions ### Materials + - Read [2019 Survey of remote workers](https://buffer.com/state-of-remote-work-2019) - Watch [10 tips for productive remote work](https://www.youtube.com/watch?v=0JbeJgcRPMM) ### Lesson + **Remote work** is defined as working offsite from a traditional office. **Remote collaboration** is defined as working with at least one person who is physically at another site, independent of whether the sites are within a traditional office setting. Both present both pros and cons. For example, some pros would be that remote collaboration saves both the employees and company the costs of travel time, and remote work saves the employee the costs of commuting and the company the costs of office space. On the con side, both remote collaboration and remote work lose the benefits of interpersonal communication that can take place when everyone involved are within proximity. Challenges on the con side are exemplified in the first minute and a half of this video on the [remote work revolution](https://www.youtube.com/watch?v=wUTd35A7I6c), where the speaker notes the following quote: > 1995: The information superhighway will mean anyone can do anything from anywhere @@ -60,12 +67,13 @@ The term "working remotely" simply means that an employee is working outside of The quote references a job posting by a tech company that produces software for remote collaboration! It appears they prefer their workers onsite! Because many companies are testing the value of remote work and there is a lack of visual interactions between coworkers, one must be cognizant of how to navigate remote work and collaboration professionally and how to optimize the use of the tools available for professionalism and professional growth. #### Working from home or a rented office + - **Work/Life balance** - As shown in the "2019 Survey of remote workers" blog post, one of the main struggles for remote workers is disconnecting from work. When work and life begin to mix together it is very important to have: - A dedicated area(s) for where you do your work - A set of rituals that are done before and after work - such as getting dressed as if going into the office and walking around the block for a "commute", before sitting down at the work station - A separate computer or account to separate work from personal computer time - A discussion about expectations with family or roommates regarding your work time, and a plan as to when and how to interact with others that may share the same household -- **Time management and productivity** - Another struggle closely related to work/life balance is time management. This problem arises because as opposed to being around others in a traditional office, there are no social queues for break and lunch times and an environment where you see everyone quiet and working. Tips: +- **Time management and productivity** - Another struggle closely related to work/life balance is time management. This problem arises because as opposed to being around others in a traditional office, there are no social queues for break and lunch times and an environment where you see everyone quiet and working. Tips: - Have a clean and uncluttered work area - Set a specific weekly and daily schedule for work time - Plan your day with a task list @@ -74,99 +82,111 @@ The quote references a job posting by a tech company that produces software for - Avoid "busy work" and focus on your assignments - Turn off unimportant notifications and leave the TV for "life" hours - Block time to get in the coding zone, list your other todos that aren't immediate and block time for those separately - - A proper diet - one can keep a journal and monitor their energy levels according to what they eat to see what's best + - A proper diet - one can keep a journal and monitor their energy levels according to what they eat to see what's best - Plan meals - make a specific lunch time as opposed to snacking - Exercise - many tech jobs are completely sedentary, exercise can boost productivity and morale -* **Ergonomics** - Just like any other working situation, it is vitally important to maintain good ergonomics while working remotely. However, the responsibility will likely be on you, the maintainer of your working space, to take the lead on either assessing your work station, or, working with a supervisor or HR to have someone from your business assess your workstation +* **Ergonomics** - Just like any other working situation, it is vitally important to maintain good ergonomics while working remotely. However, the responsibility will likely be on you, the maintainer of your working space, to take the lead on either assessing your work station, or, working with a supervisor or HR to have someone from your business assess your workstation - If you are responsible for doing your own assessment, carefully go over our [ergonomic materials](../onboarding/ergonomics.md) and make a list of issues and equipment to address those issues. - - Determine with HR/Supervisor who will be paying for equipment. If it is your company, you will need to follow their recommendations. If it is you, review our keep your receipts for potential tax purposes. - - Carefully research ergonomic choices, and if at all possible, find a way to test chairs and desks. In the Bay Area, you can try [Interior Motions](http://www.interiormotions.com/), [Arranged4Comfort](https://www.arranged4comfort.com/contact-us/) or [The Chair Place](http://thechairplace.com/) - - The most important thing is to proactively set your workstation up to take care of your body, and over time, listen to your body. Any unexpected pain or numbness are an indicator to reassess your workstation and make adjustments + - Determine with HR/Supervisor who will be paying for equipment. If it is your company, you will need to follow their recommendations. If it is you, review our keep your receipts for potential tax purposes. + - Carefully research ergonomic choices, and if at all possible, find a way to test chairs and desks. In the Bay Area, you can try [Interior Motions](http://www.interiormotions.com/), [Arranged4Comfort](https://www.arranged4comfort.com/contact-us/) or [The Chair Place](http://thechairplace.com/) + - The most important thing is to proactively set your workstation up to take care of your body, and over time, listen to your body. Any unexpected pain or numbness are an indicator to reassess your workstation and make adjustments - Maintaining proper ergonomics is a preventative measure. If you wait until you are in pain; it may be too late to recover without medical intervention, which can be both costly and time consuming. Further, maintaining a long, successful career without a healthy neck, back, arms, hands, and wrists will be very difficult - #### Remote environment tools -* **Kanban and Scrum** - While tools for these methods are prevalent in software development, many companies that maintain a traditional office may not use them, but they are very likely to be a part of a remote working environment. A challenge with these are that you simply can't repetitively lean over to the person next to you and just ask "how do I configure X?" Thus it's important to: + +- **Kanban and Scrum** - While tools for these methods are prevalent in software development, many companies that maintain a traditional office may not use them, but they are very likely to be a part of a remote working environment. A challenge with these are that you simply can't repetitively lean over to the person next to you and just ask "how do I configure X?" Thus it's important to: - Know you will have to get up to speed with these tools quickly - Ask what the tools are before your first day to give you additional time to look up tutorials or documentation -* **Version Control System (VCS)** - While you have used GitHub, it isn't the only VCS host out there, and some VCSs are not Git-based. Furthermore, some are integrated with project management software such as [Jira](https://www.atlassian.com/software/jira): +- **Version Control System (VCS)** - While you have used GitHub, it isn't the only VCS host out there, and some VCSs are not Git-based. Furthermore, some are integrated with project management software such as [Jira](https://www.atlassian.com/software/jira): - Git-based includes: [GitHub](https://github.com/), [GitLab](https://about.gitlab.com/), [Bitbucket](https://bitbucket.org/product) - Others include: [Subversion (SVN)](https://subversion.apache.org/), [Mercurial](https://www.mercurial-scm.org/) #### Communication -* **Communicating online** - Obviously, if you are working remotely, you won’t only be communicating by email. It is imperative that you become familiar with the etiquette or “netiquette” when working online and to remain professional during web conferencing. + +- **Communicating online** - Obviously, if you are working remotely, you won’t only be communicating by email. It is imperative that you become familiar with the etiquette or “netiquette” when working online and to remain professional during web conferencing. + - Every message, email, or call to `@here` on Slack can disturb people’s work, so it’s important to plan your communication - - Do people email after hours? Until you find out, try to send anything outside of normal working hours through scheduled send + - Do people email after hours? Until you find out, try to send anything outside of normal working hours through scheduled send - In a remote environment, messages that are text only won’t have the social context that one would have if speaking with someone where they can see them, so use care in crafting your email and messages - It pays to be explicit, not implicit, so that the other people you are communicating with know what you intend - For video conferencing, download and try the software ahead of time. You don’t want updates to make you late for your first meeting - Assume the video and audio is on when you log in, reduce distracting noises before hand - Look professional, and wear professional clothing, both for presence, but also in case you have to suddenly run out of the room. Leave the camera on so people get to know you -* **Pairing remotely** - Besides web conferencing tools like Zoom, there are a number of screen sharing tools that work for software development. Again, ask early on if there are any specific tools used to share code, so you can familiarize yourself with them ahead of time. Some software for sharing code include: +- **Pairing remotely** - Besides web conferencing tools like Zoom, there are a number of screen sharing tools that work for software development. Again, ask early on if there are any specific tools used to share code, so you can familiarize yourself with them ahead of time. Some software for sharing code include: - [Tuple](https://tuple.app/) - [Screen](https://screen.so/) - [CodeSandbox](https://codesandbox.io/) - [Teletype](https://teletype.atom.io/) for Atom - [Live Share](https://visualstudio.microsoft.com/services/live-share/) for Visual Studio Code - For a more complete list see this list from [designmodo](https://designmodo.com/code-collaboration/) -* **Asking questions** - In a remote environment, you can’t lean over and ask questions to the person sitting next to you or in the breakroom. To help you get the help you need you should: +- **Asking questions** - In a remote environment, you can’t lean over and ask questions to the person sitting next to you or in the breakroom. To help you get the help you need you should: - Ask your supervisor or team lead what channels you should subscribe to on the company’s chat program - Identify, through looking at various channels, where certain technical and non-technical questions should be directed to. This may be hr@yourcompany.com for some questions, or a slack message for the devops channel for others - Build relationships with your team - see the section below for more info #### Professionalism and Growth -* **Being visible for professional growth** - The old adage, “out of sight, out of mind” can easily apply to remote working situations, and it can be hard to make an impression when you are not in the same proximity as your co-workers. Making an effort to bridge the distance will not only make it easier to work with your team, it will help you make connections you will utilize throughout your career. + +- **Being visible for professional growth** - The old adage, “out of sight, out of mind” can easily apply to remote working situations, and it can be hard to make an impression when you are not in the same proximity as your co-workers. Making an effort to bridge the distance will not only make it easier to work with your team, it will help you make connections you will utilize throughout your career. + - Let people know what you are working on - you don’t need to give everyone a long list, but be "vocal" online about your projects and share any roadblocks you might have. Sharing an occasional screenshot or screencap of a feature completed or problem solved is another good way to show progress. With that said, be self-sufficient and try to solve hiccups on your own before consulting the team, and, make sure to help others resolve their blockers too - - Let people know your availability - Keep your calendar up-to-date and be sure it is shared with the team. Put your lunch break on it too, especially if you aren’t taking your lunch exactly at noon. If your team can’t get in contact with you when they need you, they might think you aren’t actually working. Also be sure to set up away messages and notifications on communication apps when you will be unavailable for a large portion of the day. And that goes double for your days off and vacations! + - Let people know your availability - Keep your calendar up-to-date and be sure it is shared with the team. Put your lunch break on it too, especially if you aren’t taking your lunch exactly at noon. If your team can’t get in contact with you when they need you, they might think you aren’t actually working. Also be sure to set up away messages and notifications on communication apps when you will be unavailable for a large portion of the day. And that goes double for your days off and vacations! - Set up "one-on-ones" with people you need to know before remote or collaborative work begins. This helps to get to know your teammates, their roles, and their expectations, and vice versa -* **Fitting into the culture and building relationships** - While it can take a while to understand all of the cultural nuances of a new workplace, here are some things you can do to get up to speed quickly: - - Read the mission statement, company values, founding principles, or similar, on the company website. Can’t find it? The employment section of the company website often covers at least part of these topics. - - Your team might have its own culture in addition to that of the company. In your introductory one-on-ones, ask people about the culture. It’s especially important to know about things such as taboos and rituals. It would be awkward to show up to video standup in your halloween costume and find out that your new workplace doesn’t do holidays! -* **Confidentiality** - There’s a pretty good chance that something you are working on shouldn’t be shared with those outside your company. Working remotely can sometimes be a risk for inadvertently exposing “company secrets” to others. - - If you are in proximity to others, always use headphones for short video and phone calls. This will ensure that the words of others aren’t overheard. If you do plan to discuss something confidential, you might need to book a telephone booth at your office rental or ask your roommate to check out your new Spotify playlist, etc. +- **Fitting into the culture and building relationships** - While it can take a while to understand all of the cultural nuances of a new workplace, here are some things you can do to get up to speed quickly: + - Read the mission statement, company values, founding principles, or similar, on the company website. Can’t find it? The employment section of the company website often covers at least part of these topics. + - Your team might have its own culture in addition to that of the company. In your introductory one-on-ones, ask people about the culture. It’s especially important to know about things such as taboos and rituals. It would be awkward to show up to video standup in your halloween costume and find out that your new workplace doesn’t do holidays! +- **Confidentiality** - There’s a pretty good chance that something you are working on shouldn’t be shared with those outside your company. Working remotely can sometimes be a risk for inadvertently exposing “company secrets” to others. + + - If you are in proximity to others, always use headphones for short video and phone calls. This will ensure that the words of others aren’t overheard. If you do plan to discuss something confidential, you might need to book a telephone booth at your office rental or ask your roommate to check out your new Spotify playlist, etc. - It’s important to be transparent with your team if others are around. Most people understand that it’s impossible to always be in isolation, but being upfront about it can prevent awkwardness or accidental secret spilling. - - Do not work on confidential projects in public places such as coffee shops, airports, or public libraries. Especially don’t work on confidential projects while connected to open wifi networks - - If someone near you accidentally overheard something confidential, fess up immediately. Your company can consult their legal team and decide what to do about it - - This should be true in any company, but don’t gossip about your co-workers with the people in your life. It can be really surprising how interconnected we all are + - Do not work on confidential projects in public places such as coffee shops, airports, or public libraries. Especially don’t work on confidential projects while connected to open wifi networks + - If someone near you accidentally overheard something confidential, fess up immediately. Your company can consult their legal team and decide what to do about it + - This should be true in any company, but don’t gossip about your co-workers with the people in your life. It can be really surprising how interconnected we all are -* **Maintain and Build Your Skills** - Learning is a lifetime endeavor, especially so in development. Technologies are constantly changing, and you will need to be proactive to remain competent on your team and competitive in the job market. +- **Maintain and Build Your Skills** - Learning is a lifetime endeavor, especially so in development. Technologies are constantly changing, and you will need to be proactive to remain competent on your team and competitive in the job market. - Pay attention to the tools, languages, and platforms your company is using. If you are unfamiliar with any of them, research them for a basic understanding of how they work - - When you have one-on-ones with your supervisor, treat them as professional development opportunities. Ask questions and request feedback on your performance. Ask your supervisor about new skills you should be learning. + - When you have one-on-ones with your supervisor, treat them as professional development opportunities. Ask questions and request feedback on your performance. Ask your supervisor about new skills you should be learning. - If there is a skill you want to learn, talk to your supervisor about ways to incorporate it into the work you are already doing - - Most companies have a professional development policy which allows staff a certain number of hours a year to dedicate to learning new skills. Many companies also have a budget to cover the costs + - Most companies have a professional development policy which allows staff a certain number of hours a year to dedicate to learning new skills. Many companies also have a budget to cover the costs - Be proactive about learning new things - if there isn’t a training opportunity within your company to learn, you can often find online courses to teach you, or consider working on open source projects ### Common Mistakes & Misconceptions + - **I can work exactly where I feel like, when I feel like!** - While this may be true for experienced independent contractors, many companies will set your hours according to time zone, or at minimum require a set of hours that they know you will be working and available for meetings, calls, and reporting. Also consider that it would be unprofessional to do video conferencing from a cafe or outdoors where background noise will be an issue. - **Remote work sounds like a great way to be judged solely by my programming skills** - Whether this sounds good because you are an introvert or you don't like office politics, in order to grow professionally, you may have to try even harder to build your network and gain a solid professional reputation. - **They are giving me a laptop, now I don't need to buy a new one** - If you are thinking that now you don’t have to buy a new computer to contribute to your non-profit or build your Etsy shop, think again. Your work laptop is your company’s property, it should be used for work only. Moreover, some companies may install software that monitors your work. ### Guided Practice + In groups of 2 or 3, set up a remote pairing environment using only Slack (or another online tool) to communicate to simulate a remote collaboration. For this, an easy to set up free online pairing system is [CodeSandbox](https://codesandbox.io/) which only needs GitHub authentication to pair. See the instructions for pairing [here](https://www.ma-no.org/en/software/development/10-collaborative-coding-tools-for-remote-pair-programming), along with other choices. While still communicating online, work on one of the Techtonica daily code challenges. If you finish it, and still have time remaining to continue, pair on one of the daily code challenges that one of you were stuck on previously. ### Independent Practice + With a colleague or fellow apprentice, do a video conference call, and help each other determine if their sound levels and lighting are acceptable, and the background appears professional. ### Challenge + In this challenge, you will use a professional online video conferencing platform and a kanban style board to solve a handful of coding challenges - 1. Form a team with 1 or 2 fellow apprentices or colleagues outside of Techtonica - 1. Assign one person to open an online video conferencing account on [Zoom](https://zoom.us/pricing) and start a session with the other participants - 1. Have another person open a Google Sheet to make a kanban board. See this [post-it kanban board](https://lifehacker.com/productivity-101-how-to-use-personal-kanban-to-visuali-1687948640) for an example. Add 3 columns to the board titled "Todo", "Doing", "Done", and share it with the group so all can edit - 1. Then have everyone navigate to [Code Wars](https://www.codewars.com/) and pick out a handful of kata challenges in JavaScript (beginners should screen for Kyu (level) 7 or 8 challenges). Click on the ones that seem interesting and copy and paste the links into the "Todo" column of the kanban board - 1. Once you have a list of 6-10 challenges, pick out one challenge for each person, and move those into the "Doing" column on the kanban board - 1. Start working on the challenges - 1. When the first person has completed a challenge, have them move the link into the "Done" column, and then pair program with one of the other people that are still working on their challenge until completed - 1. If the team has a total of two people, start another round picking two new challenges from the "Todo" column. Otherwise, if there is a third person, have the two that just wrapped up the second code challenge together team up with the third person to complete the round. Then again, pick out 3 new challenges, and repeat + +1. Form a team with 1 or 2 fellow apprentices or colleagues outside of Techtonica +1. Assign one person to open an online video conferencing account on [Zoom](https://zoom.us/pricing) and start a session with the other participants +1. Have another person open a Google Sheet to make a kanban board. See this [post-it kanban board](https://lifehacker.com/productivity-101-how-to-use-personal-kanban-to-visuali-1687948640) for an example. Add 3 columns to the board titled "Todo", "Doing", "Done", and share it with the group so all can edit +1. Then have everyone navigate to [Code Wars](https://www.codewars.com/) and pick out a handful of kata challenges in JavaScript (beginners should screen for Kyu (level) 7 or 8 challenges). Click on the ones that seem interesting and copy and paste the links into the "Todo" column of the kanban board +1. Once you have a list of 6-10 challenges, pick out one challenge for each person, and move those into the "Doing" column on the kanban board +1. Start working on the challenges +1. When the first person has completed a challenge, have them move the link into the "Done" column, and then pair program with one of the other people that are still working on their challenge until completed +1. If the team has a total of two people, start another round picking two new challenges from the "Todo" column. Otherwise, if there is a third person, have the two that just wrapped up the second code challenge together team up with the third person to complete the round. Then again, pick out 3 new challenges, and repeat See how many challenges you can get through, and save the sheet in case you have time in the future to solve more challenges. Seeing the list grow will build your confidence! ### Check for Understanding + Go onto Youtube or search for blog posts about the “pros and cons” of remote work, the etiquette of communicating online, or professional growth for remote workers. Write a short summary of what you found to be a surprise or misconception, or on the other hand, solidified your beliefs about the subject. ### Supplemental Materials + - [How to set discipline at home](https://www.youtube.com/watch?v=WqZiBugq4ts) - 3:10 video - [Overview of Kanban](https://www.atlassian.com/agile/kanban) - 5 min read, 5:30 min video - [Overview of Scrum](https://www.atlassian.com/agile/scrum) - 1 min read, 3:30 min video diff --git a/databases/relational-databases.md b/databases/relational-databases.md index 37a311019..fab32a818 100644 --- a/databases/relational-databases.md +++ b/databases/relational-databases.md @@ -19,7 +19,6 @@ Total Time: 5-6 hours - [SQL](/databases/sql.md) - [Data Models](/databases/data-models.md) - ### Motivation To understand, query, and insert information into a relational database, a technology that is commonly used to store data for web and mobile applications. Also relational database model seems very feasible because of its tabular form which makes insertion and querying easy. @@ -68,11 +67,12 @@ To understand, query, and insert information into a relational database, a techn #### Relational Database Basics - The specific problems a database solves + - Persistence of information - Centralized information - Search stored information - Form relationships between sets of information - + - Few basic column types - `varchar` - `text` @@ -105,10 +105,10 @@ To understand, query, and insert information into a relational database, a techn - `INSERT INTO` - without modifiers (entire table) - ````sql + ```sql INSERT INTO table_name VALUES (value1, value2, value3, ...); - ```` + ``` - from another table `(INSERT INTO a SELECT x, y, z from b)` - from another table with constraints `(INSERT INTO a SELECT x, y, z FROM b WHERE x = 'a thing')` diff --git a/deploying/deploying-to-heroku.md b/deploying/deploying-to-heroku.md index f2e54c5ca..534a0c742 100644 --- a/deploying/deploying-to-heroku.md +++ b/deploying/deploying-to-heroku.md @@ -53,121 +53,123 @@ Your backend, on the other hand, is dynamic -- when you make an API request, the 1. cd into the React app you created and move _everything_ into a new directory named `client`. - ``` - cd - mkdir client - mv * client - ``` + ``` + cd + mkdir client + mv * client + ``` 1. Create a server directory. Copy all the files from your Express API folder (1-3 JS files + package.json) into the `server` folder you're about to create inside your React app. _**This is where your API code will live from now on -- don't modify or use the old directory or repo**_ - ``` - mkdir server - cp -r ~/path.to.source/. ~/path.to.destination/ - # We need to keep package.json, package-lock.json, and node_modules at the top level. - mv server/package.json . - mv server/package-lock.json . - mv server/node_modules . - ``` + ``` + mkdir server + cp -r ~/path.to.source/. ~/path.to.destination/ + # We need to keep package.json, package-lock.json, and node_modules at the top level. + mv server/package.json . + mv server/package-lock.json . + mv server/node_modules . + ``` - At this point, you should have the following directory structure: + At this point, you should have the following directory structure: - ``` - ./eventonica-app - ./eventonica-app/client/* # The code for your React App - ./eventonica-app/server/* # Your express API (app.js) - ./eventonica-app/package.json # Top level package.json used by Heroku to run your app - ./eventonica-app/package-lock.json # Top level package-lock.json used by Heroku to run your app - ``` - The `*` here denotes all contents within a folder. So `./eventonica-app/client/*` refers to all the files & folders within this ‘client’ folder that make up your frontend React app. + ``` + ./eventonica-app + ./eventonica-app/client/* # The code for your React App + ./eventonica-app/server/* # Your express API (app.js) + ./eventonica-app/package.json # Top level package.json used by Heroku to run your app + ./eventonica-app/package-lock.json # Top level package-lock.json used by Heroku to run your app + ``` - `./eventonica-app/server/*` refers to all the content within this ‘server’ folder that make up your backend application using Node.js/ Express. This may include the main Node.js application file, ex. `app.js`, and the Express API connecting to the Postgres database. + The `*` here denotes all contents within a folder. So `./eventonica-app/client/*` refers to all the files & folders within this ‘client’ folder that make up your frontend React app. + + `./eventonica-app/server/*` refers to all the content within this ‘server’ folder that make up your backend application using Node.js/ Express. This may include the main Node.js application file, ex. `app.js`, and the Express API connecting to the Postgres database. 1. Test out your new server locally. - ``` - # Make sure you use the you used when you created your Express API - node server/ you used when you created your Express API + node server/", - "heroku-postbuild": "cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build" - ``` + ```json + "start": "node server/", + "heroku-postbuild": "cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build" + ``` 1. Create a free Heroku account. https://signup.heroku.com/dc. - Through the Heroku web UI, create a new Application. - Once you create the app, add the Postgres add-on by going to the Resources tab and searching in the "Add-ons" search box for Postgres. Click the "Heroku Postgres" option. Finally, select the free version and click "Provision." + Through the Heroku web UI, create a new Application. + Once you create the app, add the Postgres add-on by going to the Resources tab and searching in the "Add-ons" search box for Postgres. Click the "Heroku Postgres" option. Finally, select the free version and click "Provision." 1. Install the Heroku CLI from the command line. `brew tap heroku/brew && brew install heroku` then use `heroku login` 1. Attach your Heroku app to your code. Run `heroku git:remote -a YOUR-APP-NAME` inside the terminal at the root of your project directory. - If the command is successful, you will see the output `set git remote heroku to https://git.heroku.com/YOUR-APP-NAME.git` in the terminal. A [git remote](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes) is a version of your repository existing on another server. The output confirms that you now have a [git remote hosted on Heroku](https://devcenter.heroku.com/articles/git#creating-a-heroku-remote) — you will be pushing your code to *this* repository to deploy your app to Heroku. + If the command is successful, you will see the output `set git remote heroku to https://git.heroku.com/YOUR-APP-NAME.git` in the terminal. A [git remote](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes) is a version of your repository existing on another server. The output confirms that you now have a [git remote hosted on Heroku](https://devcenter.heroku.com/articles/git#creating-a-heroku-remote) — you will be pushing your code to _this_ repository to deploy your app to Heroku. + +1. Configure your database. Heroku will specify environment variables you can use to connect to the DB. Insert the piece of code below into the main Node.js application file (ex. `server/app.js`). Fill in your local database name in the Postgres URL. This is the default database URL when your app is running locally. -1. Configure your database. Heroku will specify environment variables you can use to connect to the DB. Insert the piece of code below into the main Node.js application file (ex. `server/app.js`). Fill in your local database name in the Postgres URL. This is the default database URL when your app is running locally. - - When you [create the database on Heroku](https://devcenter.heroku.com/articles/getting-started-with-nodejs#provision-a-database) in the next step, it will be automatically set the `DATABASE_URL` environment variable. The code snippet below ensures that the `DATABASE_URL` is used in lieu of the local Postgres URL when the app runs on Heroku. + When you [create the database on Heroku](https://devcenter.heroku.com/articles/getting-started-with-nodejs#provision-a-database) in the next step, it will be automatically set the `DATABASE_URL` environment variable. The code snippet below ensures that the `DATABASE_URL` is used in lieu of the local Postgres URL when the app runs on Heroku. - ```javascript - const { Pool } = require('pg'); - new Pool({ - // Make sure you swap out for the name you gave your postgres database - connectionString: process.env.DATABASE_URL || 'postgres://localhost:5432/' - // Use SSL only in production - ssl: process.env.NODE_ENV === 'production' - }); - ``` + ```javascript + const { Pool } = require('pg'); + new Pool({ + // Make sure you swap out for the name you gave your postgres database + connectionString: process.env.DATABASE_URL || 'postgres://localhost:5432/' + // Use SSL only in production + ssl: process.env.NODE_ENV === 'production' + }); + ``` - Note: If you haven't previously, install [`node-postgres`](https://node-postgres.com/) using `npm install pg` on the terminal. This module is used to connect to the database. + Note: If you haven't previously, install [`node-postgres`](https://node-postgres.com/) using `npm install pg` on the terminal. This module is used to connect to the database. 1. Use Heroku to create the database tables you need. - `heroku pg:psql` You should use the same commands you ran to create your database locally `create table events (.....)` - If you've forgotten, `psql` into your local database and check your table schema with `\d events`. Copy that schema into your new Heroku database. + `heroku pg:psql` You should use the same commands you ran to create your database locally `create table events (.....)` + If you've forgotten, `psql` into your local database and check your table schema with `\d events`. Copy that schema into your new Heroku database. 1. Commit everything! - ``` - git add server - git add client - git add package.json + ``` + git add server + git add client + git add package.json - git commit -am "Heroku setup\!" - ``` - Ensure you don't have any missing files: `git status` and commit them if you need to. + git commit -am "Heroku setup\!" + ``` + + Ensure you don't have any missing files: `git status` and commit them if you need to. 1. Deploy your app! -`git push heroku main` This takes a long time. This will print the URL your app was deployed to. Trying going to it. If something goes wrong, use `heroku logs --tail` to debug. + `git push heroku main` This takes a long time. This will print the URL your app was deployed to. Trying going to it. If something goes wrong, use `heroku logs --tail` to debug. ### Wrapping Up @@ -183,14 +185,13 @@ Lastly, we'll configure your create-react-app client to work seamlessly with you - Don't forget to configure `port` to come from `process.env` - Use `heroku logs --tail` to see what's wrong -All done! Small differences in the way you've set up your site may make bits of this process not work as expected, so there may be some debugging required. +All done! Small differences in the way you've set up your site may make bits of this process not work as expected, so there may be some debugging required. Here is a [sample repository](https://github.com/esausilva/example-create-react-app-express) that’s been deployed to Heroku using steps in this [blog post](https://esausilva.com/2017/11/14/how-to-use-create-react-app-with-a-node-express-backend-api/). The project uses React for the frontend & Node.js/ Express for the backend. Note: the project does not make use of a Postgres database. Here is a repository with similar heroku deployment steps performed entirely using the command line and heroku CLI: https://github.com/FTraian/node-express-postgresql-heroku-tutorial. [[Heroku CLI Documentation, for reference]](https://devcenter.heroku.com/articles/heroku-cli-commands) - ### Supplemental Resources - [Tutorial - Heroku Dev Center Deployment](https://devcenter.heroku.com/articles/deploying-nodejs) -- [Overview of Deployment Options - MDN Express & Node Deployment](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/deployment) \ No newline at end of file +- [Overview of Deployment Options - MDN Express & Node Deployment](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/deployment) diff --git a/deploying/deploying.md b/deploying/deploying.md index 2e486a8f5..7229d3592 100644 --- a/deploying/deploying.md +++ b/deploying/deploying.md @@ -105,7 +105,7 @@ if (process.env.NODE_ENV === 'production') { // Serve any static files app.use(express.static(path.join(__dirname, '../client/build'))); // Handle React routing, return all requests to React app - app.get('*', function(req, res) { + app.get('*', function (req, res) { res.sendFile(path.join(__dirname, '../client/build', 'index.html')); }); } @@ -124,18 +124,16 @@ You can replace `node server/server.js` with whatever you named your API code file. 7. Create a free Heroku account at https://signup.heroku.com/dc. - Through the Heroku web UI, create a new Application. - Once you create the app, add the Postgres add-on by going to the Resources tab - and searching in the "Add-ons" search box for Postgres. - Click the "Heroku Postgres" option. Finally, select the free version and click "Provision". - Or you can create a new Application from the CLI. To create an application with name, install the Heroku CLI and run the following command - ```heroku create app_name``` + ThroughtheHerokuwebUI,createanewApplication.Onceyoucreatetheapp,addthePostgresadd-onbygoingtotheResourcestabandsearchinginthe"Add-ons"searchboxforPostgres.Clickthe"HerokuPostgres"option.Finally,selectthefreeversionandclick"Provision".OryoucancreateanewApplicationfromtheCLI.Tocreateanapplicationwithname,installtheHerokuCLIandrunthefollowingcommand`heroku create app_name` This command will only be used on an initialized git repository. In that case, the command creates the application as well as a git remote, that you can use to push your code to Heroku: + ```mkdir example cd example git init heroku apps:create app_name + ``` + 8. Install the Heroku CLI: `brew tap heroku/brew && brew install heroku` then use `heroku login` 9. Attach your Heroku app to your code by running `heroku git:remote -a YOUR-APP-NAME` diff --git a/dev-tools/command-line-advanced.md b/dev-tools/command-line-advanced.md index 8945e6174..e67ce88bd 100644 --- a/dev-tools/command-line-advanced.md +++ b/dev-tools/command-line-advanced.md @@ -50,6 +50,7 @@ Front-end development is web development, and the web has a strong bias towards - [Input/Output Redirection in the Shell (Bash and zsh)](https://thoughtbot.com/blog/input-output-redirection-in-the-shell) **Video Tutorials** + - [Learn Zsh in 80 Mins (Oh My ZSH)](https://www.youtube.com/watch?v=MSPu-lYF-A8) - [Apropos command (3 min)](https://www.youtube.com/watch?v=jxQzuha8TbU) - [Pushd & Popd command (2 min)](https://www.youtube.com/watch?v=CdWazJlfue8) @@ -209,46 +210,55 @@ This lesson helps you create an executable script. It will read information from 2. Create a small file with the filename 'lunch' (not lunch.txt) by typing `touch lunch`. 3. Using a text editor of your choice, modify the contents of this brand-new `lunch` file so that it contains the following text: - ```sh - lunch=$1 - echo $lunch is for lunch - ``` - `$1` refers to the first argument a user will pass into the lunch program. - Save the file and, if you're using a command line text editor, exit it. + + ```sh + lunch=$1 + echo $lunch is for lunch + ``` + + `$1` refers to the first argument a user will pass into the lunch program. + Save the file and, if you're using a command line text editor, exit it. 4. Return to the command line. Make sure you're in the directory that `lunch` is in. Make the file `lunch` into an executable file by running this command: - ```sh - chmod a+x lunch - ``` + + ```sh + chmod a+x lunch + ``` 5. Run your new tiny program on the command line by typing the filename preceded by `./` - First, try running it with no arguments. - ```sh - ./lunch - ``` - You will see nothing for lunch because we haven't specified any arguments yet. Try running your program again, but pass in the argument `Soda`, like so: - ```sh - ./lunch Soda - ``` - You should see that Soda is for lunch! + First, try running it with no arguments. + + ```sh + ./lunch + ``` + + You will see nothing for lunch because we haven't specified any arguments yet. Try running your program again, but pass in the argument `Soda`, like so: + + ```sh + ./lunch Soda + ``` + + You should see that Soda is for lunch! 6. Now create a file containing some foods. This time we're going to add text to it without using any text editors (either command line or graphical) by using the shovel operators we talked about above. The first command has double quotes because `&` is a special character. Enter these commands one at a time in your command line: - ```sh - echo "mac & cheese" > foods.txt - echo dim sum >> foods.txt - echo an apple >> foods.txt - ``` - After this, type `cat foods.txt` into your command line to check the contents of your new `foods.txt` file. + + ```sh + echo "mac & cheese" > foods.txt + echo dim sum >> foods.txt + echo an apple >> foods.txt + ``` + + After this, type `cat foods.txt` into your command line to check the contents of your new `foods.txt` file. 7. Edit `lunch` by adding these two new lines to the bottom, so the file ends up looking like this: - ```sh - lunch=$1 - echo $lunch is for lunch - echo We also offer: - cat foods.txt - ``` + ```sh + lunch=$1 + echo $lunch is for lunch + echo We also offer: + cat foods.txt + ``` Save and exit your text editor. @@ -263,32 +273,38 @@ Greg's Wiki is full of common mistakes (e.g. [why you shouldn't parse ls](http:/ Now you know how to move using your command line, let's get deep into [Homebrew](https://brew.sh/). It's a package manager for masOS or Linux which provides a simple way to install programs or tools, similar to an app store for CLI. Before getting started, check that the following requirements are fullfilled: -|macOS |Linux | +|macOS |Linux | |------------------|-------------| |**64-bit Intel** CPU | **64-bit x86_64** CPU | -| Compatible shell (`.bash` or **zsh**)| **GCC** 4.7.0 or newer | +| Compatible shell (`.bash` or **zsh**)| **GCC** 4.7.0 or newer | |**macOS** 10.13 or newer|**Linux** 2.6.32 or newer| |Command Line Tools for [Xcode](https://apps.apple.com/us/app/xcode/id497799835)|**Glibc** 2.13 or newer| Then, installation will take three steps: + 1. Open a macOS Terminal or Linux shell prompt. 2. Run the install script : + ```sh /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" ``` + 3. Verify your installation checking its version: `brew --version`. If no errors appear, everything went perfectly. -For further details, visit [Homebrew installation page](https://docs.brew.sh/Installation). + For further details, visit [Homebrew installation page](https://docs.brew.sh/Installation). 4. Finally, run `brew doctor` which will check your system for potential problems. #### Applications Now that it's installed, prompt can be used to manage the packages we need: + ```sh brew install package-name ``` + And `package-name` can be any package from the [listing](https://formulae.brew.sh/formula/) that Homebrew provides. Let's see an example of how to install `wget`: `brew install wget` After that, to check that it has been properly installed, we can verify that the version of the package installed matches with the one provided in the [listing](https://formulae.brew.sh/formula/). + ```sh wget --version ``` @@ -296,12 +312,14 @@ wget --version ### Independent Practice Spend 15 minutes checking out these materials: + - [A User's Guide to the Z-Shell](http://zsh.sourceforge.net/Guide/zshguide.html) - [Filenames and Pathnames in Shell: How to do it Correctly](https://www.dwheeler.com/essays/filenames-in-shell.html) - [Input/Output Redirection in the Shell (Bash and zsh)](https://thoughtbot.com/blog/input-output-redirection-in-the-shell) ### Challenge with Homebrew -Try to install other optional utility using Homebrew, for example `tree` . + +Try to install other optional utility using Homebrew, for example `tree` . ### Challenge with `Awk` Command diff --git a/dev-tools/command-line-interface.md b/dev-tools/command-line-interface.md index ab5fec4e7..bfc8d8bc5 100644 --- a/dev-tools/command-line-interface.md +++ b/dev-tools/command-line-interface.md @@ -29,13 +29,14 @@ $ cd Downloads/ ``` ### Installation and Set Up zsh -If you recently purchased a Mac with the latest operating system, **Catalina**, *zsh* is already installed by default. You can check your current default shell by entering the command below: + +If you recently purchased a Mac with the latest operating system, **Catalina**, _zsh_ is already installed by default. You can check your current default shell by entering the command below: ``` echo $SHELL ``` -If the result turns out to be `/bin/zsh`, then you already have *zsh* set as your default shell. If not, you can change your default shell using the `chsh` command: +If the result turns out to be `/bin/zsh`, then you already have _zsh_ set as your default shell. If not, you can change your default shell using the `chsh` command: ``` chsh -s /bin/zsh @@ -43,7 +44,7 @@ chsh -s /bin/zsh When prompted, enter your password. Log off your terminal and log back on for the changes to apply. -If you do not have *zsh* installed yet, you can install it using Homebrew. +If you do not have _zsh_ installed yet, you can install it using Homebrew. If you have [Homebrew](http://brew.sh/) installed, use this command: @@ -52,6 +53,7 @@ brew install zsh ``` #### Installing Homebrew + If your system does not have Homebrew installed, you need to have **Xcode** installed first. To check and see if you have Xcode installed, enter the following in the Terminal: ``` @@ -71,7 +73,7 @@ source=Apple source=Apple System ``` -If the results are anything else other than the above three, you can install Xcode from the [Mac App Store](https://apps.apple.com/us/app/xcode/id497799835?mt=12). Once you have *XCode* installed, you can install Homebrew by entering this in the Terminal below: +If the results are anything else other than the above three, you can install Xcode from the [Mac App Store](https://apps.apple.com/us/app/xcode/id497799835?mt=12). Once you have _XCode_ installed, you can install Homebrew by entering this in the Terminal below: ``` ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" @@ -85,19 +87,19 @@ brew help #### Installing zsh -With both XCode and Homebrew installed, you can install *zsh* with the following command: +With both XCode and Homebrew installed, you can install _zsh_ with the following command: ``` brew install zsh ``` -After installation, you can set *zsh* as your default shell with the command below: +After installation, you can set _zsh_ as your default shell with the command below: ``` chsh -s /bin/zsh ``` -Lastly, log out of your Terminal and log back in. You can check again to be sure that *zsh* is your default shell: +Lastly, log out of your Terminal and log back in. You can check again to be sure that _zsh_ is your default shell: ``` echo $SHELL @@ -108,6 +110,7 @@ The result should give you the default shell the Terminal was set up and shell's ### Objectives **Participants will be able to:** + - Create a directory and files - Navigate to a directory - Change the name of the file @@ -259,7 +262,7 @@ Scroll through the manual and see if you can get an idea of what the format of a #### Configure your Terminal with Oh My ZSH (Optional) -[Oh My ZSH](https://ohmyz.sh/) is a framework created specifically for configuring and customizing *zsh*. You can download a variety of plugins and themes to customize your look and efficiency of your Terminal. Please follow the guidelines [here](https://github.com/ohmyzsh/ohmyzsh) on how to set up and install Oh My ZSH. +[Oh My ZSH](https://ohmyz.sh/) is a framework created specifically for configuring and customizing _zsh_. You can download a variety of plugins and themes to customize your look and efficiency of your Terminal. Please follow the guidelines [here](https://github.com/ohmyzsh/ohmyzsh) on how to set up and install Oh My ZSH. You can also use the complete [Oh My ZSH Wiki](https://github.com/ohmyzsh/ohmyzsh/wiki) on how to customize and configure your Terminal further. @@ -274,15 +277,16 @@ In some cases, you would see mentions and suggestions to download and use third- - Differentiate between Absolute and Relative path. ### Supplemental Materials + - [A Guide for Upgrading macOS Catalina and Migrating the Default Shell from Bash to zsh](https://dev.to/saltyshiomix/a-guide-for-upgrading-macos-to-catalina-and-migrating-the-default-shell-from-bash-to-zsh-4ep3) - [Lifehacker's intro command line article](http://lifehacker.com/5633909/who-needs-a-mouse-learn-to-use-the-command-line-for-almost-anything) - [Getting Started with zsh](https://opensource.com/article/19/9/getting-started-zsh) - [10 Zsh Tips & Tricks: Configuration, Customization & Usage](https://www.sitepoint.com/zsh-tips-tricks/) - [Jazz Up Your zsh Terminal In Seven Steps - A Visual Guide](https://www.freecodecamp.org/news/jazz-up-your-zsh-terminal-in-seven-steps-a-visual-guide-e81a8fd59a38/) -- [Learning ZSH](https://riptutorial.com/Download/zsh.pdf) - eBook which also includes *Oh My ZSH* and other useful ZSH features. +- [Learning ZSH](https://riptutorial.com/Download/zsh.pdf) - eBook which also includes _Oh My ZSH_ and other useful ZSH features. - [Bash vs. zsh: A Comparison of two command line shells](https://sunlightmedia.org/bash-vs-zsh/) - General comparisons and differences between Bash and zsh. - [Filenames and Pathnames in Shell: How to do it Correctly](https://www.dwheeler.com/essays/filenames-in-shell.html) - [TLDR: Crowd sourced and simplified man pages](https://tldr.ostera.io/) -- [Command Line Power User](https://commandlinepoweruser.com) - A free command line course using *zsh* and other *zsh*-related tools. -- Kiddle, Oliver, Peek, Jerry, and Stepheson, Peter. *From Bash to Z Shell: Conquering the Command Line*. Apress, 2005. -- Kissel, Joe. *Take Control of The Mac Command Line With Terminal*, Third Edition. alt concepts inc, 2020. +- [Command Line Power User](https://commandlinepoweruser.com) - A free command line course using _zsh_ and other _zsh_-related tools. +- Kiddle, Oliver, Peek, Jerry, and Stepheson, Peter. _From Bash to Z Shell: Conquering the Command Line_. Apress, 2005. +- Kissel, Joe. _Take Control of The Mac Command Line With Terminal_, Third Edition. alt concepts inc, 2020. diff --git a/dev-tools/dot-profile.md b/dev-tools/dot-profile.md index f590ecbca..1560893f0 100644 --- a/dev-tools/dot-profile.md +++ b/dev-tools/dot-profile.md @@ -15,8 +15,8 @@ Here are links to lessons that should be completed before this lesson: With knowledge about dot profile, you can customize your computer’s environment. -The *.zshrc*`* file is a personal initialization file for configuring the user environment [(Sample .zshrc file/template)](http://zsh.sourceforge.net/Contrib/startup/std/zshrc). -Below are a few things that make configuring *.zshrc* easier and faster: +The _.zshrc_`_ file is a personal initialization file for configuring the user environment [(Sample .zshrc file/template)](http://zsh.sourceforge.net/Contrib/startup/std/zshrc). +Below are a few things that make configuring _.zshrc\* easier and faster: - You can create your own shortcuts and use them. - It gives you more control to change your environment. @@ -32,12 +32,14 @@ Below are a few things that make configuring *.zshrc* easier and faster: - Create an alias ### Materials + - [Moving to zsh](https://scriptingosx.com/zsh/): online zsh guide and eBook specifically for MacOS. -**Note**: If you did not complete the optional Oh My ZSH challenge from the *Command Line Interface*(/command-line/command-line-interface.md) lesson and plan to make your own customizations, please install Oh My ZSH(https://ohmyz.sh/) first. Oh My ZSH will automatically write its default configurations in *.zshrc* and will possibly overwrite any similar customizations if manual configurations were done first. -You can also refer to the [Moving to zsh](https://scriptingosx.com/2019/06/moving-to-zsh-part-2-configuration-files/) online guide/eBook for more information about the above video tutorials and how to add them to your *.zshrc* file. + **Note**: If you did not complete the optional Oh My ZSH challenge from the _Command Line Interface_(/command-line/command-line-interface.md) lesson and plan to make your own customizations, please install Oh My ZSH(https://ohmyz.sh/) first. Oh My ZSH will automatically write its default configurations in _.zshrc_ and will possibly overwrite any similar customizations if manual configurations were done first. + You can also refer to the [Moving to zsh](https://scriptingosx.com/2019/06/moving-to-zsh-part-2-configuration-files/) online guide/eBook for more information about the above video tutorials and how to add them to your _.zshrc_ file. **Video tutorials** -The following video tutorials below are the same with zsh, but create these settings by editing the *.zshrc* file. +The following video tutorials below are the same with zsh, but create these settings by editing the _.zshrc_ file. + - [Learn Zsh in 80 Minutes - Oh My Zsh - Command Line Power User](https://www.youtube.com/watch?v=MSPu-lYF-A8) - [Zsh: Syntax Highlighting, vi-mode, Autocomplete, more](https://youtu.be/eLEo4OQ-cuQ) - [Command Line Power User](https://commandlinepoweruser.com/): Free online video tutorial course using Zsh. @@ -68,12 +70,12 @@ to change to your home directory. You can add your own environmental variables. mkdir $HOME/scripts ``` -. Open `~/.zshrc` and add the following: `export SCRIPTS="$HOME/scripts"`. -The export command is saying that you want to make `SCRIPTS` available anytime time *.zshrc* file is loaded. Since -*.zshrc* is loaded each time you open up new terminal shell its always available. -Close the shell and open a new terminal shell. -To use an environmental variable you need to prepend it with the dollar sign. -Change your directory to scripts using your environmental variable: +. Open `~/.zshrc` and add the following: `export SCRIPTS="$HOME/scripts"`. +The export command is saying that you want to make `SCRIPTS` available anytime time _.zshrc_ file is loaded. Since +_.zshrc_ is loaded each time you open up new terminal shell its always available. +Close the shell and open a new terminal shell. +To use an environmental variable you need to prepend it with the dollar sign. +Change your directory to scripts using your environmental variable: ``` cd $SCRIPTS @@ -105,8 +107,8 @@ chmod a+x ~/scripts/hello_world ``` - Let's add line to our `.zshrc` file: `export PATH=$PATH:$HOME/scripts`. What this says is that everytime we open -a terminal shell all of the files that are inside of `$HOME/scripts` which is the same as `~/scripts` can be called -from anywhere. + a terminal shell all of the files that are inside of `$HOME/scripts` which is the same as `~/scripts` can be called + from anywhere. - Save & open a new Terminal window or `source ~/.zshrc` and type the following to demonstrate: @@ -122,7 +124,7 @@ of helpful libraries are written using scripts in this way. Please refer to (Moving to zsh: Alias and Functions)[https://scriptingosx.com/2019/07/moving-to-zsh-part-4-aliases-and-functions/] for more information. -It's often helpful to make commands for yourself that are short cuts. Zsh aliases allows you to set a shortcut command for a longer command. For example what if you want to change to your directory but you don't want to type `cd ~/scripts`. What if you could just type `cdscr` instead? Aliases can be defined in your *.zshrc* file. +It's often helpful to make commands for yourself that are short cuts. Zsh aliases allows you to set a shortcut command for a longer command. For example what if you want to change to your directory but you don't want to type `cd ~/scripts`. What if you could just type `cdscr` instead? Aliases can be defined in your _.zshrc_ file. An alias has the following structure: @@ -136,21 +138,22 @@ Let's make a file called `aliases` in our scripts folder, type the following: alias cdscr='cd "$HOME/scripts"' ``` -Next let's add the following to our `~/.zshrc`: +Next let's add the following to our `~/.zshrc`: ``` source "$HOME/scripts/aliases" ``` When we type source and a file after it, it's saying, import all of the aliases in our file so we can call them -by name no matter where we are in our file system. That's why we do the same when we make changes to our `.zshrc`. +by name no matter where we are in our file system. That's why we do the same when we make changes to our `.zshrc`. When we open a new terminal window after changing our `.zshrc` the system essentiall calls `source .zshrc` before -we do anything. +we do anything. Let's test our alias. -- Save & open a new Terminal window or `source ~/.zshrc` -- type ```cdsrc``` and hit enter. You should now be in `~/scripts` + +- Save & open a new Terminal window or `source ~/.zshrc` +- type `cdsrc` and hit enter. You should now be in `~/scripts` #### Nano Tool @@ -169,7 +172,7 @@ Nano is a Linux command line text editor. It is relatively easy to learn and use You can change the value of your system's environmental files to change how your termimal prompt appears. -The $PS1 variable sets what you see. +The \$PS1 variable sets what you see. Add the following to your `.zshrc` change what your prompt displays: `export PS1="\u@\h "` Save & open a new Terminal window or `source ~/.zshrc` to reload this. Notice how the prompt now displays something simliar to `david@Davids-MacBook-Pro` now. @@ -177,9 +180,11 @@ Save & open a new Terminal window or `source ~/.zshrc` to reload this. Notice ho (Optional:) More info on - (Moving to zsh: Customizing the zsh Prompt)[https://scriptingosx.com/2019/07/moving-to-zsh-06-customizing-the-zsh-prompt/]. ### Common Mistakes & Misconceptions -Sometimes people think they need to have a different set of files to configure and customize like Bash and other shells. Zsh only requires one file, *.zshrc*, to have all these configurations. + +Sometimes people think they need to have a different set of files to configure and customize like Bash and other shells. Zsh only requires one file, _.zshrc_, to have all these configurations. ### Independent Practice + [Moving to Zsh](https://scriptingosx.com/2019/06/moving-to-zsh/): A comprehensive guide to Zsh specifically for Mac users from the basics, configuration, to advanced scripting. ### Check for understanding @@ -187,4 +192,4 @@ Sometimes people think they need to have a different set of files to configure a - How do you export environment variables to make them always available when you open a terminal shell? - How do you add a file to the `$PATH` environment variable? - How do you change the terminal prompt? -- How do you create an alias? \ No newline at end of file +- How do you create an alias? diff --git a/electives/databases/mongoose.md b/electives/databases/mongoose.md index 9745c37c9..dc1c57082 100644 --- a/electives/databases/mongoose.md +++ b/electives/databases/mongoose.md @@ -54,7 +54,7 @@ Some great reference resources to get you started: ### Common Mistakes / Misconceptions - **"I already learned how to use MongoDB database on its shell. I'll just stick with that. They both store data anyway."** - To understand why you must/can make use of ORM/ODM's check out this great Medium article: ['What is an ORM and Why You Should Use It' by Mario Hoyos](https://blog.bitsrc.io/what-is-an-orm-and-why-you-should-use-it-b2b6f75f5e2a) (4 min read). + Tounderstandwhyyoumust/canmakeuseofORM/ODM'scheckoutthisgreatMediumarticle:['What is an ORM and Why You Should Use It' by Mario Hoyos](https://blog.bitsrc.io/what-is-an-orm-and-why-you-should-use-it-b2b6f75f5e2a) (4 min read). ### Guided Practice @@ -107,9 +107,9 @@ We'll be using the Mongoose npm package to build a small app. Do this by using t ``` We'll be adding data to the database named dog_app with a collection with Schema defined as above. - Check the configuration by running the following command: - `node app.js` - If you don't receive any errors on your node console then you're good to go forward. + Checktheconfigurationbyrunningthefollowingcommand: + `node app.js` + Ifyoudon'treceiveanyerrorsonyournodeconsolethenyou'regoodtogoforward. **4. Adding/Inserting data to the data base with the `create()` method** @@ -244,10 +244,10 @@ Form small groups and discuss: - [List of popular ORMs](https://en.wikipedia.org/wiki/List_of_object-relational_mapping_software) - Some other MongoDB ORM/ODMs: - -[Caminte](https://www.npmjs.com/package/caminte) - -[Cormo](https://www.npmjs.com/package/cormo) - -[Node-ORM](https://www.npmjs.com/package/node-orm) + -[Caminte](https://www.npmjs.com/package/caminte) + -[Cormo](https://www.npmjs.com/package/cormo) + -[Node-ORM](https://www.npmjs.com/package/node-orm) - Some Relational-Database ORM/ODMs: - -[Sequelize](https://www.npmjs.com/package/sequelize) - -[Book Shelf](https://www.npmjs.com/package/bookshelf) + -[Sequelize](https://www.npmjs.com/package/sequelize) + -[Book Shelf](https://www.npmjs.com/package/bookshelf) diff --git a/electives/mocha-testing.md b/electives/mocha-testing.md index f0169ec9a..759525c35 100644 --- a/electives/mocha-testing.md +++ b/electives/mocha-testing.md @@ -96,12 +96,12 @@ _Syntax_ ```javascript const assert = require('assert'); -describe('Mocha String Test', function() { - it('should return the exact number of characters in a string', function() { +describe('Mocha String Test', function () { + it('should return the exact number of characters in a string', function () { assert.equal('Hello'.length, 4); // this line will fail }); - it('should return first character of the string', function() { + it('should return first character of the string', function () { assert.equal('Hello'.charAt(0), 'H'); // this line will pass }); }); @@ -137,7 +137,7 @@ Mocha String Test var assert = require('assert'); function asyncFunction(stringToTest, callback) { - setTimeout(function() { + setTimeout(function () { callback(stringToTest.charAt(0) === 'H'); }, 1); } @@ -145,9 +145,9 @@ function asyncFunction(stringToTest, callback) { // Note: setTimeout has been used to simulate the async behavior // Warn: Using setTimeout is not the best practice since it's execution time is unpredictable or unreliable -describe('Mocha String Test', function() { - it('should return first character of the string', function(done) { - asyncFunction('Hello', function(isValid) { +describe('Mocha String Test', function () { + it('should return first character of the string', function (done) { + asyncFunction('Hello', function (isValid) { assert.equal(isValid, true); done(); }); diff --git a/git/git-version-control.md b/git/git-version-control.md index 2c0cb69aa..5e8f15933 100644 --- a/git/git-version-control.md +++ b/git/git-version-control.md @@ -102,8 +102,9 @@ _Imagine you are coloring on a flower coloring book. You colored in green for al Techtonica staff will assign pairs. Go through the following steps on one pair partner's computer first, then go through all the steps again the other pair partner's computer. The repetition of doing this twice will help solidify the new concepts. 1. Launch your Terminal and run `git --version`. If a version number appears, you already have git installed. If a version number does not appear: - - Install `git` via Homebrew: `brew install git` -> If Homebrew isn't install, check out [Command Line Advanced lesson](/dev-tools/command-line-advanced.md). + + - Install `git` via Homebrew: `brew install git` + > If Homebrew isn't install, check out [Command Line Advanced lesson](/dev-tools/command-line-advanced.md). - Or run `git` and follow the prompts to install Git. 2. Using the Terminal, navigate to the Desktop. diff --git a/javascript/JavaScript-React-Modularity.md b/javascript/JavaScript-React-Modularity.md index 3bd2a5c80..0ae8f22a6 100644 --- a/javascript/JavaScript-React-Modularity.md +++ b/javascript/JavaScript-React-Modularity.md @@ -11,47 +11,57 @@ Check for Understanding:20 min There is not touch prerequisites for learning JavaScript. Here are some of the prerequisite for learning JavaScript: -+ Basic programming knowledge. Knowledge of core Java sufficient. +- Basic programming knowledge. Knowledge of core Java sufficient. -+ You should have knowledge of HTML. Check [HTML tutorials here.](https://github.com/Techtonica/curriculum/blob/main/web/html.md) +- You should have knowledge of HTML. Check [HTML tutorials here.](https://github.com/Techtonica/curriculum/blob/main/web/html.md) ### Motivation Why it is worth learning React Modularity? -+ React is scalable -+ React has an awesome community. -+ React is preferred by developers. -+ React is just cool. - +- React is scalable +- React has an awesome community. +- React is preferred by developers. +- React is just cool. ## Objective of React Modularity -+ Understand why it's important to split up our code into smaller files -+ Learn how `import` and `export` support our ability to build modular code -+ Understand the different ways to import and export code +- Understand why it's important to split up our code into smaller files +- Learn how `import` and `export` support our ability to build modular code +- Understand the different ways to import and export code ## Lesson + React is a JavaScript library (not a framework) that creates user interfaces (UIs) in a predictable and efficient way using declarative code. You can use it to help build single page applications and mobile apps, or to build complex apps if you utilise it with other libraries. React works in declarative code. -[For more reference](https://github.com/Techtonica/curriculum/tree/main/react-js) +[For more reference](https://github.com/Techtonica/curriculum/tree/main/react-js) ### Modular Code + Modular code is code that is separated into segments (modules), where each file is responsible for a feature or specific functionality. Developers separate their code into modules for many reasons: 1. Adhere to the single-responsiblity principle -+ Each module is responsible for accomplishing a certain piece of functionality, or adding a specific feature to the application + +- Each module is responsible for accomplishing a certain piece of functionality, or adding a specific feature to the application + 2. Easier to navigate -+ Modules that are separated and clearly named make code more readable for other developers + +- Modules that are separated and clearly named make code more readable for other developers + 3. Easier to debug -+ Bugs have less room to hide in isolated, contained code + +- Bugs have less room to hide in isolated, contained code + 4. Produce clean and DRY code -+ Modules can be reused and repurposed throughout applications + +- Modules can be reused and repurposed throughout applications ##### Example + 1. **React Component Example** + ``` function Welcome(props) { return

Hello, {props.name}

; @@ -63,9 +73,11 @@ ReactDOM.render( document.getElementById('root') ); ``` + `name="Faisal Arkan"`will give value into `{props.name}` from `function Welcome(props)` and returning a component that has given value by `name="Faisal Arkan"`. After that React will render the element into html. 2. **Class Type Components** + ``` class Cat extends React.Component { constructor(props) { @@ -89,9 +101,10 @@ class Cat extends React.Component { ``` 3. **Functional Components** + ``` const Cat = props => { - return ( + return (

{props.name}

{props.color}

@@ -99,12 +112,13 @@ const Cat = props => { ); }; ``` -[For more reference](https://www.freecodecamp.org/news/react-examples-reactjs/ ) - +[For more reference](https://www.freecodecamp.org/news/react-examples-reactjs/) ### Guided Practice + 1. **Modularizing React Code:** React makes the modularization of code easy by introducing the component structure. + ``` class Hogwarts extends React.Component { render() { @@ -116,7 +130,9 @@ class Hogwarts extends React.Component { } } ``` + It's standard practice to give each of these components their own file. It is not uncommon to see a React program file tree that looks something like this: + ``` ├── README.md ├── public @@ -125,9 +141,11 @@ It's standard practice to give each of these components their own file. It is no ├── Hogwarts.js └── Houses.js ``` + 2. **Export Default:** We can only use export default once per module. The syntax allows us to disregard naming conventions when we want to import the given module. **For example:** + ``` // src/houses/HagridsHouse.js import React from 'react'; @@ -138,6 +156,7 @@ function whoseHouse() { export default whoseHouse; ``` + [For more Reference](https://learn.co/lessons/react-modular-code) ### Independent Practice @@ -148,8 +167,7 @@ export default whoseHouse; 1. Build a social media app 2. Build an E-Commerce App -[To know more](https://www.freecodecamp.org/news/5-react-projects-you-need-in-your-portfolio/) - + [To know more](https://www.freecodecamp.org/news/5-react-projects-you-need-in-your-portfolio/) ### Supplementary Materials diff --git a/javascript/React_JavaScript.md b/javascript/React_JavaScript.md index d73c1d151..d81104a80 100644 --- a/javascript/React_JavaScript.md +++ b/javascript/React_JavaScript.md @@ -11,20 +11,21 @@ Check for Understanding:20 min There is not touch prerequisites for learning JavaScript. Here are some of the prerequisite for learning JavaScript: -+ Basic programming knowledge. Knowledge of core Java sufficient. +- Basic programming knowledge. Knowledge of core Java sufficient. -+ You should have knowledge of HTML. Check [HTML tutorials here.](https://github.com/Techtonica/curriculum/blob/main/web/html.md) +- You should have knowledge of HTML. Check [HTML tutorials here.](https://github.com/Techtonica/curriculum/blob/main/web/html.md) ### Motivation Why it is worth learning JavaScript? -+ **Implement Client-Side Scripts:** The web developers can easily write custom client-side scripts in JavaScript, and integrate the scripts seamlessly into HTML. They can further use JavaScript to make the web pages interactive, respond to users instantaneously, and create richer user interfaces, without less server interaction and reduces server load. -+ **Responsive Web Design:** Most developers nowadays adopt responsive web design to make a website accessible and look good across multiple browsers, devices and browsers.The developers must use JavaScript to optimize web pages for mobile devices. -+ **Google AMP Project:** Google has initiated the Accelerated Mobile Pages (AMP) project to create websites that deliver richer user experience across varying mobile devices. Google has combined several optimization techniques to increase the loading speed of mobile web pages directly.The programmers have to use JavaScript while optimizing websites for mobile devices with AMP. -[For more reference](https://medium.com/@mindfiresolutions.usa/how-important-is-javascript-for-modern-web-developers-2854309b9f52) +- **Implement Client-Side Scripts:** The web developers can easily write custom client-side scripts in JavaScript, and integrate the scripts seamlessly into HTML. They can further use JavaScript to make the web pages interactive, respond to users instantaneously, and create richer user interfaces, without less server interaction and reduces server load. +- **Responsive Web Design:** Most developers nowadays adopt responsive web design to make a website accessible and look good across multiple browsers, devices and browsers.The developers must use JavaScript to optimize web pages for mobile devices. +- **Google AMP Project:** Google has initiated the Accelerated Mobile Pages (AMP) project to create websites that deliver richer user experience across varying mobile devices. Google has combined several optimization techniques to increase the loading speed of mobile web pages directly.The programmers have to use JavaScript while optimizing websites for mobile devices with AMP. + [For more reference](https://medium.com/@mindfiresolutions.usa/how-important-is-javascript-for-modern-web-developers-2854309b9f52) ## Lesson + React is a JavaScript library (not a framework) that creates user interfaces (UIs) in a predictable and efficient way using declarative code. You can use it to help build single page applications and mobile apps, or to build complex apps if you utilise it with other libraries. React works in declarative code. [For more reference](https://github.com/Techtonica/curriculum/tree/main/react-js) @@ -32,7 +33,9 @@ React works in declarative code. 1. [Tutorial Using slide](https://www.slideshare.net/asllani94/introduction-to-react-js-63948385) ##### Example + 1. **React Component Example** + ``` function Welcome(props) { return

Hello, {props.name}

; @@ -44,9 +47,11 @@ ReactDOM.render( document.getElementById('root') ); ``` + `name="Faisal Arkan"`will give value into `{props.name}` from `function Welcome(props)` and returning a component that has given value by `name="Faisal Arkan"`. After that React will render the element into html. 2. **Class Type Components** + ``` class Cat extends React.Component { constructor(props) { @@ -70,9 +75,10 @@ class Cat extends React.Component { ``` 3. **Functional Components** + ``` const Cat = props => { - return ( + return (

{props.name}

{props.color}

@@ -80,15 +86,16 @@ const Cat = props => { ); }; ``` -[For more reference](https://www.freecodecamp.org/news/react-examples-reactjs/ ) +[For more reference](https://www.freecodecamp.org/news/react-examples-reactjs/) ## Common Mistake and Misconceptions 1. **Creating memory leaks** -Memory leaks are almost inevitable JavaScript problems if you’re not consciously coding to avoid them. There are numerous ways for them to occur, so we’ll just highlight a couple of their more common occurrences. + Memory leaks are almost inevitable JavaScript problems if you’re not consciously coding to avoid them. There are numerous ways for them to occur, so we’ll just highlight a couple of their more common occurrences. #### Example: + ``` var theThing = null; var replaceThing = function () { @@ -109,6 +116,7 @@ var replaceThing = function () { }; setInterval(replaceThing, 1000); // invoke `replaceThing' once every second ``` + If you run the above code and monitor memory usage, you’ll find that you’ve got a massive memory leak, leaking a full megabyte per second! And even a manual GC doesn’t help. So it looks like we are leaking `longStr` every time `replaceThing` is called. But why? Let’s examine things in more detail: @@ -138,6 +146,7 @@ class IconButton extends React.Component { } ``` + 2. **Consolidate duplicate code – DRY your code** ``` @@ -158,7 +167,8 @@ return (
); ``` -3. ***Separate stateful aspects from rendering*** + +3. **_Separate stateful aspects from rendering_** ``` import RenderTable from './RenderTable'; @@ -178,12 +188,15 @@ class Table extends Component { } } ``` + [For more reference](https://www.codeinwp.com/blog/react-best-practices/) + ### Independent Practice [Create-react-app](https://medium.com/in-the-weeds/learning-react-with-create-react-app-part-1-a12e1833fdc) ### Challenges + 1. [Exercise for JavaScript](https://www.w3resource.com/javascript-exercises/) 2. Develop a weather app using javascript? 3. Make a calculator using javascript? diff --git a/javascript/common-functions-cheatsheet.md b/javascript/common-functions-cheatsheet.md index 9abd6212b..f02efc3b0 100644 --- a/javascript/common-functions-cheatsheet.md +++ b/javascript/common-functions-cheatsheet.md @@ -1,104 +1,124 @@ # Cheatsheet + ## Commonly used functions on [Array](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays) + ### [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) #### Description + Creates an array by calling a specific function on each element present in the parent array. #### Syntax + ```javascript array.map(function(currentValue) ``` -| Parameter | Description | -| :-------- | :---------- | +| Parameter | Description | +| :--------------------- | :------------------------------------------------- | | function(currentValue) | Required function to be run for each array element | -#### Return value +#### Return value + An Array containing the results of calling the provided function for each element in the original array. ### [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) #### Description + Creates an array filled with all array elements that pass a test (provided as a function). #### Syntax - ```javascript - array.filter(function(currentValue) - ``` -| Parameter | Description | -| :-------- | :---------- | +```javascript +array.filter(function(currentValue) +``` + +| Parameter | Description | +| :--------------------- | :------------------------------------------------- | | function(currentValue) | Required function to be run for each array element | #### Return value + Array containing all elements that pass the test else an empty array. #### Example + ```javascript -let filtered = [112, 52, 0, -1, 944].filter(function(value){ - return value > 0;}) +let filtered = [112, 52, 0, -1, 944].filter(function (value) { + return value > 0; +}); ``` -*Output:* + +_Output:_ [112,52,944] - + ### [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) #### Description + reduces the array to a single value and executes provided function for each value of the array (from left-to-right). #### Syntax - ```javascript - array.reduce( function(total, currentValue, currentIndex, arr), initialValue ) - ``` -| Parameter | Description | -| :-------- | :---------- | +```javascript +array.reduce( function(total, currentValue, currentIndex, arr), initialValue ) +``` + +| Parameter | Description | +| :--------------------- | :------------------------------------------------- | | function(currentValue) | Required function to be run for each array element | #### Return value + returns accumulated result fron the last call of the callback function. #### Example + ```javascript const array1 = [1, 2, 3, 4]; -const reducer = function(accumulator, currentValue) -{ +const reducer = function (accumulator, currentValue) { return accumulator + currentValue; -} +}; console.log(array1.reduce(reducer)); console.log(array1.reduce(reducer, 5)); ``` -*Output:* - - 10 - 15 + +_Output:_ + +10 +15 ### [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) #### Description + Returns the selected elements in an array, as a new array object and selects the elements starting at the given start argument, and ends at the given end argument(excluding end argument). #### Syntax - ```javascript - array.slice(start, end) - ``` - | Parameter | Description | - | :-------- | :---------- | - | start | Optional. specifies starting index of the selection | - | end | Optional. specifies ending index of the selection | +```javascript +array.slice(start, end); +``` - #### Return value - New array containing the selected elements. +| Parameter | Description | +| :-------- | :-------------------------------------------------- | +| start | Optional. specifies starting index of the selection | +| end | Optional. specifies ending index of the selection | + +#### Return value + +New array containing the selected elements. + +#### Example - #### Example ```javascript -let arr = [1,2,3,4,5,6]; +let arr = [1, 2, 3, 4, 5, 6]; let new_arr = arr.slice(3); -``` -*Output:* +``` + +_Output:_ [1,2,3,4,5,6] [4,5,6] @@ -106,132 +126,153 @@ let new_arr = arr.slice(3); ### [splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) #### Description + Adds/removes items to/from an array, and returns the removed item(s). #### Syntax - ```javascript - array.splice(index, howmany, item1, ....., itemX) - ``` -| Parameter | Description| -| :-------- | :--------- | -| index | Required. An integer that specifies at what position to add/remove items | -| howmany | Optional. The number of items to be removed.| -| item1, ..., itemX | Optional. The new item(s) to be added to the array | +```javascript +array.splice(index, howmany, item1, ....., itemX) +``` + +| Parameter | Description | +| :---------------- | :----------------------------------------------------------------------- | +| index | Required. An integer that specifies at what position to add/remove items | +| howmany | Optional. The number of items to be removed. | +| item1, ..., itemX | Optional. The new item(s) to be added to the array | #### Return value + Array without the removed items. #### Example + ```javascript -const languages = ['C++', 'Java', 'Html', 'Python', 'C']; -// Add 'Julia' and 'Php' after removing 'Html'. -const removed = languages.splice(2, 1, 'Julia', 'Php') +const languages = ['C++', 'Java', 'Html', 'Python', 'C']; +// Add 'Julia' and 'Php' after removing 'Html'. +const removed = languages.splice(2, 1, 'Julia', 'Php'); ``` -*Output:* + +_Output:_ C++,Java,Html,Python,C C++,Java,Julia,Php,Python,C _**Note**_ | splice | slice | -| :--- | :--- | +| :--- | :--- | | Returns the removed item(s) in an array| Returns the selected element(s) in an array, as a new array object| | Changes the original array| Doesn’t change the original array| | Can take n number of arguments(1 required)| Can take 2 arguments(1 required)| - ### [concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) #### Description + Used to add a single item to an array(or to add two or more arrays). #### Syntax - ```javascript - array1.concat(item) - ``` - _or_ - ```javascript - array1.concat(array2, array3, ..., arrayX) - ``` - -| Parameter | Description | -| :-------- | :---------- | + +```javascript +array1.concat(item); +``` + +_or_ + +```javascript +array1.concat(array2, array3, ..., arrayX) +``` + +| Parameter | Description | +| :-------------------------- | :--------------------------------- | | array2, array3, ..., arrayX | Required. The arrays to be joined. | #### Return value + Joined array #### Example + ```javascript -const num1 = [1,2,3], -num2 = [4,5,6], -num3 = 7; -console.log(num1.concat(num2,num3)); +const num1 = [1, 2, 3], + num2 = [4, 5, 6], + num3 = 7; +console.log(num1.concat(num2, num3)); ``` -*Output:* + +_Output:_ [1,2,3,4,5,6,7] _*Note*_ | concat | .push | -| :--- | :--- | +| :--- | :--- | | Adds elements to the end of an array| Adds element or merges arrays| | Returns the new length of the array| Returns a new array| - + ### [join](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) #### Description + Returns the array as a string. The elementsare separated by a specified separator. The default separator is comma (,). #### Syntax - ```javascript - array.join(separator) - ``` + +```javascript +array.join(separator); +``` | Parameter | Description | | :-------- | :---------- | -| separator | Optional. | +| separator | Optional. | #### Return value + String, representing the array values, separated by the specified separator. #### Example + ```javascript -const languages = ['C++', 'Java', 'Html', 'Python', 'C']; -languages.join(); -languages.join('.'); -languages.join('-'); +const languages = ['C++', 'Java', 'Html', 'Python', 'C']; +languages.join(); +languages.join('.'); +languages.join('-'); ``` -*Output:* + +_Output:_ C++,Java,Html,Python,C C++.Java.Html.Python.C C++-Java-Html-Python-C - + ### [push](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push) #### Description + Adds new items to the end of an array, and returns the new length. #### Syntax - ```javascript - array.push(item1, item2, ..., itemX) - ``` -| Parameter | Description | -| :-------- | :---------- | +```javascript +array.push(item1, item2, ..., itemX) +``` + +| Parameter | Description | +| :----------------------- | :---------------------------------------- | | item1, item2, ..., itemX | Required. The item(s) to add to the array | #### Return value + New length of the array. #### Example + ```javascript -let arr = [1,2,3,4,5]; -console.log(arr.push(6,7,8)); +let arr = [1, 2, 3, 4, 5]; +console.log(arr.push(6, 7, 8)); ``` -*Output:* + +_Output:_ 8 [1,2,3,4,5,6,7,8] @@ -239,214 +280,255 @@ console.log(arr.push(6,7,8)); ### [find](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find) #### Description + Returns the value of the first element in an array that pass a test (provided as a function). #### Syntax - ```javascript - array.find(function(currentValue) - ``` -| Parameter | Description | -| :-------- | :---------- | -| function(currentValue) | Required. A function to be run for each element in the array.| +```javascript +array.find(function(currentValue) +``` + +| Parameter | Description | +| :--------------------- | :------------------------------------------------------------ | +| function(currentValue) | Required. A function to be run for each element in the array. | #### Return value - The array element value if any of the elements in the array pass the test, otherwise it returns 'undefined'. + +The array element value if any of the elements in the array pass the test, otherwise it returns 'undefined'. #### Example -```javascript - let array = [1,3,5,7,9]; - const found = array.find(function(element){ - return element > 4; - }) -// Printing desired value. -``` -*Output:* - + +```javascript +let array = [1, 3, 5, 7, 9]; +const found = array.find(function (element) { + return element > 4; +}); +// Printing desired value. +``` + +_Output:_ + 5 ### [indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) #### Description + returns the position of the first occurrence of a specified value in a string. #### Syntax - ```javascript - string.indexOf(searchvalue, start) - ``` -| Parameter | Description | -| :-------- | :---------- | -| searchvalue | Required. The string to search for | -| start | Optional.
Default 0. At which position to start the search.| +```javascript +string.indexOf(searchvalue, start); +``` + +| Parameter | Description | +| :---------- | :-------------------------------------------------------------- | +| searchvalue | Required. The string to search for | +| start | Optional.
Default 0. At which position to start the search. | #### Return value + Number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs. #### Example + ```javascript console.log('Departed Train'.indexOf('Train')); ``` -*Output:* - - 9 - -## Common String Functions -[Full Mozilla MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) + +_Output:_ + +9 + +## Common String Functions + +[Full Mozilla MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) ### [substring](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substring) #### Description + Extracts the characters in a string between "start" and "end", not including "end" itself. #### Syntax - ```javascript - string.substring(start, end) - ``` -| Parameter | Description | -| :-------- | :---------- | -| start | Required. The position where to start the extraction. First character is at index 0 | -| end | Optional. The position (up to, but not including) where to end the extraction. If omitted, it extracts the rest of the string| +```javascript +string.substring(start, end); +``` + +| Parameter | Description | +| :-------- | :---------------------------------------------------------------------------------------------------------------------------- | +| start | Required. The position where to start the extraction. First character is at index 0 | +| end | Optional. The position (up to, but not including) where to end the extraction. If omitted, it extracts the rest of the string | #### Return value + New string containing the extracted characters. #### Example + ```javascript -// Taking a string as variable -const string = "JavaScriptCheatsheet"; -a = string.substring(0, 4) -b = string.substring(1, 6) -c = string.substring(5) -d = string.substring(0) -// Printing new string which are -// the part of the given string -``` -*Output:* - - Java - avaSc - criptCheatsheet - JavaScriptCheatsheet +// Taking a string as variable +const string = 'JavaScriptCheatsheet'; +a = string.substring(0, 4); +b = string.substring(1, 6); +c = string.substring(5); +d = string.substring(0); +// Printing new string which are +// the part of the given string +``` + +_Output:_ + +Java +avaSc +criptCheatsheet +JavaScriptCheatsheet _*Note*_ | array.slice() | string.substring() | | :--- | :--- | -| Displays selected array elements | Displays selected part of string| +| Displays selected array elements | Displays selected part of string| | Returns new array| Returns new string| ### [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) #### Description + Used to split a string into an array of substrings, and returns the new array. #### Syntax - ```javascript - string.split(separator, limit) - ``` -| Parameter | Description | -| :-------- | :---------- | -|separator | Optional. Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned (an array with only one item)| -| limit | Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array | +```javascript +string.split(separator, limit); +``` + +| Parameter | Description | +| :-------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| separator | Optional. Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned (an array with only one item) | +| limit | Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array | #### Return value + Array containing splitted values. #### Example + ```javascript -let str = 'It iS a great Day.' -let array = str.split(" "); +let str = 'It iS a great Day.'; +let array = str.split(' '); ``` -*Output:* + +_Output:_ ["It","iS","a","great","Day."] ### [toLowerCase](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) #### Description + Converts a string to lowercase letters. #### Syntax - ```javascirpt - string.toLowerCase() - ``` + +```javascirpt +string.toLowerCase() +``` #### Return value + A string, representing the value of a string converted to lowercase. #### Example -```javascript + +```javascript const str = 'It iS a Great Day.'; const string = str.toLowerCase(); ``` -*Output:* + +_Output:_ it is a great day. ### [trim](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/trim) #### Description + Removes whitespace from both sides of a string. #### Syntax - ```javascript - string.trim() - ``` - + +```javascript +string.trim(); +``` + #### Return value + String, representing the string with removed whitespace from both ends #### Example + ```javascript -const str = " \"JavaScript\" "; +const str = ' "JavaScript" '; const st = str.trim(); ``` -*Output:* - + +_Output:_ + "Javascript" ### [charAt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt) #### Description + Returns the character at the specified index in a string. #### Syntax: + ```javascript -string.charAt(index) +string.charAt(index); ``` #### Return value + String, representing the character at the specified index, or an empty string if the index number is not found #### Example: + ```javascript const str = 'JavaScript is object oriented language'; console.log(str.charAt(9)); -``` -*Output:* +``` + +_Output:_ t - + ## For Loop Variants ### [for...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) + #### Syntax - ```javascript - for (var in object) - { - //code block to be executed - } - ``` + +```javascript +for (var in object) +{ + //code block to be executed +} +``` + #### Example - ```javascript - const array1 = ['a', 'b', 'c']; - for (const element in array1) { - console.log(element); - } + +```javascript +const array1 = ['a', 'b', 'c']; +for (const element in array1) { + console.log(element); +} ``` -*Output:* + +_Output:_ "a" "b" @@ -455,82 +537,96 @@ console.log(str.charAt(9)); ### [for...of](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) #### Description + Loops through the values of an object. #### Syntax - ```javascript - for (variable of object) - { - // code block to be executed - } - ``` + +```javascript +for (variable of object) { + // code block to be executed +} +``` #### Example -```javascript -const languages = { first : "C", second : "Java", - third : "Python", fourth : "PHP", - fifth : "JavaScript" }; -// iterate through every property of the -// object languages and print all of them -// using for..in loops -for (itr in languages) - { - console.log(languages[itr]); - } -``` -*Output:* - - C - Java - Python - PHP - JavaScript + +```javascript +const languages = { + first: 'C', + second: 'Java', + third: 'Python', + fourth: 'PHP', + fifth: 'JavaScript' +}; +// iterate through every property of the +// object languages and print all of them +// using for..in loops +for (itr in languages) { + console.log(languages[itr]); +} +``` + +_Output:_ + +C +Java +Python +PHP +JavaScript ### [for loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement) #### Description + Traditional index-based loop as found in many languages. #### Syntax + ```javascript -for (statement 1; statement 2; statement 3) +for (statement 1; statement 2; statement 3) { // code block to be executed } ``` #### Example + ```javascript -const i; -for (i = 0; i < 10; i++) -{ - console.log("Hello World!\n"); +const i; +for (i = 0; i < 10; i++) +{ + console.log("Hello World!\n"); } ``` -This will print *Hello World* on the screen 10 times. + +This will print _Hello World_ on the screen 10 times. ### [.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) #### Description + Calls a function once for each element in an array, in order. #### Syntax + ```javascript array.forEach(function(currentValue) ``` -| Parameter | Description | -| :--- | :--- | -| function(currentValue)| Required. A function to be run for each element in the array.| +| Parameter | Description | +| :--------------------- | :------------------------------------------------------------ | +| function(currentValue) | Required. A function to be run for each element in the array. | #### Example: + ```javascript const items = [1, 29, 47]; const copy = []; -items.forEach(function(item){ - copy.push(item*item); +items.forEach(function (item) { + copy.push(item * item); }); ``` -*Output :* It squares each number in the array *items* . - - 1,841,2209 + +_Output :_ It squares each number in the array _items_ . + +1,841,2209 diff --git a/javascript/first-js-oop-project.md b/javascript/first-js-oop-project.md index 2b4f2559e..aa717442c 100644 --- a/javascript/first-js-oop-project.md +++ b/javascript/first-js-oop-project.md @@ -111,9 +111,9 @@ This mini project will help you to learn basic concepts about objects in JavaScr - `.html()` is used to return the HTML code from jQuery to the target element of the HTML page. - **event** is the target element in the below code. ```javascript - $(document).ready(function() { + $(document).ready(function () { let html = ''; - $.each(eventArray, function(index, item) { + $.each(eventArray, function (index, item) { html += `
  • ${item.name} - ${item.description}
  • `; }); // insert final html into #event... diff --git a/javascript/javascript-7-oop.md b/javascript/javascript-7-oop.md index 19e0e2fb5..241d6f3ff 100644 --- a/javascript/javascript-7-oop.md +++ b/javascript/javascript-7-oop.md @@ -37,7 +37,6 @@ Virtually all companies will use object-oriented programming in their code. For - The software development lifecycle has to go through many different stages. Writing clean, organized, reusable code is essential for developers to maintain projects. Hence, the five principles of SOLID applied in JavaScript are important to master the ability to write clean and professional code. Here are a few resources on SOLID principles and the importance of OOP in JS: - [SOLID - the first 5 principles of OOD with JS](https://medium.com/@cramirez92/s-o-l-i-d-the-first-5-priciples-of-object-oriented-design-with-javascript-790f6ac9b9fa) [SOLID principles in JS](https://dev.to/francescoxx/solid-principles-in-javascript-3pek) diff --git a/javascript/require-and-import-mini-lesson.md b/javascript/require-and-import-mini-lesson.md index b69b8f8ef..a65594b08 100644 --- a/javascript/require-and-import-mini-lesson.md +++ b/javascript/require-and-import-mini-lesson.md @@ -37,7 +37,6 @@ Why it is worth learning this topic - [Difference between import and require](#difference-between-import-and-require) - [Chart of the Differences](#chart-of-the-differences) - ### Lesson With JavaScript, when you want to include code that another developer has produced and made available to the open source community, you now have two main ways to bring in that code into your own script: `require` and `import`. When starting out, it can sometimes become confusing when to use one or another. So, in order to clarify this a little bit, let's dive into the core of what they are, how they differ, and when you should use one or the other. @@ -54,7 +53,7 @@ When using Node, if you want to include modules that are in another file, you ca 2. Installed NPM Modules. It will look in the node_modules folder. For example: `express` -3. Local Modules. +3. Local Modules. It is important to note that if the specified module name has a `./`, a `/` or a `../`, it will look for the directory/file in the given path, matching the `.js` and `.json` extensions. Moreover, if you want to import a file, you can just use the filename without the extension. For example, if you would like to import `code.js`, you could simply do: @@ -68,22 +67,22 @@ In the [guided practice below](#guided-practice), you will be able to test the ` #### What is import? -The `import` statement was first introduced in ES6, in 2015. It is a *static* import statement, which basically means that it will only bring in what has been exclusively and specifically exported from another module. +The `import` statement was first introduced in ES6, in 2015. It is a _static_ import statement, which basically means that it will only bring in what has been exclusively and specifically exported from another module. The syntax is also quite different, as the module path must be a string literal, whereas when we use `require`, the module path can be dynamic. For example, with `require`, this will work: ```javascript -const name = "module2"; -const obj = require("./" + name); +const name = 'module2'; +const obj = require('./' + name); ``` However, due to the static aspect of `import`, you cannot do: ```javascript // THIS WILL NOT WORK -const name = "module2"; +const name = "module2"; import * from "./" + name; ``` @@ -93,7 +92,7 @@ For example: ```javascript // Named imports -import {Component} from 'react'; +import { Component } from 'react'; ``` You can also import a complete namespace. To do so, you simply use the following syntax: @@ -114,10 +113,10 @@ And, of course, you can combine these: ```javascript // Combinations: -import React, {Component} from 'react'; +import React, { Component } from 'react'; ``` -Finally, you can also refer to an ES Module (if you need more information on modules, see the reference in the [supplemental materials](#supplemental-materials)). +Finally, you can also refer to an ES Module (if you need more information on modules, see the reference in the [supplemental materials](#supplemental-materials)). This means that you can export objects and methods you have created. @@ -140,13 +139,12 @@ While there are many differences between `require` and `import`, which are det For your convienience, here is a detailed chart of the differences between `require` and `import`. -|REQUIRE|IMPORT| -|--|--| -|Can be called at any time and place in the program.|Always run in the beginning of the file.| -|You can directly run the code with the require statement.|Will not run directly in Node without lots of annoying special setup.| -|Can leave out a .js extension when importing a local module|Cannot leave the extension| -|To include multiple functions, you first export the functions in an object, then import them using `require`|To include multiple functions, simply import them between curly braces.| - +| REQUIRE | IMPORT | +| ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- | +| Can be called at any time and place in the program. | Always run in the beginning of the file. | +| You can directly run the code with the require statement. | Will not run directly in Node without lots of annoying special setup. | +| Can leave out a .js extension when importing a local module | Cannot leave the extension | +| To include multiple functions, you first export the functions in an object, then import them using `require` | To include multiple functions, simply import them between curly braces. | ### Guided Practice @@ -155,7 +153,7 @@ For your convienience, here is a detailed chart of the differences between `requ The first thing we need to to is to create our export file. So, opening your favorite code editor, navigate to a new a folder for this practice and create a file named `my-module-for-require.js`. Inside the file, enter the following snippet: ```javascript -const messageToExport = "This message has been exported."; +const messageToExport = 'This message has been exported.'; module.exports = messageToExport; ``` @@ -166,7 +164,7 @@ Then, you need to create the file in which we will call our module. So within th ```javascript // require your module -const message = require("./my-module-for-require"); +const message = require('./my-module-for-require'); // console log it console.log(message); @@ -199,14 +197,14 @@ Don't worry if this seems a bit confusing as we just need to use this in order t First, create a file named `my-module-for-import.js` and enter the following code: ```javascript -export const firstMessage = "This is a the first message!"; -export const secondMessage = "This is a the second message!" +export const firstMessage = 'This is a the first message!'; +export const secondMessage = 'This is a the second message!'; ``` Then, create a file named `example-for-imports.js` and enter the following code: ```javascript -import { firstMessage, secondMessage} from './my-module-for-import.js'; +import { firstMessage, secondMessage } from './my-module-for-import.js'; console.log(firstMessage); console.log(secondMessage); @@ -261,7 +259,6 @@ Now, pat yourself on the back, as you've gone through somewhat tough material. G - Make a detailed cheatsheet of the syntax for `require` and `import`, clearly differentiating between the different imports for the latest. - ### Supplemental Materials - [Official MDN documentation on modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) @@ -289,4 +286,3 @@ Now, pat yourself on the back, as you've gone through somewhat tough material. G - [Understanding ES6 Modules](https://www.sitepoint.com/understanding-es6-modules/) - [Import vs Require in Node.js - Mastering JS](https://masteringjs.io/tutorials/node/import-vs-require) - diff --git a/javascript/spread-operator.md b/javascript/spread-operator.md index f721c64b0..48757bf93 100644 --- a/javascript/spread-operator.md +++ b/javascript/spread-operator.md @@ -8,21 +8,25 @@ About 40-50 minutes - 25 min for examples ## Spread operator + Spread operator allows an iterable such as strings, objects, array and sets to spread or expand individually inside a receiver. The **syntax** of spread operator is `[...value]`. ## Why it is useful? -+ We can merge two objects together using spread operator. -Example: + +- We can merge two objects together using spread operator. + Example: + ``` let obj1 = {a: 1, b: 2, c: 3} let obj2 = {d: 4, e: 5, f: 6} -let merge = {...obj1, ...obj2} +let merge = {...obj1, ...obj2} ``` + **Output:** merge is {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6} -+ Spread operator with object is used to make copy of existing object or to make a new object with properties. +- Spread operator with object is used to make copy of existing object or to make a new object with properties. ## Examples @@ -41,61 +45,60 @@ const combined = { }; console.log(combined); ``` + **Output:**{name: 'AppDividend', author: 'Krunal Lathiya' , age: 25} ### Arrays - -#### normal array concat() method +#### normal array concat() method ```javaScript -let arr = [1,2,3]; -let arr2 = [4,5]; - -arr = arr.concat(arr2); - -console.log(arr); // [ 1, 2, 3, 4, 5 ] +let arr = [1,2,3]; +let arr2 = [4,5]; + +arr = arr.concat(arr2); + +console.log(arr); // [ 1, 2, 3, 4, 5 ] ``` -#### spread operator doing the concat job +#### spread operator doing the concat job ```javaScript -let arr = [1,2,3]; -let arr2 = [4,5]; - -arr = [...arr,...arr2]; -console.log(arr); // [ 1, 2, 3, 4, 5 ] +let arr = [1,2,3]; +let arr2 = [4,5]; + +arr = [...arr,...arr2]; +console.log(arr); // [ 1, 2, 3, 4, 5 ] ``` -#### spread operator for copying +#### spread operator for copying + +```javaScript +let arr = ['a','b','c']; +let arr2 = [...arr]; + +console.log(arr); // [ 'a', 'b', 'c' ] + +arr2.push('d'); //inserting an element at the end of arr2 -```javaScript -let arr = ['a','b','c']; -let arr2 = [...arr]; - -console.log(arr); // [ 'a', 'b', 'c' ] - -arr2.push('d'); //inserting an element at the end of arr2 - -console.log(arr2); // [ 'a', 'b', 'c', 'd' ] -console.log(arr); // [ 'a', 'b', 'c' ] +console.log(arr2); // [ 'a', 'b', 'c', 'd' ] +console.log(arr); // [ 'a', 'b', 'c' ] ``` -#### copying without the spread operator +#### copying without the spread operator ```javaScript -let arr = ['a','b','c']; -let arr2 = arr; - -console.log(arr2); // [ 'a', 'b', 'c' ] +let arr = ['a','b','c']; +let arr2 = arr; + +console.log(arr2); // [ 'a', 'b', 'c' ] ``` + [From geeksforgeeks](https://www.geeksforgeeks.org/javascript-spread-operator/) ### Spread in object literals -The spread operator copies enumerable properties from a provided object onto a new object. In object literals, merging of objects is now possible using a shorter syntax than [Object.assign()] -(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) - +The spread operator copies enumerable properties from a provided object onto a new object. In object literals, merging of objects is now possible using a shorter syntax than [Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) ```JavaScript const obj1 = { foo: 'bar', x: 42 }; @@ -116,6 +119,7 @@ The **syntax** of slice method is `array.slice(start, end)`. ### Example: #### Add Element(s) to the Middle of an Array Using splice() + ``` array.splice( start, deleteCount [, item1 [, item2 [, ...] ] ] ) ``` @@ -195,16 +199,15 @@ for (let i = 0; i < arr1.length; i++) { } } ``` + [from freecodecamp](https://www.freecodecamp.org/forum/t/how-do-i-build-a-nested-object-in-javascript-dynamically/304543/3) ## Challenges + 1. [Write a function that uses spread as the solution ?](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-the-spread-operator-to-evaluate-arrays-in-place) -2. [Write a function that uses slice as the solution ?](https://curt-park.github.io/2018-09-13/algorithm-max-slice-sum/) -(**Note:** The example code here is in python, but you should still follow the directions) +2. [Write a function that uses slice as the solution ?](https://curt-park.github.io/2018-09-13/algorithm-max-slice-sum/) + (**Note:** The example code here is in python, but you should still follow the directions) ## Additional Materials - [Spread-Operator Playground](https://www.codingame.com/playgrounds/7998/es6-tutorials-spread-operator-with-fun) - - - diff --git a/node-js/node-lab-exercise-part-1.md b/node-js/node-lab-exercise-part-1.md index d9bf99ca3..d35cdbcbd 100644 --- a/node-js/node-lab-exercise-part-1.md +++ b/node-js/node-lab-exercise-part-1.md @@ -57,12 +57,15 @@ Follow the installation steps in nvm's readme. Most importantly, these steps: 1. Install nvm via Homebrew: `brew install nvm` 2. Create a system directory for nvm: `mkdir ~/.nvm` 3. Open your `.zshrc` file and append the following lines: + ``` # NVM export NVM_DIR=~/.nvm source $(brew --prefix nvm)/nvm.sh ``` - - This will update your path, so remember to reset your Terminal after this step. + +- This will update your path, so remember to reset your Terminal after this step. + 4. [Verify your nvm installation](https://github.com/creationix/nvm#verify-installation) by typing `command -v nvm` in your terminal. You should just see the output `nvm` in your terminal. (See their readme to read about why `which nvm` does not work. Do not be alarmed that `which nvm` returns nothing!) - If `command -v nvm` did not work, there's a note that may help you in the Install section of nvm's readme. It starts with the text "Note: On OS X, if you get nvm: command not found after running the install script, one of the following might be the reason:" -- try those. Usually it has to do with where the nvm install script put the script that sources nvm for you every time you start your terminal. 5. [Download the latest version of node](https://github.com/creationix/nvm#usage) using the command `nvm install node` (see their readme for more information about how to download specific versions of node). diff --git a/objectives/week-6-assessment.md b/objectives/week-6-assessment.md index 8b68cd84b..dfee5ff4f 100644 --- a/objectives/week-6-assessment.md +++ b/objectives/week-6-assessment.md @@ -196,8 +196,8 @@ function calculateAge(birthDate) { return Math.abs(ageDate.getFullYear() - 1970); } -describe('calculateAge()', function() { - it('should do something', function() { +describe('calculateAge()', function () { + it('should do something', function () { expect(true).toBe(true); }); }); diff --git a/onboarding/ergonomics.md b/onboarding/ergonomics.md index c64fcd81d..4c9844953 100644 --- a/onboarding/ergonomics.md +++ b/onboarding/ergonomics.md @@ -97,7 +97,6 @@ None - Seek out variation in tasks (emails, meetings, coding) and workstations. - Take breaks (stop looking at your screen and stretch a bit) every 50-55 minutes. - Mix non-computer-related tasks into the workday, e.g meetings, lunch with colleagues, walking to someone’s desk to talk to them - ### Common Mistakes / Misconceptions diff --git a/onboarding/professionalism.md b/onboarding/professionalism.md index fa721ac81..cc75e9342 100644 --- a/onboarding/professionalism.md +++ b/onboarding/professionalism.md @@ -1,7 +1,9 @@ # Professionalism ### Projected Time + About 2 hours + - 20 minutes for video walkthrough of slides - 9 minutes for "Being Professional at Work" video - 7 minutes for "How to Deal with People You Don't Like at Work" @@ -10,32 +12,37 @@ About 2 hours - 20 minutes for Independent Practice - 15 minutes for Check for Understanding - ### Prerequisites + - [Expectations While at Techtonica](https://docs.google.com/document/d/1IWny-IXB-XDWW21l3JODwPuh1QOVBFQbii_DjvF0g00/edit?usp=sharing) - [Interpersonal Conflict Resolution](conflict-resolution.md) - [Diversity, Inclusion & Implicit Bias](../diversity-inclusion-bias/inclusion.md) ### Motivation + Techtonica is a simulated work environment representative of common tech industry offices. Apprentices are expected to behave professionally and to interact professionally with their Techtonica colleagues and staff. An apprentice's level of professionalism is an important point of consideration for sponsoring companies. Importance to professionalism in workplace: + - Creates Boundaries - Creates an Atmosphere of Improvement - The sense of Responsibility - Mitigates Conflicts - Increased Job Satisfaction - Personal Growth -[(imarticus.org)](https://imarticus.org/professionalism-important-workplace/) + [(imarticus.org)](https://imarticus.org/professionalism-important-workplace/) ### Objectives + **Participants will be able to:**: + - Understand what is meant by "professionalism" - Understand why professionalism is important both at Techtonica and in a work setting - Understand what behaviors are expected of a professional - Understand what accepted standards of professionalism are ### Specific Things to Learn + - Dictionary definition of a professional, and an interpretation of this definition - Myths about behaving professionally - What it means to behave professionally @@ -48,71 +55,72 @@ Importance to professionalism in workplace: - Standards for the work day itself ### Materials + - [Professionalism (video walkthrough of slides)](https://drive.google.com/open?id=1WOor8RnhFz8yJimUSGf_QRY1_aplHure) - [Professionalism (slides)](https://docs.google.com/presentation/d/1kvpeT1HTNJKDmnZr9amMe8TRrU_mCD8kwDRGxbomTFs/edit?usp=sharing) -- [Being Professional at Work (video)](https://www.youtube.com/watch?v=QphclWBVzGQ) -- [How to Deal with People You Don't Like at Work (video)](https://www.youtube.com/watch?v=Pm8kU37u0Ho) -- [Top 10 Tips for Early Career Professionals (video)](https://www.youtube.com/watch?v=bx6HTcQ8i2U) +- [Being Professional at Work (video)](https://www.youtube.com/watch?v=QphclWBVzGQ) +- [How to Deal with People You Don't Like at Work (video)](https://www.youtube.com/watch?v=Pm8kU37u0Ho) +- [Top 10 Tips for Early Career Professionals (video)](https://www.youtube.com/watch?v=bx6HTcQ8i2U) ### Lesson Importance to professionalism in workplace: + - Creates Boundaries – Workers who conduct themselves professionally avoid crossing their line with subordinates, superiors or clients - Creates an Atmosphere of Improvement – A professional atmosphere is more conducive to success. -- The sense of Responsibility – In a professional atmosphere, an employee while handling a task, sees the larger purpose, and hence are able to own their actions and take appropriate decisions. One takes pride in performing the tasks assigned to them. This adds to the overall image of not only the employee but also showcases the value by which the organisation stands. +- The sense of Responsibility – In a professional atmosphere, an employee while handling a task, sees the larger purpose, and hence are able to own their actions and take appropriate decisions. One takes pride in performing the tasks assigned to them. This adds to the overall image of not only the employee but also showcases the value by which the organisation stands. - Mitigates Conflicts – businesses which promote a professional atmosphere also makes it easier to deal with diverse environments in which subordinates or even clients could have a difference of opinion however they can agree to disagree and come together on common grounds. - Increased Job Satisfaction – Professionalism eliminates stress to a great degree and once that is taken care of an employee thrives in a healthy atmosphere leading to enhanced performance. - Personal Growth – Not only in terms of job advancement, but there are a certain dignity and pride in one’s work that develops. You get appreciated for consistently good quality output and that in turn builds your confidence, makes you a more secure person who is then capable of handling difficult situations with refined emotional maturity. -[(imarticus.org)](https://imarticus.org/professionalism-important-workplace/) + [(imarticus.org)](https://imarticus.org/professionalism-important-workplace/) + +The slides and video walkthrough follow along with this lesson. Be sure to view the rest of the materials section as well. -The slides and video walkthrough follow along with this lesson. Be sure to view the rest of the materials section as well. - What is professionalism in Workplace? - - Behave Professionally - - Professional behaviour include the quality of work (skills) and the ability to communicate effectively with managers,teammates and clients - - How they maintain their reputation and trust in colleagues - - How they are regarded in the industry by others tells about their professional behaviour - - - Speak Professionally - - Don't use swear words and foul language at workplace - - Think before you speak, someone maybe offended by something which you think is funny - - Communicate with your colleagues with the language which is primary of your workplace - - - Dress Professionally - - No Profanity / insensitive language/images on clothes - - Pants should neither be tight not baggy and should not be ripped, regardless if they are in fashioin - - Clothes should be free from stains and wrinkles and having matching socks - - Workout clothes and pajamas are not allowed - - Guidelines for women - - Shirts can be sleeveless, but it should be fully cover bras and end below your pants' waistsband - - Shorts should be as long as your fingertip when you stand with your arm straight down, Skirts shouldn't be shorter than few inches above your knees - - - Your Arrival at Workplace - - If you have **planned** absence or late arrival, notify those colleagues who will be affected with your presence as soon as you aware your absence or late arrival - - Arrive early enough so that you can give yourself sometime to get settled before the start of a workday or meeting - - - Your behaviour during the Workday - - Do your best, try to avoid "stealing time" , which means doing non-work things during the non-break hours in the workplace - - Don't Complain much while you're stuck in something, try to learn from your colleagues and experts how to find out solutions of a particular problem - - You should treat everyone respectfully even if you don't even like them - - Make sure you submit your assignment and given task timely, ensure yourself that you have enough skills and tools for the assigned task or work, if you don't have just feel free to ask your colleagues and take their help - - If you can’t make a deadline, let those affected know as soon as you realize it - - - Your Departure from Workplace - - Normally working hours is 8 ,and because you spent one hour in break, So try to compensate it with working 9 hours - - Try to leave after you finish your assigned task, if you can't complete it then speak to your manager about re-setting the expectations - - - Music at Workplace - - Use headphones at workplace, but if you are not using headphones then make sure no one can hear your music - + - Behave Professionally + + - Professional behaviour include the quality of work (skills) and the ability to communicate effectively with managers,teammates and clients + - How they maintain their reputation and trust in colleagues + - How they are regarded in the industry by others tells about their professional behaviour + + - Speak Professionally - Don't use swear words and foul language at workplace - Think before you speak, someone maybe offended by something which you think is funny - Communicate with your colleagues with the language which is primary of your workplace + + - Dress Professionally + - No Profanity / insensitive language/images on clothes + - Pants should neither be tight not baggy and should not be ripped, regardless if they are in fashioin + - Clothes should be free from stains and wrinkles and having matching socks + - Workout clothes and pajamas are not allowed + - Guidelines for women + - Shirts can be sleeveless, but it should be fully cover bras and end below your pants' waistsband + - Shorts should be as long as your fingertip when you stand with your arm straight down, Skirts shouldn't be shorter than few inches above your knees + - Your Arrival at Workplace + - If you have **planned** absence or late arrival, notify those colleagues who will be affected with your presence as soon as you aware your absence or late arrival + - Arrive early enough so that you can give yourself sometime to get settled before the start of a workday or meeting + - Your behaviour during the Workday + + - Do your best, try to avoid "stealing time" , which means doing non-work things during the non-break hours in the workplace + - Don't Complain much while you're stuck in something, try to learn from your colleagues and experts how to find out solutions of a particular problem + - You should treat everyone respectfully even if you don't even like them + - Make sure you submit your assignment and given task timely, ensure yourself that you have enough skills and tools for the assigned task or work, if you don't have just feel free to ask your colleagues and take their help + - If you can’t make a deadline, let those affected know as soon as you realize it + + - Your Departure from Workplace + + - Normally working hours is 8 ,and because you spent one hour in break, So try to compensate it with working 9 hours + - Try to leave after you finish your assigned task, if you can't complete it then speak to your manager about re-setting the expectations + + - Music at Workplace + - Use headphones at workplace, but if you are not using headphones then make sure no one can hear your music + ### Common Mistakes / Misconceptions + - **"This is irrelevant to me right now because I'm an apprentice. I'll start acting professionally once I'm hired."** Many serious athletes "practice like they play", meaning they approach their practice and training with as much seriousness and intensity as they'd put in during a real game. This makes them well-prepared for game days. Techtonica has a similar approach, and we expect apprentices to "practice like they play". - **"If someone tells me to behave professionally, they are telling me to act more like an higher-income white person."** If someone tells you to behave more professionally, they are referring to the (sometimes unwritten) behaviors outlined in this lesson. These behaviors are generally accepted across industries, roles and employment types to be "professional". - **"Behaving professionally makes me appear weak."** Behaving professionally demonstrates that you value your role, your team, your employer and are conscientious. -- **"I cannot be my authentic self and behave professionally."** Being yourself and behaving professionally are not mutually exclusive. Sometimes, the "professional" you is one part of your true self who gets to come out at work, while other parts of your true self get to come out at other times. +- **"I cannot be my authentic self and behave professionally."** Being yourself and behaving professionally are not mutually exclusive. Sometimes, the "professional" you is one part of your true self who gets to come out at work, while other parts of your true self get to come out at other times. - **"It won't matter what I do or how I act because I'll just be a junior software engineer after Techtonica."** Junior software engineers are valued team members and are held to the same standard of professionalism as everyone else at the company. Behaving professionally demonstrates that you value your role, your team, your employer and are conscientious. Start your reputation off on good footing. - ### Group Practice 1. On their own, each person writes a text message to a team member saying they're running late to a meeting. Then, each person shares their message aloud with the group. @@ -121,13 +129,12 @@ The slides and video walkthrough follow along with this lesson. Be sure to view 3. On their own, each person writes an email to a manager notifying them that they won't be finished with a project by the agreed-upon deadline. Then, each person shares their message aloud with the group. - ### Independent Practice 1. Find a partner. Take turns role playing the following scenario: One of you is a team member and you need to tell your manager in person that you'll be missing a week of work next month. The other person is the manager and should express disappointment that the team member will be gone, but also express that you understand. Be sure to switch roles. 2. Find a partner. Take turns role playing the following scenario: One of you is a team member and you need to tell your manager in person that your project is likely not going to be finished by the agreed-upon deadline. The other person is the manager and should express unhappiness about this, but also work together to come up with a new, reasonable deadline or some other alternative (reduce the scope of the project or get help from a team member). Be sure to switch roles. - ### Check for Understanding + Write your reflections about this lesson. What, if any, of the concepts presented were new to you? Is there anything you disagree with? What did it feel like to deliver potentially bad news during the role play? Was this practice useful? Feel free to share other thoughts you have. diff --git a/prework/2_ConditionalsExercise.js b/prework/2_ConditionalsExercise.js index f4a297649..91b262328 100644 --- a/prework/2_ConditionalsExercise.js +++ b/prework/2_ConditionalsExercise.js @@ -14,7 +14,7 @@ // // ------------------------------------------ // // Write your code for exercise 1 below here: // // ------------------------------------------ -// +// // // ------------------------------------------ // // And above here // // ------------------------------------------ @@ -37,12 +37,11 @@ // } // First try answering these without using references or looking up any information. -// Then, check your answer by using references and/or running your code. +// Then, check your answer by using references and/or running your code. // You can run your JS code using the Chrome or Firefox Developer tools, or by using Node.js. // Feel free to update your answers if you got them wrong at first -- this exercise is for your own learning. // But make sure you understand why the correct answer is right. - // EXERCISE 1. // First reassign the value of `answer1` so that it has the value of: // "num1 is small" @@ -63,7 +62,6 @@ function exercise1(num1) { return answer1; } - // EXERCISE 2. // Write an if/else conditional statement that if given a number will assign // a string value of: @@ -86,7 +84,6 @@ function exercise2(num2) { return answer2; } - // EXERCISE 3. // Write an if/else if/else block such that if `num3` is positive, then // answer3 is assigned the string value of: @@ -108,7 +105,6 @@ function exercise3(num3) { return answer3; } - // EXERCISE 4. // Write an if/else statement such that if `varA` and `varB` are strings or // numbers and they have equal values, then change the value of answer4 to @@ -127,13 +123,11 @@ function exercise4(varA, varB) { return answer4; } - // EXERCISE 5. // In exercise 4, what are some of the unexpected cases where `varA` and `varB` // seemed like they are equal, but would not pass the tests? In your analysis // consider other data types beside strings and variables. - // EXERCISE 6. // Here, assign the value of true to answer6 if: // `varA` and `varB` are equal, but `varA` or `varB` does not equal `varC` @@ -150,7 +144,6 @@ function exercise6(varA, varB, varC) { return answer6; } - // EXERCISE 8. // Use a switch conditional statement with case clauses such that if `num7` is // a number and it has a value of 1 that `answer7` is assigned the string: @@ -212,7 +205,6 @@ function exercise9(item) { return answer9; } - // EXERCISE 10. // This is question is a modified version of a classic programming question // called "Fizz Buzz" @@ -236,7 +228,7 @@ function exercise10(num10) { } // Congrats, you made it to the end! You rock! -// Did you find this easy or hard? If you used references, which ones helped you? +// Did you find this easy or hard? If you used references, which ones helped you? // Please answer in a comment below. // diff --git a/prework/4_FunctionsExercise.js b/prework/4_FunctionsExercise.js index 0728e78ea..a96b518bb 100644 --- a/prework/4_FunctionsExercise.js +++ b/prework/4_FunctionsExercise.js @@ -4,43 +4,36 @@ // exercise prompt. // First try answering these without using references or looking up any information. -// Then, check your answer by using references and/or running your code. +// Then, check your answer by using references and/or running your code. // You can run your JS code using the Chrome or Firefox Developer tools, or by using Node.js. // Feel free to update your answers if you got them wrong at first -- this exercise is for your own learning. // But make sure you understand why the correct answer is right. +// Exercise 1. Define a function called logGreeting() that prints the string “Hello!” (use console.log). +// Underneath the function, write the line of code that runs the function. -// Exercise 1. Define a function called logGreeting() that prints the string “Hello!” (use console.log). -// Underneath the function, write the line of code that runs the function. - - -// Exercise 2. Define a function called getName() that *returns* a string that is your name. +// Exercise 2. Define a function called getName() that *returns* a string that is your name. // Remember, this function should return the string -- not print it. -// Then print your name in the console by passing getName() into the console.log() function. - +// Then print your name in the console by passing getName() into the console.log() function. -// Exercise 3. Call a function within a function -- Write a function called logGreeting2() +// Exercise 3. Call a function within a function -- Write a function called logGreeting2() // that prints a full sentence that contains your name: "Hello! My name is ." // logGreeting2 should call myName() to get your name. -// Then print your greeting to the console by calling logGreeting2(). - +// Then print your greeting to the console by calling logGreeting2(). // Exercise 4. Write a function that takes 3 parameters that are all numbers. // The function should return the sum of the 3 numbers. // Then write some function calls you would use to test your function. - // Exercise 5. Let's say a museum gives a discount for children ages 14 or under, and seniors 65 or older. // Write a function that takes in a person's age and returns true if they should get a discount. // Otherwise it should return false. // Then write some function calls you would use to test your function. - // Exercise 6. Write a function that takes 2 parameters -- one number and one string. // The function should print the string the given number of times. // Then write some function calls you would use to test your function. - // Exercise 7. Read the following code (don't run it yet) function mysteryFunction1(p1) { return p1 * 2; @@ -51,14 +44,12 @@ console.log("The value of y is " + y); console.log("The value of z is " + z); // Without running the code, write down in a comment: -// 1. What mysteryFunction1 does +// 1. What mysteryFunction1 does // 2. What prints out for the value of y // 3. What prints out for the value of z // Now run the code and see if you're correct. // Were you correct? If not, what did you learn? - - // Exercise 8. Read the following code (don't run it yet) function mysteryFunction2(p1, p2) { const x = p1 - p2; @@ -70,13 +61,12 @@ console.log("The value of a is " + a); console.log("The value of b is " + b); // Without running the code, write down in a comment: -// 1. What mysteryFunction2 does +// 1. What mysteryFunction2 does // 2. What prints out for the value of a // 3. What prints out for the value of b // Now run the code and see if you're correct. // Were you correct? If not, what did you learn? - // Exercise 9. This exercise is to practice reading the documentation for functions. // String.split() is a function in the JavaScript standard library that you can use in your code. // Read about the split() function here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split @@ -84,19 +74,17 @@ console.log("The value of b is " + b); // Here's a string I made representing my grocery list. // Using split() and groceryList, make an array of my grocery list items -const groceryList = "eggs,carrots,orange juice" +const groceryList = "eggs,carrots,orange juice"; // Here's a string I made representing my morning schedule. // Using split() and mySchedule, make an array of the *first 2* things I do in the morning // There are multiple ways to do this, but try doing it using only the split() function. -const mySchedule = 'wake up--->brush teeth--->eat breakfast--->go to work' - - +const mySchedule = "wake up--->brush teeth--->eat breakfast--->go to work"; // Congrats, you made it to the end! -// Did you find this easy or hard? If you used references, which ones helped you? +// Did you find this easy or hard? If you used references, which ones helped you? // Please answer in a comment below. // -// Email your file to the course staff, +// Email your file to the course staff, // or commit your file to GitHub and email us a link. diff --git a/prework/5_ArraysObjectsExercise.js b/prework/5_ArraysObjectsExercise.js index e2a3b1611..4535616dc 100644 --- a/prework/5_ArraysObjectsExercise.js +++ b/prework/5_ArraysObjectsExercise.js @@ -4,48 +4,37 @@ // exercise prompt. // First try answering these without using references or looking up any information. -// Then, check your answer by using references and/or running your code. +// Then, check your answer by using references and/or running your code. // You can run your JS code using the Chrome or Firefox Developer tools, or by using Node.js. // Feel free to update your answers if you got them wrong at first -- this exercise is for your own learning. // But make sure you understand why the correct answer is right. - // Exercise 1. Make an empty array named animals - // Exercise 2. Add the string "frog" to the array - // Exercise 3. Add 4 more animals of your choice to the array. Try to add all of them in one line of code. - // Exercise 4. Update the first item in the array to be "gorilla" - // Exercise 5. Print the number of items in the array (use the array property that will give you this information) - // Exercise 6. Print the first item in the array - // Exercise 7. Print the last item in the array (as part of your answer, use the same array property you used in exercise 5 above) - // Exercise 8. Remove the last item from the array - // Exercise 9. Now make a new array named assortedThings that contains at least 3 strings and 3 numbers. - // Exercise 10. Write a for loop that iterates through the assortedThings array and prints each index and item, such as: // Item #0 is potato // Item #1 is 4 // Item #2 is Hello World // ... - -// Exercise 11. Write a function that takes an array of numbers as a parameter. For each number in the array, -// print the number and "BIG" if it's over 100, "small" if it's between 0 and 100, and "negative" if +// Exercise 11. Write a function that takes an array of numbers as a parameter. For each number in the array, +// print the number and "BIG" if it's over 100, "small" if it's between 0 and 100, and "negative" if // it's less than 0. Example: // if the array is [-2, 200, 50], print: // -2 negative @@ -54,25 +43,20 @@ // // Then write some function calls you would use to test your function. - // Exercise 12. Make an object called me that contains the following keys: name, favoriteAnimal, favoriteNumber // The values of those keys can be whatever you choose. - // Exercise 13. Add another 2 keys and values to the object (you choose what they are) - // Exercise 14. Update the favoriteAnimal value to something different - -// Exercise 15. Print the value of favoriteAnimal. +// Exercise 15. Print the value of favoriteAnimal. // Note: there are at least 2 ways to get the value of a key, try to write both. - // Congrats, you made it to the end! -// Did you find this easy or hard? If you used references, which ones helped you? +// Did you find this easy or hard? If you used references, which ones helped you? // Please answer in a comment below. // -// Email your file to the course staff, +// Email your file to the course staff, // or commit your file to GitHub and email us a link. diff --git a/prework/6_DomExercise.html b/prework/6_DomExercise.html index c83263d10..c58c305cf 100644 --- a/prework/6_DomExercise.html +++ b/prework/6_DomExercise.html @@ -18,79 +18,66 @@ --> - - Animals: -
      -
    1. Frog
    2. -
    3. Dog
    4. -
    5. Bunny
    6. -
    + + Animals: +
      +
    1. Frog
    2. +
    3. Dog
    4. +
    5. Bunny
    6. +
    -
    -

    This is the text in div id1

    -

    Hope you enjoy my HTML

    -
    +
    +

    This is the text in div id1

    +

    Hope you enjoy my HTML

    +
    -

    Here's some text in a paragraph

    +

    Here's some text in a paragraph

    -
    - I love learning about HTML and JavaScript -
    +
    + I love learning about HTML and JavaScript +
    -

    - Coding is fun -

    +

    + Coding is fun +

    - -

    - - + +

    + + - + // Exercise 11: Make it so when the button2 is clicked, + // the children of the element with id "id1" each have their text replaced with a random number 1-100 + // How was this exercise (easy, hard, fun, confusing)? + // What references did you use to help? + // Please put your answers in a comment below: + // + diff --git a/prework/codeSamples.js b/prework/codeSamples.js index 9830a1f48..0427fcd53 100644 --- a/prework/codeSamples.js +++ b/prework/codeSamples.js @@ -1,39 +1,36 @@ // Code samples for use as JS reference -const myVariable = 1; +const myVariable = 1; console.log(`Value of myVariable is ${myVariable}`); - if (myVariable < 10) { - console.log("< 10"); + console.log("< 10"); } else if (myVariable === 10) { - console.log("=== 10"); + console.log("=== 10"); } else { - console.log("> 10"); + console.log("> 10"); } - for (let i = 0; i < 10; i++) { - console.log(i); + console.log(i); } let j = 0; while (j < 10) { - console.log(j); - j++; + console.log(j); + j++; } - function myFunc1(param1) { - return param1 * 7; + return param1 * 7; } myFunc1(8); const myFunc2 = (param1, param2) => { - return param1 + param2; -} + return param1 + param2; +}; myFunc2(5, 3); @@ -44,9 +41,8 @@ myArray.pop(); myArray[0] = "goodbye"; console.log(myArray.length); - const obj = { - prop1: "value1", - prop2: "value2" -} + prop1: "value1", + prop2: "value2" +}; obj.prop1 = "new value"; diff --git a/projects/Eventful-API-test-page/app.js b/projects/Eventful-API-test-page/app.js index ae635722d..896014d98 100644 --- a/projects/Eventful-API-test-page/app.js +++ b/projects/Eventful-API-test-page/app.js @@ -1,84 +1,96 @@ -const inquirer = require('inquirer'); -const pool = require('./connection'); +const inquirer = require("inquirer"); +const pool = require("./connection"); const app = {}; app.startQuestion = (closeConnectionCallback) => { - inquirer.prompt({ - type: 'list', - message: 'What action would you like to do?', - choices: [ - 'Complete a sentence', - 'Create a new user', - 'Find one event of a particular type in San Francisco next week', - 'Mark an existing user to attend an event in database', - 'See all events that a particular user is going to', - 'See all the users that are going to a particular event', - 'Exit' - ], - name: 'action', - }).then((res) => { - const continueCallback = () => app.startQuestion(closeConnectionCallback); - - if (res.action === 'Complete a sentence') app.completeSentence(continueCallback); - if (res.action === 'Create a new user') app.createNewUser(continueCallback); - if (res.action === 'Find one event of a particular type in San Francisco next week') app.searchEventful(continueCallback); - if (res.action === 'Mark an existing user to attend an event in database') app.matchUserWithEvent(continueCallback); - if (res.action === 'See all events that a particular user is going to') app.seeEventsOfOneUser(continueCallback); - if (res.action === 'See all the users that are going to a particular event') app.seeUsersOfOneEvent(continueCallback); - if (res.action === 'Exit') { - closeConnectionCallback(); - return; - } - }) -} + inquirer + .prompt({ + type: "list", + message: "What action would you like to do?", + choices: [ + "Complete a sentence", + "Create a new user", + "Find one event of a particular type in San Francisco next week", + "Mark an existing user to attend an event in database", + "See all events that a particular user is going to", + "See all the users that are going to a particular event", + "Exit" + ], + name: "action" + }) + .then((res) => { + const continueCallback = () => app.startQuestion(closeConnectionCallback); + + if (res.action === "Complete a sentence") + app.completeSentence(continueCallback); + if (res.action === "Create a new user") + app.createNewUser(continueCallback); + if ( + res.action === + "Find one event of a particular type in San Francisco next week" + ) + app.searchEventful(continueCallback); + if (res.action === "Mark an existing user to attend an event in database") + app.matchUserWithEvent(continueCallback); + if (res.action === "See all events that a particular user is going to") + app.seeEventsOfOneUser(continueCallback); + if ( + res.action === "See all the users that are going to a particular event" + ) + app.seeUsersOfOneEvent(continueCallback); + if (res.action === "Exit") { + closeConnectionCallback(); + return; + } + }); +}; app.completeSentence = (continueCallback) => { //YOUR WORK HERE - console.log('Please write code for this function'); + console.log("Please write code for this function"); //End of your work continueCallback(); -} +}; app.createNewUser = (continueCallback) => { //YOUR WORK HERE - console.log('Please write code for this function'); + console.log("Please write code for this function"); //End of your work continueCallback(); - -} +}; app.searchEventful = (continueCallback) => { //YOUR WORK HERE - console.log('Please write code for this function'); + console.log("Please write code for this function"); //End of your work continueCallback(); -} +}; app.matchUserWithEvent = (continueCallback) => { //YOUR WORK HERE - console.log('Please write code for this function'); + console.log("Please write code for this function"); //End of your work continueCallback(); -} +}; app.seeEventsOfOneUser = (continueCallback) => { //YOUR WORK HERE - console.log('Please write code for this function'); + console.log("Please write code for this function"); //End of your work continueCallback(); -} +}; app.seeUsersOfOneEvent = (continueCallback) => { //YOUR WORK HERE - console.log('Please write code for this function'); + console.log("Please write code for this function"); //End of your work continueCallback(); -} +}; module.exports = app; diff --git a/projects/Eventful-API-test-page/connection.js b/projects/Eventful-API-test-page/connection.js index 896b186c1..221607486 100644 --- a/projects/Eventful-API-test-page/connection.js +++ b/projects/Eventful-API-test-page/connection.js @@ -1,11 +1,10 @@ //require packages const pg = require("pg"); -const pgKey = require('./keys').pg; -const Pool = require('pg').Pool; +const pgKey = require("./keys").pg; +const Pool = require("pg").Pool; - //create PostgreSQL connection - const connection = new Pool({ - +//create PostgreSQL connection +const connection = new Pool({ host: "localhost", port: 5432, user: "XXXXXXX", // type your username here @@ -13,4 +12,4 @@ const Pool = require('pg').Pool; database: "XXXXXXX" // type your database name here }); -module.exports = connection; \ No newline at end of file +module.exports = connection; diff --git a/projects/Eventful-API-test-page/eventfulAPI.js b/projects/Eventful-API-test-page/eventfulAPI.js index 276ea500e..e29f9d8f3 100644 --- a/projects/Eventful-API-test-page/eventfulAPI.js +++ b/projects/Eventful-API-test-page/eventfulAPI.js @@ -1,30 +1,35 @@ const eventfulKey = require("./keys.js").eventful; -const eventful = require('eventful-node'); +const eventful = require("eventful-node"); const client = new eventful.Client(eventfulKey); //sample search, try running it to see it in action -client.searchEvents({ - keywords: 'tango', - location: 'San Francisco', - date: "Next Week" -}, function(err, data) { - if(err){ - return console.error(err); +client.searchEvents( + { + keywords: "tango", + location: "San Francisco", + date: "Next Week" + }, + function (err, data) { + if (err) { + return console.error(err); + } + const resultEvents = data.search.events.event; + console.log("Received " + data.search.total_items + " events"); + console.log("Event listings: "); + for (let i = 0; i < resultEvents.length; i++) { + console.log( + "===========================================================" + ); + console.log("title: ", resultEvents[i].title); + console.log("start_time: ", resultEvents[i].start_time); + console.log("venue_name: ", resultEvents[i].venue_name); + console.log("venue_address: ", resultEvents[i].venue_address); + } } - const resultEvents = data.search.events.event; - console.log('Received ' + data.search.total_items + ' events'); - console.log('Event listings: '); - for ( let i = 0 ; i < resultEvents.length; i++) { - console.log("===========================================================") - console.log('title: ', resultEvents[i].title); - console.log('start_time: ', resultEvents[i].start_time); - console.log('venue_name: ', resultEvents[i].venue_name); - console.log('venue_address: ', resultEvents[i].venue_address); - } -}); +); //export a custom function that searches via Eventful API, displays the results AND stores some of the data into MySQL -module.exports = function(optionsObj) { +module.exports = function (optionsObj) { // YOUR WORK HERE - console.log("You need to create this functionality yourself") -} + console.log("You need to create this functionality yourself"); +}; diff --git a/projects/Eventful-API-test-page/index.js b/projects/Eventful-API-test-page/index.js index d9504f905..2736b73fd 100644 --- a/projects/Eventful-API-test-page/index.js +++ b/projects/Eventful-API-test-page/index.js @@ -1,19 +1,19 @@ -const pool = require('./connection'); -const app = require('./app'); +const pool = require("./connection"); +const app = require("./app"); const pgConnect = () => { pool.connect((err, client) => { if (err) throw err; - console.log('Welcome to Eventonica') + console.log("Welcome to Eventonica"); console.log("connected as Administrator"); app.startQuestion(() => { client.release(); pool.end().then(() => process.exit()); }); - }) -} + }); +}; // *Uncomment below line once you have postgreSQL setup diff --git a/projects/Eventful-API-test-page/package.json b/projects/Eventful-API-test-page/package.json index 25466e862..12ad6a65e 100644 --- a/projects/Eventful-API-test-page/package.json +++ b/projects/Eventful-API-test-page/package.json @@ -7,4 +7,4 @@ "scripts": { "start": "node index.js" } -} \ No newline at end of file +} diff --git a/projects/eventonica/eventonica-part6-postgres.md b/projects/eventonica/eventonica-part6-postgres.md index 3a6cb5138..38f2be979 100644 --- a/projects/eventonica/eventonica-part6-postgres.md +++ b/projects/eventonica/eventonica-part6-postgres.md @@ -49,21 +49,20 @@ In addition to the usual steps: Ex: Adding a user ```javascript - // in Express, e.g. index.js app.post('/users', (req, res) => { - eventRecommender.addUser(res.body) - .then(() => res.sendStatus(204)); + eventRecommender.addUser(res.body).then(() => res.sendStatus(204)); }); + ``` +// in EventRecommender.js - // in EventRecommender.js +addUser(data) { +return db.one('INSERT INTO users (name) values (\$1) RETURNING id, name', [data.name]); +// note: this returns a PROMISE +} - addUser(data) { - return db.one('INSERT INTO users (name) values ($1) RETURNING id, name', [data.name]); - // note: this returns a PROMISE - } - ``` +``` 1. Test that your new APIs work using Postman and your webpage. Using `PGAdmin` or `psql`, check that the database contains the information you would expect. @@ -73,8 +72,8 @@ In addition to the usual steps: 1. Create a `user_events` table in your database with two columns: `user_id` and `event_id`. Use this table to store which events have been saved for each user, replacing whichever method you used before. When creating the table, - - Add [foreign keys](https://www.postgresql.org/docs/12/ddl-constraints.html#DDL-CONSTRAINTS-FK) to link `user_id` to the `users` table and `event_id` to the `events` table. Specifying `ON DELETE CASCADE` for each column means that deleting a user/event will also delete all linked entries in this table. This ensures that you won't have deleted events saved for users, or events saved for deleted users. Test that your constraints work by saving events for users and deleting the user or event. - - These columns should be unique together (i.e., you do not want to save an event for a user more than once), see [unique constraints](https://www.postgresql.org/docs/12/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS). Test what happens when you try to save the same event for a user twice. +- Add [foreign keys](https://www.postgresql.org/docs/12/ddl-constraints.html#DDL-CONSTRAINTS-FK) to link `user_id` to the `users` table and `event_id` to the `events` table. Specifying `ON DELETE CASCADE` for each column means that deleting a user/event will also delete all linked entries in this table. This ensures that you won't have deleted events saved for users, or events saved for deleted users. Test that your constraints work by saving events for users and deleting the user or event. +- These columns should be unique together (i.e., you do not want to save an event for a user more than once), see [unique constraints](https://www.postgresql.org/docs/12/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS). Test what happens when you try to save the same event for a user twice. 1. (Only if you created the `user_events` table): Now, when displaying users and their events on the webpage, can you use SQL joins to get a list of event names that each user has saved? @@ -85,7 +84,7 @@ If you are getting HTTP 304 back from your GET requests, it means that the conte ### Challenge - Add API test coverage for your endpoints using supertest - - example test, use POST/PUT to create a new user and then GET the users to confirm that user was added and saved +- example test, use POST/PUT to create a new user and then GET the users to confirm that user was added and saved - Add [not-null constraints](https://www.postgresqltutorial.com/postgresql-not-null-constraint/) to all fields in `users` and `events` that must have a value. Test what happens when you try to insert a null value into those fields. - Create a [unique constraint](https://www.postgresql.org/docs/12/ddl-constraints.html#DDL-CONSTRAINTS-UNIQUE-CONSTRAINTS) on your `events` table using event name, category, and date fields. This will prevent users from adding the same event multiple times. Test what happens when you try to insert the same event twice. - For either of the above constraints, decide how best to show this error to the user? How will you tell the browser code that something went wrong? Remember, HTTP Status Codes are your friend. @@ -100,9 +99,10 @@ TL;DR - they are taking their in-memory backend data objects from Part 5 and usi ### Common Issues - README should contain instructions on how to load the testing database schema (likely with data) - - A big part of reviewing this is checking it out and making sure it works - - I've been using a new [beta GitHub CLI](https://cli.github.com/) that can quickly checkout a PR - - README should also mention how to run any tests +- A big part of reviewing this is checking it out and making sure it works +- I've been using a new [beta GitHub CLI](https://cli.github.com/) that can quickly checkout a PR +- README should also mention how to run any tests - SQL commands should be in the EventRecommender "DAO" object, not in the Express app route handlers - - If the code is all stuffed into the handlers, send your preferred explanatory link about the concept of system layers +- If the code is all stuffed into the handlers, send your preferred explanatory link about the concept of system layers - If there are no unit tests or API tests, flag that as an area of possible improvement +``` diff --git a/projects/eventonica/starter-code/eventRecommenderSpec.js b/projects/eventonica/starter-code/eventRecommenderSpec.js index 62aa9b351..613f47e17 100644 --- a/projects/eventonica/starter-code/eventRecommenderSpec.js +++ b/projects/eventonica/starter-code/eventRecommenderSpec.js @@ -1,6 +1,6 @@ describe("EventRecommender", () => { - const { EventRecommender, User, Event } = require('../YourFilenameHere.js'); // Update with your class names and file name - let er; + const { EventRecommender, User, Event } = require("../YourFilenameHere.js"); // Update with your class names and file name + let er; beforeEach(() => { er = new EventRecommender(); diff --git a/projects/mongo-assessment.md b/projects/mongo-assessment.md index 36e2140fc..ed259ac25 100644 --- a/projects/mongo-assessment.md +++ b/projects/mongo-assessment.md @@ -24,7 +24,8 @@ In this project, you will have 30 minutes to create a new database and a few doc 3. Email your required screenshots to be reviewed at the end of the assessment. ## Setup Instructions -- [ ] Know how to take screenshots on your machine. For mac, you can press `command + shift + 4` to draw a box around the part of the screen you want to capture (in this case, your command line terminal), and it should appear on your desktop with the name "Screenshot..." followed by a hash. + +- [ ] Know how to take screenshots on your machine. For mac, you can press `command + shift + 4` to draw a box around the part of the screen you want to capture (in this case, your command line terminal), and it should appear on your desktop with the name "Screenshot..." followed by a hash. - [ ] You should already have MongoDB installed after [this lesson](https://github.com/Techtonica/curriculum/blob/main/electives/databases/mongo-db.md). - [ ] Don't clear your terminal as you are working - the more of your progress we can see in your command line, the better. Mistakes are not a problem, but you will have a limited amount of time to complete the database correctly. diff --git a/projects/node-http-exercise/node-http-exercise.md b/projects/node-http-exercise/node-http-exercise.md index 7f6c8bfda..d645aed67 100644 --- a/projects/node-http-exercise/node-http-exercise.md +++ b/projects/node-http-exercise/node-http-exercise.md @@ -56,6 +56,7 @@ const http = require('http') // require core url module const url = require('url) ``` + 2. Create a server using the `createServer()` http method: ```javascript @@ -124,7 +125,7 @@ Back to creating the logic of your server, now. When the client makes a request ```javascript let response = { - message: 'Not Found', + message: 'Not Found' }; ``` @@ -233,8 +234,8 @@ const routes = { '/test': { status: 200, contentType: 'text/html', - message: 'It Works!', - }, + message: 'It Works!' + } // create your other routes here }; ``` diff --git a/projects/node-http-exercise/node-http-server-assignment.postman_collection.json b/projects/node-http-exercise/node-http-server-assignment.postman_collection.json index 097db5415..ace0db09c 100644 --- a/projects/node-http-exercise/node-http-server-assignment.postman_collection.json +++ b/projects/node-http-exercise/node-http-server-assignment.postman_collection.json @@ -1,196 +1,160 @@ { - "info": { - "_postman_id": "64979725-c0e2-4f70-96ea-d9eee4ace15a", - "name": "techtonia-node-http-server-assignment", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" - }, - "item": [ - { - "name": "Initial Request", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:5000/", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "5000", - "path": [ - "" - ] - }, - "description": "Use this to test the functionality of your server.\r\nYou should get an object as a response, with the default parameters as you have set them in your API." - }, - "response": [] - }, - { - "name": "Test route: \"/test\"", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:5000/test", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "5000", - "path": [ - "test" - ] - }, - "description": "This should give you back the message you put in the \"/test\" route." - }, - "response": [] - }, - { - "name": "Test route: \"/spin\"", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:5000/spin", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "5000", - "path": [ - "spin" - ] - }, - "description": "This should return you an empty object with 200 OK status." - }, - "response": [] - }, - { - "name": "Test route: \"/head\"", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:5000/head", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "5000", - "path": [ - "head" - ] - }, - "description": "This should return 204 and leave the headers available for you to work with." - }, - "response": [] - }, - { - "name": "Test route: \"/hello\"", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:5000/hello", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "5000", - "path": [ - "hello" - ] - }, - "description": "This shoud respond with text: Hello and 200 status." - }, - "response": [] - }, - { - "name": "Test route: \"/echo\"", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:5000/echo?message=xyz", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "5000", - "path": [ - "echo" - ], - "query": [ - { - "key": "message", - "value": "xyz" - } - ] - }, - "description": "Entering information in the message parameter in this route should enable return you the message." - }, - "response": [] - }, - { - "name": "Test route: \"/error\"", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:5000/error", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "5000", - "path": [ - "error" - ] - }, - "description": "This should return with 500. Optional: return \"Server Error!\" in the body." - }, - "response": [] - }, - { - "name": "Test route: \"/time.json\"", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:5000/time.json", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "5000", - "path": [ - "time.json" - ] - }, - "description": "This should should respond with 200, body with Content-Type of application/json and { \"now\": \"Sat Feb 15 2020 14:29:20 GMT-0800\" } where it's the current time of the response." - }, - "response": [] - }, - { - "name": "Test route: \"/github\"", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:5000/github", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "5000", - "path": [ - "github" - ] - }, - "description": "This should respond with 302 that redirects to Techtonica GitHub page." - }, - "response": [] - } - ], - "protocolProfileBehavior": {} -} \ No newline at end of file + "info": { + "_postman_id": "64979725-c0e2-4f70-96ea-d9eee4ace15a", + "name": "techtonia-node-http-server-assignment", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "Initial Request", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:5000/", + "protocol": "http", + "host": ["localhost"], + "port": "5000", + "path": [""] + }, + "description": "Use this to test the functionality of your server.\r\nYou should get an object as a response, with the default parameters as you have set them in your API." + }, + "response": [] + }, + { + "name": "Test route: \"/test\"", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:5000/test", + "protocol": "http", + "host": ["localhost"], + "port": "5000", + "path": ["test"] + }, + "description": "This should give you back the message you put in the \"/test\" route." + }, + "response": [] + }, + { + "name": "Test route: \"/spin\"", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:5000/spin", + "protocol": "http", + "host": ["localhost"], + "port": "5000", + "path": ["spin"] + }, + "description": "This should return you an empty object with 200 OK status." + }, + "response": [] + }, + { + "name": "Test route: \"/head\"", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:5000/head", + "protocol": "http", + "host": ["localhost"], + "port": "5000", + "path": ["head"] + }, + "description": "This should return 204 and leave the headers available for you to work with." + }, + "response": [] + }, + { + "name": "Test route: \"/hello\"", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:5000/hello", + "protocol": "http", + "host": ["localhost"], + "port": "5000", + "path": ["hello"] + }, + "description": "This shoud respond with text: Hello and 200 status." + }, + "response": [] + }, + { + "name": "Test route: \"/echo\"", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:5000/echo?message=xyz", + "protocol": "http", + "host": ["localhost"], + "port": "5000", + "path": ["echo"], + "query": [ + { + "key": "message", + "value": "xyz" + } + ] + }, + "description": "Entering information in the message parameter in this route should enable return you the message." + }, + "response": [] + }, + { + "name": "Test route: \"/error\"", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:5000/error", + "protocol": "http", + "host": ["localhost"], + "port": "5000", + "path": ["error"] + }, + "description": "This should return with 500. Optional: return \"Server Error!\" in the body." + }, + "response": [] + }, + { + "name": "Test route: \"/time.json\"", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:5000/time.json", + "protocol": "http", + "host": ["localhost"], + "port": "5000", + "path": ["time.json"] + }, + "description": "This should should respond with 200, body with Content-Type of application/json and { \"now\": \"Sat Feb 15 2020 14:29:20 GMT-0800\" } where it's the current time of the response." + }, + "response": [] + }, + { + "name": "Test route: \"/github\"", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "http://localhost:5000/github", + "protocol": "http", + "host": ["localhost"], + "port": "5000", + "path": ["github"] + }, + "description": "This should respond with 302 that redirects to Techtonica GitHub page." + }, + "response": [] + } + ], + "protocolProfileBehavior": {} +} diff --git a/projects/utils-js.md b/projects/utils-js.md index 00442a908..416ef93f8 100644 --- a/projects/utils-js.md +++ b/projects/utils-js.md @@ -7,14 +7,17 @@ Every project of any size grows a utils module that contains random helpers. Man Create your own mini utils file and implement the following functions from lodash: ### Array + - [intersection](https://lodash.com/docs/4.17.15#intersection) - [difference](https://lodash.com/docs/4.17.15#difference) - [uniq](https://lodash.com/docs/4.17.15#uniq) ### Map + - [mapValues](https://lodash.com/docs/4.17.15#mapValues): their impl uses plain objects. I suggest you use the JS Map ### String + - [template](https://lodash.com/docs/4.17.15#template) - similar to the built-in backtick strings of ES6 In addition, choose **three more functions** from the (long) list in the [lodash docs](https://lodash.com/docs/4.17.15). @@ -25,5 +28,6 @@ In addition, choose **three more functions** from the (long) list in the [lodash - Don't forget about edgecases like someone passing in `undefined` or empty input ### Bonus + - Measure your testing coverage with an open source tool so you can see if you missed any test coverage - Publish it as a real NPM package, with a unique package name such as `yourname-utils` and nice README so it looks nice on NPM diff --git a/runtime-complexity/index.html b/runtime-complexity/index.html index 5ce7f1e43..816cb5f62 100644 --- a/runtime-complexity/index.html +++ b/runtime-complexity/index.html @@ -1,25 +1,25 @@ - - - - - - - + } + + +
    - +
    - + diff --git a/runtime-complexity/runtime.js b/runtime-complexity/runtime.js index a6b782832..fb03ad27d 100644 --- a/runtime-complexity/runtime.js +++ b/runtime-complexity/runtime.js @@ -2,33 +2,49 @@ // Work in Progress. // Note: Some of the function definitions have been moved to runtime1-analyzing.js -const now = require('performance-now'); -const Chart = require('chart.js') -const randomstring = require('randomstring'); -const evaluate = function(f, _ns) { - const ns = _ns || [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 40000]; +const now = require("performance-now"); +const Chart = require("chart.js"); +const randomstring = require("randomstring"); +const evaluate = function (f, _ns) { + const ns = _ns || [ + 1000, + 2000, + 3000, + 4000, + 5000, + 6000, + 7000, + 8000, + 9000, + 10000, + 20000, + 30000, + 40000 + ]; const runs = 100; let timeUsed = 0; let startTs = 0; const timeStart = () => { startTs = now(); - } + }; const timeEnd = () => { timeUsed += now() - startTs; - } + }; const warmUp = 100; for (let i = 0; i < warmUp; i++) { - f(1000, () => { - }, () => { - }) + f( + 1000, + () => {}, + () => {} + ); } - const points = [] + const points = []; - ns.map(n => { - const label = `Running, n = ${n}` + ns.map((n) => { + const label = `Running, n = ${n}`; for (let run = 0; run < runs; run++) { f(n, timeStart, timeEnd); } @@ -42,7 +58,7 @@ const evaluate = function(f, _ns) { }); return points; -} +}; const wrapArray = (f, sorted) => { const ret = (n, startTime, endTime) => { @@ -57,9 +73,9 @@ const wrapArray = (f, sorted) => { const res = f(a); endTime(); return res; - } + }; return ret; -} +}; const wrapString = (f) => { const ret = (n, startTime, endTime) => { @@ -67,19 +83,19 @@ const wrapString = (f) => { startTime(); f(s); endTime(); - } + }; return ret; -} +}; const wrapN = (f) => { return (n, startTime, endTime) => { startTime(); f(n); endTime(); - } -} + }; +}; -const mysteryFunction0 = function(array) { +const mysteryFunction0 = function (array) { const myFavoriteNum = 7; for (i = 0; i < array.length; i++) { if (array[i] === myFavoriteNum) { @@ -87,60 +103,63 @@ const mysteryFunction0 = function(array) { } } return false; -} +}; -const mysteryFunction1 = function(array) { +const mysteryFunction1 = function (array) { index = 4; return array[index]; -} +}; const timings = [ { - label: 'mysteryFunction0', + label: "mysteryFunction0", data: evaluate(wrapArray(mysteryFunction0)), pointBorderColor: "rgba(255,0,0,1)" }, { - label: 'mysteryFunction1', + label: "mysteryFunction1", data: evaluate(wrapArray(mysteryFunction1)), pointBorderColor: "rgba(0,255,0,1)" } -] - -main = function(document) { +]; +main = function (document) { const elem = document.getElementById("myChart"); const ctx = elem.getContext("2d"); const myChart = new Chart(ctx, { - type: 'scatter', - data: { - datasets: timings - }, - options: { - scales: { - yAxes: [{ - ticks: { - beginAtZero:true - }, - scaleLabel: { - display: true, - labelString: 'time in milliseconds' - } - }], - xAxes: [{ - ticks: { - beginAtZero:true - }, - scaleLabel: { - display: true, - labelString: 'n (number of elements)' - } - }] - }, - title: { - display: true, - text: 'Runtimes' + type: "scatter", + data: { + datasets: timings + }, + options: { + scales: { + yAxes: [ + { + ticks: { + beginAtZero: true + }, + scaleLabel: { + display: true, + labelString: "time in milliseconds" + } + } + ], + xAxes: [ + { + ticks: { + beginAtZero: true + }, + scaleLabel: { + display: true, + labelString: "n (number of elements)" + } } + ] + }, + title: { + display: true, + text: "Runtimes" } + } }); -} +}; diff --git a/runtime-complexity/runtime1-analyzing.js b/runtime-complexity/runtime1-analyzing.js index 05a9eea2a..fb470da79 100644 --- a/runtime-complexity/runtime1-analyzing.js +++ b/runtime-complexity/runtime1-analyzing.js @@ -6,7 +6,6 @@ Read the following functions. For each one, figure out: - When the input size doubles, what happens to the time it takes to run? */ - const mysteryFunction0 = function (array) { const myFavoriteNum = 7; for (i = 0; i < array.length; i++) { @@ -15,17 +14,15 @@ const mysteryFunction0 = function (array) { } } return false; -} - +}; const mysteryFunction1 = function (array) { index = 4; return array[index]; -} - +}; const mysteryFunction2 = function (n) { - const primes = [] + const primes = []; for (i = 2; i < n; i++) { let factorFound = false; for (j = 2; j < n; j++) { @@ -38,8 +35,7 @@ const mysteryFunction2 = function (n) { } } return primes.length; -} - +}; const mysteryFunction3 = function (array) { myLength = array.length; @@ -48,30 +44,26 @@ const mysteryFunction3 = function (array) { } else { return "odd length"; } -} - +}; const mysteryFunction4 = function (string) { let eCount = 0; for (i = 0; i < string.length; i++) { - if (string[i] === 'e') { + if (string[i] === "e") { eCount++; } } return eCount; -} - +}; const mysteryFunction5 = function (array) { array.sort(); -} - +}; const mysteryFunction6 = function (dict, key) { const value = dict[key]; return value; -} - +}; const mysteryFunction7 = function (array) { // Assume `array` is an array of ints sorted from smallest to biggest @@ -90,8 +82,7 @@ const mysteryFunction7 = function (array) { guessIndex = Math.floor((lowerBound + upperBound) / 2); } return false; -} - +}; const mysteryFunction8 = function (dictionary) { for (let key in dictionary) { @@ -101,6 +92,4 @@ const mysteryFunction8 = function (dictionary) { } return false; } -} - - +}; diff --git a/runtime-complexity/runtime2-comparisions.js b/runtime-complexity/runtime2-comparisions.js index 1ef0db454..92a1feeb4 100644 --- a/runtime-complexity/runtime2-comparisions.js +++ b/runtime-complexity/runtime2-comparisions.js @@ -8,22 +8,21 @@ For each function: Which solution would be fastest for large input sizes? */ - // The following 4 functions all look for duplicated elements in an array. -// For example, if the input is [5,2,4,5,4], the function should return [5,4] +// For example, if the input is [5,2,4,5,4], the function should return [5,4] // because those elements are in the array twice. const findDuplicatesA = (array) => { const duplicated = []; for (let i = 0; i < array.length; i++) { - for (let j = i+1; j < array.length; j++) { + for (let j = i + 1; j < array.length; j++) { if (array[i] === array[j]) { duplicated.push(array[j]); } } } return duplicated; -} +}; const findDuplicatesB = (array) => { const seen = new Set(); @@ -36,7 +35,7 @@ const findDuplicatesB = (array) => { seen.add(value); } return duplicates; -} +}; const findDuplicatesC = (array) => { array.sort(); @@ -49,7 +48,7 @@ const findDuplicatesC = (array) => { } } return duplicates; -} +}; const findDuplicatesD = (array) => { const duplicated = []; @@ -62,12 +61,11 @@ const findDuplicatesD = (array) => { seen.push(item); } return duplicated; -} - +}; -// The following 3 functions all count how many times an item is in an array +// The following 3 functions all count how many times an item is in an array // and return a dictionary of the counts -// For example, if the input is [5,2,4,5,4,5], the function should return {5:3, 4:2, 2:1} +// For example, if the input is [5,2,4,5,4,5], the function should return {5:3, 4:2, 2:1} const countOccurencesA = (array) => { const counts = {}; @@ -84,7 +82,7 @@ const countOccurencesA = (array) => { } } return counts; -} +}; const countOccurencesB = (array) => { const counts = {}; @@ -103,7 +101,7 @@ const countOccurencesB = (array) => { } } counts[currentItem] = itemCount; -} +}; const countOccurencesC = (array) => { const counts = {}; @@ -115,4 +113,4 @@ const countOccurencesC = (array) => { counts[item] += 1; } return counts; -} +}; diff --git a/testing-and-tdd/integration-testing.md b/testing-and-tdd/integration-testing.md index 83949c996..91001eb61 100644 --- a/testing-and-tdd/integration-testing.md +++ b/testing-and-tdd/integration-testing.md @@ -461,7 +461,7 @@ describe('GET /', () => { ]; expectedResults = JSON.stringify({ error: false, todo: todoContents }); - const mockGetTodo = function(todoCallback) { + const mockGetTodo = function (todoCallback) { todoCallback(false, { rows: todoContents }); }; @@ -492,7 +492,6 @@ to build testable code that utilizes external services? One possible way of doing this is up on [glitch][backend-ii]. (Open the console and enter 'mocha' to run tests.) - ## Independent Practice - Deploy your own version of the sample TODO project to heroku, netlify, or diff --git a/testing-and-tdd/jasmine-pair-activity.js b/testing-and-tdd/jasmine-pair-activity.js index 72dccee82..9c25eeec3 100644 --- a/testing-and-tdd/jasmine-pair-activity.js +++ b/testing-and-tdd/jasmine-pair-activity.js @@ -15,6 +15,4 @@ correctness. Think of all the input that could come in and decide what to do with them via tests. */ -function invert() { - -} +function invert() {} diff --git a/testing-and-tdd/jasmine-testing.md b/testing-and-tdd/jasmine-testing.md index dbb15f998..81188253e 100644 --- a/testing-and-tdd/jasmine-testing.md +++ b/testing-and-tdd/jasmine-testing.md @@ -91,8 +91,8 @@ _Jasmine Syntax_ - Let's look at a complete example. Add the following code to your `string.spec.js` file: ```javascript -describe('A string', function() { - it('containing 4 letters should have length 4', function() { +describe('A string', function () { + it('containing 4 letters should have length 4', function () { WORD = 'word'; expect(WORD.length == 4).toBe(true); }); @@ -143,15 +143,15 @@ _Adding more tests_ - Right now, we only have one spec in our file. Let's add another by adding an additional `it` statement. ```javascript -describe('A string', function() { - it('containing 4 letters should have length 4', function() { +describe('A string', function () { + it('containing 4 letters should have length 4', function () { WORD = 'word'; expect(WORD.length == 4).toBe(true); }); // New spec! - it('should be equal to an identical string', function() { + it('should be equal to an identical string', function () { WORD = 'word'; expect(WORD == 'word').toBe(true); @@ -163,14 +163,14 @@ describe('A string', function() { - Notice that we used the same value for `WORD` twice. Multiple `it` statements can use the same variables if they are declared under the `describe` scope. ```javascript -describe('A string', function() { +describe('A string', function () { let WORD = 'word'; - it('containing 4 letters should have length 4', function() { + it('containing 4 letters should have length 4', function () { expect(WORD.length == 4).toBe(true); }); - it('should be equal to an identical string', function() { + it('should be equal to an identical string', function () { expect(WORD == 'word').toBe(true); }); }); @@ -184,13 +184,13 @@ _Other matchers_ - Let's add a (failing) test using the `toBeGreaterThan` matcher. ```javascript -describe('A string', function() { +describe('A string', function () { let WORD = 'word'; // ... previous tests // New test - it('should be more than 5 characters long', function() { + it('should be more than 5 characters long', function () { expect(WORD.length).toBeGreaterThan(5); }); }); @@ -213,10 +213,10 @@ Failures: - Remember our last failing test? This one has a more helpful error message, because it tells us exactly what's wrong: "Expected 4 to be greater than 5." Oops! `WORD.length` is 4 - let's provide a different value so that our test passes: ```javascript -describe('A string', function() { +describe('A string', function () { // ... previous tests - it('should have a length greater than 5', function() { + it('should have a length greater than 5', function () { expect('elephant'.length).toBeGreaterThan(5); }); }); diff --git a/testing-and-tdd/mocking-and-abstraction.md b/testing-and-tdd/mocking-and-abstraction.md index 8cb125177..9709bed65 100644 --- a/testing-and-tdd/mocking-and-abstraction.md +++ b/testing-and-tdd/mocking-and-abstraction.md @@ -40,6 +40,7 @@ Continuing with our testing lesson, we will explore here that the core of our te ### Specific Things To Learn Testing external services + - Mocking & abstractions - [Simple Mock][simplemock-home] - [Nock][nock-home] ([intro tutorial][nock-intro]) @@ -116,6 +117,7 @@ describe('Get User tests', () => { **Challenge** Following example above, try to represent the following scenarios and think about what would happen: + - Call `getUser('not-octocat')`? - Change `mockObject.id` to be `42`? - Change `mockObject.name` to `Techtonica`? @@ -126,7 +128,6 @@ Think back to [Eloquent JavaScript Ch 5][ejs-5] when you learned about _Abstract [ejs-5]: https://eloquentjavascript.net/05_higher_order.html - **An Example:** Let's look at some places where abstraction can help us make our code easier to understand and maintain. @@ -222,11 +223,12 @@ app.get('/', (req, res) => { }); }); ``` + But how do we test this? Well, it's tricky because `getTodo` is still making an external call to the database which is difficult to handle. Let's hold off getting into until the Guided Practice section but as a hint it's just more layers of capturing behavior in a function and passing it around to our endpoint's implementation. ### Common Mistakes & Misconceptions -It's very common to test the external APIs I'm using to make sure my code still works. An easy way to do it is writing mock classes that return information in the format you expect it. +It's very common to test the external APIs I'm using to make sure my code still works. An easy way to do it is writing mock classes that return information in the format you expect it. Also, it's a good practice to use these mocks to test expected and unexpected behavior, so you won't need to hit an external API on every test. @@ -256,7 +258,7 @@ We can use the same principles of encapsulation and injection here to make the ` ```javascript function mkSaveTodo(dbPool) { - return function(todo, callback) { + return function (todo, callback) { return dbPool.query( 'INSERT INTO todo_items (entry) VALUES($1)', [todo], @@ -279,7 +281,7 @@ setup.constructRoutes(app, ..., saveTodo) > Note: There are two things worth calling out a about this example. > > First: A totally valid question is "why not have `mkSaveTodo` take in a `query` function instead of `dbPool`? -> +> > The answer is one of mental framing: When deciding what to pull out I approached it as a problem of "How do I make the database a variable." Within that context it made more sense for `dbPool` to be passed in. This also means if I need to do other things with the database in the future it doesn't change. Even so if you wanted to just pass in a `query` function that is also totally fine. > > Second: Once you dig into the reference project provided for part three you'll notice the solution there is a bit different than the one above, why is that? diff --git a/web/html-forms.md b/web/html-forms.md index 1c1cad35a..fd7dc2835 100644 --- a/web/html-forms.md +++ b/web/html-forms.md @@ -29,6 +29,7 @@ HTML Form is one of the most popular ways to gather user information and send it to an application. It is the most efficient way to let the user enter the data. For example, it can be used to collect things like a name and email in a sign-up form. When the user/visitor enters the details in the form, it is posted to the backend server where the processing is done and then the necessary data is stored in the database. There are various elements which can be used in the form which are as follows: + 1. Input element : It is the most commonly used field in the form which allows the user to specify different types of values. It can be text field, number field, password field, checkbox etc. Following is an example which shows the code snippet to declare the input element. @@ -41,8 +42,8 @@ Following is an example which shows the code snippet to declare the input elemen ``` - Label is an element which is used to provide the context of the input field. Like in the above example the input field is provided to enter the Name. -- Type is used to define the type of the input box. -Checkbox is a type of input field which allows the user to select options from the given choices. +- Type is used to define the type of the input box. + Checkbox is a type of input field which allows the user to select options from the given choices. - The for attribute of the `