diff --git a/.husky/.gitignore b/.husky/.gitignore deleted file mode 100644 index 31354ec1389..00000000000 --- a/.husky/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_ diff --git a/.husky/pre-commit b/.husky/pre-commit deleted file mode 100755 index 146c0dfd0de..00000000000 --- a/.husky/pre-commit +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -. "$(dirname "$0")/_/husky.sh" - -npx lint-staged --allow-empty diff --git a/content/ai/ai.md b/content/ai/ai 3.md similarity index 100% rename from content/ai/ai.md rename to content/ai/ai 3.md diff --git a/content/ai/concepts/ai-ethics/ai-ethics.md b/content/ai/concepts/ai-ethics/ai-ethics.md deleted file mode 100644 index b508b4ba500..00000000000 --- a/content/ai/concepts/ai-ethics/ai-ethics.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -Title: 'AI Ethics' -Description: 'The study of how AI systems ought to be developed, distributed, and used.' -Subjects: - - 'AI' -Tags: - - 'AI' - - 'Accessibility' - - 'Deep Learning' - - 'Neural Networks' - - 'Justice' -CatalogContent: - - 'paths/machine-learning-ai-engineering-foundations' - - 'intro-to-ai-strategy' ---- - -**AI ethics** is the study of ethical issues that arise in the development, distribution, and use of AI systems. As AI-based technologies become more powerful and accurate, they will have a large influence on many aspects of human societies. Already, AI systems are being deployed to help make decisions in finance, law, transportation, employment, and many other areas. It is therefore extremely important for those involved in the development and distribution of AI technologies to carefully consider ethical issues that will arise in the use of these technologies. - -AI ethics is both a practical and a philosophical endeavor. Some of the key tasks involved in these two facets are described below. - -## Philosophical Tasks of AI Ethics - -The central philosophical tasks of AI ethics are: - -- Determining general ethical principles that should govern AI systems as they are deployed in any area of human society. -- Making ethical judgments about particular uses of AI and situations involving AI systems. -- Discerning and publicizing relevant ethical factors that should be considered by developers of AI, users of AI, and governmental authorities. - -## Practical Tasks of AI Ethics - -The central practical tasks of AI ethics are: - -- Developing ways of implementing ethical principles into AI systems to ensure positive outcomes. -- Making decisions about the ethical development, distribution and use of AI even under both factual and ethical uncertainty. -- Creating laws governing the development, distribution, and use of AI. - -## Specific Issues and Concepts in AI Ethics - -The specific issues and concepts involved in AI ethics are described in the term pages below. diff --git a/content/ai/concepts/ai-ethics/terms/opacity/opacity.md b/content/ai/concepts/ai-ethics/terms/opacity/opacity.md deleted file mode 100644 index 67c8d426b8c..00000000000 --- a/content/ai/concepts/ai-ethics/terms/opacity/opacity.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -Title: 'Opacity' -Description: 'The inability to explain the inner workings of some AI systems.' -Subjects: - - 'AI' -Tags: - - 'AI' - - 'Accessibility' - - 'Deep Learning' - - 'Neural Networks' - - 'Opacity' -CatalogContent: - - 'learn-explainable-ai-xai' - - 'paths/build-deep-learning-models-with-tensorflow' ---- - -Some AI systems are labelled as "black boxes" because it is difficult to explain their inner workings. This feature is known as AI **opacity**. - -Opacity is not inherent to all AI systems, but tends to be associated especially with deep learning methods as implemented by [neural networks](https://www.codecademy.com/resources/docs/ai/neural-networks). The problem is that when data is fed into a neural network, that input passes through hidden layers of nodes. These layers perform thousands of computations in a manner that is not predictable in advance. Moreover, the inner meaning of the path that the input takes through these hidden layers is not known by the human programmer. The result is that it may be difficult to explain why the system classified a certain input in the way that it did. - -## Problems of AI Opacity - -Some reasons for thinking that opaque AI systems are ethically problematic are discussed below. - -### The Right to Explanation - -Some theorists have argued that AI opacity is a problem because it conflicts with the **right to explanation**. They posit that some decisions must be backed by a substantive explanation of the reasons behind the decision that can be given to those affected by that decision. For example, judges do not merely deliver verdicts and sentences, they explain the reasons behind those decisions in written opinions. - -Imagine a neural network that took in the data of a legal case and produced a verdict (with a sentence, if appropriate) as an output. Because of the opacity of neural networks, it might be impossible to give a humanly-understandable, accurate explanation of why the system produced the verdict that it did. Proponents of the right to explanation argue that the use of such an AI system would be unjust, because it conflicts with the rights of legal defendants to be given an adequate explanation of the verdict of their case. - -An opposing view is that there is no right to explanation, but only a right to a reliable decision-making process. On this view, so long as an AI system can reliably (at or above expert-human levels) classify cases, there is no further ethical need to explain those decisions. In the present example, this would mean as long as the system could accurately classify defendants as guilty or not guilty at or above the performance of a human judge, defendants would have no legitimate complaint against the use of the system to decide their case. - -### Engaging with AI Decisions - -AI opacity implies the reasons behind certain AI decisions are inaccessible to human users. This also means that users cannot engage rationally with these reasons. In other words, they cannot check the reasoning against other sources of knowledge, or deliberate with the AI system about those reasons, as can be done with a human decision-maker. - -This inability to rationally cross-check AI decision-making becomes an issue when AI decisions are surprising. Suppose, for example, that an AI system is used to forecast how much of a certain material a company should order, and that, on a particular occasion, it makes a surprisingly large recommendation. If employees at the company are unable to understand the reasons behind that particular recommendation, they will be unable to assess those reasons and therefore be unable to know whether to trust the recommendation. - -The limitations on rationally engaging with AI decision-making are another potentially ethically problematic feature of relying on AI systems to make high-stakes, morally significant decisions. - -## Explainable AI (XAI) - -The goal of **Explainable AI (XAI)** is to develop techniques for explaining the processes and outputs of AI systems, thereby addressing the challenges above. Some of the techniques currently used in XAI are explained in the _Learn Explainable AI (XAI)_ course linked below this article. - -## Further Reading on AI Opacity - -- Fleisher, W. (2022). Understanding, Idealization, and Explainable AI. _Episteme 19_ (4): 534-560. DOI: 10.1017/epi.2022.39. -- Gunning, D. et al (2019). XAI — Explainable artificial intelligence. _Science Robotics 4_ (37): 1-2. DOI: 10.1126/scirobotics.aay7120. -- Ross, Amber (2022). AI and the expert; a blueprint for the ethical use of opaque AI. _AI & Society_. DOI: 10.1007/s00146-022-01564-2. -- Uwe, Peters (2023). Explainable AI lacks regulative reasons: why AI and human decision-making are not equally opaque. _AI and Ethics 3_: 963-974. DOI: 10.1007/s43681-022-00217-w. diff --git a/content/ai/concepts/chatgpt/chatgpt.md b/content/ai/concepts/chatgpt/chatgpt.md deleted file mode 100644 index c3c85c8111f..00000000000 --- a/content/ai/concepts/chatgpt/chatgpt.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -Title: 'ChatGPT' -Description: 'ChatGPT is an AI-powered chatbot designed by OpenAI to generate human-like responses using deep learning.' -Subjects: - - 'AI' - - 'Machine Learning' -Tags: - - 'AI' - - 'Attention' - - 'Data' - - 'Transformers' -CatalogContent: - - 'intro-to-generative-ai' - - 'paths/data-science' ---- - -[**ChatGPT**](https://chatgpt.com) is an AI-powered chatbot designed by OpenAI, built on Large Language Models (LLMs) like GPT-4 (Generative Pre-Trained Transformer). It generates human-like text responses by analyzing input context and predicting the most likely continuation of a conversation. ChatGPT is widely used for content creation, coding assistance, customer service, and more. - -## How ChatGPT Works - -ChatGPT is based on **transformer neural networks**, an AI architecture designed for handling sequential text data. It predicts words based on patterns it has learned during training. Other notable LLMs include **BERT** (used by Google for search), **Claude** (Anthropic's AI model), and **Mistral** (an open-source competitor). - -### What Sets ChatGPT Apart from Search Engines? - -ChatGPT differs from search engines in several ways: - -- It does not browse the internet in real-time (unless using specific plugins or connected to retrieval-based systems). -- Its knowledge is limited to training data, meaning it lacks awareness of recent events unless fine-tuned. -- It does not retrieve exact sources but instead generates patterns-based responses. -- It uses **Reinforcement Learning from Human Feedback (RLHF)** to improve quality and alignment with human expectations. - -## Advancements in ChatGPT - -Since its initial release, ChatGPT has seen several advancements: - -- **GPT-4 (2023)**: Improved reasoning, factual accuracy, and multimodal capabilities. -- **ChatGPT Plus**: A premium subscription plan offering faster responses and access to the latest models. -- **Plugins and Browsing (2023)**: Optional features allowing access to real-time data retrieval and API integrations. -- **Memory Capabilities (2024)**: ChatGPT can now retain information across conversations, improving personalization. -- **Integration with Microsoft Products**: ChatGPT technology is embedded into Microsoft Copilot, powering AI-driven workflows in Word, Excel, and Teams. -- **GPT-4o (2024)**: Can reason across audio, vision, and text. - -## History of ChatGPT - -There were several generations of AI technologies that have led up to ChatGPT. - -### Feed Forward Networks - -**Artificial Neural Networks** (ANNs) are a class of computational functions inspired by how neurons work in the human brain. Neurons are arranged in layers and training occurs by guiding the network to differentiate between correct and incorrect answers. These are called feed-forward networks because signals move forward through the system. - -One example of a common ANN is a **Convolutional Neural Network** (CNN). These are commonly used in image recognition. A _convolution_ can be thought of as a filter applied to the image to make things like edges or specific features stand out. - -### Recurrent Neural Networks - -One limitation of ANNs is that they don’t have the concept of time sequences and the input size is fixed. So for language processing where a sequence of words or a sentence exists, **Recurrent Neural Networks** (RNNs) were created. - -RNNs feed decision results back into the system. So for example, if the sentence “What time is it?” were to be translated, the system would already know all about the question when the word “it” is encountered. - -While RNNs are very useful for language translation, they do not scale well with large amounts of information. Also, computations cannot be done in parallel. - -### Breakthrough with Transformers - -The breakthrough that allowed BERT and ChatGPT-based models to flourish is called **transformers**, introduced in a paper from 2017 entitled [_Attention Is All You Need_](https://en.wikipedia.org/wiki/Attention_Is_All_You_Need). It was presented as a way to build machine translation with much faster parallel execution. It also introduced a new concept called _Self Attention_ to make sense of long language sequences further. It creates connections between different parts of the sequence. This allowed for highly scalable and efficient text generation, leading to models like GPT-3, GPT-4, and beyond. - -So how does it all work? In the transformer-based model, each word is transformed into a token. As tokens are read as part of an input sentence, the model starts predicting what the output should be - similar in concept to sentence completion. - -Due to the use of transformers in creating the model, the potential output is not just a prediction of the next word. Because the model is trained with deep understanding and _attention_, whole sentences and groupings of text are generated. The model used by ChatGPT can accept several thousand tokens as input. - -## Risks and Limitations - -### Misinformation & Hallucinations - -ChatGPT may produce confident but incorrect responses (hallucinations). While improvements have reduced errors, it remains a significant challenge. With prompt engineering, ChatGPT can be told to not give an answer unless it has high confidence in the results. This can reduce hallucinations but not completely solve the problem. - -### Bias - -All models inherit biases from training data, which can impact fairness in responses. OpenAI continues to refine its moderation techniques to minimize harmful outputs. - -### Data Privacy - -ChatGPT does not store user data permanently, but queries are analyzed to improve the model. Users should avoid sharing sensitive information. - -### Cost and Energy Consumption - -Training LLMs like ChatGPT requires massive computing power, raising concerns about sustainability and accessibility. - -## The Future - -### Expanding Capabilities - -ChatGPT is evolving beyond text-based chat. Future enhancements include: - -- Improved memory for contextual awareness over multiple conversations. -- Expanded multimodal capabilities (processing images, audio, and video). -- Advanced personalization for tailored user experiences. - -### AI in Everyday Use - -ChatGPT is already embedded into: - -- Microsoft Copilot (Windows & Office integration) -- AI-powered Google search -- AI-assisted customer service platforms -- Code generation tools (e.g., GitHub Copilot) - -### OpenAI's Roadmap - -- **GPT-5 (TBA)**: Expected to bring even greater reasoning, memory and adaptability. -- **AI Regulation & Safety**: OpenAI collaborates with governments to ensure responsible AI development. - -### Cost - -Costs to train an LLM can be millions of dollars - so training frequently may hit commercial challenges. After training, each _inference_ or transaction costs some amount of money and computing power. diff --git a/content/ai/concepts/foundation-models/foundation-models.md b/content/ai/concepts/foundation-models/foundation-models.md deleted file mode 100644 index 7c4367fd5b4..00000000000 --- a/content/ai/concepts/foundation-models/foundation-models.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -Title: 'Foundation Models' -Description: 'Foundation models power AI systems that are trained on text, images, code, and other formats of data.' -Subjects: - - 'Machine Learning' -Tags: - - 'AI' - - 'NLP' - - 'Deep Learning' -CatalogContent: - - 'paths/data-science-nlp' - - 'intro-to-chatgpt' ---- - -**Foundation models** power AI systems that are trained on text, images, code, and other formats of data. These models pre-train on large amounts of unlabeled data from the internet. They can then be fine-tuned to perform various downstream tasks, like generating content (referred to as [generative AI (GenAI)](https://www.codecademy.com/resources/docs/ai/generative-ai)). - -Foundation models are capable of powering downstream tasks that involve language, vision, robotics, reasoning, and human interactions. - -Five attributes for foundation models include: - -1. Expressivity: Can capture information and present it with realism. -2. Scalability: Can handle large amounts of high-dimensional data. -3. Multimodality: Can consume, process, and create content from many sources and domains. -4. Memory: Can store and access knowledge. -5. Compositionality: Can generalize. - -## Data - -Large amounts of data are passed to foundation models to improve the ability to perform downstream tasks. - -### Risks - -Due to the nature of the data that models train on, biases and stereotypes pose a serious risk. Malicious actors may spread disinformation using AI systems to generate exaggerated content. Misinformation is also a possibility due to artificial hallucinations. Therefore, it's important to train models on data from trusted sources to minimize these risks. - -## Model Architecture - -Foundation models use various architecture types. One of which includes the transformer architecture (like evolved transformer or vanilla transformer). - -## Training - -Foundation models are based on [deep learning](https://www.codecademy.com/resources/docs/ai/machine-learning) standards and transfer learning. - -Pre-training models on data is vital in transfer learning, which deals with the application of knowledge learned from one task onto another task. As computer hardware increases in speed and memory, the amount of training data that is able to be processed increases as well. - -## Existing Models - -Some examples of existing foundation models include: - -- BERT (Bidirectional Encoder Representations from Transformers) is a model introduced by Google in 2018. -- LaMDA (Language Model for Dialogue Applications) is a model introduced by Google in 2020, and powers Bard which was released in March 2023. -- GPT (Generative Pre-trained Transformer) is a model that was first introduced by OpenAI in 2018. It is trained on text and code, and powers [ChatGPT](https://www.codecademy.com/resources/docs/ai/chatgpt) which was released in November 2022. -- DALL-E is a model introduced in 2021 by OpenAI. It is based on GPT-3 and is used to produce images. - -## Model Types - -Foundation models are a fundamental part of an AI system. Below are some of the types of models: diff --git a/content/ai/concepts/foundation-models/terms/diffusion-models/diffusion-models.md b/content/ai/concepts/foundation-models/terms/diffusion-models/diffusion-models.md deleted file mode 100644 index 9749459b124..00000000000 --- a/content/ai/concepts/foundation-models/terms/diffusion-models/diffusion-models.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -Title: 'Diffusion Models' -Description: 'Diffusion Models are generative models, which means they are used to generate data similar to what they were trained on. The models work by destroying training data through the addition of Gaussian noise, and then learning to recover that data.' -Subjects: - - 'Machine Learning' - - 'Data Science' -Tags: - - 'AI' - - 'Image Generation Model' - - 'Denoising' - - 'Prompts' - - 'Prompt Engineering' - - 'Text-To-Image' - - 'Deep Learning' -CatalogContent: - - 'machine-learning' - - 'paths/data-science' ---- - -**Diffusion Models** are generative models, which means they are used to generate data similar to what they were trained on. The models work by destroying training data through the addition of Gaussian noise, and then learning to recover that data. - -### About Diffusion Models - -A Diffusion model is a deep learning generative model that works by adding noise to the available training data known as the forward diffusion process, it then reverses the process to recover the data. This is known as denoising or the reverse diffusion process. - -The three fundamental mathematical frameworks that support the science behind diffusion models, work on the same principles of adding noise and removing it to generate new samples. - -- **DDPMs** : Denoising Diffusion Probabilistic Models are generative models mainly used to remove noise from visual or audio data. - -- **SGMs** : Noise-Conditioned Score-Based Generative Models can generate new samples from a given distribution. They work by learning an estimation score function that can estimate the log density of the target distribution. This means building an estimate based on observed data to be sampled. - -- **SDEs** : Stochastic Differential Equations describe changes in random processes concerning time. Widely used in physics and financial markets involving random factors that significantly impact market outcomes. - -## Image Generation - -![image of diffusion process](https://raw.githubusercontent.com/Codecademy/docs/main/media/ai-diffusion-model-example.png) - -- Diffusion models start with a base image from what it has been previously trained on and slowly adds more and more gaussian noise over time. -- It then gradually removes the noise, this learned denoising process then generates new, high-quality images from random seeds also known as random noised images. diff --git a/content/ai/concepts/foundation-models/terms/large-language-models/large-language-models.md b/content/ai/concepts/foundation-models/terms/large-language-models/large-language-models.md deleted file mode 100644 index cb9412e0bb0..00000000000 --- a/content/ai/concepts/foundation-models/terms/large-language-models/large-language-models.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -Title: 'Large Language Models (LLMs)' -Description: 'Large Language Models are artificial intelligence systems that are designed to process and generate human language on a massive scale.' -Subjects: - - 'Machine Learning' -Tags: - - 'AI' - - 'NLP' - - 'Deep Learning' -CatalogContent: - - 'paths/data-science-nlp' - - 'intro-to-chatgpt' ---- - -**Large language models (LLMs)** are artificial intelligence systems that are designed to process and generate human language on a massive scale. These models are trained on vast amounts of text data and use advanced machine learning algorithms to learn the patterns and structures of language. LLMs have become increasingly popular in recent years due to their ability to perform a wide range of language-related tasks such as language translation, text summarization, and question-answering. - -LLMs typically consist of a large neural network architecture that is trained on massive datasets. These models are trained using [unsupervised learning](https://www.codecademy.com/resources/docs/ai/machine-learning) techniques, which means that they do not require explicit human supervision to learn. Instead, they learn from the patterns and structures present in the data. - -LLMs are typically evaluated on their ability to perform a specific task, such as language translation or text generation. They are often fine-tuned on smaller datasets to improve their performance on specific tasks. However, the use of these models has raised concerns about their ethical implications, particularly with regard to bias and the potential for misuse. - -## Existing LLMs - -Large language models are a powerful tool for processing and generating human language, and their applications are likely to grow in the years to come. Some examples of existing LLMs are: - -- [OpenAI's](https://openai.com) GPT series -- Google's BERT and LaMDA (powers Bard) -- Facebook's [RoBERTa](https://www.open-roberta.org) diff --git a/content/ai/concepts/generative-ai/generative-ai.md b/content/ai/concepts/generative-ai/generative-ai.md deleted file mode 100644 index dbd8629d5b2..00000000000 --- a/content/ai/concepts/generative-ai/generative-ai.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -Title: 'Generative AI' -Description: 'Generative AI (GenAI) uses AI to create new content from simple text prompts. It can generate various types of content, including text, images, and code.' -Subjects: - - 'Machine Learning' - - 'Data Science' -Tags: - - 'AI' -CatalogContent: - - 'paths/machine-learning-engineer' - - 'intro-to-chatgpt' ---- - -**Generative AI** (GenAI) involves the creation of new and unique digital content. Before GenAI, digital content of this level could only be created by human beings. These unique creations are driven by natural language prompts. - -## Generative AI - -GenAI is based on **Large Language Models (LLMs)**. LLMs are trained on terabytes of textual data from the Internet. These models have the capability of delivering complex, high-level responses to human language prompts. - -In the case of ChatGPT, one breakthrough was the discovery that with some additional training, the LLMs can be used to produce impressive text-based results. - -GenAI is the connection of LLMs with technologies that, in addition to text results, can generate digital content such as images, video, music, or code. - -There is exploration of going beyond digital content and using this technology for things as varied as the discovery of new molecules and 3D designs. - -Things are changing quickly and the impact is only just starting to be predicted and felt. Most people are expecting changes in work and living lifestyles. - -### Foundation Models - -In the past, AI applications were very task specific. The recent technology shift has been to use [foundation models](https://www.codecademy.com/resources/docs/ai/foundation-models) to drive a number of different tasks. - -The models have a generative ability and were the start of Generative AI. ChatGPT demonstrated the ability to generate text based on natural language prompts. - -Using the concept of foundation models, vast amount of pre-trained data can be leveraged with a small amount of additional tuning and prompting. Tuning adds labels into the data. Prompting bridges the gap between training and intention. While training the LLM is expensive, the usage referred to as inference is more cost effective. - -### The Question of Intelligence? - -Artificial Intelligence (AI) is the matching or exceeding the intelligence of a human being. Things that are often associated with intelligence such as doing math, playing chess, or remembering vast amounts of data already can be done more quickly and better by computer. - -With LLMs and a technology called diffusion AI, systems can now match or exceed other skills we often associate with intelligence such as: - -- Accurately responding to language inputs and creating new text content. -- Writing original stories and poems. -- Analyzing content for tone and emotions. -- Creating unique images and video. - -### Is It Art? - -In 2022 Jason Allen’s AI generated work, _Théâtre D’opéra Spatial_, won first place in the digital category at the Colorado State Fair. The artist did indicate that he used the GenAI platform Midjourney. It was later discovered that the judges weren't familiar with the tool at the time of judging. - -The question "Does GenAI create art?" is now being asked. When photography was introduced, only painting had been considered art. Photography wasn't considered art and the same discussion took place. Now, few people would argue that photography cannot be art. - -Another argument is that since there is no advanced skill required from the operator, it is not art. Some consider art as the application of skills developed over many years. However, some modern art has been about concept and technique - not necessarily skill. - -An additional argument against it being art is that that the human element is not present in GenAI created works. The counter argument is that the creation is still driven by a person who has emotion, creativity, and intent. - -## Applications - -Generative AI is a combination of several technologies and has many applications. Effective LLMs are used to process a natural language prompt and technologies such as diffusion models are used in the case of image generation. - -Some content types GenAI is being used for include: - -- [Text](https://www.codecademy.com/resources/docs/ai/generative-ai/text) -- [Images](https://www.codecademy.com/resources/docs/ai/generative-ai/images) -- [Music](https://www.codecademy.com/resources/docs/ai/generative-ai/music) -- [Code](https://www.codecademy.com/resources/docs/ai/generative-ai/code) - -### Other Areas - -While GenAI is generally discussed in the context of text, images, music, and coding, there are many other active areas. Some of these include: - -- High fidelity text to speech -- Scientific Discovery (generating hypothesis and accelerating discovery) -- Chemistry (molecule and drug discovery) -- Medical imaging -- 3D Models (text to space creation) -- Video (movies, animations, transition between real and generated) -- Education (personalizing, customizing lessons, tutoring) - -## Impact and Possibilities - -### Legality - -The legal aspects of Generative AI are not yet defined. Class action lawsuits due to training data are showing up as infringing on the rights of artists. Related US laws include the first amendment and the fair use copyright act of 1976. These laws allow for the limited use of copyrighted material without permission of the copyright holder. - -Some uses are allowed, such as commentary, search engines, news reporting, research, and other transformative work. **Transformative** is defined as bringing a new expression, meaning, or message to the work. It can be argued that GenAI content can be transformative. - -### Policy - -Different companies are quickly setting up policies around Generative-AI. Google announced that they are allowing AI-generated advertising content. Shutterstock has announced that they will allow the selling of content generated with OpenAI and are working on a royalty system for content used to sell generated content based on original work. - -### Accuracy - -The correctness of the input data used during model training controls the accuracy of the generated content. There is no way to guarantee quality, accuracy, lack of bias, or timeliness. With the increased consumption of generated content, cases of misinformation (unintended and intended) are being considered. - -### Speed of change - -What is different about Generative AI is the speed of change. This is creating fear of the unknown as it is difficult to predict what will happen next. Digital artists and some prominent tech leaders are calling for the halting of Generative AI until the impacts on society are more understood. - -### Impact on Jobs - -Generative AI is expected to have significant impacts on the working world. Hundreds of millions of jobs will be directly affected. - -In some sense the change is expected to be welcomed as jobs that are currently mundane or have been difficult to automate will go away. For example frame editing, common artwork generation, and basic copywriting. - -One impact of this reduction will be how new joiners are mentored. New joiners are often given basic tasks. The approach to mentorship will change with the ability of Generative AI to accomplish these same tasks. - -### Possibilities - -While any new disruptive technology creates a lot of uncertainties many people are also excited about what the future may bring. - -Generative AI may open up entirely new ways to create and consume content. For example, media now is difficult and time-consuming to create even just in one length and format. Generative AI may allow different versions of movies, stories, and short videos to be generated from the same source media to allow new ways of media consumption. - -Generation of speech based on text with high fidelity style will allow creators to make content where they were limited by voice overlay before. - -With regards to code generation, automating repetitive work may result in higher quality code. Also it gives coders more time to focus on new creative user-centric solutions. - -Movies and video creation once expensive and possible only by large studios and digital production groups can instead be created by individuals and is bound only by their imagination. - -Generative AI may help people understand more about how creative processes work in general and how to continually enhance the human process. diff --git a/content/ai/concepts/generative-ai/terms/code/code.md b/content/ai/concepts/generative-ai/terms/code/code.md deleted file mode 100644 index c756e50b7d2..00000000000 --- a/content/ai/concepts/generative-ai/terms/code/code.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -Title: 'Code' -Description: 'Generative coding is the use of Generative AI (GenAI) to assist in software development. It was one of the first applications of Generative AI technology to be commercialized.' -Subjects: - - 'Machine Learning' - - 'Data Science' -Tags: - - 'AI' -CatalogContent: - - 'paths/machine-learning-engineer' - - 'intro-to-chatgpt' ---- - -**Generative coding** is the use of Generative AI (GenAI) to assist in software development. It was one of the first applications of Generative AI technology to be commercialized. - -## Code - -Generative AI is at an early stage of development. It often yields impressive, but not perfect results. Generally, the most productive workflows use the generated output as a starting point, and then includes further reviews and improvements. For example, GitHub has released Copilot X which acts as an AI-paired programmer. Some features include: - -- Code completion. -- Chat ability that can explain what the code does. -- Ability to generate unit tests. -- Answer questions based on existing documentation such as MDN; a major open source web technology documentation site. -- Voice coding. -- Fill-in-the-text parts of pull requests; for example the summary and description. - -GenAI for coding offers many future possibilities. It's showing promise in many areas such as writing functional code blocks, building user interfaces, and even connecting different systems by mapping fields and values. Some other uses include: - -- Bug fixing. -- Code refactoring. -- Style fixing. -- Web site creation. -- Creating fast prototypes. diff --git a/content/ai/concepts/generative-ai/terms/images/images.md b/content/ai/concepts/generative-ai/terms/images/images.md deleted file mode 100644 index cdb046bdb59..00000000000 --- a/content/ai/concepts/generative-ai/terms/images/images.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -Title: 'Images' -Description: 'GenAI can generate new images from existing text prompts and images. Because of a random seed, the images generated are unique creations. GenAI uses diffusion models to create these new unique images.' -Subjects: - - 'Machine Learning' - - 'Data Science' -Tags: - - 'AI' -CatalogContent: - - 'paths/machine-learning-engineer' - - 'intro-to-chatgpt' ---- - -**Generative images** is the generation of new unique images from text prompts and existing images. Because of a random seed, the images generated are unique creations. GenAI uses diffusion models to create these new unique images. - -## Diffusion Models - -Image creation is mainly based on a relatively new development called a **diffusion model**. - -Until recently, Generative Adversarial Networks (GANs) were the standard way to create images. With this approach, random noise is used to create an image. The image is then fed into another network which is trained to determine the quality. With more iterations, both networks (adversaries) can improve. - -Diffusion models are instead inspired by the world of physics. Imagine a pot of coffee brewing in a large room. Eventually the molecules that can be smelled will diffuse into the air and travel throughout. If later someone asked for another pot of coffee, we could trace back the motion track of the molecules and create another pot. - -GenAI image platforms are trained on vast amounts of data. By using diffusion models, these platforms can turn natural language descriptions into photo-realistic images. Some of these platforms include: - -- DALL-E -- Midjourney -- Imagery -- Stable Diffusion diff --git a/content/ai/concepts/generative-ai/terms/music/music.md b/content/ai/concepts/generative-ai/terms/music/music.md deleted file mode 100644 index 313fd5e4d9c..00000000000 --- a/content/ai/concepts/generative-ai/terms/music/music.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -Title: 'Music' -Description: 'GenAI allows for the creation of long-playing high-fidelity music from text descriptions and additional sound input conditions.' -Subjects: - - 'Machine Learning' - - 'Data Science' -Tags: - - 'AI' -CatalogContent: - - 'paths/machine-learning-engineer' - - 'intro-to-chatgpt' ---- - -**Generative Music** is the creation of long-playing high-fidelity music from text descriptions and additional sound input conditions. - -GenAI can take the recorded hum of a melody and turn it into a song being played by guitar. It can change the style of any melody or song, for example, changing it to jazz, rock, or computer music. - -Inputs can also be stories, images, or even music created from different media. - -Some common tools include: - -- Mubert Studio -- Jukebox from OpenAI -- MusicLM from Google diff --git a/content/ai/concepts/generative-ai/terms/text/text.md b/content/ai/concepts/generative-ai/terms/text/text.md deleted file mode 100644 index 793109f54c8..00000000000 --- a/content/ai/concepts/generative-ai/terms/text/text.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -Title: 'Text' -Description: 'Generative AI can create blogs, write ad copy, create new content based on text input, and is capable of summarizing and changing the style and tone of text content.' -Subjects: - - 'Machine Learning' - - 'Data Science' -Tags: - - 'AI' -CatalogContent: - - 'paths/machine-learning-engineer' - - 'intro-to-chatgpt' ---- - -**Generative text** is a commonly discussed type of generated content. Some applications include: - -- Generating poems. -- Writing stories. -- Writing legal contracts. -- Summarizing a meeting. -- Write a blog entry. -- Create Ad copy. - -Generative AI can create new content based upon text input and prompts. It can summarize and alter the style and tone of text. - -Some common tools include: - -- GPT -- Jasper -- AI-Writer -- Lex diff --git a/content/ai/concepts/machine-learning/machine-learning.md b/content/ai/concepts/machine-learning/machine-learning.md deleted file mode 100644 index 887f6a2e80d..00000000000 --- a/content/ai/concepts/machine-learning/machine-learning.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -Title: 'Machine Learning' -Description: 'Machine learning is a branch of computer science that uses data and algorithms to create programs that enhance performance at tasks without explicit programming.' -Subjects: - - 'Machine Learning' - - 'Data Science' -Tags: - - 'AI' - - 'Deep Learning' - - 'Algorithms' - - 'Scikit-learn' - - 'Tensorflow' - - 'Keras' -CatalogContent: - - 'machine-learning' - - 'paths/data-science' ---- - -**Machine learning (ML)** is a discipline of computer science that uses data and algorithms to develop computer programs that improve their performance at tasks without being explicitly programmed to do so. Machine Learning is considered a branch of Artificial Intelligence, as some machine learning algorithms are designed to imitate the way that humans learn and interact with their environment. - -## Branches of Machine Learning - -### Supervised Learning - -Machine Learning algorithms that receive labeled data as input and produce a prediction as output. - -- Regression: Predicts a continuous-valued output. - - Linear regression: Plots the line or plane of "best fit" of optimal values for prediction tasks. - - Logistic regression: Classifies elements in a data set into discrete categories. -- Classification: Categorizes data points into discrete groups. - - Naïve-Bayes classifier: Uses Bayes' theorem of probability to perform classification of elements. - - Support vector machine (SVM): Margin classifiers that define hyperplanes to separate data points into discrete categories. - - Artificial Neural Networks (ANN): Classifiers modeled after biological neural networks with relatively high-performance capabilities in regression and classification tasks. - -### Unsupervised Learning - -Machine Learning algorithms that receive unlabeled data as input and produce a grouping or clustering as output. - -- Clustering: Recognize patterns and structures in unlabeled data by grouping them into clusters. - - K-Means: Categorizes data points into clusters based on their proximity to cluster centroids. - - Hierarchical Agglomerative Clustering: Groups data points into clusters based on various measures of similarity, such as the smallest average distance between all points, minimal variance between data points, or smallest maximum distance between data points. -- Dimensionality Reduction: Scale down the dimensions in the dataset from a high-dimensional space into a low-dimensional space while maintaining the maximum amount of relevant information. - - Principal Component Analysis (PCA): Reduces the dimensionality of a dataset to the 'n' number of principal dimensions that contain the most valuable information. - -### Reinforcement Learning - -Machine learning algorithms that act as agents in an environment receive a current state, environment, reward, and goal as input and produce a policy of best action relative to the stated goal as output. - -- Model-Free: Act as trial-and-error algorithms that use only real samples of the environment to calculate optimal actions instead of the transition probability distribution to create a model of the environment. -- Model-Based: Create models of the environment to generate predictions of the next state and reward to calculate optimal actions. - -Some methods used in reinforcement learning include: - -- Markov Decision Processes (MDPs): Use a model of the environment based on their state transition probability and reward functions to create a policy of optimal action and satisfy the Markov property. -- Monte-Carlo methods: Model-Free randomized algorithms that learn from episodes of experience, whether continuous or terminal, to calculate the value for a state based on the average return from those experiences. -- Q-Learning/Deep Q-Learning: Model-Free algorithms that focus on maximizing the expected value of reward using q-tables, or artificial neural networks. - -## Machine Learning vs. Deep Learning - -Deep Learning is the subset of machine learning that focuses on artificial neural networks. The "deep" component of the name is in reference to the many hidden layers that typically are embedded within neural networks that simulate the function of a biological brain. - -The relatively high performance of neural networks in human-like tasks such as speech and object recognition distinguishes deep learning from other machine learning algorithms. - -## Model Development - -Based on the evaluation results, the model's user might modify the model's hyperparameters or adjust the model architecture to improve its performance. There are several methods to further refine models that may include strategies such as: - -- Hyperparameter Tuning: Hyperparameters are configuration settings for a machine learning model that are not learned during training but are set before training begins. These settings can significantly impact a model's performance. -- Model Architecture Adjustments: There are several methods to accurately adjust the architecture of ML algorithms. There are techniques such as feature engineering, model selection, and ensemble methods. - -## Evaluation - -There are several methods to accurately evaluate the performance of ML algorithms. Methods vary based on which algorithm is being evaluated and for which purpose. For classifiers such as Logistic Regression, confusion matrices inform analysts of the number of true and false positives as well as negatives to calculate values such as recall, precision, and F1 scores. - -These values help analysts understand if their models are underfitting or overfitting, which is critical to improving and maintaining their performance. diff --git a/content/ai/concepts/machine-learning/terms/classification/classification.md b/content/ai/concepts/machine-learning/terms/classification/classification.md deleted file mode 100644 index 652f97a1378..00000000000 --- a/content/ai/concepts/machine-learning/terms/classification/classification.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -Title: 'Classification' -Description: 'Classification is a supervised technique in machine learning used to categorize data into predefined classes or labels.' -Subjects: - - 'AI' - - 'Machine Learning' -Tags: - - 'AI' - - 'Machine Learning' - - 'Supervised Learning' - - 'Unsupervised Learning' -CatalogContent: - - 'learn-python-3' - - 'paths/intermediate-machine-learning-skill-path' ---- - -**Classification** is a supervised technique in machine learning used to categorize data into predefined classes or labels. It involves training a model using labeled data and then using the model to predict labels for new data. Common applications include spam detection, sentiment analysis, and medical diagnosis. - -## Classification Process - -The general process for performing classification involves the following steps: - -```pseudo -1. Import necessary libraries -2. Load and preprocess the dataset -3. Split the dataset into training and testing sets -4. Initialize the classifier (e.g., Logistic Regression, Decision Tree, SVM). -5. Fit the model on the training set -6. Make predictions on the test set -7. Evaluate the model using metrics such as accuracy, precision, recall, and F1-score -``` - -## Example - -[Python](https://www.codecademy.com/resources/docs/python) provides several libraries for performing classification, such as [Scikit-learn](https://www.codecademy.com/resources/docs/sklearn). - -Here is an example that demonstrates how to perform classification using Logistic Regression in Scikit-learn: - -```py -from sklearn.datasets import load_iris -from sklearn.model_selection import train_test_split -from sklearn.linear_model import LogisticRegression -from sklearn.metrics import accuracy_score - -# Load the Iris dataset -iris = load_iris() -X = iris.data -y = iris.target - -# Split the dataset into training and testing sets -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) - -# Initialize the classifier (Logistic Regression) -model = LogisticRegression() - -# Fit the model on the training set -model.fit(X_train, y_train) - -# Make predictions on the test set -y_pred = model.predict(X_test) - -# Evaluate the model -accuracy = accuracy_score(y_test, y_pred) -print(f"Accuracy: {accuracy:.2f}") -``` - -The above code produces the following output: - -```shell -Accuracy: 1.00 -``` - -## Codebyte Example - -The following codebyte example demonstrates how to perform classification using [Decision Tree](https://www.codecademy.com/resources/docs/sklearn/decision-trees) in Scikit-learn: - -```codebyte/python -from sklearn.datasets import load_iris -from sklearn.model_selection import train_test_split -from sklearn.tree import DecisionTreeClassifier -from sklearn.metrics import accuracy_score - -# Load the Iris dataset -iris = load_iris() -X = iris.data -y = iris.target - -# Split the dataset into training and testing sets -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) - -# Define the base classifier (Decision Tree) -model = DecisionTreeClassifier() - -# Fit the model on the training set -model.fit(X_train, y_train) - -# Make predictions on the test set -y_pred = model.predict(X_test) - -# Evaluate the model -accuracy = accuracy_score(y_test, y_pred) -print(f"Accuracy: {accuracy:.2f}") -``` diff --git a/content/ai/concepts/machine-learning/terms/regression/regression.md b/content/ai/concepts/machine-learning/terms/regression/regression.md deleted file mode 100644 index e020fa95f02..00000000000 --- a/content/ai/concepts/machine-learning/terms/regression/regression.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -Title: 'Regression' -Description: 'Regression models relationships between variables to predict a dependent variable utilizing one or more independent variables.' -Subjects: - - 'AI' - - 'Data Science' -Tags: - - 'Machine Learning' - - 'Python' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -**Regression** is a mathematical process used to model data by identifying a function that best represents its patterns. In machine learning, regression functions are used for predictive analysis. - -There are various regression techniques and the choice depends on factors such as data distribution. A simple form is linear regression, represented by the equation: - -``` -y = a\*x + b -``` - -Visualizing this equation as a straight line on a 2D graph: - -- `y`: The dependent (outcome) variable, plotted on the y-axis (vertical). -- `x`: The independent (predictor) variable, plotted on the x-axis (horizontal). -- `b`: The intercept, representing the value of `y` when `x = 0`. -- `a`: The slope, indicating how `y` changes when `x` increases by one unit. - -## Example - -The following code predicts a person's weight based on a person's height: - -```py -import pandas as pd -import statsmodels.api as sm -import matplotlib.pyplot as plt - -# Sample data -heights = [150, 152, 160, 172, 176, 176, 180, 189] -weights = [50, 65, 65, 70, 80, 90, 90, 89] - -# Create a DataFrame -measurements = pd.DataFrame({'height': heights, 'weight': weights}) - -# Fit the linear regression model -model = sm.OLS.from_formula("weight ~ height", data=measurements) -results = model.fit() - -# Print the summary of the model -print(results.summary()) - -# Plot the data and the regression line -plt.scatter(measurements['height'], measurements['weight'], label='Data') -plt.plot(measurements['height'], results.predict(measurements), color='red', label='Regression Line') -plt.xlabel('Height (cm)') -plt.ylabel('Weight (kg)') -plt.title('Height vs Weight with Regression Line') -plt.legend() - -# Save the plot as an image file -plt.savefig('height-vs-weight-plot.png') - -# Show the plot -plt.show() -``` - -This code performs linear regression using `statsmodels` to analyze the relationship between height and weight. It fits a model of the form `weight = a * height + b`, prints the regression summary, and visualizes the data with a scatter plot and a best-fit line. - -The output of this code is as follows: - -![The output for the above example](https://raw.githubusercontent.com/Codecademy/docs/main/media/height-vs-weight-plot.png) diff --git a/content/ai/concepts/machine-learning/terms/reinforcement-learning/reinforcement-learning.md b/content/ai/concepts/machine-learning/terms/reinforcement-learning/reinforcement-learning.md deleted file mode 100644 index 7a980b5f306..00000000000 --- a/content/ai/concepts/machine-learning/terms/reinforcement-learning/reinforcement-learning.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -Title: 'Reinforcement Learning' -Description: 'Reinforcement Learning is a branch of machine learning where an agent learns optimal decision-making by interacting with an environment and receiving feedback in the form of rewards.' -Subjects: - - 'Machine Learning' - - 'Data Science' -Tags: - - 'AI' - - 'Deep Learning' - - 'Algorithms' - - 'Scikit-learn' - - 'Tensorflow' - - 'Keras' -CatalogContent: - - 'machine-learning' - - 'paths/data-science' ---- - -**Reinforcement Learning (RL)** is a type of [machine learning](https://www.codecademy.com/resources/docs/ai/machine-learning) Reinforcement Learning (RL) is a type of machine learning where an agent learns to make optimal decisions by interacting with an environment, receiving rewards or penalties, and refining its strategy to maximize cumulative rewards. RL is widely used in robotics, game-playing, autonomous systems, and decision-making applications. - -## Key Concepts - -- **Agent**: The decision-maker that interacts with the environment. -- **Environment**: The system in which the agent operates. -- **State (s)**: A representation of the environment at a given time. -- **Action (a)**: A decision made by the agent to influence the environment. -- **Reward (r)**: A numerical signal indicating the success of an action. -- **Policy (π)**: A strategy that defines how the agent chooses actions. -- **Q-value (Action-Value Function)**: The expected reward of taking an action in a given state. - -## Process - -- **Exploration**: The agent tries different actions to explore the environment. -- **Exploitation**: The agent uses learned strategies to maximize the reward. -- **Trial and Error**: The agent learns from the consequences of actions and adjusts accordingly. - -## Algorithms in Reinforcement Learning - -- **Q-learning**: A model-free algorithm where the agent learns the value of action-state pairs to maximize future rewards. -- **Deep Q Networks (DQN)**: An extension of Q-learning that uses deep learning techniques to approximate the Q-value function. -- **Policy Gradient Methods**: These algorithms directly optimize the policy by updating the probability distribution of actions based on the gradient of the reward. -- **Actor-Critic Methods**: Combine the benefits of both value-based and policy-based methods by using two models: one for the policy (actor) and one for the value function (critic). -- **Proximal Policy Optimization (PPO)**: A modern RL algorithm that balances exploration and exploitation more effectively than previous methods. - -## Types of Reinforcement Learning - -1. **Model-free RL**: The agent learns through interactions without building a model of the environment. Example algorithms include Q-learning and Deep Q Networks (DQN). -2. **Model-based RL**: The agent builds a model of the environment and uses it to plan actions. Example methods include Monte Carlo Tree Search (MCTS). - -## Applications - -Reinforcement Learning enables AI systems to learn optimal strategies through trial and error, making it a powerful approach in dynamic decision-making scenarios such as: - -- **Game Playing**: RL has been used in AlphaGo, OpenAI Five, and Chess engines. -- **Robotics**: Teaching robots to walk, grasp objects, and navigate. -- **Autonomous Vehicles**: Self-driving cars optimizing navigation. -- **Finance**: Stock trading strategies using RL models. -- **Healthcare**: Optimizing personalized treatment plans. - -## Challenges - -- **Exploration vs Exploitation**: Balancing between exploring new actions and exploiting learned strategies. -- **Sample Efficiency**: The amount of data and interactions required for effective learning. -- **Sparse Rewards**: Environments where feedback is infrequent or delayed. -- **Credit Assignment Problem**: Determining which action was responsible for a delayed reward. diff --git a/content/ai/concepts/machine-learning/terms/self-supervised-learning/self-supervised-learning.md b/content/ai/concepts/machine-learning/terms/self-supervised-learning/self-supervised-learning.md deleted file mode 100644 index c9c76184739..00000000000 --- a/content/ai/concepts/machine-learning/terms/self-supervised-learning/self-supervised-learning.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -Title: 'Self-Supervised Learning' -Description: 'A machine learning paradigm that leverages unlabeled data by generating pseudo-labels from inherent structures within the data.' -Subjects: - - 'AI' - - 'Machine Learning' -Tags: - - 'AI' - - 'Deep Learning' - - 'Machine Learning' - - 'Unsupervised Learning' -CatalogContent: - - 'learn-python-3' - - 'paths/intermediate-machine-learning-skill-path' ---- - -**Self-Supervised Learning (SSL)** is a machine learning approach that bridges the gap between supervised and unsupervised learning. It enables models to learn meaningful representations from unlabeled data by deriving supervision signals through pretext tasks. - -SSL is widely applied in domains such as natural language processing (NLP), computer vision, and speech recognition. - -## Pipeline - -Self-Supervised Learning (SSL) follows a structured pipeline consisting of the following steps: - -1. **Pretext Task Creation**: Define a task where the model learns meaningful representations by predicting missing or transformed aspects of the input data. -2. **Feature Learning**: Train a model using the pretext task to extract useful features from the data. -3. **Fine-Tuning**: Transfer the learned features to a downstream task (e.g., classification, object detection). - -For example, in computer vision, a common pretext task is predicting missing parts of an image: - -```pseudo -# Pseudo code for an SSL pipeline -Initialize model -Load unlabeled dataset - -For each epoch: - - Apply transformation (e.g., masking, rotation, cropping) - - Train model to predict missing or transformed part - - Compute loss and update model parameters - -Save learned representations -Fine-tune model on downstream task (e.g., classification) -``` - -## Example - -In the example below, a simple self-supervised learning model uses an autoencoder to learn feature representations by reconstructing unlabeled input data: - -```py -import torch -import torch.nn as nn -import torch.optim as optim - -# Define a simple self-supervised learning model (Autoencoder) -class SimpleSSLModel(nn.Module): - def __init__(self, input_dim, hidden_dim): - super(SimpleSSLModel, self).__init__() - # Encoder: Learns meaningful feature representations - self.encoder = nn.Sequential( - nn.Linear(input_dim, hidden_dim), - nn.ReLU() - ) - - # Decoder: Reconstructs input from learned representations - self.decoder = nn.Sequential( - nn.Linear(hidden_dim, input_dim), - nn.Sigmoid() - ) - - def forward(self, x): - encoded = self.encoder(x) # Generate feature representation - decoded = self.decoder(encoded) # Reconstruct input from encoded features - return decoded - -# Generate random unlabeled input data -data = torch.randn(100, 20) - -# Define model, loss function, and optimizer -model = SimpleSSLModel(input_dim=20, hidden_dim=10) -criterion = nn.MSELoss() -optimizer = optim.Adam(model.parameters(), lr=0.01) - -# Training loop for self-supervised learning -for epoch in range(100): - optimizer.zero_grad() - reconstructed = model(data) - loss = criterion(reconstructed, data) - loss.backward() - optimizer.step() - -print("Self-supervised model training complete!") -``` - -This approach trains a model to reconstruct input data, allowing it to learn meaningful features without labeled supervision. diff --git a/content/ai/concepts/machine-learning/terms/semi-supervised-learning/semi-supervised-learning.md b/content/ai/concepts/machine-learning/terms/semi-supervised-learning/semi-supervised-learning.md deleted file mode 100644 index c2869b616a3..00000000000 --- a/content/ai/concepts/machine-learning/terms/semi-supervised-learning/semi-supervised-learning.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -Title: 'Semi-Supervised Learning' -Description: 'A machine learning approach that leverages both labeled and unlabeled data for training, improving model performance when labeled data is scarce.' -Subjects: - - 'AI' - - 'Machine Learning' -Tags: - - 'AI' - - 'Machine Learning' - - 'Supervised Learning' - - 'Unsupervised Learning' -CatalogContent: - - 'learn-python-3' - - 'paths/intermediate-machine-learning-skill-path' ---- - -**Semi-Supervised Learning** is an approach in machine learning that combines elements of both [supervised learning](https://www.codecademy.com/resources/docs/ai/machine-learning/supervised-learning) and unsupervised learning. It is particularly helpful when a dataset contains a small amount of labeled data and a large amount of unlabeled data. - -By leveraging patterns in the unlabeled data, semi-supervised learning improves model accuracy and generalization while reducing the reliance on extensive labeled datasets. - -## Syntax - -The general approach for implementing semi-supervised learning follows these steps: - -```pseudo -1. Train an initial model using the available labeled data. -2. Use the trained model to predict labels for the unlabeled data. -3. Select high-confidence pseudo-labels and add them to the labeled dataset. -4. Retrain the model with the expanded labeled dataset. -5. Repeat steps 2-4 iteratively until convergence or stopping criteria is met. -``` - -## Example - -A common example of semi-supervised learning is using a [self-training](https://www.codecademy.com/resources/docs/sklearn/self-training) classifier with [Scikit-learn](https://www.codecademy.com/resources/docs/sklearn) in Python: - -```py -import numpy as np -from sklearn import datasets -from sklearn.model_selection import train_test_split -from sklearn.semi_supervised import SelfTrainingClassifier -from sklearn.ensemble import RandomForestClassifier -from sklearn.metrics import accuracy_score - -# Load dataset -X, y = datasets.load_digits(return_X_y=True) - -# Create a mask to simulate unlabeled data (-1 represents unlabeled samples) -unlabeled_mask = np.random.rand(len(y)) < 0.8 -y_unlabeled = np.copy(y) -y_unlabeled[unlabeled_mask] = -1 # Set 80% of labels to -1 (unlabeled) - -# Split into training and test datasets -X_train, X_test, y_train, y_test_masked = train_test_split(X, y_unlabeled, test_size=0.2, random_state=42) - -# Get the true labels for the test set -_, y_test_true = train_test_split(y, test_size=0.2, random_state=42) # True labels for evaluation - -# Define the base classifier -base_classifier = RandomForestClassifier(n_estimators=100, random_state=42) - -# Create the semi-supervised model -self_training_model = SelfTrainingClassifier(base_classifier) - -# Train the model -self_training_model.fit(X_train, y_train) - -# Get predictions -y_pred = self_training_model.predict(X_test) - -# Evaluate the model -accuracy = accuracy_score(y_test_true, y_pred) -print(f"Semi-Supervised Model Accuracy: {accuracy:.2f}") -``` - -This example demonstrates the use of a self-training classifier, where an initial model is trained on labeled data and iteratively labels the unlabeled data to improve its learning capability. The output of this code will be: - -```shell -Semi-Supervised Model Accuracy: 0.89 -``` - -> **Note:** Since the dataset splitting and unlabeled mask generation involve randomness (`np.random.rand()` and `train_test_split()`), the accuracy may change slightly each time unless a fixed random seed (`np.random.seed()`) is set before creating the mask. diff --git a/content/ai/concepts/machine-learning/terms/supervised-learning/supervised-learning.md b/content/ai/concepts/machine-learning/terms/supervised-learning/supervised-learning.md deleted file mode 100644 index 8d051eb22a7..00000000000 --- a/content/ai/concepts/machine-learning/terms/supervised-learning/supervised-learning.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -Title: 'Supervised Learning' -Description: 'Supervised learning is a machine learning technique where algorithms learn from labeled data to make predictions.' -Subjects: - - 'AI' - - 'Data Science' - - 'Machine Learning' -Tags: - - 'AI' - - 'Deep Learning' - - 'Classification' - - 'Regression' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -**Supervised learning (ML)** is a type of machine learning where an algorithm learns from labeled data. It involves training a model using input-output pairs so it can generalize and make accurate predictions for new, unseen data. The labeled outputs act as a guide, helping the model learn the correct relationships. - -**Examples:** Identifying handwritten digits, predicting car prices based on features, detecting spam emails based on content and metadata. - -### Key Components - -- **Training Data:** A dataset containing input-output pairs (e.g., images labeled with digits or emails marked as spam/not spam). -- **Model:** A machine learning algorithm (e.g., decision trees, neural networks) that learns patterns from the data. -- **Loss Function:** A metric that measures how well the model’s predictions match the actual labels. (e.g., Mean Squared Error for regression, Cross-Entropy Loss for classification). -- **Optimization:** A process of adjusting model parameters to minimize the loss and improve accuracy, often using gradient descent or other optimization techniques. - -## Types of Supervised Learning - -### Classification - -Classification involves training an algorithm on labeled data, where each input is associated with a specific category. The model then classifies new, unseen data based on learned patterns. - -**Examples:** Spam Detection, handwritten digit recognition, image classification, medical diagnosis. - -#### Types of Classification - -- **Binary Classification:** The task of classifying data points into one of two classes. -- **Multi-class Classification:** The task of classifying data points into one of more than two classes. -- **Multi-label Classification:** The task of assigning multiple labels to each data point. This is different from multi-class classification, where each data point can only belong to one class. - -**Common Classification Algorithms:** Logistic Regression, Support Vector Machines (SVMs), Decision Trees, Random Forests, Naive Bayes, K-Nearest Neighbors (KNN) - -### Regression - -Regression is a supervised learning task focused on predicting a continuous numerical output. Unlike classification, which assigns data points to categories, regression aims to estimate a value within a range. - -**Examples:** House price prediction, stock price prediction, temperature forecasting, sales forecasting. - -#### Types of Regression - -- **[Linear Regression:](https://www.codecademy.com/learn/linear-regression-mssp):** Models a linear relationship between inputs and a target variable by finding the line of best fit that minimizes the sum of squared errors. -- **Polynomial Regression:** Captures non-linear relationships by fitting a polynomial curve to the data. -- **[Multiple Linear Regression:](https://www.codecademy.com/learn/multiple-linear-regression-course):** Used when there are multiple input features influencing the target variable. -- **[Support Vector Regression (SVR):](https://www.codecademy.com/resources/docs/sklearn/support-vector-machines):** Uses SVM principles to find the best-fitting hyperplane within a margin of error. -- **[Decision Tree Regression:](https://www.codecademy.com/article/mlfun-decision-trees-article):** Uses a tree structure where nodes represent feature-based decisions, and leaves represent predicted values. -- **[Random Forest Regression:](https://www.codecademy.com/learn/machine-learning-random-forests-decision-trees):** An ensemble method that combines multiple decision trees to improve prediction accuracy and reduce overfitting. -- **Neural Network Regression:** Uses neural networks to learn complex non-linear relationships between features and the target variable. - -**Common Classification Algorithms:** Linear Regression, Polynomial Regression, Support Vector Regression (SVR), Decision Tree Regression, Random Forest Regression, Neural Network Regression. diff --git a/content/ai/concepts/machine-learning/terms/unsupervised-learning/unsupervised-learning.md b/content/ai/concepts/machine-learning/terms/unsupervised-learning/unsupervised-learning.md deleted file mode 100644 index 48a59cbaab5..00000000000 --- a/content/ai/concepts/machine-learning/terms/unsupervised-learning/unsupervised-learning.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -Title: 'Unsupervised Learning' -Description: 'Unsupervised Learning is a type of machine learning where a model identifies patterns, structures, or relationships in unlabeled data without explicit supervision.' -Subjects: - - 'AI' - - 'Data Science' - - 'Machine Learning' -Tags: - - 'AI' - - 'Deep Learning' - - 'Classification' - - 'Regression' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -**Unsupervised Learning** is a machine learning approach where the model is trained on unlabeled data, meaning there are no predefined target values. The goal is for the algorithm to identify hidden patterns, structures, or relationships in the data. - -## Key Concepts - -- **Data Without Labels**: Unlike [supervised learning](https://www.codecademy.com/resources/docs/ai/machine-learning/supervised-learning), the data used in unsupervised learning does not have associated target labels. The model must infer relationships and structures from the input data alone. -- **Clusters**: Grouping similar data points together based on shared characteristics. -- **Dimensionality Reduction**: Reducing the number of features in the dataset while preserving essential information, often to improve model efficiency or visualization. -- **Anomaly Detection**: Identifying data points that deviate significantly from the expected pattern. - -## Types of Unsupervised Learning - -1. **Clustering**: Organizing data into groups (clusters) where items within the same cluster are more similar to each other than to those in other clusters. Common algorithms include: - - - **K-Means Clustering**: Partitions data into k distinct clusters based on similarity. - - **Hierarchical Clustering**: Builds a tree-like structure that groups data in a hierarchy. - - **DBSCAN (Density-Based Spatial Clustering)**: Groups data based on density, effective for irregularly shaped clusters. - -2. **Association**: Finding rules that describe relationships between variables in large datasets. A common algorithm is: - - - **Apriori**: Used for discovering association rules in transactional data. - -3. **Dimensionality Reduction**: Reducing the number of input variables in a dataset while retaining important information, making the data easier to visualize and process. Key methods include: - - - **Principal Component Analysis (PCA)**: Identifies the principal components that explain the variance in the data. - - **t-SNE (t-Distributed Stochastic Neighbor Embedding)**: A non-linear method that reduces dimensions while preserving local data structure. - -4. **Anomaly Detection**: Identifying rare or unusual patterns in data that do not conform to the expected behavior, used in fraud detection or network security. - -## Applications - -- **Customer Segmentation**: Grouping customers based on purchasing behavior to target marketing efforts. -- **Market Basket Analysis**: Identifying associations between products frequently bought together. -- **Image Compression**: Reducing image size while preserving essential details. -- **Anomaly Detection**: Detecting unusual behavior, such as fraud detection in financial transactions or outlier detection in sensor data. - -## Challenges - -- **Interpretability**: Since there are no labels to guide the learning process, the results of unsupervised learning models can be harder to interpret. -- **Evaluation**: Without predefined outcomes, it can be difficult to assess the performance of unsupervised learning models. -- **Scalability**: Many unsupervised learning algorithms, especially clustering and dimensionality reduction techniques, can be computationally expensive for large datasets. diff --git a/content/ai/concepts/machine-learning/terms/weakly-supervised-learning/weakly-supervised-learning.md b/content/ai/concepts/machine-learning/terms/weakly-supervised-learning/weakly-supervised-learning.md deleted file mode 100644 index ad074e410b0..00000000000 --- a/content/ai/concepts/machine-learning/terms/weakly-supervised-learning/weakly-supervised-learning.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -Title: 'Weakly-Supervised Learning' -Description: 'A machine learning approach that uses limited labeled data alongside large amounts of unlabeled data for training models.' -Subjects: - - 'AI' - - 'Machine Learning' -Tags: - - 'AI' - - 'Machine Learning' - - 'Supervised Learning' - - 'Unsupervised Learning' -CatalogContent: - - 'learn-python-3' - - 'paths/intermediate-machine-learning-skill-path' ---- - -**Weakly-Supervised Learning** is a machine learning paradigm that trains models using a small amount of labeled data alongside a large amount of unlabeled data. - -This approach is particularly valuable when obtaining fully labeled datasets is costly or impractical. By incorporating elements of both supervised and unsupervised learning, it bridges the gap between the two, enabling more efficient model training with minimal labeled data. - -## Syntax - -The syntax of weakly-supervised learning varies depending on the technique used. Common approaches include: - -- **Semi-Supervised Learning**: Utilizes a small labeled dataset alongside a larger unlabeled dataset to enhance model learning. -- **Weak Labeling**: Employs noisy, incomplete, or imprecise labels to guide the training process. -- **Distant Supervision**: Leverages external sources or heuristic rules to generate labels automatically. - -For example, in Python using the `scikit-learn` library, weakly-supervised learning can be applied with semi-supervised learning methods: - -```pseudo -# 1. Load or generate labeled and unlabeled data -data = [labeled_data, unlabeled_data] - -# 2. Select a weakly-supervised learning technique: -- Semi-supervised learning -- Weak labeling -- Distant supervision - -# 3. Apply the selected weak supervision method: -- Train a model using weak supervision -- Use heuristics, pseudo-labeling, or propagation techniques - -# 4. Evaluate and fine-tune the model -- Validate using available labeled data -- Refine the model to improve accuracy -``` - -## Example - -A practical example of weakly-supervised learning is in _image classification_, where only a subset of images is labeled, and the model learns to infer labels for the remaining dataset. - -This code demonstrates weakly-supervised learning using `SelfTrainingClassifier`, where a Random Forest model learns from a dataset with both labeled and unlabeled data, inferring missing labels through self-training: - -```py -import numpy as np -from sklearn.semi_supervised import SelfTrainingClassifier -from sklearn.ensemble import RandomForestClassifier - -# Sample dataset with some missing labels -X_train = np.array([[1, 2], [2, 3], [3, 4], [8, 7], [9, 8], [10, 9]]) -y_train = np.array([0, 0, 0, -1, 1, -1]) # -1 indicates unlabeled data - -# Using a base classifier (Random Forest) with self-training -base_classifier = RandomForestClassifier() -model = SelfTrainingClassifier(base_classifier) - -# Train the model on weakly labeled data -model.fit(X_train, y_train) - -# Predict labels for all data points -predicted_labels = model.predict(X_train) -print(predicted_labels) # Outputs predicted labels, including inferred ones -``` - -Here is the output: - -```shell -[0 0 0 1 1 1] -``` - -Weakly-supervised learning is widely used in fields like natural language processing, medical diagnosis, and autonomous systems, where fully labeled data is scarce or expensive to obtain. diff --git a/content/ai/concepts/minimax-algorithm/minimax-algorithm.md b/content/ai/concepts/minimax-algorithm/minimax-algorithm.md deleted file mode 100644 index 4ecdcdf97e3..00000000000 --- a/content/ai/concepts/minimax-algorithm/minimax-algorithm.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -Title: 'Minimax Algorithm' -Description: 'A recursive algorithm used in decision-making and game theory.' -Subjects: - - 'AI' - - 'Computer Science' -Tags: - - 'AI' - - 'Algorithms' - - 'Graphs' - - 'Graph Search' -CatalogContent: - - 'intro-to-generative-ai' - - 'paths/data-science' ---- - -The **minimax algorithm** is a fundamental concept in artificial intelligence used for decision-making in games and other scenarios. It is widely used in two-player games where players alternate turns, such as tic-tac-toe, chess, backgammon, etc. - -In these games, each player wants to make the best or most optimal move to maximize their chances of winning, while also trying to minimize their opponent's chances. These two actions, maximize and minimize, are combined to form the name of the algorithm. This algorithm helps the computer or AI decide its next move by considering all possible moves it can make and all possible responses from the opponent. It does this by simulating the game's future moves and outcomes. - -## Implementation - -The minimax algorithm uses a [depth-first search](https://www.codecademy.com/resources/docs/ai/search-algorithms/depth-first-search) approach to thoroughly explore the entire game tree. In this approach, the algorithm proceeds down to the terminal node of the tree and then backtracks the tree using [recursion](https://www.codecademy.com/resources/docs/python/recursion). - -Here is an example of the depth-first search approach: - -![Depth-First Search](https://raw.githubusercontent.com/Codecademy/docs/main/media/Depth-First-Search-Example.png) - -In this algorithm, two players are involved: - -- One who wants to score the maximizer as high as possible. -- One who wants to score the minimizer as low as possible. - -Both players try to outsmart each other, with the minimizer aiming to make the maximizer's score as low as they can while trying to improve their own score. It's like a game of strategy where one player tries to win big, and the other tries to keep the losses small. - -Here's how it works when AI plays with a human in a tic-tac-toe game: - -1. For the current player's turn, AI generates a tree of possible moves. Each node in the tree represents a move that the player can make. -2. The AI then evaluates each node or move based on how favorable it is for itself. It assigns a score to each node, with higher scores indicating better moves. -3. Simultaneously, it assumes the opponent will make the best possible move to minimize the AI's chances of winning. So, for each of the AI's moves, it looks at the opponent's best responses and assigns scores accordingly. -4. The AI then selects its move based on these scores. If it's the AI's turn, it chooses the move with the highest score (maximizing its chances). If it's the opponent's turn, it selects the move with the lowest score (minimizing the AI's chances). - -In summary, the minimax algorithm helps the AI make optimal decisions by considering the best and worst possible outcomes for each move, assuming both players play perfectly. The main issue with this algorithm is that it can take a long time to make decisions in complex games like chess. These games have many possible moves, which create a lot of branches in the decision tree. To address this problem, alpha-beta pruning can be used to speed up the algorithm. - -## Example - -Below is a Python example of the minimax algorithm applied to a tic-tac-toe game. This code demonstrates how the AI can make optimal moves. It prints the current board, asks for the user's move, and then makes the AI move until the game is over: - -```py -# Tic-tac-toe board representation -board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] - -# Printing the board -def print_board(): - for i in range(0, 9, 3): - print(board[i] + '|' + board[i + 1] + '|' + board[i + 2]) - -# Checking if the game is over -def game_over(): - # Checking for a win - for i in range(0, 9, 3): - if board[i] == board[i + 1] == board[i + 2] != ' ': - return True - for i in range(3): - if board[i] == board[i + 3] == board[i + 6] != ' ': - return True - if board[0] == board[4] == board[8] != ' ': - return True - if board[2] == board[4] == board[6] != ' ': - return True - - # Checking for a tie - if ' ' not in board: - return True - - return False - -# Minimax algorithm -def minimax(board, depth, is_maximizing): - if game_over(): - if 'X' in board: - return -1 # Player X wins - elif 'O' in board: - return 1 # Player O wins - else: - return 0 # It's a tie - - if is_maximizing: - best_score = -float('inf') - for i in range(9): - if board[i] == ' ': - board[i] = 'O' - score = minimax(board, depth + 1, False) - board[i] = ' ' - best_score = max(score, best_score) - return best_score - else: - best_score = float('inf') - for i in range(9): - if board[i] == ' ': - board[i] = 'X' - score = minimax(board, depth + 1, True) - board[i] = ' ' - best_score = min(score, best_score) - return best_score - -# Finding the best move for the AI -def find_best_move(): - best_move = -1 - best_score = -float('inf') - for i in range(9): - if board[i] == ' ': - board[i] = 'O' - score = minimax(board, 0, False) - board[i] = ' ' - if score > best_score: - best_score = score - best_move = i - return best_move - -# Main game loop -while not game_over(): - print_board() - player_move = int(input("Enter your move (0-8): ")) - if board[player_move] == ' ': - board[player_move] = 'X' - else: - print("Invalid move. Try again.") - continue - - if game_over(): - break - - ai_move = find_best_move() - board[ai_move] = 'O' - -print_board() -if 'X' in board: - print("Player X wins!") -elif 'O' in board: - print("Player O wins!") -else: - print("It's a tie!") -``` diff --git a/content/ai/concepts/multimodal-models/multimodal-models.md b/content/ai/concepts/multimodal-models/multimodal-models.md deleted file mode 100644 index 93a6cb415ad..00000000000 --- a/content/ai/concepts/multimodal-models/multimodal-models.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -Title: 'Multimodal models' -Description: 'Multimodal models process and integrate multiple data types, such as text, images, and audio, to enhance AI capabilities and improve decision-making.' -Subjects: - - 'Machine Learning' - - 'Data Science' -Tags: - - 'AI' -CatalogContent: - - 'paths/machine-learning-engineer' - - 'paths/build-a-machine-learning-model' ---- - -**Multimodal models** are AI systems capable of processing and integrating multiple types of data, such as text, images, audio, and video. These models enhance machine understanding and decision-making by leveraging information from different modalities simultaneously. - -## Why use Multimodal AI? - -Traditional AI models are often unimodal, meaning they work with only one type of data (e.g., text-only or image-only). However, real-world data is inherently multimodal. For example: - -- A self-driving car processes visual data from cameras and sensor data from LiDAR. -- Virtual assistants like Siri or Alexa analyze spoken language (audio) and respond with text-based outputs. -- AI-powered healthcare systems analyze medical images, patient records, and genetic data for diagnosis. - -By combining multiple modalities, multimodal AI provides a more holistic understanding of complex scenarios. - -## How Multimodal Models Work - -Multimodal AI models process different data types by: - -1. **Feature Extraction**: Extracting key features from each modality (e.g., converting images into pixel embeddings or audio into spectrograms). -2. **Fusion Mechanisms**: Combining information from different modalities using techniques like: - - **Early fusion** (combining raw input features before model processing) - - **Late fusion** (processing modalities separately, then merging outputs) - - **Hybrid fusion** (combining at different levels of the model) -3. **Cross-Modal Learning**: Using shared representations to improve performance across modalities. - -## Examples of Multimodal AI Models - -- **CLIP (Contrastive Language-Image Pretraining)**: Learns connections between text and images to generate accurate image descriptions. -- **DALL·E**: Generates images from textual descriptions by understanding text and visual relationships. -- **GPT-4V**: Processes both text and images, allowing vision-based reasoning. - -## Challenges in Multimodal AI - -- **Data Alignment**: Ensuring that different modalities correctly correspond (e.g., matching text to the right image). -- **Computational Complexity**: Processing multiple data streams requires more power and memory. -- **Interpretability**: Understanding how AI integrates information across modalities remains a challenge. - -## Implementation structure - -Multimodal AI can be implemented in various ways using deep learning frameworks like TensorFlow, PyTorch, or HuggingFace Transformers. However, a common structure involves: - -1. **Defining Separate Modalities**: Identify and prepare data sources like text, images, or audio. -2. **Processing Each Modality**: Use specialized models (e.g., CNNs for images, Transformers for text, RNNs for audio) to extract features. -3. **Fusing Modalities**: Combine features using techniques like concatenation, attention mechanisms, or cross-modal transformers. -4. **Generating Output**: Use the fused representation for tasks like classification, translation, or content generation. diff --git a/content/ai/concepts/neural-networks/neural-networks.md b/content/ai/concepts/neural-networks/neural-networks.md deleted file mode 100644 index cfac0921836..00000000000 --- a/content/ai/concepts/neural-networks/neural-networks.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -Title: 'Neural Networks' -Description: 'A neural network is a method in artificial intelligence that teaches computers to process data in a way that is inspired by the human brain.' -Subjects: - - 'Machine Learning' - - 'Computer Science' -Tags: - - 'AI' - - 'Machine Learning' - - 'Neural Networks' - - 'Weight & Bias' - - 'Deep Learning' - - 'Perceptrons' -CatalogContent: - - 'machine-learning' - - 'paths/data-science' ---- - -**Artificial neural networks (ANN)** are a method in artificial intelligence that teaches computers to process data in a way similar to the human brain. - -## What Is An Artificial Neural Network (ANN) - -- An ANN a type of machine learning process, called deep learning, that uses interconnected nodes or neurons in a layered structure that resembles the human brain. -- An ANN is one of the main tools used for machine learning. It is a brain-inspired system used to replicate the way that humans learn. - -### The Process - -- Neural networks are trained on specific data which is broken down into the input layer (where information is fed into), then to the hidden layer (where weight and bias are calculated from the input layer), and lastly the output layer (where information is output after algorithms are processed from the hidden and input layers). This is done via perceptrons (similar to human neurons but for machines to process, store, calculate, and move data forward). - -## Relation To AI - -### AI - -- AI works on a collection of technologies that allow the computer to sense, learn, reason & act. -- AI works because of machine learning which is equipped with algorithms and vast amounts of datasets trained to recognize patterns and solve complex problems. - -### ANN - -- Neural networks are the core of deep learning algorithms. A neural network is trained on specific datasets from which it extracts the information and passes it through different layers searching for patterns. -- Once a neural network is trained on a dataset, it can start to encounter new scenarios and start making predictions based on that previous dataset. diff --git a/content/ai/concepts/neural-networks/terms/activation-function/activation-function.md b/content/ai/concepts/neural-networks/terms/activation-function/activation-function.md deleted file mode 100644 index aaaa90aefa8..00000000000 --- a/content/ai/concepts/neural-networks/terms/activation-function/activation-function.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -Title: 'Activation Function' -Description: 'An activation function is the function used by a node in a neural network to take the summed weighted input to the node and transform it into the output value.' -Subjects: - - 'Machine Learning' - - 'Data Science' - - 'Computer Science' -Tags: - - 'AI' - - 'Machine Learning' - - 'Neural Networks' - - 'Functions' -CatalogContent: - - 'machine-learning' - - 'paths/data-science' ---- - -An **activation function** is the function used by a node in a neural network to take the summed weighted input to the node and transform it into the output value. The output value can be fed into the next hidden layer or received from the output layer. For networks that engage in tasks of any significant complexity, the activation function needs to be non-linear. - -## Types of Activation Functions - -There are a number of different types of activation functions that can be used: - -- **Linear**: The node returns what was provided as input, also known as the "identity" function. -- **Binary Step**: The node either provides an output or not, depending on some threshold applied to the input. -- **[Sigmoid](https://www.codecademy.com/resources/docs/ai/neural-networks/sigmoid-activation-function)**: Takes the input and returns a value between 0 and 1. The more positive (larger) the input, the closer the value is to 1. The more negative (smaller) the input, the closer the value is to 0. -- **Tanh**: Like the sigmoid function but produces values between -1 and 1. -- **Gaussian**: Takes the input and distributes it in a bell curve with values between 0 and 1. -- **ReLU (Rectified Linear Unit)**: Represents the positive part of the input, returning 0 for values less than 0, and behaving like a linear function for positive values. diff --git a/content/ai/concepts/neural-networks/terms/adagrad/adagrad.md b/content/ai/concepts/neural-networks/terms/adagrad/adagrad.md deleted file mode 100644 index 8659a2e2082..00000000000 --- a/content/ai/concepts/neural-networks/terms/adagrad/adagrad.md +++ /dev/null @@ -1,245 +0,0 @@ ---- -Title: 'Adagrad' -Description: 'Implements an adaptive learning rate optimization algorithm for training neural networks.' -Subjects: - - 'Data Science' - - 'Machine Learning' -Tags: - - 'Algorithms' - - 'Neural Networks' - - 'Optimization' - - 'PyTorch' -CatalogContent: - - 'learn-pytorch' - - 'paths/machine-learning' ---- - -**Adagrad** is an adaptive learning rate optimization [algorithm](https://www.codecademy.com/resources/docs/general/algorithm) used for training [deep learning](https://www.codecademy.com/resources/blog/what-is-deep-learning/) models. It automatically adapts the learning rate for each parameter based on the historical gradient information, allowing for more efficient training especially with infrequent data. Adagrad modifies the general learning rate for each parameter according to the accumulated squared gradients, giving larger updates to infrequent parameters and smaller updates to frequent ones. - -Adagrad is particularly effective when dealing with infrequent data, such as in [natural language processing](https://www.codecademy.com/resources/blog/what-is-nlp/) and recommendation systems. By automatically adjusting learning rates for each parameter, it eliminates the need for manual tuning of the learning rate hyperparameter, which can be a time-consuming process in model optimization. - -## Working of Adagrad with Detailed Steps - -Adagrad works by maintaining a sum of squared gradients for each parameter and using this information to adapt the learning rate. Here's how it works: - -1\. **Initialization**: The model parameters are initialized, and a small value (ε) is defined to prevent division by zero. - -2\. **Gradient Computation**: For each parameter at time step t, compute the gradient of the loss function with respect to that parameter. - -3\. **Accumulate Squared Gradients**: Keep track of the sum of squared gradients for each parameter over time. - -$$G_t = G_{t-1} + g_t^2$$ - -Where $$\ G_t \$$ is the accumulated squared gradient and $$\ g_t \$$ is the current gradient. - -4\. **Update Parameters**: Adjust each parameter using its own adaptive learning rate. - -$$\theta_{t+1} = \theta_t - \left( \frac{\eta}{\sqrt{G_t + \epsilon}} \right) g_t$$ - -Where: - -- $$\ \theta_t \$$ is the parameter at time `t` -- `η` is the initial learning rate -- $$\ G_t \$$ is the sum of squared gradients up to time `t` -- `ε` is a small constant to prevent division by zero -- $$\ g_t \$$ is the gradient at time `t` - -This approach causes parameters with frequently occurring features to receive smaller updates, while parameters with infrequent features receive larger updates. - -## Comparison with Adam and RMSprop - -Adagrad adapts learning rates but suffers from diminishing rates, Adam balances first and second moment estimates for stability, and RMSprop prevents diminishing rates by using a moving average of squared gradients. To explore more about each, refer to their respective entries: - -- [Adam optimization](https://www.codecademy.com/resources/docs/ai/neural-networks/adam-optimization) -- [RMSprop](https://www.codecademy.com/resources/docs/ai/neural-networks/rmsprop) - -## Advantages and Limitations of Adagrad - -### Advantages - -1. **Adaptive Learning Rates**: Automatically adjusts the learning rate for each parameter based on historical gradients. -2. **Efficient for Sparse Data**: Performs well on sparse datasets by giving larger updates to infrequent parameters. -3. **No Manual Tuning**: Reduces the need for manual tuning of learning rates for different parameters. -4. **Feature-Specific Learning**: Allows different learning rates for different features based on their importance and frequency. - -### Limitations - -1. **Diminishing Learning Rates**: The accumulated squared gradients in the denominator continue to grow during training, causing the learning rate to become infinitesimally small and eventually stopping the learning process. -2. **Memory Requirements**: Requires storing an additional variable (accumulated gradient) for each parameter, which can be memory-intensive for very large models. -3. **Initial Learning Rate Sensitivity**: Performance can still be sensitive to the choice of initial learning rate. -4. **No Momentum**: Lacks a momentum term, which can sometimes lead to slower convergence in certain problems. - -## Syntax - -In PyTorch, Adagrad can be implemented using the following syntax: - -```pseudo -torch.optim.Adagrad(params, lr=0.01, lr_decay=0, weight_decay=0, initial_accumulator_value=0, eps=1e-10) -``` - -**Parameters:** - -- `params`: Iterable of parameters to optimize or dicts defining parameter groups -- `lr`: Learning rate (default=`0.01`) -- `lr_decay`: Learning rate decay (default=`0`) -- `weight_decay`: Weight decay (L2 penalty) (default=`0`) -- `initial_accumulator_value`: Initial value for the sum of squared gradients (default=`0`) -- `eps`: Term added to the denominator to improve numerical stability (default=`1e-10`) - -**Return value:** - -It returns an optimizer instance that can be used to update model parameters. - -## Example 1: Basic Adagrad Implementation with Linear Regression - -This example demonstrates how to use Adagrad optimizer for a simple linear regression problem: - -```py -import torch -import torch.nn as nn -import torch.optim as optim - -# Create synthetic data -x = torch.linspace(-10, 10, 100).view(-1, 1) -y = 2 * x + 3 + 0.1 * torch.randn(x.size()) # y = 2x + 3 + noise - -# Define a simple linear model -class LinearRegression(nn.Module): - def __init__(self): - super(LinearRegression, self).__init__() - self.linear = nn.Linear(1, 1) - - def forward(self, x): - return self.linear(x) - -# Initialize model, loss function, and optimizer -model = LinearRegression() -criterion = nn.MSELoss() -optimizer = optim.Adagrad(model.parameters(), lr=0.1) - -# Training loop -for epoch in range(100): - # Forward pass - y_pred = model(x) - loss = criterion(y_pred, y) - - # Backward pass and optimization - optimizer.zero_grad() - loss.backward() - optimizer.step() - - if (epoch+1) % 20 == 0: - print(f'Epoch {epoch+1}, Loss: {loss.item():.4f}') - -# Print model parameters -w, b = model.linear.weight.item(), model.linear.bias.item() -print(f'Model parameters: w = {w:.4f}, b = {b:.4f}') -print(f'Ground truth: w = 2, b = 3') -``` - -This example shows how Adagrad adjusts learning rates based on gradient history, helping converge to the optimal solution for a linear regression problem. - -## Example 2: Training a Neural Network for Image Classification - -This example demonstrates using Adagrad for training a [neural network](https://www.codecademy.com/resources/docs/ai/neural-networks) on the [MNIST dataset](https://www.kaggle.com/datasets/hojjatk/mnist-dataset): - -```py -import torch -import torch.nn as nn -import torch.optim as optim -import torchvision -import torchvision.transforms as transforms - -# Load MNIST dataset (code shortened for brevity) -transform = transforms.Compose([ - transforms.ToTensor(), - transforms.Normalize((0.1307,), (0.3081,)) -]) -train_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform) -train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True) - -# Define a simple neural network -class MNISTNet(nn.Module): - def __init__(self): - super(MNISTNet, self).__init__() - self.flatten = nn.Flatten() - self.fc1 = nn.Linear(28 * 28, 128) - self.relu = nn.ReLU() - self.fc2 = nn.Linear(128, 10) - - def forward(self, x): - x = self.flatten(x) - x = self.relu(self.fc1(x)) - x = self.fc2(x) - return x - -# Initialize model, loss function, and optimizer -model = MNISTNet() -criterion = nn.CrossEntropyLoss() -optimizer = optim.Adagrad(model.parameters(), lr=0.01) - -# Training loop (abbreviated) -def train(epochs=3): - for epoch in range(epochs): - running_loss = 0.0 - for i, (inputs, labels) in enumerate(train_loader): - optimizer.zero_grad() - outputs = model(inputs) - loss = criterion(outputs, labels) - loss.backward() - optimizer.step() - - running_loss += loss.item() - - print(f'Epoch {epoch+1}, Loss: {running_loss/len(train_loader):.4f}') - -train() # Train for 3 epochs -``` - -## Example 3: Natural Language Processing with Word Embeddings - -This example demonstrates using Adagrad for training word embeddings in a simple text classification task: - -```py -import torch -import torch.nn as nn -import torch.optim as optim - -# Sample data (simplified) -texts = ["I love this movie", "Great film", "Terrible experience", "Waste of time"] -labels = [1, 1, 0, 0] # 1 for positive, 0 for negative - -# Create a simple vocabulary -word_to_idx = {} -for text in texts: - for word in text.lower().split(): - if word not in word_to_idx: - word_to_idx[word] = len(word_to_idx) - -# Simple text classification model -class TextClassifier(nn.Module): - def __init__(self, vocab_size, embedding_dim): - super(TextClassifier, self).__init__() - self.embedding = nn.Embedding(vocab_size, embedding_dim) - self.fc = nn.Linear(embedding_dim, 1) - - def forward(self, x): - embedded = self.embedding(x) - # Take average of embeddings across sequence length - embedded = torch.mean(embedded, dim=1) - return self.fc(embedded).squeeze() - -# Initialize model with Adagrad optimizer -vocab_size = len(word_to_idx) -model = TextClassifier(vocab_size, embedding_dim=50) -criterion = nn.BCEWithLogitsLoss() -optimizer = optim.Adagrad(model.parameters(), lr=0.1) - -# Training would continue here with proper batching and data loading -print(f"Model initialized with vocab size: {vocab_size}") -print(f"Optimizer: Adagrad with learning rate 0.1") -``` - -This example shows how Adagrad can be applied to NLP tasks where sparse features are common, as it provides larger updates for rare words and smaller updates for frequent ones. - -Explore these optimization algorithms in Codecademy's [Data Scientist: Machine Learning](https://www.codecademy.com/career-journey/data-scientist-ml) career path, which covers machine learning fundamentals, model training, and advanced techniques. diff --git a/content/ai/concepts/neural-networks/terms/adam-optimization/adam-optimization.md b/content/ai/concepts/neural-networks/terms/adam-optimization/adam-optimization.md deleted file mode 100644 index b5ef6850045..00000000000 --- a/content/ai/concepts/neural-networks/terms/adam-optimization/adam-optimization.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -Title: 'Adam Optimization' -Description: 'Adam is an optimization algorithm that calculates adaptive learning rates for each individual parameter.' -Subjects: - - 'Computer Science' - - 'Machine Learning' -Tags: - - 'AI' - - 'Neural Networks' -CatalogContent: - - 'machine-learning' - - 'paths/data-science' ---- - -**Adam** (Adaptive Moment Estimation) is a widely used optimization algorithm in deep learning. It combines the momentum technique from Stochastic Gradient Descent (SGD) with the adaptive learning rate of RMSprop (Root Mean Square Propagation). Adam can also be viewed as an extension of AdaDelta, refining the learning rate adjustments for each parameter. - -It adapts the learning rate for each parameter, making the training process faster and more efficient, especially for large datasets. Adam's ability to handle sparse gradients and adapt dynamically to different scenarios makes it highly efficient for training deep neural networks. - -## Working of Adam Optimization - -Adam works by computing adaptive learning rates for each parameter, which helps in adjusting the step size during optimization. It maintains two moving averages for each parameter: one for the gradients (momentum), and the other for the squared gradients (similar to RMSProp). These moving averages help to smooth out noisy updates and ensure consistent progress towards the minimum. - -One of Adam’s key features is bias correction, which adjusts the moving averages at the start of training to prevent initial values from being too small. This adjustment enhances Adam's stability during the initial stages of training. Furthermore, Adam adapts to different problem structures and works well with non-stationary data, such as datasets that change over time or have dynamic properties. - -Finally, because Adam adjusts learning rates individually for each parameter, it excels in problems where gradients vary widely or parameters have differing levels of importance. - -## Key Advantages - -- **Adaptive Learning Rates**: Adam adapts learning rates for each parameter, leading to more efficient training, especially in complex models. -- **Bias Correction**: This feature is significant in the early stages of training, as it adjusts the moving averages to prevent them from being too small, enhancing stability. -- **Robustness**: Adam performs well with noisy gradients and varying data distributions, making it suitable for real-world applications. - -## Example - -### MNIST Classification with Adam Optimizer - -This example shows how to train a neural network using the Adam optimizer with TensorFlow/Keras on the MNIST dataset, which consists of 70,000 grayscale images of handwritten digits (0-9) commonly used for benchmarking machine learning algorithms: - -```py -import tensorflow as tf -from tensorflow.keras.datasets import mnist -from tensorflow.keras.models import Sequential -from tensorflow.keras.layers import Dense, Flatten -from tensorflow.keras.utils import to_categorical - -# Load the MNIST dataset -(x_train, y_train), (x_test, y_test) = mnist.load_data() - -# Normalize the images to values between 0 and 1 -x_train, x_test = x_train / 255.0, x_test / 255.0 - -# One-hot encode labels -y_train, y_test = to_categorical(y_train, 10), to_categorical(y_test, 10) - -# Build and compile the model -model = Sequential([ - Flatten(input_shape=(28, 28)), - Dense(128, activation='relu'), - Dense(10, activation='softmax') -]) - -model.compile( - optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), - loss='categorical_crossentropy', - metrics=['accuracy'] -) - -# Train the model -model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.2) - -# Evaluate the model -test_loss, test_acc = model.evaluate(x_test, y_test) -print(f'Test Accuracy: {test_acc:.4f}') -``` - -The above code generates the following output: - -```shell -Test Accuracy: 0.9731 -``` - -> Note: The output will change with each run due to random weight initialization, data shuffling, and the stochastic nature of the Adam optimizer. diff --git a/content/ai/concepts/neural-networks/terms/backpropagation/backpropagation.md b/content/ai/concepts/neural-networks/terms/backpropagation/backpropagation.md deleted file mode 100644 index df56e7780d3..00000000000 --- a/content/ai/concepts/neural-networks/terms/backpropagation/backpropagation.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -Title: 'Backpropagation' -Description: 'Backpropagation is a crucial algorithm in the field of machine learning, specifically in the training of artificial neural networks (ANNs).' -Subjects: - - 'Data Science' - - 'Machine Learning' -Tags: - - 'AI' - - 'Machine Learning' -CatalogContent: - - 'learn-python-3' - - 'paths/machine-learning-ai-engineering-foundations' ---- - -**Backpropagation** is a crucial algorithm in the field of machine learning, specifically in the training of artificial neural networks (ANNs). It enables the neural network to learn and improve its performance by iteratively adjusting the weights and biases of its connections. - -## What is Backpropagation? - -Backpropagation, short for "backward propagation of errors," is a supervised learning algorithm that calculates the gradient of the loss function with respect to the network's weights. It allows the determination of how much each weight contributes to the overall error or loss of the network's predictions. - -## How is Backpropagation Used in Artificial Neural Networks? - -Artificial Neural Networks consist of interconnected nodes, called neurons, organized in layers. These layers include an input layer, one or more hidden layers, and an output layer. Backpropagation is used to adjust the weights and biases of the connections between these neurons. - -The backpropagation algorithm can be summarized in the following steps: - -1. **Forward Pass:** During the forward pass, input data is propagated through the network, layer by layer, until the output layer is reached. Each neuron in a layer receives inputs from the previous layer, calculates a weighted sum, applies an activation function, and passes the result to the next layer. - -2. **Calculating the Error:** After the forward pass, the network's output is compared to the expected output using a loss function. The error is the discrepancy between the predicted output and the desired output. - -3. **Backward Pass:** In the backward pass, the error is propagated back through the network, starting from the output layer towards the input layer. This is where backpropagation gets its name. The error is assigned to each neuron in proportion to its contribution to the overall error. - -4. **Weight and Bias Updates:** Using the calculated errors, the algorithm adjusts the weights and biases of the network's connections. This adjustment is done iteratively, typically using an optimization algorithm like gradient descent, which minimizes the error by updating the weights in the direction opposite to the gradient. - -5. **Repeat:** Steps 1 to 4 are repeated for a fixed number of iterations or until a convergence criterion is met. The network gradually learns to minimize the error and improve its predictions. - -## Benefits and Importance of Backpropagation - -Backpropagation is a fundamental technique in training artificial neural networks due to its numerous benefits: - -- **Efficient Training:** Backpropagation allows neural networks to efficiently learn complex relationships in data, making them capable of solving complex problems. - -- **Universal Approximators:** ANNs with backpropagation have the ability to approximate any continuous function, given enough neurons and training data. - -- **Generalization:** By adjusting weights and biases, backpropagation enables the neural network to generalize from training data to make accurate predictions on unseen data. - -- **Adaptability:** Backpropagation allows neural networks to adapt and improve their performance over time, making them suitable for tasks that involve changing environments or evolving data patterns. - -- **Deep Learning:** Backpropagation forms the basis of deep learning, enabling the training of deep neural networks with many layers and millions of parameters. diff --git a/content/ai/concepts/neural-networks/terms/binary-step-activation-function/binary-step-activation-function.md b/content/ai/concepts/neural-networks/terms/binary-step-activation-function/binary-step-activation-function.md deleted file mode 100644 index 025da159d49..00000000000 --- a/content/ai/concepts/neural-networks/terms/binary-step-activation-function/binary-step-activation-function.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -Title: 'Binary Step Activation Function' -Description: 'The simplest threshold based activation function which works by either firing the node in case the threshold value is surpassed or doing nothing at all.' -Subjects: - - 'Machine Learning' - - 'Data Science' - - 'Computer Science' -Tags: - - 'AI' - - 'Machine Learning' - - 'Neural Networks' - - 'Functions' -CatalogContent: - - 'machine-learning' - - 'path/data-science' ---- - -**Binary Step** is the simplest threshold-based activation function which works by either activating the node, i.e. passing on its output to the next layer in case the threshold value is surpassed, or doing nothing at all. - -![Binary Step Activation Plot](https://raw.githubusercontent.com/Codecademy/docs/main/media/binary-step-plot.png) - -Mathematically, it can be defined as: - -![Binary Step Activation Function](https://raw.githubusercontent.com/Codecademy/docs/main/media/binary-step-function.jpg) - -If the node input value is less than 0, it returns 0 as output. Else, it returns 1. - -### Usage and Limitations - -As the name suggests, binary step can be used as an activation function in the output layer of a neural network for binary classification problems. - -It is generally not suggested to use binary step in the hidden layer as it is a linear piecewise function unable to handle complex representations. - -### Codebyte Example - -The following is an example of the activation function in Python: - -```codebyte/python -def binary_step(x): - # Apply binary step activation - if x < 0: - # Deactivate node - return 0 - else: - # Activate node - return 1 - -# Examples -print(binary_step(-0.2)) -print(binary_step(0.5)) -``` diff --git a/content/ai/concepts/neural-networks/terms/convolutional-neural-networks/convolutional-neural-networks.md b/content/ai/concepts/neural-networks/terms/convolutional-neural-networks/convolutional-neural-networks.md deleted file mode 100644 index 2925ed6fa5e..00000000000 --- a/content/ai/concepts/neural-networks/terms/convolutional-neural-networks/convolutional-neural-networks.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -Title: 'Convolutional Neural Networks' -Description: 'Convolutional Neural Networks (CNNs) are neural networks primarily used for computer vision tasks like image classification, object detection, and segmentation.' -Subjects: - - 'Machine Learning' - - 'Computer Science' -Tags: - - 'AI' - - 'Neural Networks' -CatalogContent: - - 'machine-learning' - - 'paths/machine-learning-engineer' ---- - -**Convolutional Neural Networks** (CNNs) are a type of neural network that are primarily used for computer vision tasks, such as image classification, object detection, and semantic segmentation. CNNs are highly effective for [machine learning](https://www.codecademy.com/resources/docs/ai/machine-learning) tasks that involve structured grid-like data, such as images. However, they can be used in other areas of machine learning, such as natural language processing or audio signal processing. - -## What is Convolution? - -Convolution is a mathematical operation which involves combining two functions to produce a third function. It essentially “blends” or “merges” two functions together. For instance, if you have two functions, _f(x)_ and _g(x)_, convolution can be employed to combine them and generate a new function, denoted as _(f \* g)(x)_. This new function captures the combined impact of the original functions, illustrating their interaction and overlap. - -## How Does a CNN Work? - -Convolution in CNNs allows the network to automatically learn and extract visual features from images, model spatial relationships, handle variations in object position and appearance, and capture meaningful relationships within images. Important characteristics in images can be captured using CNNs, such as edges, corners, textures, and shapes. - -In a CNN's convolutional filter context, _f(x)_ represents the input data, and _g(x)_ represents the convolutional filter used in the network. The input data is a small matrix typically from an image or a feature map produced by a previous layer in the network, and the convolutional filter is a small matrix of weights that was learned in the training process. The convolutional filter essentially acts as a window that scans the input data to extract relevant features. - -During convolution, the filter (_g(x)_) is slid over the input data (_f(x)_). At each position, the filter performs element-wise multiplication of the two matrices. The products are then summed to produce a single value which is the output of the convolution in that position. This process is repeated for all positions, which results in an “output feature map,” which is a two-dimensional representation of the activations produced by applying the convolutional filters to the input data. - -## Challenges of CNNs - -Although CNNs are commonly employed in computer vision tasks, there are also some challenges, such as: - -- Computational cost: Training CNNs typically requires substantial computational resources, and training with large datasets of high-resolution images can be time-consuming. Training times can also be long, and specialized hardware (e.g., GPUs) is often used to accelerate computations. -- Need for large datasets: CNNs need large amounts of labeled training data to generalize well and learn meaningful features. "Generalization" is a crucial aspect of machine learning and refers to a model's ability to make reliable predictions for data it hasn't been exposed to in the training process. A model that "generalizes well" has learned the relevant patterns and relationships during training, so it can effectively be used to make accurate predictions on new data. Insufficient training data for CNNs can lead to overfitting, which means the model does not generalize well and fails to make reliable predictions on new, unseen data. -- Interpretability: CNNs are sometimes considered “black box models,” which means that their internal workings and decision-making processes are not easily interpretable by humans. The complex architectures and numerous parameters of CNNs make it difficult to interpret why specific predictions or decisions are made. This can raise concerns in domains where interpretability is crucial. - -## Relation to AI - -Due to their ability to extract features from images, CNNs are widely used in the field of computer vision with its applications ranging from augmented-reality to self-driving cars. Additionally, they can be used in other AI applications in natural language processing, audio signal processing, and more. diff --git a/content/ai/concepts/neural-networks/terms/gaussian-activation-function/gaussian-activation-function.md b/content/ai/concepts/neural-networks/terms/gaussian-activation-function/gaussian-activation-function.md deleted file mode 100644 index dc12b2e2718..00000000000 --- a/content/ai/concepts/neural-networks/terms/gaussian-activation-function/gaussian-activation-function.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -Title: 'Gaussian Activation Function' -Description: 'The Gaussian activation function shapes the output of a neuron into a bell-shaped curve that is symmetric about its unique peak.' -Subjects: - - 'Machine Learning' - - 'Data Science' - - 'Computer Science' -Tags: - - 'AI' - - 'Machine Learning' - - 'Neural Networks' - - 'Functions' -CatalogContent: - - 'paths/machine-learning-ai-engineering-foundations' - - 'intro-to-ai-strategy' ---- - -A **Gaussian activation function** is a mathematical function known as the normal distribution or bell curve function. It is a fundamental concept in statistics and probability theory often used in AI and neural networks as a probability distribution function to model the output of a neuron. - -## Gaussian Function - -The Gaussian function is characterized by its bell-shaped graph, where most data points are near the middle (average), and the likelihood of getting values decreases as you move away from the average. This curve is symmetric, meaning that the probabilities of getting values above the average are the same as getting values below the average. - -![Gaussian function](https://raw.githubusercontent.com/Codecademy/docs/main/media/gaussian-function-1d.png) - -## Advantages and Disadvantages of the Gaussian Activation Function - -### Advantages - -- **Smooth and Continuous**: The Gaussian activation function is smooth and continuous everywhere, making it fully differentiable with a consistent gradient. This property simplifies the process for optimization algorithms to find the best solution. -- **Non-Linear Properties**: It introduces non-linearity to the neural network, enabling the network to capture complex relationships between inputs and outputs. - -### Disadvantages - -- **Risk of Overfitting**: A more complex network can lead to overfitting, where the model overly specializes in the training data and fails to generalize to new, unseen data. -- **Increased Network Complexity**: Implementing the Gaussian function can add complexity to the neural network, often requiring more computational power and time for training. -- **Potential for Local Minima Traps**: The Gaussian function may increase the likelihood of the network getting trapped in local minima during the optimization process. This can hinder the achievement of the most optimal solutions. - -## Practical Uses for the Gaussian Activation Function - -The Gaussian activation function plays a pivotal role in various AI and machine learning applications across different industries, such as: - -- **Image Processing and Computer Vision**: In image processing, Gaussian functions are used for smoothing or blurring images. This is crucial in pre-processing steps to reduce noise and improve the quality of feature extraction, which is vital in computer vision tasks like object detection, face recognition, and image segmentation. Additionally, Gaussian functions are used for applications like earth observation, weather forecasting, and environmental monitoring. -- **Regression Analysis**: Gaussian functions are foundational in Gaussian Processes, a powerful tool for regression analysis in machine learning. They provide a probabilistic approach to modeling uncertainties in predictions, which is important in fields like financial modeling, environmental modeling, and robotics. For instance, they help model stock price variations and market trends, allowing financial analysts to predict future movements and manage risks more effectively. -- **Pattern Recognition and Classification**: Gaussian functions are often used in algorithms for pattern recognition and classification tasks. In these scenarios, they help to model the distribution of data points, allowing the system to differentiate between various categories or classes effectively. For example, in retail and e-commerce, Gaussian functions aid customer behavior analysis and sales forecasting. By modeling customer purchase patterns, businesses can predict future sales trends, optimize inventory management, and enhance personalized marketing strategies. -- **Natural Language Processing (NLP)**: In NLP, Gaussian distributions can be used in probabilistic models like Gaussian Mixture Models (GMMs) for clustering or classifying text data. They help in understanding the underlying structure of language data, which is essential for applications like sentiment analysis, topic modeling, and language generation. -- **Reinforcement Learning**: In reinforcement learning, especially in continuous action spaces, Gaussian functions are used to model the probability distribution of actions. This assists in the exploration-exploitation trade-off, where the algorithm needs to decide between exploring new actions and exploiting known rewarding actions. diff --git a/content/ai/concepts/neural-networks/terms/gradient-descent/gradient-descent.md b/content/ai/concepts/neural-networks/terms/gradient-descent/gradient-descent.md deleted file mode 100644 index ef4f66b5957..00000000000 --- a/content/ai/concepts/neural-networks/terms/gradient-descent/gradient-descent.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -Title: 'Gradient Descent' -Description: 'Gradient Descent is an optimization algorithm that minimizes a cost function by iteratively adjusting parameters in the direction of its gradient.' -Subjects: - - 'Machine Learning' - - 'Data Science' - - 'Computer Science' -Tags: - - 'AI' - - 'Machine Learning' - - 'Neural Networks' - - 'Functions' -CatalogContent: - - 'paths/data-science' - - 'paths/machine-learning' ---- - -**Gradient Descent** is an optimization algorithm commonly used in machine learning and neural networks to minimize a cost function. Its goal is to iteratively find the optimal parameters (weights) that minimize the error or loss. - -In neural networks, gradient descent computes the gradient (derivative) of the cost function with respect to each parameter. It then updates the parameters in the direction of the negative gradient, effectively reducing the cost with each step. - -## Types of Gradient Descent - -There are three main types of gradient descent: - -| Type | Description | -| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Batch Gradient Descent** | Uses the entire dataset to compute the gradient and update the weights. Typically slower but more accurate for large datasets. | -| **Stochastic Gradient Descent (SGD)** | Uses a single sample to compute the gradient and update the weights. It is faster, but the updates are noisy and can cause fluctuations in the convergence path. | -| **Mini-batch Gradient Descent** | A compromise between batch and stochastic gradient descent, using a small batch of samples to compute the gradient. It balances the speed and accuracy of the learning process. | - -## Gradient Descent Update Rule - -The basic update rule for gradient descent is: - -```pseudo -theta = theta - learning_rate * gradient_of_cost_function -``` - -- `theta`: The parameter (weight) of the model that is being optimized. -- `learning_rate`: A hyperparameter that controls the step size. -- `gradient_of_cost_function`: The gradient (derivative) of the cost function with respect to the parameters, indicating the direction and magnitude of the change needed. - -## Syntax - -Here's a basic syntax for Gradient Descent in the context of machine learning, specifically for updating the model parameters (weights) in order to minimize the cost function: - -```pseudo -# Initialize parameters (weights) and learning rate -theta = initial_value # Model Parameters (weights) -learning_rate = value # Learning rate (step size) -iterations = number_of_iterations # Number of iterations - -# Repeat until convergence -for i in range(iterations): - # Calculate the gradient of the cost function - gradient = compute_gradient(X, y, theta) # Gradient calculation - - # Update the parameters (weights) - theta = theta - learning_rate * gradient # Update rule - - # Optionally, compute and store the cost (for monitoring convergence) - cost = compute_cost(X, y, theta) - store(cost) -``` - -## Example - -In the following example, we implement simple gradient descent to minimize the cost function of a linear regression problem: - -```py -import numpy as np - -# Sample data (X: inputs, y: actual outputs) -X = np.array([1, 2, 3, 4, 5]) -y = np.array([1, 2, 1.3, 3.75, 2.25]) - -# Parameters initialization -theta = 0.0 # Initial weight -learning_rate = 0.01 # Step size -iterations = 1000 # Number of iterations - -# Cost function (Mean Squared Error) -def compute_cost(X, y, theta): - m = len(y) - cost = (1/(2*m)) * np.sum((X*theta - y)**2) # The cost function for linear regression - return cost - -# Gradient Descent function -def gradient_descent(X, y, theta, learning_rate, iterations): - m = len(y) - cost_history = [] - - for i in range(iterations): - gradient = (1/m) * np.sum(X * (X*theta - y)) # Derivative of cost function - theta = theta - learning_rate * gradient # Update theta - cost_history.append(compute_cost(X, y, theta)) # Track cost - return theta, cost_history - -# Run Gradient Descent -theta_optimal, cost_history = gradient_descent(X, y, theta, learning_rate, iterations) - -print(f"Optimal Theta: {theta_optimal}") -``` - -The output for the above code will be something like this: - -```shell -Optimal Theta: 0.6390909090909086 -``` - -> **Note**: The optimal `theta` value will be an approximation, as the gradient descent approach iteratively updates the weight to reduce the cost function. diff --git a/content/ai/concepts/neural-networks/terms/learning-rate-schedule/learning-rate-schedule.md b/content/ai/concepts/neural-networks/terms/learning-rate-schedule/learning-rate-schedule.md deleted file mode 100644 index b231508baa9..00000000000 --- a/content/ai/concepts/neural-networks/terms/learning-rate-schedule/learning-rate-schedule.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -Title: 'Learning Rate Scheduling' -Description: 'Learning rate scheduling is a technique to adjust the learning rate during training to improve convergence and model performance.' -Subjects: - - 'Machine Learning' - - 'Data Science' - - 'Computer Science' -Tags: - - 'AI' - - 'Machine Learning' - - 'Neural Networks' - - 'Functions' -CatalogContent: - - 'paths/data-science' - - 'paths/machine-learning' ---- - -**Learning Rate Scheduling** is a method to adjust the learning rate during the training process of a [neural network](https://www.codecademy.com/resources/docs/ai/neural-networks). The learning rate defines the step size used by optimization algorithms, such as [Stochastic Gradient Descent (SGD)](https://www.codecademy.com/resources/docs/ai/neural-networks/stochastic-gradient-descent), to minimize the loss function. By modifying the learning rate throughout training, a schedule can help models converge faster and achieve better accuracy. - -## Key Points - -- **Higher learning rate initially**: Helps the model explore parameter values quickly during early training. -- **Gradual reduction**: Allows fine-tuning with smaller steps as the model approaches optimal parameters. -- **Types of schedules**: - - **Step-based schedules**: Reduce the learning rate at fixed intervals (e.g., every 10 epochs). This approach is simple and works well for many cases. - - **Exponential schedules**: Reduce the learning rate by a fixed factor (e.g., multiplying it by 0.9) after every epoch or step. This ensures a smooth, gradual decay over time. - - **Adaptive schedules**: Automatically adjust the learning rate based on the model’s performance (e.g., reducing the learning rate when the validation loss stops improving). These are more dynamic and can adapt to the needs of the model during training. - -## Syntax - -Here’s a general syntax for implementing a learning rate schedule in PyTorch: - -```pseudo -torch.optim.lr_scheduler.( - optimizer, - step_size=, - gamma=, - -) -``` - -- `optimizer`: The optimizer whose learning rate will be updated. -- `step_size`: Interval (in epochs) at which the learning rate will be reduced. An epoch refers to one complete pass through the entire training dataset by the model. During each epoch, the model processes all training examples and updates its weights accordingly. -- `gamma`: Multiplicative factor by which the learning rate is reduced. -- ****: Additional parameters specific to the chosen scheduler. - -## Example - -The following example demonstrates the use of a **StepLR Learning Rate Scheduler** in PyTorch to reduce the learning rate by a factor of _0.9_ every _10_ epochs: - -```py -import torch -import torch.nn as nn -import torch.optim as optim - -# Define a simple neural network -class SimpleNN(nn.Module): - def __init__(self): - super(SimpleNN, self).__init__() - self.fc = nn.Linear(10, 1) - - def forward(self, x): - return self.fc(x) - -# Initialize the model, loss function, and optimizer -model = SimpleNN() -criterion = nn.MSELoss() -optimizer = optim.SGD(model.parameters(), lr=0.1) - -# Define the learning rate scheduler -scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.9) - -# Training loop -for epoch in range(30): # Train for 30 epochs - # Simulate training step - inputs = torch.randn(5, 10) - targets = torch.randn(5, 1) - optimizer.zero_grad() - outputs = model(inputs) - loss = criterion(outputs, targets) - loss.backward() - optimizer.step() - - # Update the learning rate - scheduler.step() - - # Print learning rate - print(f"Epoch {epoch + 1}: Learning Rate = {scheduler.get_last_lr()[0]:.5f}") -``` - -The code above produces the output as below: - -```shell -Epoch 1: Learning Rate = 0.10000 -Epoch 2: Learning Rate = 0.10000 -Epoch 3: Learning Rate = 0.10000 -Epoch 4: Learning Rate = 0.10000 -Epoch 5: Learning Rate = 0.10000 -Epoch 6: Learning Rate = 0.10000 -Epoch 7: Learning Rate = 0.10000 -Epoch 8: Learning Rate = 0.10000 -Epoch 9: Learning Rate = 0.10000 -Epoch 10: Learning Rate = 0.09000 -Epoch 11: Learning Rate = 0.09000 -Epoch 12: Learning Rate = 0.09000 -Epoch 13: Learning Rate = 0.09000 -Epoch 14: Learning Rate = 0.09000 -Epoch 15: Learning Rate = 0.09000 -Epoch 16: Learning Rate = 0.09000 -Epoch 17: Learning Rate = 0.09000 -Epoch 18: Learning Rate = 0.09000 -Epoch 19: Learning Rate = 0.09000 -Epoch 20: Learning Rate = 0.08100 -Epoch 21: Learning Rate = 0.08100 -Epoch 22: Learning Rate = 0.08100 -Epoch 23: Learning Rate = 0.08100 -Epoch 24: Learning Rate = 0.08100 -Epoch 25: Learning Rate = 0.08100 -Epoch 26: Learning Rate = 0.08100 -Epoch 27: Learning Rate = 0.08100 -Epoch 28: Learning Rate = 0.08100 -Epoch 29: Learning Rate = 0.08100 -Epoch 30: Learning Rate = 0.07290 -``` diff --git a/content/ai/concepts/neural-networks/terms/linear-activation-function/linear-activation-function.md b/content/ai/concepts/neural-networks/terms/linear-activation-function/linear-activation-function.md deleted file mode 100644 index b0eb97d09df..00000000000 --- a/content/ai/concepts/neural-networks/terms/linear-activation-function/linear-activation-function.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -Title: 'Linear Activation Function' -Description: 'The linear activation function is an activation function where the activation is proportional to the input.' -Subjects: - - 'Machine Learning' - - 'Data Science' - - 'Computer Science' -Tags: - - 'AI' - - 'Machine Learning' - - 'Neural Networks' - - 'Functions' -CatalogContent: - - 'machine-learning' - - 'path/data-science' ---- - -The **linear activation function**, also known as the identity function, is one of the most straightforward activation functions, where the output is identical to the input. -The linear activation function typically adds the weighted sum with bias and passes it as output. - -Mathematically, it can be defined as: - -![Linear Activation Function Equation](https://raw.githubusercontent.com/Codecademy/docs/main/media/linear-equ.png) - -where : - -![Linear Activation Function Expression](https://raw.githubusercontent.com/Codecademy/docs/main/media/linear-expression.png) - -### Usage and Limitations - -The problem with this activation function is that it is limited in the context of deep neural networks. - -The model cannot learn complex non-linear relationships between inputs and outputs by using linear activation functions. - -### Codebyte Example - -The following is an example of the linear activation function in Python: - -```codebyte/python -import numpy as np -from matplotlib import pyplot as plt - -# Linear activation Function -def linear(x): - ''' y = f(x) It returns the input as it is''' - return x - -# Generating data to plot -x_data = np.linspace(-6,6,100) -y_data = linear(x_data) - -# Plotting -plt.plot(x_data, y_data) -plt.title('Linear Activation Function') -plt.legend(['f(x) = x']) -plt.grid() -plt.show() -``` - -This code will return a linear activation function graph: - -![Linear Activation Function Plot](https://raw.githubusercontent.com/Codecademy/docs/main/media/linear-graph.png) diff --git a/content/ai/concepts/neural-networks/terms/long-short-term-memory-networks/long-short-term-memory-networks.md b/content/ai/concepts/neural-networks/terms/long-short-term-memory-networks/long-short-term-memory-networks.md deleted file mode 100644 index 4a712f57293..00000000000 --- a/content/ai/concepts/neural-networks/terms/long-short-term-memory-networks/long-short-term-memory-networks.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -Title: 'Long Short-Term Memory Networks' -Description: 'A type of recurrent neural network (RNN) architecture designed to capture long-term dependencies in sequential and time-series data.' -Subjects: - - 'Machine Learning' - - 'Computer Science' -Tags: - - 'AI' - - 'Neural Networks' -CatalogContent: - - 'machine-learning' - - 'paths/machine-learning-engineer' ---- - -**LSTM** networks are a type of recurrent neural network (RNN) that processes sequential data using specialized gating mechanisms. The LSTM computations at each time step can be expressed as follows: - -1. **Forget Gate:** Determines what information from the cell state should be discarded or kept. -2. **Input Gate:** Updates the cell state with new information. -3. **Cell State:** Maintains the long-term memory of the network. -4. **Output Gate:** Produces the output based on the cell state. - -## Key Features of LSTM Networks - -- **Long-Term Dependencies**: LSTMs are capable of learning long-term dependencies in data. Traditional RNNs struggle with this due to the vanishing gradient problem, where gradients diminish exponentially as they are [backpropagated](https://www.codecademy.com/resources/docs/ai/neural-networks/backpropagation) through time. LSTMs use a gating mechanism to mitigate this problem. -- **Gating Mechanisms**: LSTMs have three main components: the input gate, the forget gate, and the output gate. These gates regulate the flow of information into and out of the cell state, allowing LSTMs to selectively remember or forget information. -- **Cell State**: LSTMs have a cell state that runs through the entire sequence, acting as a memory of the network. The cell state can carry information across long sequences, making LSTMs effective for learning long-term patterns. -- **Flexibility**: LSTMs can be adapted for various types of data, including sequences of different lengths and dimensions. They are widely used in natural language processing, speech recognition, and time-series analysis. -- **Backpropagation Through Time (BPTT)**: LSTMs, like other RNNs, use BPTT for training. BPTT is an extension of backpropagation that is used to update the network’s weights by taking into account the sequential nature of the data. - -## How Does a LSTM Work? - -Imagine an LSTM network like a smart worker managing a conveyor belt assembly line in a factory: - -- Memory Storage: The worker has a good memory (cell state) and a notebook (hidden state) to keep track of tasks. -- Forget Old Information: Before adding new items to the assembly line, the worker checks the notebook and decides what old information is not needed anymore (forget gate). This helps in clearing unnecessary clutter. -- Add New Information: When new items arrive, the worker decides what's important and adds it to the notebook (input gate and candidate cell state). This is like writing down new tasks in the notebook. -- Update Memory: The worker updates their memory by combining the old remembered tasks (adjusted for what was forgotten) with the new tasks (update cell state). This ensures that important past tasks are not entirely lost. -- Determine Output: Finally, the worker looks at their notebook, chooses what to share with the boss, and tells the boss about the most important ongoing tasks (output gate). - -## Limitations of LSTMs - -- Computational Complexity: LSTMs can be computationally intensive, especially for large and complex networks, which can impact training times. -- Interpretability: Understanding the inner workings of LSTMs and interpreting their decisions can be challenging due to their complex architecture. -- Data Requirements: LSTMs require a substantial amount of data to effectively learn and generalize patterns, especially for tasks with high complexity. - -## Relation to AI - -LSTMs play a crucial role in AI by handling sequential data effectively. Their ability to capture long-term dependencies makes them essential in applications like natural language processing, speech recognition, and time-series analysis. LSTMs enable AI systems to comprehend and generate human-like language, recognize speech patterns, and make predictions based on historical data, contributing significantly to various AI-driven tasks and technologies. diff --git a/content/ai/concepts/neural-networks/terms/recurrent-neural-networks/recurrent-neural-networks.md b/content/ai/concepts/neural-networks/terms/recurrent-neural-networks/recurrent-neural-networks.md deleted file mode 100644 index 39b77822497..00000000000 --- a/content/ai/concepts/neural-networks/terms/recurrent-neural-networks/recurrent-neural-networks.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -Title: 'Recurrent Neural Networks' -Description: 'Recurrent Neural Networks are a type of neural network distinguished by storing and re-using the output from previous steps as an additional input in the current step' -Subjects: - - 'Machine Learning' - - 'Computer Science' -Tags: - - 'AI' - - 'Neural Networks' -CatalogContent: - - 'machine-learning' - - 'paths/machine-learning-engineer' ---- - -A **Recurrent Neural Network** (RNN) is a type of neural network that stores and re-uses the outputs from previous steps as additional inputs in the current step. RNNs process sequential data in groups of _timesteps_ which represent a segment of the sequence. These timesteps could represent words from a sentence or frames from an audio clip. The network uses the output from previous timesteps which are stored in a "hidden state" or "hidden variable" to compute the output for the current timestep. - -RNNs are used in cases where the sequence of data is important to the predicted output. In sequential or time-based data sets, RNNs use previous outputs as "memories" or "states", and use that to predict the output in the sequence. - -## How Does an RNN Work? - -The training data is split into time-based sequences. They are then vector-encoded and passed into the RNN as inputs. The RNN is initialized with random weights and biases which remain the same through all timesteps. The network iterates over the sequence to compute the output or hidden state for each timestep. - -The current hidden state is computed by passing the input for the current time-step, the previous hidden state, and the weights and biases for the sequence into a layer with an activation function of choice. The hidden state is then returned as an output and passed to the next timestep. The process is repeated through the rest of the timesteps. Depending on the task, the final output can either be returned as a single vector or can be a combination of output vectors returned in each timestep. For the first timestep, the previous hidden state can be initialized as a zero vector of size dependent on the intended output size. - -A loss function is used to compare the expected result and actual result returned by the model. Using the loss calculated, the loss gradient for each timestep is computed using Backpropagation Through Time (BPTT) and is used to update the weights in order to reduce the loss. Repeating this process trains the network until the expected result is produced. - -A common issue when training an RNN is the vanishing gradient problem. When backpropagating and updating the weights, the error gradient becomes smaller and smaller as it approaches the earlier inputs. As a result, the earlier inputs will have less of an impact on training process. To rectify this, networks like Long Short Term Memory (LSTM) and Gated Recurrent Unit (GRU) are often used. Although out of scope for the purpose of this doc, LSTM and GRU are both worth looking into, as well as another common problem that can come up - the exploding gradient. - -## Relation to AI - -RNNs are generally used to predict data that forms a series; this can be grouped into input-to-output classes. Some examples are: - -- Many inputs to many outputs: Speech Recognition, Language Translation, Language modeling. -- Many inputs to one output: Stock prediction, weather prediction, Sentiment analysis. -- One input to many output: Image captioning, Music Generation. -- One input to one output: Image classification. diff --git a/content/ai/concepts/neural-networks/terms/rmsprop/rmsprop.md b/content/ai/concepts/neural-networks/terms/rmsprop/rmsprop.md deleted file mode 100644 index f178d3cc6ad..00000000000 --- a/content/ai/concepts/neural-networks/terms/rmsprop/rmsprop.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -Title: 'RMSprop' -Description: 'RMSprop is an optimization algorithm that dynamically adjusts the learning rate during the training of neural networks.' -Subjects: - - 'Computer Science' - - 'Data Science' -Tags: - - 'AI' - - 'Functions' - - 'Machine Learning' - - 'Neural Networks' -CatalogContent: - - 'paths/machine-learning-ai-engineering-foundations' - - 'intro-to-ai-strategy' ---- - -**RMSprop**, an abbreviation for the term **Root Mean Square Propagation**, is an [algorithm](https://www.codecademy.com/resources/docs/general/algorithm) that is designed to adjust the learning rates dynamically for training neural network models. It helps to improve the stability and speed of the training process by adapting the learning rate based on recent gradients, making it effective for training deep neural networks. - -## Explanation - -RMSprop modifies the learning rate for each parameter individually by taking into account the magnitudes of the recent gradients to adjust the updates. Here is how it works: - -- _Exponential Decay of Squared Gradients_: RMSprop keeps track of the moving average of the squared gradients of the loss function with an exponential decay factor. The average is then used to normalise the gradients, preventing them from being too large or too small. -- _Update Rule_: For each parameter $\theta_i$, RMSprop updates the exponentially decaying average of the squared gradients $E[g^2]_t$ and then uses it to adjust the parameter. - -Here is an image that illustrates the update rule: - -![RMSprop Update Rule](https://raw.githubusercontent.com/Codecademy/docs/main/media/rmsprop-update.png) - -In the above image: - -- $g_t$ refers to the gradient at time $t$ -- $\rho$ refers to the decay rate (which is typically around $0.9$) -- $\eta$ refers to the learning rate -- $\epsilon$ refers to a small constant (around $10^{-8}$) to prevent any _division by zero_ errors - -## Example - -The following example demonstrates how RMSprop can be used for stochastic gradient descent: - -```py -import numpy as np - -# Example neural network parameters (weights) -theta = np.array([0.2, 0.4, 0.6]) - -# Learning rate (step size for updating parameters) -eta = 0.01 - -# Decay rate (used to compute the moving average of squared gradients) -rho = 0.9 - -# Small constant to prevent division by zero -epsilon = 1e-8 - -# Running average of squared gradients -E_g2 = np.zeros_like(theta) - -# Example gradients of the loss function with respect to the parameters -gradients = np.array([-0.5, 0.3, 0.24]) - -# Update the running average of squared gradients -E_g2 = rho * E_g2 + (1 - rho) * gradients**2 - -# Update the parameters using RMSprop -theta -= eta / np.sqrt(E_g2 + epsilon) * gradients - -print("Updated Parameters:", theta) -``` - -The output of the above code is as follows: - -```shell -Updated Parameters: [0.23162277 0.36837724 0.56837725] -``` - -## Codebyte Example - -The following codebyte example demonstrates the use of RMSprop in a stochastic gradient descent scenario: - -```codebyte/python -import numpy as np - -# Initialise parameters -theta = np.array([1.0, 2.0, 3.0]) -eta = 0.01 -rho = 0.9 -epsilon = 1e-8 -E_g2 = np.zeros_like(theta) - -# Example gradients -gradients = np.array([0.1, -0.2, 0.3]) - -# Update the running average of squared gradients -E_g2 = rho * E_g2 + (1 - rho) * gradients**2 - -# Apply RMSprop -theta -= eta / np.sqrt(E_g2 + epsilon) * gradients - -print("Updated parameters:", theta) -``` diff --git a/content/ai/concepts/neural-networks/terms/sigmoid-activation-function/sigmoid-activation-function.md b/content/ai/concepts/neural-networks/terms/sigmoid-activation-function/sigmoid-activation-function.md deleted file mode 100644 index 17a8951db72..00000000000 --- a/content/ai/concepts/neural-networks/terms/sigmoid-activation-function/sigmoid-activation-function.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -Title: 'Sigmoid Activation Function' -Description: 'A sigmoid activation function is a specific type of sigmoid function commonly used in machine learning and various fields of artificial intelligence.' -Subjects: - - 'Machine Learning' - - 'Data Science' - - 'Computer Science' -Tags: - - 'AI' - - 'Machine Learning' - - 'Neural Networks' - - 'Functions' -CatalogContent: - - 'machine-learning' - - 'paths/data-science' ---- - -A **sigmoid activation function** is a specific type of sigmoid function commonly used in [machine learning](https://www.codecademy.com/resources/docs/ai/machine-learning) and various fields of artificial intelligence (AI). They play a crucial role in machine learning by enabling the development of neural networks for many machine learning tasks. In other areas of AI, sigmoid activation functions can be applied to probabilistic modeling, decision making, uncertainty modeling, and more. - -## Sigmoid Functions - -A sigmoid function is a type of mathematical function that is commonly used in AI, specifically in machine learning. The graph of a sigmoid function is characterized by its S-shaped curve or “sigmoid curve”. - -![Sigmoid function](https://raw.githubusercontent.com/Codecademy/docs/main/media/sigmoid-function.png) - -Sigmoid functions transform data by mapping input values to a range between 0 and 1. The output of a sigmoid function can be interpreted as a value that represents the probability or intensity of an event. This makes sigmoid functions useful for representing relationships in data, as they can provide a measure of how likely or strong something is based on the input. - -## Sigmoid Activation Functions in Machine Learning - -A sigmoid activation function refers to the use of a sigmoid function as an [activation function](https://www.codecademy.com/resources/docs/ai/neural-networks/activation-function) in neural networks. Activation functions are like decision-making tools used in machine learning. They help determine if specific neurons in a neural network should be activated or not based on the input they receive. - -Sigmoid activation functions are commonly used in machine learning because they help neural networks understand and learn from complex patterns in data. They introduce non-linearity to the data, which means the relationship between input and output is not a simple straight line. Instead, sigmoid activation functions can help neural networks capture intricate and non-linear relationships. This is important because problems that are encountered in the real-world, such as image recognition or language processing, often have behaviors that are not straightforward or linear. Sigmoid activation functions allow the neural network to handle these complexities. - -## Practical Uses for Sigmoid Activation Functions - -Sigmoid activation functions can be used for many practical machine learning tasks, such as: - -- Binary classification: Sigmoid activation functions are especially useful in binary classification tasks, where samples are assigned to one of two classes. In such tasks, a threshold (typically 0.5) can be set so that values above the threshold are classified into one class, and values below the threshold are classified into the other class. -- Sentiment analysis: Sentiment analysis aims to determine the emotion, or sentiment, of text data. Sigmoid activation functions can be used to assign probabilities to different sentiment classes, such as positive or negative sentiment. -- Fraud detection: Sigmoid activation functions can be used in neural networks to detect the likelihood of a transaction being fraudulent based on multiple transaction features. -- Financial risk assessment: Sigmoid activation functions can be used in neural networks to assign probabilities to different risk factors, such as credit risk or the likelihood of loan defaults. diff --git a/content/ai/concepts/neural-networks/terms/stochastic-gradient-descent/stochastic-gradient-descent.md b/content/ai/concepts/neural-networks/terms/stochastic-gradient-descent/stochastic-gradient-descent.md deleted file mode 100644 index 85877803682..00000000000 --- a/content/ai/concepts/neural-networks/terms/stochastic-gradient-descent/stochastic-gradient-descent.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -Title: 'Stochastic Gradient Descent' -Description: 'Stochastic Gradient Descent is an optimizer algorithm that minimizes the loss function in machine learning and deep learning models.' -Subjects: - - 'Machine Learning' - - 'Computer Science' -Tags: - - 'AI' - - 'Neural Networks' -CatalogContent: - - 'paths/computer-science' - - 'paths/data-science' ---- - -**Stochastic Gradient Descent** (SGD) is an optimization algorithm used to minimize the loss function in machine learning and deep learning models. It is a variant of the traditional **Gradient Descent** (GD) algorithm. SGD updates the weights and biases of a model, such as those in an Artificial Neural Network (ANN), during the backpropagation process. - -The term `stochastic` refers to the randomness involved in the algorithm. Instead of using the entire dataset to compute gradients as in batch `gradient descent`, SGD uses a randomly selected data point (or a small mini-batch) to perform each update. For instance, if the dataset contains 500 rows, SGD will update the model parameters 500 times in one epoch, each time using a different randomly chosen data point (or small batch). - -This approach significantly reduces computation time, especially for large datasets, making SGD faster and more scalable. SGD is used for training models like neural networks, support vector machines (SVMs), and logistic regression. However, it introduces more noise into the learning process, which can lead to less stable convergence but also helps escape local minima, making it suitable for non-convex problems. - -## Algorithms Step - -- At each iteration, a random sample is selected from the training dataset. -- The gradient of the cost function with respect to the model parameters is computed based on the selected sample. -- The model parameters are updated using the computed gradient and the learning rate. -- The process is repeated for multiple iterations until convergence or a specified number of epochs. - -## Formula - -$$ -\large \theta = \theta - \alpha \cdot \nabla J(\theta ; x_i, y_i) -$$ - -Where: - -- `θ` represents the model parameter (weight or bias) being updated. -- `α` is the learning rate, a hyperparameter that controls the step size of the update. -- `∇J(θ;xi,yi)` is the gradient of the cost or loss function `J` with respect to the model parameter `θ`, computed based on a single training sample `(xi,yi)`. - -## Advantages - -- **Faster convergence:** SGD updates parameters more frequently hence it takes less time to converge especially for large datasets. -- **Reduced Computation Time:** SGD takes only a subset of dataset or batch for each update. This makes it easy to handle large datasets and compute faster. -- **Avoid Local Minima:** The noise introduced by updating parameters with individual data points or small batches can help escape local minima.This can potentially lead to better solutions in complex, non-convex optimization problems. -- **Online Learning:** SGD can be used in scenarios where data is arriving sequentially (online learning).- It allows models to be updated continuously as new data comes in. - -## Disadvantages - -- **Noisy Updates:** Updates are based on a single data point or small batch, which introduces variability in the gradient estimates.This noise can cause the algorithm to converge more slowly or oscillate around the optimal solution. -- **Convergence Issues:** The noisy updates can lead to less stable convergence and might make it harder to reach the exact minimum of the loss function.Fine-tuning the learning rate and other hyperparameters becomes crucial to achieving good results. -- **Hyperparameter Sensitivity:** - SGD's performance is sensitive to the choice of learning rate and other hyperparameters.Finding the right set of hyperparameters often requires experimentation and tuning. - -## Example - -The following code demonstrates **Stochastic Gradient Descent** (SGD) to fit a line to data points. Starting with initial guesses for the slope (`m`) and intercept (`b`), it updates these values iteratively by calculating the gradients of the **Mean Squared Error** (MSE) loss. The parameters are adjusted step-by-step based on the gradients, reducing the error between predicted and actual values: - -```python -import numpy as np - -# Data points (x, y) where the true line is y = 2x -x = np.array([1, 2, 3, 4, 5]) -y = np.array([2, 4, 6, 8, 10]) - -# Initial guess for parameters (slope, intercept) -params = np.array([0.0, 0.0]) - -# Learning rate and epochs -learning_rate = 0.01 -epochs = 1000 - -# Model: y = mx + b -def model(params, x): - m, b = params - return m * x + b - -# MSE loss function -def loss(pred, actual): - return np.mean((pred - actual) ** 2) # Using mean instead of sum - -# Compute gradients (partial derivatives) -def gradients(params, x, y): - m, b = params - pred = model(params, x) - grad_m = 2 * (pred - y) * x # Gradient for m - grad_b = 2 * (pred - y) # Gradient for b - return np.array([grad_m, grad_b]) - -# Training history -history = [] - -# SGD: Update parameters -for epoch in range(epochs): - total_loss = 0 - # Shuffle data - indices = np.random.permutation(len(x)) - x_shuffled = x[indices] - y_shuffled = y[indices] - - for i in range(len(x)): - # Forward pass - pred = model(params, x_shuffled[i]) - loss_value = loss(pred, y_shuffled[i]) - - # Compute gradients - grads = gradients(params, x_shuffled[i], y_shuffled[i]) - - # Update parameters - params -= learning_rate * grads - total_loss += loss_value - - # Store loss for plotting - avg_loss = total_loss / len(x) - history.append(avg_loss) - - if epoch % 100 == 0: # Print loss every 100 epochs - print(f"Epoch {epoch}, Loss: {avg_loss:.6f}") - -print(f"Final parameters: m = {params[0]:.4f}, b = {params[1]:.4f}") -``` - -The output of the code is as follows: - -```shell -Epoch 0, Loss: 22.414958 -Epoch 100, Loss: 0.001293 -Epoch 200, Loss: 0.000037 -Epoch 300, Loss: 0.000001 -Epoch 400, Loss: 0.000000 -Epoch 500, Loss: 0.000000 -Epoch 600, Loss: 0.000000 -Epoch 700, Loss: 0.000000 -Epoch 800, Loss: 0.000000 -Epoch 900, Loss: 0.000000 -Final parameters: m = 2.0000, b = 0.0000 -``` - -> **Note**: The output may vary depending on factors like the initial parameter values, learning rate, and number of epochs. - -## codebyte Example - -Here’s a Python code snippet demonstrating how to implement SGD for linear regression: - -```codebyte/python -import numpy as np - -# Generate synthetic data -np.random.seed(42) -X = 2 * np.random.rand(100, 1) -y = 4 + 3 * X + np.random.randn(100, 1) - -# Add a bias term (X0 = 1) to the input data -X_b = np.c_[np.ones((100, 1)), X] # Add a column of ones for the intercept term - -# Initialize parameters -m, n = X_b.shape -theta = np.random.randn(n, 1) # Initial weights -learning_rate = 0.01 -n_iterations = 1000 - -# Stochastic Gradient Descent function -def stochastic_gradient_descent(X, y, theta, learning_rate, n_iterations): - m = len(y) - for iteration in range(n_iterations): - # Shuffle the data - indices = np.random.permutation(m) - X_shuffled = X[indices] - y_shuffled = y[indices] - - # Update weights for each sample - for i in range(m): - xi = X_shuffled[i:i+1] - yi = y_shuffled[i:i+1] - gradient = 2 * xi.T.dot(xi.dot(theta) - yi) - theta -= learning_rate * gradient - - return theta - -# Perform SGD -theta_final = stochastic_gradient_descent(X_b, y, theta, learning_rate, n_iterations) - -print("Optimized weights:", theta_final) -``` diff --git a/content/ai/concepts/neural-networks/terms/vanishing-gradient/vanishing-gradient.md b/content/ai/concepts/neural-networks/terms/vanishing-gradient/vanishing-gradient.md deleted file mode 100644 index e4a4d1a3e85..00000000000 --- a/content/ai/concepts/neural-networks/terms/vanishing-gradient/vanishing-gradient.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -Title: 'Vanishing Gradient Problem' -Description: 'When gradients become very small during backpropagation, slowing or halting the training process.' -Subjects: - - 'AI' - - 'Data Science' -Tags: - - 'Machine Learning' - - 'Deep Learning' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -The **Vanishing gradient problem** occurs when gradients shrink as they move backward through a deep neural network. This causes slow or stalled training because updates to early layers become extremely small. It often appears in neural networks that use certain activation functions, such as sigmoid or hyperbolic tangent, or when the network has many layers. - -## How does it occur? - -- **Deep Architectures**: Deeper networks have more layers that can multiply small gradient values. -- **Sigmoid or Tanh Activations**: These functions squash input values into a narrow range, which can reduce gradient magnitude. -- **Poor Weight Initialization**: Wrong initial weight scales can cause gradients to vanish. - -## How to Fix It - -- **Use ReLU or Related Activations**: ReLU functions help avoid squashing the gradient in early layers. -- **Proper Initialization**: Techniques like Xavier or He initialization maintain stable gradients. -- **Batch Normalization**: Normalizing layer inputs can stabilize gradient flow. -- **Skip Connections**: Shortcut paths reduce the effective depth of the network. - -## Example: Demonstrating and Addressing the Vanishing Gradient Problem - -The following PyTorch example shows a simple deep network with sigmoid activation. The gradients in the earliest layers may become too small, slowing training. Switching to ReLU in the final code snippet provides a potential fix: - -```py -import torch -import torch.nn as nn -import torch.optim as optim - -# Deep feedforward network with Sigmoid -class DeepSigmoidNet(nn.Module): - def __init__(self): - super().__init__() - self.layers = nn.Sequential( - nn.Linear(100, 128), - nn.Sigmoid(), - nn.Linear(128, 128), - nn.Sigmoid(), - nn.Linear(128, 128), - nn.Sigmoid(), - nn.Linear(128, 10) - ) - - def forward(self, x): - return self.layers(x) - -# Create random data -x = torch.randn(32, 100) # batch of 32 -y = torch.randint(0, 10, (32,)) # target classes - -model = DeepSigmoidNet() -criterion = nn.CrossEntropyLoss() -optimizer = optim.SGD(model.parameters(), lr=0.01) - -# Forward pass -outputs = model(x) -loss = criterion(outputs, y) - -# Backward pass -loss.backward() - -# Check the gradient norm of the first layer -grad_norm = model.layers[0].weight.grad.norm().item() -print(f"Gradient norm (Sigmoid net, first layer): {grad_norm:.6f}") - -# Potential fix: Using ReLU -class DeepReLUNet(nn.Module): - def __init__(self): - super().__init__() - self.layers = nn.Sequential( - nn.Linear(100, 128), - nn.ReLU(), - nn.Linear(128, 128), - nn.ReLU(), - nn.Linear(128, 128), - nn.ReLU(), - nn.Linear(128, 10) - ) - - def forward(self, x): - return self.layers(x) - -model_relu = DeepReLUNet() -optimizer = optim.SGD(model_relu.parameters(), lr=0.01) - -outputs_relu = model_relu(x) -loss_relu = criterion(outputs_relu, y) - -loss_relu.backward() -grad_norm_relu = model_relu.layers[0].weight.grad.norm().item() -print(f"Gradient norm (ReLU net, first layer): {grad_norm_relu:.6f}") -``` - -The above code returns the following output: - -```shell -Gradient norm (Sigmoid net, first layer): 0.004324 -Gradient norm (ReLU net, first layer): 0.118170 -``` - -1. **DeepSigmoidNet**: A fully connected network with multiple layers of sigmoid activation. The gradient often shrinks as it propagates back through each layer. -2. **Gradient Norm**: The code checks the gradient norm of the first layer. A very small value suggests that those parameters receive negligible updates. -3. **DeepReLUNet**: Switching to ReLU reduces the vanishing effect, which can be seen in the larger gradient norm for the first layer. - -Using suitable activations, initialization, or techniques like batch normalization and skip connections makes the vanishing gradient problem less severe, making training faster and more reliable. diff --git a/content/ai/concepts/prompt-engineering/prompt-engineering.md b/content/ai/concepts/prompt-engineering/prompt-engineering.md deleted file mode 100644 index 8f45dffcd92..00000000000 --- a/content/ai/concepts/prompt-engineering/prompt-engineering.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -Title: 'Prompt Engineering' -Description: 'Prompt Engineering is the study and implementation of prompts which are used to instruct an Artificial Intelligence (AI) into completing a specific task.' # Required; ideally under 150 characters and starts with a noun (used in search engine results and content previews) -Subjects: # Please only use Subjects in the subjects.md file (https://github.com/Codecademy/docs/blob/main/documentation/subjects.md). If that list feels insufficient, feel free to create a new Subject and add it to subjects.md in your PR! - - 'Machine Learning' - - 'Large Language Model' -Tags: # Please only use Tags in the tags.md file (https://github.com/Codecademy/docs/blob/main/documentation/tags.md). If that list feels insufficient, feel free to create a new Tag and add it to tags.md in your PR! - - 'AI' - - 'Machine Learning' - - 'Prompts' - - 'Prompt Engineering' -CatalogContent: # Please use course/path landing page slugs, rather than linking to individual content items. If listing multiple items, please put the most relevant one first - - 'intro-to-chatgpt' - - 'paths/data-science' ---- - -**Prompt Engineering** is the technique of crafting instructions that will be provided to a Large Language Model (LLM) used in Artificial Intelligence (AI) systems. - -Large Language Models (LLMs) are typically trained with large amounts of data that is used to answer a prompt. As a result, when an AI is given a task, it uses all of the training data to complete the task even if the task does not require much data. This introduces a handful of issues such as hallucinations, or possibly using data that is irrelevant to completing the task. Prompt Engineering allows users to clearly define which of the training data the AI should use to complete a task. - -## General Tips to Writing a Good Prompt - -### Use Clear Language - -When creating a prompt, it is important to be precise, yet concise in our instruction. There are several benefits when following this strategy, one of which is the AI can achieve it's task in an efficient manner without additional intervention. In addition, there is typically a monetary cost associated when interacting with an LLM. Therefore prompting an LLM with the least amount of words can provide immediate benefits in terms of upfront cost. Understanding the cost associated with prompting an AI requires a basic knowledge of LLMs. - -When an LLM is given a body of text it typically breaks this text into individual units or "tokens," the base unit of information that is being sent to the LLM. You can think of a word as a token. Additional information about tokens can be found in [OpenAI's help docs](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them). It then processes these tokens in order to generate an answer. This computation comes at a cost and is the reason why companies charge a certain amount of dollars per token, particularly when these tokens are being sent through some sort of API request. In these situations, having clear language can not only save money, but also directly affect the performance of the LLM. - -One example of using unclear language could be the following: - -``` -Explain the concept of for loops in Javascript. Keep your explanation short, and do not be too descriptive. -``` - -In this example, there is too much ambiguity for an LLM. For example, there is no guidance on what "short" means, and "not be too descriptive" could have two meanings. To fix this, do not use too many words or provide a description that is easy to understand. A better prompt would be the following: - -``` -Use 2 to 3 sentences to explain the concept of for loops in Javascript to a 5 year old. -``` - -### Define Your Purpose - -Another key to writing effective prompts is defining the purpose of the prompt. In other words, effectively defining the goal for the LLM to achieve. This can be done by specifying the tone, format, and audience of the prompt.One area in which tone is important, is writing an email. For example, a different tone would be used when writing an email to a sibling, versus one to someone's boss. Therefore, when asking an LLM to write a draft of an email, it is important to make sure it understands what tone is preferred. In addition to specifying the tone, we can also specify the format of the LLM's response. In some situations, it can be specified that the LLM use a bullet list, versus a series of paragraphs.Finally, by specifying a possible audience, an LLM can even be more precise when generating an email. For instance, an LLM will most likely provide additional details when writing an email in a professional tone versus a casual tone. - -### Provide Context - -As mentioned earlier, LLMs are trained using vast amounts of data, which is used to effectively craft responses to a prompt. One way to indirectly control what data an LLM uses in its response, is by clearly defining the context of the prompt. Defining context indicates to the LLM what training data it should use to formulate a response. - -A common case in which context is important is when asking an LLM to debug an error message when writing code. For example, when encountering a specific error associated with a line of code, a good prompt would be the following. - -``` -I'm encountering an error in my code. Given the error message, and the following block of code, can you help me find a solution? - -Here is the error message: -x -Here is the block of code: -y -``` - -Keep in mind `x` and `y` are just place holders. When using this prompt, the relevant information should be provided. - -## Prompt Examples - -Here are some examples that implement some of the concepts mentioned above: - -``` -Act as a Spanish language tutor. I am new to learning Spanish. - -Provide me with 20 must know phrases in Spanish. - -Provide translation and pronunciation instructions. -``` - -In this instance, we are giving the LLM purpose by defining the familiarity with Spanish. The LLM will now craft a response knowing that it's audience is new to Spanish. - -``` -Imagine yourself as a teacher and I'm your student. You have to explain the topic that I'll ask and then quiz me with your own questions. For example: - -You: Binary addition of two bits is done with two operators - AND and XOR. When adding two bits, the output's most significant bit is set to 1 if both bits are 1, and the least significant bit is set to 1 if either bit, but not both, are 1. For example: 0b1 + 0b1 = 0b10, 0b0 + 0b1 = 0b01. Is everything clear? -Me: Yes. -You: Excellent. Solve the following examples: 0b0 + 0b0, 0b1 + 0b0 -Me: 0b0 + 0b0 = 0b01, 0b1 + 0b0 = 0b01 -You: No, 0b0 + 0b0 = 0b00 because both input bits are zeros. -Me: Oh, I see... - -And here are a few commands: -!difficulty (number) - sets the difficulty level of the problems. 0-100. The higher the difficulty, the harder the problems. -!hint (example) - asks for a hint, but not the answer. Ideally, you should guide me in the right direction rather than explain everything. -!topic (topic) - changes the "lesson" topic and forgets everything that was before. -!help - displays this list of commands and chat description. - -If you understood everything, write "OK" and nothing else. -``` - -This example is a little more advanced, but shows how an LLM can be an efficient solution. This prompt has built in commands in which we can adjust the context of the conversation dynamically. - -This prompt also shows how the LLM can be trained to respond with a specific format. diff --git a/content/ai/concepts/search-algorithms/search-algorithms.md b/content/ai/concepts/search-algorithms/search-algorithms.md deleted file mode 100644 index 1402d36d97c..00000000000 --- a/content/ai/concepts/search-algorithms/search-algorithms.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -Title: 'Search Algorithms' -Description: 'Search algorithms are a class of algorithms used to find an optimal solution to a problem by exploring a search space.' -Subjects: - - 'Machine Learning' - - 'Computer Science' -Tags: - - 'AI' - - 'Algorithms' - - 'Graphs' - - 'Graph Search' -CatalogContent: - - 'paths/data-science' ---- - -A **search algorithm** is a type of algorithm used in artificial intelligence to find the best or most optimal solution to a problem by exploring a set of possible solutions, also called a search space. A search algorithm filters through a large number of possibilities to find a solution that works best for a given set of constraints. - -Search algorithms typically operate by organizing the search space into a particular type of graph, commonly a tree, and evaluate the best score, or cost, of traversing each branch of the tree. A solution is a path from the start state to the goal state that optimizes the cost given the parameters of the implemented algorithm. - -Search algorithms are typically organized into two categories: - -- Uninformed Search: Algorithms that are general purpose traversals of the state space or search tree without any information about how good a state is. These are also referred to as blind search algorithms. - -- Informed Search: Algorithms that have information about the goal during the traversal, allowing the search to prioritize its expansion toward the goal state instead of exploring directions that may yield a favorable cost but don't lead to the goal, or global optimum. By including extra rules that aid in estimating the location of the goal (known as heuristics) informed search algorithms can be more computationally efficient when searching for a path to the goal state. - -## Types of Search Algorithms - -There are many types of search algorithms used in artificial intelligence, each with their own strengths and weaknesses. Some of the most common types of search algorithms include: - -### Depth-First Search (DFS) - -This algorithm explores as far as possible along each branch before backtracking. DFS is often used in combination with other search algorithms, such as iterative deepening search, to find the optimal solution. Think of DFS as a traversal pattern that focuses on digging as deep as possible before exploring other paths. - -### Breadth-First Search (BFS) - -This algorithm explores all the neighbor nodes at the current level before moving on to the nodes at the next level. Think of BFS as a traversal pattern that tries to explore broadly across many different paths at the same time. - -### Uniform Cost Search (UCS) - -This algorithm expands the lowest cumulative cost from the start, continuing to explore all possible paths in order of increasing cost. UCS is guaranteed to find the optimal path between the start and goal nodes, as long as the cost of each edge is non-negative. However, it can be computationally expensive when exploring a large search space, as it explores all possible paths in order of increasing cost. - -### Heuristic Search - -This algorithm uses a heuristic function to guide the search towards the optimal solution. A\* search, one of the most popular heuristic search algorithms, uses both the actual cost of getting to a node and an estimate of the cost to reach the goal from that node. - -## Application of Search Algorithms - -Search algorithms are used in various fields of artificial intelligence, including: - -### Pathfinding - -Pathfinding problems involve finding the shortest path between two points in a given graph or network. BFS or A\* search can be used to explore a graph and find the optimal path. - -### Optimization - -In optimization problems, the goal is to find the minimum or maximum value of a function, subject to some constraints. Search algorithms such as hill climbing or simulated annealing are often used in optimization cases. - -### Game Playing - -In game playing, search algorithms are used to evaluate all possible moves and choose the one that is most likely to lead to a win, or the best possible outcome. This is done by constructing a search tree where each node represents a game state and the edges represent the moves that can be taken to reach the associated new game state. - -The following algorithms have dedicated, more in-depth content: diff --git a/content/ai/concepts/search-algorithms/terms/a-star-search/a-star-search.md b/content/ai/concepts/search-algorithms/terms/a-star-search/a-star-search.md deleted file mode 100644 index f1d7e46eb5c..00000000000 --- a/content/ai/concepts/search-algorithms/terms/a-star-search/a-star-search.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -Title: 'A* Search' -Description: 'An informed graph searching algorithm that efficiently determines a path between nodes based on an evaluation function.' -Subjects: - - 'Data Science' - - 'AI' -Tags: - - 'Search Algorithms' - - 'AI' -CatalogContent: - - 'learn-python-3' - - 'paths/machine-learning-ai-engineering-foundations' ---- - -**A\* Search** is an informed [best-first search algorithm](https://www.codecademy.com/resources/docs/ai/search-algorithms/best-first-search) that efficiently determines the lowest cost path between any two nodes in a directed weighted graph with non-negative edge weights. This algorithm is a variant of Dijkstra's algorithm. A slight difference arises from the fact that an evaluation function is used to determine which node to explore next. - -## Evaluation Function - -The evaluation function, **f(x)**, for the A\* search algorithm is the following: - -```pseudo -f(x) = g(x) + h(x) -``` - -Where **g(x)** represents the cost to get to node **x** and **h(x)** represents the estimated cost to arrive at the goal node from node **x**. - -For the algorithm to generate the correct result, the evaluation function must be **admissible**, meaning that it never overestimates the cost to arrive at the goal node. - -## The Algorithm - -The A\* algorithm is implemented in a similar way to Dijkstra's algorithm. Given a weighted graph with non-negative edge weights, to find the lowest-cost path from a start node **S** to a goal node **G**, two lists are used: - -- An **open list**, implemented as a priority queue, which stores the next nodes to be explored. Because this is a priority queue, the most promising candidate node (the one with the lowest value from the evaluation function) is always at the top. Initially, the only node in this list is the start node **S**. -- A **closed list** which stores the nodes that have already been evaluated. When a node is in the closed list, it means that the lowest-cost path to that node has been found. - -To find the lowest cost path, a search tree is constructed in the following way: - -1. Initialize a tree with the root node being the start node **S**. -2. Remove the top node from the open list for exploration. -3. Add the current node to the closed list. -4. Add all nodes that have an incoming edge from the current node as child nodes in the tree. -5. Update the lowest cost to reach the child node. -6. Compute the evaluation function for every child node and add them to the open list. - -Just like in Dijkstra's algorithm, the lowest cost is updated as the algorithm progresses in the following way: - -```pseudo -current_lowest_cost = min(current_lowest_cost, parent_node_cost + edge_weight) -``` - -All nodes except for the start node start with a lowest cost of infinity. The start node has an initial lowest cost of 0. - -The algorithm concludes when the goal node **G** is removed from the open list and explored, indicating that a shortest path has been found. The shortest path is the path from the start node **S** to the goal node **G** in the tree. - -> Note: The algorithm ends when the goal node **G** has been explored, NOT when it is added to the open list. - -## Example - -Consider the following example of trying to find the shortest path from **S** to **G** in the following graph: - -![Example Graph](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-example-graph_corrected.png) - -Each edge has an associated weight, and each node has a heuristic cost (in parentheses). - -An open list is maintained in which the node **S** is the only node in the list. The search tree can now be constructed. - -Exploring **S**: - -![a-star-1](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-tree-1.png) - -**A** is the current most promising path, so it is explored next: - -![a-star-2](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-tree-2.png) - -Exploring **D**: - -![a-star-3](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-tree-3.png) - -Exploring **F**: - -![a-star-4](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-tree-4.png) - -Notice that the goal node **G** has been found. However, it hasn't been explored, so the algorithm continues because there may be a shorter path to G. The node **B** has two entries in the open list: one at a cost of 16 (child of **S**) and one at a cost of 18 (child of **A**). The one with the lowest cost is explored next: - -![a-star-5](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-tree-5.png) - -Exploring **C**: - -![a-star-6](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-tree-6.png) - -The next node in the open list is again **B**. However, because **B** has already been explored, meaning the shortest path to **B** has been found, it is not explored again, and the algorithm continues to the next candidate. - -![a-star-7](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-tree-7.png) - -The next node to be explored is the goal node **G**, meaning the shortest path to **G** has been found! The path is constructed by tracing the graph backwards from **G** to **S**: - -![a-star-8](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-tree-8.png) - -## Using the A\* Algorithm - -This algorithm is guaranteed to find the shortest path if one exists. One of the main uses of this algorithm is route planning, but there are many other uses. - -## Example Code - -Here is an example of the A\* algorithm implemented in Python that solves the above example graph: - -```py -from heapq import heappop, heappush - -def a_star_search(graph: dict, start: str, goal: str, heuristic_values: dict) -> int: - ''' - A* search algorithm implementation. - - @param graph: The graph to search. - @param start: The starting node. - @param goal: The goal node. - @param heuristic_values: The heuristic values for each node. The goal node must be admissible, and the heuristic value must be 0. - @return: The path cost from the start node to the goal node. - ''' - - # A min heap is used to implement the priority queue for the open list. - # The heapq module from Python's standard library is utilized. - # Entries in the heap are tuples of the form (cost, node), ensuring that the entry with the lowest cost is always smaller during comparisons. - # The heapify operation is not required, as the heapq module maintains the heap invariant after every push and pop operation. - - # The closed list is implemented as a set for efficient membership checking. - - open_list, closed_list = [(heuristic_values[start], start)], set() - - while open_list: - cost, node = heappop(open_list) - - # The algorithm ends when the goal node has been explored, NOT when it is added to the open list. - if node == goal: - return cost - - if node in closed_list: - continue - - closed_list.add(node) - - # Subtract the heuristic value as it was overcounted. - cost -= heuristic_values[node] - - for neighbor, edge_cost in graph[node]: - if neighbor in closed_list: - continue - - # f(x) = g(x) + h(x), where g(x) is the path cost and h(x) is the heuristic. - neighbor_cost = cost + edge_cost + heuristic_values[neighbor] - heappush(open_list, (neighbor_cost, neighbor)) - - return -1 # No path found - -EXAMPLE_GRAPH = { - 'S': [('A', 4), ('B', 10), ('C', 11)], - 'A': [('B', 8), ('D', 5)], - 'B': [('D', 15)], - 'C': [('D', 8), ('E', 20), ('F', 2)], - 'D': [('F', 1), ('I', 20), ('H', 16)], - 'E': [('G', 19)], - 'F': [('G', 13)], - 'H': [('J', 2), ('I', 1)], - 'I': [('K', 13), ('G', 5), ('J', 5)], - 'J': [('K', 7)], - 'K': [('G', 16)] -} - -# Node heuristic values (admissible heuristic values for the nodes) -EXAMPLE_HEURISTIC_VALUES = { - 'S': 7, - 'A': 8, - 'B': 6, - 'C': 5, - 'D': 5, - 'E': 3, - 'F': 3, - 'G': 0, - 'H': 7, - 'I': 4, - 'J': 5, - 'K': 3 -} - -EXAMPLE_RESULT = a_star_search(EXAMPLE_GRAPH, 'S', 'G', EXAMPLE_HEURISTIC_VALUES) -print(EXAMPLE_RESULT) -``` - -The code above produces the following output: - -```shell -23 -``` - -## Complexity Analysis - -For time complexity, one might notice that each heappush corresponds to an edge, which would be the dominating complexity for most cases. Indeed, A\* is equivalent to Dijkstra's algorithm when the heuristic function is 0, and A\* is equivalent to Dijkstra's algorithm with reduced cost when the heuristic function is admissible i.e. `O(V+Elog(V))` time complexity. - -However, a good heuristic function can drastically decrease A*'s complexity. The idea here is we need to look at exponentially fewer nodes with a better heuristic. So the time and space complexity are actually `O(b1^d)`, where b1 is the effective branching factor, i.e., an empirical average of neighboring nodes not in the closed list, and d is the search depth, i.e., optimal path length. The large space complexity is the biggest disadvantage of the A* search, giving rise to other algorithm variations. diff --git a/content/ai/concepts/search-algorithms/terms/beam-search/beam-search.md b/content/ai/concepts/search-algorithms/terms/beam-search/beam-search.md deleted file mode 100644 index 4ca80dc1e24..00000000000 --- a/content/ai/concepts/search-algorithms/terms/beam-search/beam-search.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -Title: 'BEAM Search' -Description: 'A graph searching algorithm that is a variant of breadth-first search.' -Subjects: - - 'Data Science' - - 'AI' -Tags: - - 'Search Algorithms' - - 'AI' -CatalogContent: - - 'learn-python-3' - - 'paths/machine-learning-ai-engineering-foundations' ---- - -**BEAM Search**, a variant of [breadth-first Search](https://www.codecademy.com/resources/docs/ai/search-algorithms/breadth-first-search), is an algorithm that searches a weighted graph for an optimal path from some start node **S** to some goal node **G**. The difference between BEAM search and breadth-first search is that at every level of the search tree, only the top _β_ candidates are chosen for further exploration. Here, β is known as the _beam width_. The reasoning behind this is that a path from **S** to **G** is likely to pass through some top number of most promising nodes. This leads to an algorithm that is fast and memory-efficient because it can disregard many nodes that may appear to be too far from the goal. This, however, sometimes causes the algorithm to overlook a potential shortest path because a candidate node is greater than the beam width. This renders the algorithm as _incomplete_, meaning that finding the shortest path is not guaranteed. Since the algorithm can find a reasonably short path, trading completeness for efficiency is accepted. Much like [A\* search](https://www.codecademy.com/resources/docs/ai/search-algorithms/a-star-search) and [best-first search](https://www.codecademy.com/resources/docs/ai/search-algorithms/best-first-search), an evaluation function is used to evaluate the candidacy of nodes for further exploration. - -## The Algorithm - -Similar to A\* search, the algorithm uses an **open list** and a **closed list** for the exploration of nodes. In this algorithm, the open list is an ordinary queue. The algorithm begins with a start node **S**, which also serves as the root node for the search tree. - -1. Initialize a search tree with the root node being the start node **S**. This is level zero in the tree. -2. Add **S** to the closed list and evaluate all nodes adjacent to **S**. -3. Select the top β nodes and add them as child nodes to **S** in the tree. Disregard all other nodes. -4. Add the selected nodes to the **open list** for further exploration. -5. Remove all nodes in the **open list**. Once a node is removed from the **open list** for exploration, add it to the **closed list**. -6. Evaluate all adjacent nodes and sort them according to the evaluation function. -7. Select the top β nodes and add them to the tree, connecting them to their respective parent nodes. -8. Repeat this process until the goal node **G** is removed from the open list, indicating that a path has been found. - -It is important to note that every level of the search tree contains at most β number of nodes. - -## Example - -Consider the following example of searching a graph from **S** to **G**. For simplicity, only the edge weights will be used for evaluation. A beam width of β = 2 will be used, meaning only the top two nodes are considered at every level. - -![Example-graph](https://raw.githubusercontent.com/Codecademy/docs/main/media/BEAM-Search-example-graph.png) - -Initialize the tree and add **S** to the **closed list**: - -![BEAM-Search-1](https://raw.githubusercontent.com/Codecademy/docs/main/media/BEAM-Search-Tree-1.png) - -**S** only has one adjacent node, so it is added to the tree: - -![BEAM-Search-2](https://raw.githubusercontent.com/Codecademy/docs/main/media/BEAM-Search-Tree-2.png) - -Explore **I**. Nodes **N** and **H** are the top two nodes, so those are added to the tree: -![BEAM-Search-3](https://raw.githubusercontent.com/Codecademy/docs/main/media/BEAM-Search-Tree-3.png) - -Nodes **F** (adjacent to **H** in the graph) and **L** (adjacent to **N** in the graph) are next: -![BEAM-Search-4](https://raw.githubusercontent.com/Codecademy/docs/main/media/BEAM-Search-Tree-4.png) - -The incompleteness of this algorithm can be seen in this step. Node **G** has appeared in the **open list** but unfortunately, it has been eliminated by the beam width. Nodes **M** and **C** are next: -![BEAM-Search-5](https://raw.githubusercontent.com/Codecademy/docs/main/media/BEAM-Search-Tree-5.png) - -It is in this step that node **G** has been found: -![BEAM-Search-6](https://raw.githubusercontent.com/Codecademy/docs/main/media/BEAM-Search-Tree-6.png) - -Trace the path from **S** to **G**: -![Final-path](https://raw.githubusercontent.com/Codecademy/docs/main/media/BEAM-Search-final-path.png) - -## Advantages and Disadvantages - -As stated before, the advantage of BEAM search is that it is efficient both in time and memory. The disadvantage can be seen from the example in that a possible shortest path from **S** to **G** was overlooked. This can be somewhat corrected by varying the beam width to include more nodes. This, however, would reduce the efficiency of the algorithm. Selecting the optimal beam width is problem-specific and usually requires further insight into the problem. - -## Applications of BEAM Search - -The BEAM search algorithm is commonly used in natural language processing and machine translation. An encoder is used to process the text from the source language and BEAM search selects the most probable words (the beam width) in the target language. The evaluation function in this context is the conditional probability of a word in the target language. diff --git a/content/ai/concepts/search-algorithms/terms/best-first-search/best-first-search.md b/content/ai/concepts/search-algorithms/terms/best-first-search/best-first-search.md deleted file mode 100644 index 059a76593a6..00000000000 --- a/content/ai/concepts/search-algorithms/terms/best-first-search/best-first-search.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -Title: 'Best-First Search' -Description: 'A graph searching algorithm that determines a path between nodes based on an evaluation function.' -Subjects: - - 'Data Science' - - 'AI' -Tags: - - 'Search Algorithms' - - 'AI' -CatalogContent: - - 'learn-python-3' - - 'paths/machine-learning-ai-engineering-foundations' ---- - -**Best-first search** is a class of search algorithms that explores a graph (the graph can be weighted or unweighted) for a path from some start node to a goal node. These algorithms are known as informed search algorithms, meaning that they incorporate information regarding the location of the goal node relative to any other node. This information is quantified by an evaluation function denoted by _f(x)_. In a weighted graph, the evaluation function can combine information regarding the edge weights and some heuristic function, _h(x)_, that represents a measure from a node (_x_ in this case) to the goal node. When searching for the goal node, a BFS algorithm (not to be confused with breadth-first search) selects the node with the most promising value determined by the evaluation function. - -## Evaluation Function - -An evaluation function estimates the cost to reach the goal node from the current node. For example, consider the case of a robot having to navigate from point A (start state) to point B (goal state) in a room containing obstacles and obstructions. The robot can move one unit of length in the forward direction, backward direction, to the right, or to the left. The robot wishes to reach point B in the shortest possible time. What should the robot do? In this case, an evaluation function is defined as the straight-line distance (Euclidean distance) from any point in the room to point B ignoring all obstructions. The next position the robot chooses to move to will be the one with the shortest distance to point B. However, if there is an obstruction preventing this move, the robot will choose to move to the second-best position in the room. And if there is an obstruction there, the third-best and so on. - -In a weighted graph, the total cost from the start node to the goal node is the sum of the cost of every visited edge along the path. The values from the evaluation function do not contribute to the total cost. They are only there to guide the search. - -## Best-First Search Algorithms - -The following is a list of Best-First search algorithms. - -- Greedy Best-First Search: A search algorithm where the evaluation function is strictly equal to the heuristic function, disregarding the edge weights in a weighted graph. -- A\* Search: A search algorithm where the evaluation function takes into account the edge weights as well as the heuristic measure. -- BEAM Search: A search algorithm where, in a weighted graph, only the _n_ (in this case, _n_ is known as the beam width) most promising nodes are considered for further exploration. diff --git a/content/ai/concepts/search-algorithms/terms/breadth-first-search/breadth-first-search.md b/content/ai/concepts/search-algorithms/terms/breadth-first-search/breadth-first-search.md deleted file mode 100644 index a49fd165668..00000000000 --- a/content/ai/concepts/search-algorithms/terms/breadth-first-search/breadth-first-search.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -Title: 'Breadth-First Search' -Description: 'A shortest-path and traversing algorithm for unweighted graphs.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Graphs' - - 'Graph Search' - - 'Algorithms' -CatalogContent: - - 'learn-python' - - 'paths/computer-science' ---- - -**Breadth-first search (BFS)** is a traversing algorithm for unweighted graphs. This is a foundational algorithm in [graph](https://www.codecademy.com/resources/docs/general/graph) theory from which many other algorithms start. - -## Features - -Some of the features and constraints that define the use and functionality of a breadth-first search algorithm include the following: - -- A relatively simple and efficient algorithm for finding the shortest-path in graphs that do not have edge weights. -- It has a time complexity of **O(|V| + |E|)**, which is the sum of the vertices and edges. -- In addition to finding the shortest path between two nodes, this algorithm can be used to map or traverse a graph to find all connections or if a given path exists between any pair of nodes. - -## Implementation - -The example below walks through a basic implementation of BFS that will take a starting node, an end node, and a graph as arguments. However, to start, a brief overview of the necessary steps or pseudocode will serve as an outline for the final implementation. - -The BFS algorithm is built upon a simple process of elimination. It begins with the selection of a node and the identification of all the neighboring nodes. The algorithm iterates through these basic steps until all nodes have been evaluated (or another objective has been achieved). Through this process, the graph is explored in a layered approach where each node at a given level (or degree) is evaluated before moving on to the next. Implicitly, a search employing this process will yield the shortest path between any two nodes. - -As noted in the description above, the BFS process is an iterative one. The implementation commonly revolves around adding and removing nodes as their evaluated from a queue. - -The implementation below can be broken down into the following steps: - -- A list is initialized with the starting node, and nodes will be added to and removed from this list in a queue-like manner. -- Another list is initialized for tracking nodes that have already been processed. -- A variable is initialized for tracking the path (the sequence of nodes from the source to the final node). -- A variable is initialized to represent the current node being evaluated (the last item in the path). -- A loop is set to iterate over items in the list/queue. -- The process starts in earnest by iterating over all edge-pairs to identify the starting node. -- If the starting node is present in an edge-pair, as the source or destination, then the accompanying (neighboring) node is added to the `neighbors` list. -- Once all the neighbors have been collected, another loop iterates over this list. -- A second variable for updating the path (`curr_path`) is instantiated. This variable is the sum of the existing steps in addition to the current node. -- Each neighbor is tested. If it matches the destination node, the search is complete and `curr_path` is returned. -- If the neighbor is not a match, the path is added to the queue. -- Once all the neighbors have been exhausted, the `curr_node` is added to the tested nodes list. Now, the process starts again from the top with the next path in the queue. -- The loop iterates until the queue is empty or until a path is returned. -- If all the nodes are processed and there is no path, an empty list is returned. - -## Example - -The example below generates a random graph and solves the shortest path between two nodes. For the sake of succinctness, the example below leverages the Python library, `networkx`, for generating a random graph. This library is available by default within [Google Colaboratory](https://colab.research.google.com) and can serve as a convenient environment for reproducing this example. - -```python -# Imports and graph setup -import networkx as nx -from matplotlib import pyplot as plt -plt.rcParams["figure.figsize"] = (10,10) - -# Generating a random graph -G = nx.random_graphs.fast_gnp_random_graph(12, 0.4, seed=15) - -# Displaying the graph -def draw_graph(G): - pos = nx.spring_layout(G) - nx.draw_networkx_nodes(G, pos, node_size=500, alpha=0.5) - nx.draw_networkx_labels(G, pos) - nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5) - -draw_graph(G) -``` - -This will yield the following output: - -![Output of draw_graph function](https://raw.githubusercontent.com/Codecademy/docs/main/media/networkx-graph-example.png) - -Finally, the BFS code is as follows: - -```python -# The function implementing the BFS algorithm -def get_shortest_path(graph_data, node_one, node_two): - node_q = [[node_one]] - tested_nodes = [] - - while node_q: - path = node_q.pop(0) - curr_node = path[-1] - - if curr_node not in tested_nodes: - neighbors = [] - - for pair in list(graph_data.edges): # The edges attribute provides a list of tuples containing all edge pairs - if curr_node in pair: - neighbors.append(pair[0]) if pair[0] != curr_node else neighbors.append(pair[1]) - - for n in neighbors: - - curr_path = path + [n] - if n == node_two: - return curr_path - - node_q.append(curr_path) - - tested_nodes.append(curr_node) - - return [] - -# Testing the BFS function -get_shortest_path(G,2,10) -``` - -Which will yield: - -```shell -[2, 0, 5, 10] -``` diff --git a/content/ai/concepts/search-algorithms/terms/depth-first-search/depth-first-search.md b/content/ai/concepts/search-algorithms/terms/depth-first-search/depth-first-search.md deleted file mode 100644 index dae5de7ccd8..00000000000 --- a/content/ai/concepts/search-algorithms/terms/depth-first-search/depth-first-search.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -Title: 'Depth-First Search' -Description: 'A traversing algorithm for unweighted graphs.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Graphs' - - 'Graph Search' - - 'Algorithms' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -**Depth-first search (DFS)** is a traversing algorithm for unweighted graphs.Like BFS (Breadth-first search), it is a foundational algorithm in [graph](https://www.codecademy.com/resources/docs/general/graph) theory from which many other algorithms begin. - -## Features - -Some of the features and constraints that define the use and functionality of the DFS algorithm include the following: - -- DFS traverses a graph by following a given path as far as possible. Once a dead end is reached, the algorithm backtracks to explore the most recent unvisited neighbours. A stack is used to retrieve the next vertex, to restart a search, when a dead end is found in any given iteration. -- It is a relatively simple algorithm that can be built upon for finding cycles within a graph, to conduct a topological sort of vertices, as well as a range of other useful applications. -- It has a time complexity of **O(|V| + |E|)**, which is the sum of the vertices and edges. -- It finds a solution, a path between vertices, but it may or may not be optimal one as in BFS. -- A disadvantage of DFS is that it may get stuck in infinite loop if the depth is infinite. - -## Implementation - -The example below walks through a basic implementation of DFS that will take a starting node, an end node, and a graph as arguments. The algorithm will return the path it navigated between starting and end node provided. - -The DFS algorithm starts with the initial node of graph `G` and goes deeper until it finds the goal node or a node with no children. -Because of the recursive nature of the traversal process, a stack data structure can be used to implement the DFS algorithm. - -The implementation below can be broken down into the following steps: - -1. First, initiate a stack with the starting vertex for the traversal. -2. Pop from the stack and set this vertex as the "current" element or node. -3. Now, find the neighboring vertexes (of the current node), and if they haven't been visited push them into the stack. -4. If no unvisited vertexes remain, go back and pop a vertex from the stack. -5. Repeat steps 2, 3, and 4 until the stack is empty. - -## Example - -![Depth-First Search example](https://raw.githubusercontent.com/Codecademy/docs/main/media/Depth-First-Search-Example.png) - -The following is an implementation in Python: - -```python -# The visited variable keeps a record of the nodes explored -def dfs(graph,start,goal,stack,visited): - stack.append(start) - visited.append(start) - print('The path traversed is:') - while stack: - # Pop from stack to set current element - element=stack.pop() - print(element,end=" ") - if(element==goal): - break - for neighbor in graph[element]: - if neighbor not in visited: - stack.append(neighbor) - visited.append(neighbor) -# A dictionary representing the illustrated graph -graph={ - 'A':['C','B'], - 'B':['E','D'], - 'C':['G','F'], - 'D':[], - 'E':['I','H'], - 'F':[], - 'G':['J'], - 'H':[], - 'I':[], - 'J':[] -} -start='A' -goal='J' -visited=[] -stack=[] - -dfs(graph,start,goal,visited,stack) -``` - -```shell -The path traversed is: -A B D E H I C F G J -``` diff --git a/content/ai/concepts/search-algorithms/terms/gradient-descent/gradient-descent.md b/content/ai/concepts/search-algorithms/terms/gradient-descent/gradient-descent.md deleted file mode 100644 index aeaab5fe404..00000000000 --- a/content/ai/concepts/search-algorithms/terms/gradient-descent/gradient-descent.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -Title: 'Gradient Descent' -Description: 'Gradient descent is an optimization search algorithm that is widely used in machine learning to train neural networks and other models.' -Subjects: - - 'Data Science' - - 'AI' -Tags: - - 'Search' - - 'Algorithms' - - 'AI' -CatalogContent: - - 'learn-python-3' - - 'paths/machine-learning-ai-engineering-foundations' ---- - -**Gradient descent** is an optimization search [algorithm](https://www.codecademy.com/resources/docs/general/algorithm) that is widely used in [machine learning](https://www.codecademy.com/resources/docs/ai/machine-learning) to train neural networks and other models. It is a fundamental optimization algorithm that is used in many fields of [artificial intelligence](https://www.codecademy.com/resources/docs/ai), such as natural language processing, computer vision, and robotics. - -## How Does Gradient Descent Work? - -Gradient descent works by minimizing the cost (or loss) function of a model. Cost functions measure the performance of machine learning models by quantifying the difference between the predicted and actual outputs. A low cost function indicates that a model is performing well on the training data because its predicted output values are close to the actual output values. - -Gradient descent is an iterative optimization algorithm, which means that it iteratively, or repeatedly, updates the parameters of a model until a specific outcome is achieved. Parameters can be thought of as the “settings” for a machine learning model. The purpose of gradient descent is to iterate until the local or global minimum is found in a given solution space or “local neighborhood." The “gradient” refers to the rate of change, or slope, of the cost function. Thus, a gradient descent algorithm iteratively moves down (descends) the gradient (slope of the cost function) to find the minimum point, which represents the optimal values (the best performance) for the model in the given context. - -In each iteration of the algorithm, the following steps are performed: - -1. Compute the gradient: The gradient is computed to determine the direction of steepest descent of the cost function, guiding the algorithm towards the minimum. -2. Update parameters: Based on the calculated gradient, the algorithm updates the model's parameters. The magnitude of these updates is determined by the learning rate, which is a specified value chosen by the data scientist/engineer that controls the step size. -3. Calculate the cost function: The cost function is recalculated using the updated parameters, providing a measure of how well the model is currently performing. - -These steps are repeated iteratively until a stopping criterion is met, such as reaching a maximum number of iterations or achieving a desired level of convergence. The number of iterations and the convergence criterion are typically set by the data scientist/engineer implementing the gradient descent algorithm. - -## Gradient Descent and Machine Learning - -Gradient descent is a fundamental optimization algorithm widely used in machine learning. An advantage of gradient descent is its ability to handle models with a large number of parameters, making it suitable for complex machine learning tasks. It is especially valuable when dealing with non-linear data, where patterns and relationships are not easily captured by simple linear models. - -Gradient descent is a simple, efficient, and flexible algorithm that can be scaled to multiple different machine learning tasks and datasets with large amounts of data. By leveraging computed gradients, the algorithm guides iterative parameter adjustments, which leads to enhanced model performance over time. - -Additionally, there are different variations of gradient descent which can be customized for specific tasks. For example, mini-batch gradient descent and stochastic gradient descent are specialized versions that offer efficiency advantages in different scenarios. - -## Gradient Descent Challenges - -Although gradient descent is commonly used in machine learning, there are also some challenges, such as: - -- Learning rate selection: The learning rate selected can significantly impact the algorithm’s performance, and choosing an appropriate learning rate is crucial. If the learning rate is too low, the algorithm will be slow, but if the learning rate is too high, the algorithm may overshoot the minimum. -- Overfitting: The algorithm can overfit the training data, which leads to poor performance on new data. This is more likely to happen if the learning rate selected is too high or if the model is too complex. -- Convergence to local minima: Converging to a local minimum can be problematic if the cost function has many local minima. In these cases, the algorithm should search for a global minimum. diff --git a/content/ai/concepts/search-algorithms/terms/greedy-best-first-search/greedy-best-first-search.md b/content/ai/concepts/search-algorithms/terms/greedy-best-first-search/greedy-best-first-search.md deleted file mode 100644 index 8072cfa22e0..00000000000 --- a/content/ai/concepts/search-algorithms/terms/greedy-best-first-search/greedy-best-first-search.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -Title: 'Greedy Best-First Search' -Description: 'Greedy best-first search is an informed search algorithm where the evaluation function is strictly equal to the heuristic function.' -Subjects: - - 'Data Science' - - 'AI' -Tags: - - 'Search Algorithms' - - 'AI' -CatalogContent: - - 'learn-python-3' - - 'paths/machine-learning-ai-engineering-foundations' ---- - -**Greedy best-first search** is an informed search algorithm where the evaluation function is strictly equal to the heuristic function, disregarding the edge weights in a weighted graph because only the heuristic value is considered. In order to search for a goal node it expands the node that is closest to the goal as determined by the heuristic function. This approach assumes that it is likely to lead to a solution quickly. However, the solution from a greedy best-first search may not be optimal since a shorter path may exist. - -In this algorithm, search cost is at a minimum since the solution is found without expanding a node that is not on the solution path. This algorithm is minimal, but not complete, since it can lead to a dead end. It's called "Greedy" because at each step it tries to get as close to the goal as it can. - -## Evaluation Function - -The evaluation function, **f(x)**, for the greedy best-first search algorithm is the following: - -```pseudo -f(x) = h(x) -``` - -Here, the evaluation function is equal to the heuristic function. Since this search disregards edge weights, finding the lowest-cost path is not guaranteed. - -### Heuristic Function - -A heuristic function, **h(x)**, evaluates the successive node based on how close it is to the target node. In other words, it chooses the immediate low-cost option. As this is the case, however, it does not necessarily find the shortest path to the goal. - -Suppose a bot is trying to move from point A to point B. In greedy best-first search, the bot will choose to move to the position that brings it closest to the goal, disregarding if another position ultimately yields a shorter distance. In the case that there is an obstruction, it will evaluate the previous nodes with the shortest distance to the goal, and continuously choose the node that is closest to the goal. - -## The Algorithm - -1. Initialize a tree with the root node being the start node in the open list. -2. If the open list is empty, return a failure, otherwise, add the current node to the closed list. -3. Remove the node with the lowest **h(x)** value from the open list for exploration. -4. If a child node is the target, return a success. Otherwise, if the node has not been in either the open or closed list, add it to the open list for exploration. - -## Example - -Consider finding the path from **P** to **S** in the following graph: - -![Greedy Best-first Search Example Graph](https://raw.githubusercontent.com/Codecademy/docs/main/media/greedy-best-first-search-example-graph.png) - -In this example, the cost is measured strictly using the heuristic value. In other words, how close it is to the target. - -![Greedy Best-first Search 1](https://raw.githubusercontent.com/Codecademy/docs/main/media/greedy-best-first-search-tree-1.png) - -**C** has the lowest cost of 6. Therefore, the search will continue like so: - -![Greedy Best-first Search 2](https://raw.githubusercontent.com/Codecademy/docs/main/media/greedy-best-first-search-tree-2.png) - -**U** has the lowest cost compared to **M** and **R**, so the search will continue by exploring **U**. Finally, **S** has a heuristic value of 0 since that is the target node: - -![Greedy Best-first Search 3](https://raw.githubusercontent.com/Codecademy/docs/main/media/greedy-best-first-search-tree-3.png) - -The total cost for the path (**P** -> **C** -> **U** -> **S**) evaluates to 11. The potential problem with a greedy best-first search is revealed by the path (**P** -> **R** -> **E** -> **S**) having a cost of 10, which is lower than (**P** -> **C** -> **U** -> **S**). Greedy best-first search ignored this path because it does not consider the edge weights. - -![Greedy Best-first Search Final Example Graph](https://raw.githubusercontent.com/Codecademy/docs/main/media/greedy-best-first-search-final-example-graph.png) - -## Advantages - -- _Faster Exploration_: Expands nodes closer to the goal, often leading to faster solutions in large search spaces. -- _Simple and Easy Implementation_: Simple to implement with only a heuristic function, making it quick to set up. -- _Low Memory Usage_: Requires less memory since it stores only nodes close to the goal in the open list. -- _Efficient for Certain Problems_: Works well when the heuristic is accurate and the goal is easily identified. - -## Disadvantages - -- _Non-optimal Solution_: Since the algorithm only considers the heuristic value and ignores edge weights, it may find a solution that is not the shortest or least costly. This can lead to suboptimal paths. -- _Incomplete_: The search may fail to find a solution, especially if there are dead ends or if the goal node is unreachable. Greedy Best-First Search does not always explore all possible paths. -- _Doesn't Consider Edge Weights_: By ignoring edge weights, the algorithm may miss paths that are less heuristic-optimal but ultimately cheaper in terms of cost. This can lead to inefficient pathfinding. -- _Sensitive to Heuristic Quality_: The algorithm's effectiveness is heavily dependent on the accuracy of the heuristic function. A poorly designed heuristic can result in inefficient search or failure to find the goal. -- _Can Get Stuck in Local Minima_: Greedy Best-First Search may get stuck in local minima, focusing too much on immediate low-cost paths and overlooking potentially better, longer paths that lead to the goal. diff --git a/content/ai/concepts/search-algorithms/terms/hill-climbing/hill-climbing.md b/content/ai/concepts/search-algorithms/terms/hill-climbing/hill-climbing.md deleted file mode 100644 index c990d4153f4..00000000000 --- a/content/ai/concepts/search-algorithms/terms/hill-climbing/hill-climbing.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -Title: 'Hill Climbing' -Description: 'Hill climbing is a simple local search algorithm used in optimization problems. It is inspired by the metaphor of climbing a hill to reach the peak.' -Subjects: - - 'AI' - - 'Data Science' -Tags: - - 'Search' - - 'Algorithms' - - 'AI' -CatalogContent: - - 'learn-python-3' - - 'paths/machine-learning-ai-engineering-foundations' ---- - -The **hill climbing** search algorithm is a local search algorithm used for optimization problems. It is designed to find the highest point or the best solution within a given search space by iteratively exploring neighboring solutions. - -## Algorithm Overview - -The hill climbing algorithm follows a simple iterative process to search for the best solution: - -- Initialization: Start with an initial solution within the search space. -- Evaluation: Evaluate the quality of the current solution using an objective function or fitness measure. -- Neighbor Generation: Generate neighboring solutions by making small modifications to the current solution. -- Selection: Choose the best neighboring solution based on its objective function value. -- Comparison: Compare the objective function value of the best neighboring solution with the current solution. -- Iteration: Repeat the process until a termination condition is met. - -## Usage - -To use the hill climbing algorithm for your optimization problem, follow these steps: - -- Step 1: Define the search space: Determine the range or domain of possible solutions for the problem. -- Step 2: Define the objective function: Create a function that measures the quality or fitness of a solution. -- Step 3: Initialization: Generate or select an initial solution within the search space. -- Step 4: Iterative process: Repeat the following steps until a termination condition is met: - - Evaluate the current solution using the objective function. - - Generate neighboring solutions by making small modifications to the current solution. - - Select the best neighboring solution based on its objective function value. - - Compare the objective function value of the best neighboring solution with the current solution. - - If the neighboring solution is better, update the current solution. Otherwise, terminate the algorithm. -- Step 5: Termination condition: Define a condition to stop the algorithm, such as reaching a maximum number of iterations, achieving a specific threshold for the objective function value, or exceeding a time limit. - -## Limitations - -The hill climbing algorithm has certain limitations to keep in mind: - -- Local Optima: It may get stuck in local optima, suboptimal solutions that are better than their neighbors but worse than the global optimum. -- Plateaus: It has difficulty navigating flat regions or plateaus where there are no uphill moves. -- Multiple Peaks: It may miss the global optimum if the search space has multiple peaks or valleys. -- Dependency on Initial solution: The quality of the final solution can be highly dependent on the initial solution chosen. - -## Code Example - -```pseudo -import random - -def objective_function(solution): - # Define your objective function here - # This function should evaluate the quality of a solution and return a value - # The higher the value, the better the solution - # Modify this function based on your specific optimization problem - return sum(solution) - -def generate_neighbor(current_solution): - # Generate a neighboring solution by making a small modification to the current solution - # This function should implement the logic to generate a neighboring solution - # Modify this function based on your specific optimization problem - neighbor = current_solution[:] - index = random.randint(0, len(neighbor) - 1) - neighbor[index] = 1 - neighbor[index] # Flip the value at the selected index - return neighbor - -def hill_climbing(): - # Initialization - current_solution = [random.randint(0, 1) for _ in range(10)] # Generate an initial solution - current_fitness = objective_function(current_solution) - - # Iterative process - while True: - # Neighbor generation - neighbor = generate_neighbor(current_solution) - neighbor_fitness = objective_function(neighbor) - - # Comparison - if neighbor_fitness >= current_fitness: - current_solution = neighbor - current_fitness = neighbor_fitness - else: - break # Terminate if no better solution is found - - return current_solution, current_fitness - -# Usage example -best_solution, best_fitness = hill_climbing() -print("Best Solution:", best_solution) -print("Best Fitness:", best_fitness) -``` - -Suppose there is a game where the best solution needs to be found in order to win. This code helps find that solution. - -First, the code uses a special tool called [`random`](https://www.codecademy.com/resources/docs/python/random-module) to help make random choices. This will be useful later. - -Next, a function called `objective_function()` determines how good a solution is. The function looks at the solution given to it and adds up all the parts. If the total is high, it means the solution is good. - -Then, the `generate_neighbor()` function helps make small changes to a solution. It takes a solution and picks a random spot. It then either flips a switch there (from 0 to 1 or 1 to 0) or leaves it as it is. It's like changing one small thing in the solution. - -Now is the main part, called `hill_climbing()`. This is where the magic happens! It starts by making a random solution with switches set to 0 or 1. Then, it asks the judge (the `objective_function()`) how good this solution is. This is the starting point. - -The code then keeps making changes to the solution and checking with the judge how good the new solution is. If the new solution is better than the current one, it becomes the new solution. It does this repeatedly, always trying to find a better solution. - -But, there is a rule: if the new solution is not better than the current one, it stops trying to find a better solution, meaning it has reached the top of the hill and can't climb any higher. It's like saying, "I tried my best, but this is as good as it gets." - -Finally, when the code can't find any better solutions, it responds with the best solution it found and how good it is. It's like saying, "Hey, I found the best way to win the game! This is it, and it's really good!" diff --git a/content/ai/concepts/search-algorithms/terms/simulated-annealing/simulated-annealing.md b/content/ai/concepts/search-algorithms/terms/simulated-annealing/simulated-annealing.md deleted file mode 100644 index 9dafb8a8c50..00000000000 --- a/content/ai/concepts/search-algorithms/terms/simulated-annealing/simulated-annealing.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -Title: 'Simulated Annealing' -Description: 'An optimization algorithm used to solve problems where it is impossible or computationally expensive to find a global optimum. It evaluates many solutions each with a different score, and the goal of the algorithm is to find the best score.' -Subjects: - - 'Data Science' - - 'Computer Science' - - 'Data Visualization' -Tags: - - 'Search Algorithms' - - 'Machine Learning' - - 'AI' -CatalogContent: - - 'paths/data-science' - - 'paths/machine-learning-ai-engineering-foundations' ---- - -**Simulated annealing** is an optimization algorithm used to solve problems where it is impossible or computationally expensive to find a global optimum. In these situations simulated annealing can often find an approximate global optimum that works well. - -As the algorithm runs it employs a permissive evaluation process that will accept worse solutions in order to complete a comprehensive search of the solution space. And as the space is explored the algorithm slowly decreases the probability that worse solutions will be accepted. Each solution has a different score and the goal of the algorithm is to find the best score over the course of the search. - -## The Implementation - -- Simulated annealing begins by creating a trial point randomly, then the algorithm selects the distance between the current point and the trial point through a probability distribution. -- The algorithm then determines if the new point is better than the older point, or not. If the new point is better, it is set as the next point, but if the new point is worse, it can still be accepted depending on the evaluation function. -- The annealing parameters are set, raising and reducing the temperatures (the scale of such distribution from point to point) for lowering values. The simulated annealing concludes when it reaches the lowest minima or hits a given stopping criteria. - -## Background - -Simulated annealing is a probabilistic algorithm which tests points across a solution space to find the lowest minima. The algorithm is termed "simulated annealing" because it mirrors physical annealing, a process in which a material is repeatedly heated and cooled to elicit desired structural properties. diff --git a/content/ai/concepts/search-algorithms/terms/stochastic-gradient-descent/stochastic-gradient-descent.md b/content/ai/concepts/search-algorithms/terms/stochastic-gradient-descent/stochastic-gradient-descent.md deleted file mode 100644 index 874e0472e74..00000000000 --- a/content/ai/concepts/search-algorithms/terms/stochastic-gradient-descent/stochastic-gradient-descent.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -Title: 'Stochastic Gradient Descent' -Description: 'Stochastic Gradient Descent (SGD) is a variant of the Gradient Descent optimization algorithm, widely used in machine learning to efficiently train models on large datasets.' -Subjects: - - 'Data Science' - - 'AI' -Tags: - - 'Search Algorithms' - - 'Algorithms' - - 'AI' -CatalogContent: - - 'learn-python-3' - - 'paths/machine-learning-ai-engineering-foundations' ---- - -**Stochastic Gradient Descent (SGD)** is a variant of the [Gradient Descent](https://www.codecademy.com/resources/docs/ai/search-algorithms/gradient-descent) optimization [algorithm](https://www.codecademy.com/resources/docs/general/algorithm), widely used in [machine learning](https://www.codecademy.com/resources/docs/ai/machine-learning) to efficiently train models, particularly when dealing with large datasets. - -## How Does Stochastic Gradient Descent Work? - -Similar to Gradient Descent, Stochastic Gradient Descent also aims to minimize the cost function of a model. However, instead of updating the model parameters after evaluating the entire dataset, SGD updates the parameters after each individual data point. This approach makes SGD computationally more efficient, as it avoids the need to process the entire dataset in each iteration. - -The following is the pseudocode of the process: - -```pseudo -Shuffle Training Data -for each epoch: - for each mini-batch b: - Compute Gradient using b - Update Parameters using the Gradient and Learning Rate -``` - -In each iteration of SGD, the following steps are performed: - -1. **Shuffle Data**: Training data is randomly shuffled before each epoch to introduce randomness and prevent biases in updates. -2. **Mini-Batch Selection**: A small subset (mini-batch) of data points is randomly selected from the shuffled training dataset. -3. **Compute Gradient**: The gradient of the cost function is computed using the selected mini-batch of data points. The gradient represents the direction of the steepest descent, guiding the algorithm towards the minimum. -4. **Update Parameters**: Based on the calculated gradient, the model's parameters are updated. The learning rate determines the step size of these updates and controls the convergence speed of the algorithm. -5. **Repeat**: Steps 2 to 4 are repeated for a specified number of epochs or until a convergence criterion is met. - -## Uses in Machine Learning - -SGD is widely used in machine learning, especially for large-scale tasks like training deep neural networks. Its efficiency in processing large datasets, coupled with the ability to escape local minima, makes it a popular choice in modern machine learning frameworks. Moreover, SGD's adaptability allows it to be used in online learning settings where new data continuously arrives. - -## Advantages of Stochastic Gradient Descent - -- Efficiency: SGD processes only a small subset of data in each iteration, making it faster than traditional Gradient Descent for large datasets. -- Convergence: SGD can escape local minima due to its stochastic nature, improving exploration of the solution space. -- Noise Tolerance: The inherent randomness in mini-batch selection adds noise, which helps avoid convergence to undesirable solutions. - -## Challenges of Stochastic Gradient Descent - -- High Variance: The randomness introduced by mini-batch selection may lead to higher variance in parameter updates, resulting in noisy convergence. -- Learning Rate Tuning: Choosing an appropriate learning rate is crucial, as a large learning rate may cause divergence, while a small one may slow down convergence. -- Approximate Minima: SGD may not converge to the global minimum due to its stochastic updates. diff --git a/content/blockchain/blockchain.md b/content/blockchain/blockchain 3.md similarity index 100% rename from content/blockchain/blockchain.md rename to content/blockchain/blockchain 3.md diff --git a/content/c-sharp/c-sharp.md b/content/c-sharp/c-sharp.md deleted file mode 100644 index 78b0b438f46..00000000000 --- a/content/c-sharp/c-sharp.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -Title: 'C#' -Description: 'C# is a general purpose programming language developed by Microsoft and released in 2000.' -Codecademy Hub Page: 'https://www.codecademy.com/catalog/language/c-sharp' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -C# is a general-purpose programming language developed by Microsoft and released in 2000. It is used for a variety of tasks such as web apps, to desktop apps, to mobile apps, and games. - -C# was designed as a C-like language that utilizes Microsoft's .Net Framework. The core syntax is similar to [C](https://www.codecademy.com/resources/docs/c), [C++](https://www.codecademy.com/resources/docs/cpp), and [Java](https://www.codecademy.com/resources/docs/java). diff --git a/content/c-sharp/concepts/arrays/arrays.md b/content/c-sharp/concepts/arrays/arrays.md deleted file mode 100644 index d0f3f96b3db..00000000000 --- a/content/c-sharp/concepts/arrays/arrays.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -Title: 'Arrays' -Description: 'An array is a data structure used in C# to store a sequential collection of elements.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arrays' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -An **array** is a data structure used in [C#](https://www.codecademy.com/resources/docs/c-sharp) to store a sequential collection of elements. Its size is immutable (cannot be changed after creation). The elements of an array are all of the same type, but it is possible to define a C# array that can hold elements of any type by specifying the type of the array as an object. In C#, all types directly or indirectly inherit from `Object`. - -## Syntax - -There are several ways to create an array in C#: - -```pseudo -// Create a variable of type "type[]" without initializing it: -type[] arrayName; - -// Create the array variable and initialize it with an array of N items: -type[] arrayName = new type[N]; - -// Create the array variable and initialize it by specifying the contents: -type[] arrayName = new type[] { value1, value2, value3, ... valueN }; - -// Alternative way of creating the array and specifying the contents: -type[] arrayName = { value1, value2, value3, ... valueN }; -``` - -> **Note:** Arrays in C# have a set size, meaning the number of elements they hold cannot be changed once the array has been created. - -## Example - -Each element in an array is assigned a specific index starting at zero. To access or modify an element in the array, you refer to it by its index and operate on it accordingly. - -```cs -using System; - -public class Example -{ - public static void Main(string[] args) - { - char[] vowels = {'a', 'e', 'i', 'o', 'u'}; - // indexes: 0 1 2 3 4 - - Console.WriteLine(vowels[0]); // Output: a - - vowels[0] = 'r'; - - Console.WriteLine(vowels[0]); // Output: r - } -} -``` - -In the example above, an array of `char`s was initialized with all the vowels. The first element in the array at index 0 was printed. Then, the element at index 0 was modified by assigning it a new value of `'r'`. Then, the value at index 0 was printed again. - -## Array Methods - -Arrays in C# are objects, not just contiguous blocks of memory as in C and C++. `Array` is the base type of all arrays, and any array can use the properties and methods of the `Array` object, a few of which are listed below: diff --git a/content/c-sharp/concepts/arrays/terms/clear/clear.md b/content/c-sharp/concepts/arrays/terms/clear/clear.md deleted file mode 100644 index 25e5440c8d7..00000000000 --- a/content/c-sharp/concepts/arrays/terms/clear/clear.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -Title: '.Clear()' -Description: 'Clears the contents of an array, returning each element to its default value.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arrays' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Clear()`** method is used to clear the contents of an array, returning each element to its default value. - -## Syntax - -```pseudo -// Clears the array myArray -Array.Clear(myArray); - -// Clears N elements from myArray starting at index -Array.Clear(myArray, index, N); -``` - -`.Clear()` is a static method of the `Array` object. When it is called with just an array as an argument, it clears the whole array. When it is called with an array, a start index, and a number, it clears `N` amount of elements in the array starting from the specified `index` by zeroing, falsifying, or nulling out all the elements (depending on the array's element type). - -## Example - -The following example initializes `myArray` with values, and clears it from a specified index; the number of elements cleared is set to the length of the array using the [`.Length`](https://www.codecademy.com/resources/docs/c-sharp/arrays/length) property: - -```cs -using System; - -public class Example -{ - public static void Main(string[] args) - { - int[] myArray = {0, 1, 2, 3, 4}; - - Array.Clear(myArray, 0, myArray.Length); - - System.Console.WriteLine(myArray[2]); // Output: 0 - } -} -``` - -## Codebyte Example - -This example creates an integer array `numbers` with some initial values. It then calls `.Clear()`, to clear the elements of the array. -The `PrintArray()` method is used to print the array before and after clearing it. - -```codebyte/csharp -using System; - -public class ClearExample -{ - public static void Main() - { - int[] numbers = { 1, 2, 3, 4, 5 }; - - Console.WriteLine("Original Array:"); - PrintArray(numbers); - - // Clear the array - Array.Clear(numbers, 0, numbers.Length); - - Console.WriteLine("Cleared Array:"); - PrintArray(numbers); - } - - static void PrintArray(int[] array) - { - foreach (int element in array) - { - Console.Write(element + " "); - } - Console.WriteLine(); - } -} -``` diff --git a/content/c-sharp/concepts/arrays/terms/copy/copy.md b/content/c-sharp/concepts/arrays/terms/copy/copy.md deleted file mode 100644 index 793e09b7387..00000000000 --- a/content/c-sharp/concepts/arrays/terms/copy/copy.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -Title: '.Copy()' -Description: 'Copies elements in an array within a certain range.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arrays' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Copy()`** method in [C#](https://www.codecademy.com/resources/docs/c-sharp) copies a range of elements from one array to another array. - -## Syntax - -```pseudo -Array.Copy(sourceArray, destinationArray, length); - -Array.Copy(sourceArray, sourceStartingIndex, destinationArray, destinationStartingIndex, length); -``` - -`.Copy()` is a static method of the `Array` object. It takes the following arguments: - -- `sourceArray` is copied, starting from the first element of the array. -- `destinationArray` is where the `sourceArray` is copied to. -- `length` is specified as an integer and determines how many elements are copied from the source to the destination array. - -It is also possible to overload this method with two additional parameters: - -- `sourceStartingIndex` is the index where the source array's elements are first copied from. -- `destinationStartingIndex` is the destination array's index to which the elements from the source array are copied to. - -## Example - -The following example initializes the array `sourceArray` and the array `destinationArray`. Using a `foreach` loop, the contents of `destinationArray` are printed to the console: - -```cs -using System; - -public class Example -{ - public static void Main(string[] args) - { - string[] sourceArray = new string[] { "red", "orange", "yellow", "green", "blue", "indigo", "violet"}; - string[] destinationArray = new string[sourceArray.Length]; - - // sourceArray.Length returns the integer for the third parameter, length. - Array.Copy(sourceArray, destinationArray, sourceArray.Length); - foreach (string element in destinationArray) - { - Console.Write($"{element} "); - } - } -} -``` - -This is what is printed to the console: - -```shell -red orange yellow green blue indigo violet -``` - -## Codebyte Example - -The following codebyte is runnable and shows one of the several overload functions with the `Array.Copy()` method. In this example, `sourceArray` is copied starting from the third element in the array `[2]`and stores elements `[2]`, `[3]`, `[4]` starting as the first element in `destinationArray`. The remaining elements return `0`: - -```codebyte/csharp -using System; - -public class OverloadExample -{ - public static void Main(string[] args) - { - int[] sourceArray = new int[] {10, 20, 30, 40, 50, 60, 70}; - // array index [0] [1] [2] [3] [4] [5] [6] - int[] destinationArray = new int[sourceArray.Length]; - - Array.Copy(sourceArray, 2, destinationArray, 0, 3); - - foreach (int element in destinationArray) - { - Console.Write($"{element} "); - } - } -} -``` diff --git a/content/c-sharp/concepts/arrays/terms/copyto/copyto.md b/content/c-sharp/concepts/arrays/terms/copyto/copyto.md deleted file mode 100644 index 58db94f7bac..00000000000 --- a/content/c-sharp/concepts/arrays/terms/copyto/copyto.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -Title: '.CopyTo()' -Description: 'Copies the elements of an array to another array.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arrays' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The `.CopyTo()` method in C# provides the ability to copy elements from one array to another or to a specific location within an array. - -It offers a convenient way to duplicate array contents, ensuring that the target array holds the same values in the specified range. By specifying the destination array and the starting index, precise control over the element copying process is achieved, facilitating efficient data manipulation and array operations. - -## Syntax - -```pseudo -CopyTo(destinationArray, destinationIndex) -``` - -The `destinationArray` parameter is the target array where the elements will be copied to, and the `destinationIndex` parameter represents the starting index in the `destinationArray` where the elements will be copied. - -## Example - -In this example, there is a source array named `sourceArray` with elements [10, 20, 30, 40, 50]. A destination array named `destinationArray` is created with the size 6. Then, the `.CopyTo()` method is used to copy elements from `sourceArray` to `destinationArray`, starting at index 1. - -```cs -using System; - -class CopyTo -{ -static void Main(string[] args) -{ - int[] sourceArray = { 10, 20, 30, 40, 50 }; - int[] destinationArray = new int[6]; - sourceArray.CopyTo(destinationArray, 1); - Console.WriteLine("Source Array:"); - PrintArray(sourceArray); - Console.WriteLine("Destination Array:"); - PrintArray(destinationArray); -} -static void PrintArray(int[] array) -{ - foreach (int element in array) - { - Console.Write(element + " "); - } - Console.WriteLine(); -} -} -``` - -The output for the above code will be: - -```shell -Source Array: -10 20 30 40 50 -Destination Array: -0 10 20 30 40 50 -``` - -## Codebyte Example - -This example is runnable and shows another implementation of the `CopyTo()` method. The codebyte down below will throw a `Unhandled Exception` error which can be solved by referring to the above entry. - -> **Note:** Copying arrays requires compatibility between the source and destination: if the destination array is too small to accommodate the values of the source array an `Unhandled Exception` will be thrown. - -```codebyte/cs -using System; - -class CopyTo -{ -static void Main(string[] args) -{ - string[] sourceArray = { "apple", "banana", "orange", "kiwi", "grape" }; - string[] destinationArray = new string[3]; - sourceArray.CopyTo(destinationArray, 1); - - Console.WriteLine("Source Array:"); - PrintArray(sourceArray); - - Console.WriteLine("Destination Array:"); - PrintArray(destinationArray); -} -static void PrintArray(string[] array) -{ - foreach (string element in array) - { - Console.Write(element + " "); - } - Console.WriteLine(); -} -} -``` diff --git a/content/c-sharp/concepts/arrays/terms/length/length.md b/content/c-sharp/concepts/arrays/terms/length/length.md deleted file mode 100644 index 66de4131ae0..00000000000 --- a/content/c-sharp/concepts/arrays/terms/length/length.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -Title: '.Length' -Description: 'Returns the total number of elements in the array.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arrays' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Length`** property returns the total number of elements in the array, including all dimensions of the array. - -## Syntax - -```pseudo -int myLength = myArray.Length; -``` - -`myArray.Length` returns an `int` that represents the number of elements in `myArray`. - -## Example - -The following example initializes an array, then prints out the number of elements it contains: - -```cs -using System; - -public class Example -{ - public static void Main(string[] args) - { - int[] myArray = {0, 1, 2, 3, 4}; - Console.WriteLine(myArray.Length); // Output: 5 - } -} -``` - -## Codebyte Example - -The following runnable code uses the `.Length` property to return the length of the `numbers` array: - -```codebyte/csharp -using System; - -public class LengthExample -{ - public static void Main() - { - int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7 }; - - Console.WriteLine(numbers.Length); - } -} -``` diff --git a/content/c-sharp/concepts/arrays/terms/resize/resize.md b/content/c-sharp/concepts/arrays/terms/resize/resize.md deleted file mode 100644 index bac0757431a..00000000000 --- a/content/c-sharp/concepts/arrays/terms/resize/resize.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -Title: '.Resize()' -Description: 'Updates the size of an existing array.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arrays' - - 'Methods' - - 'Collections' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Resize()`** method changes the number of elements of a one-dimensional array to the specified new size. - -## Syntax - -```pseudo -// Sets a new size for the specified array -Array.Resize(ref int[] array, int newSize); -``` - -`.Resize()` is a method of the `Array` object. When used with a one-dimensional array, it defines the number of elements acceptable by the array, or redefines the size of an array. This can be used to both lengthen or shorten the number of elements within a given array. - -## Example - -The following example will conceptualize how the `.Resize()` method functions within an array. - -```cs -using System; - -public class Example -{ - public static void Main() - { - // Martians have intercepted a broadcast of the musical album, Jeff Wayne's "War of the Worlds", and they love it. The Martians have created an array of the songs they were able to intercept. - String[] WaroftheWorlds = {"The_Eve_of_the_War", "Horsell_Common_and_the_Heat_Ray", "The_Artilleryman_and_the_Fighting_Machine", "Forever_Autumn", "Thunder_Child", "The_Red_Weed_(Part_1)", "The_Spirit_of_Man", "The_Red_Weed_(Part_2)", "The_Artilleryman_Returns", "Brave_New_World"}; - Console.WriteLine("Broadcast from Earth:"); - PrintUlla(WaroftheWorlds); - - // The Martians know that there are still three songs on the album, but they do not know what these songs are called. Instead, they resize their array to set empty placeholders for these songs. - Array.Resize(ref WaroftheWorlds, WaroftheWorlds.Length + 3); - Console.WriteLine("Complete Broadcast (Will Receive Soon):"); - PrintUlla(WaroftheWorlds); - - // The Martians favorite part of the album is really where they triumph over humanity. They decide that this part of the array is their favorite, and resize the array to only include the first five songs. - Array.Resize(ref WaroftheWorlds, 5); - Console.WriteLine("Invasion Plan:"); - PrintUlla(WaroftheWorlds); - } - - public static void PrintUlla(String[] WaroftheWorlds) - { - for(int i = 0; i < WaroftheWorlds.Length; i++) - { - Console.WriteLine(" [{0}] : {1}", i, WaroftheWorlds[i]); - } - Console.WriteLine(); - } -} -``` - -The example above will return the following output: - -```shell -Broadcast from Earth: - [0] : The_Eve_of_the_War - [1] : Horsell_Common_and_the_Heat_Ray - [2] : The_Artilleryman_and_the_Fighting_Machine - [3] : Forever_Autumn - [4] : Thunder_Child - [5] : The_Red_Weed_(Part_1) - [6] : The_Spirit_of_Man - [7] : The_Red_Weed_(Part_2) - [8] : The_Artilleryman_Returns - [9] : Brave_New_World - -Complete Broadcast (Will Receive Soon): - [0] : The_Eve_of_the_War - [1] : Horsell_Common_and_the_Heat_Ray - [2] : The_Artilleryman_and_the_Fighting_Machine - [3] : Forever_Autumn - [4] : Thunder_Child - [5] : The_Red_Weed_(Part_1) - [6] : The_Spirit_of_Man - [7] : The_Red_Weed_(Part_2) - [8] : The_Artilleryman_Returns - [9] : Brave_New_World - [10] : - [11] : - [12] : - -Invasion Plan: - [0] : The_Eve_of_the_War - [1] : Horsell_Common_and_the_Heat_Ray - [2] : The_Artilleryman_and_the_Fighting_Machine - [3] : Forever_Autumn - [4] : Thunder_Child -``` - -## Codebyte Example - -The following executable example of the `.Resize()` method initializes an array `numbers` and then doubles the length of it. - -```codebyte/csharp -using System; - -public class ResizeExample -{ - public static void Main() - { - int[] numbers = { 1, 2, 3, 4, 5 }; - - Console.WriteLine(numbers.Length); - - // Resize the array to double its length - Array.Resize(ref numbers, numbers.Length * 2); - - Console.WriteLine(numbers.Length); - } -} -``` diff --git a/content/c-sharp/concepts/arrays/terms/reverse/reverse.md b/content/c-sharp/concepts/arrays/terms/reverse/reverse.md deleted file mode 100644 index b241655aa55..00000000000 --- a/content/c-sharp/concepts/arrays/terms/reverse/reverse.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -Title: '.Reverse()' -Description: 'Reverses the sequence of a subset of the elements in a one-dimensional array.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arrays' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/build-web-apps-with-asp-net' ---- - -The **`.Reverse()`** method reverses the sequence of a subset of the elements in a one-dimensional array. - -## Syntax - -```pseudo -Array.Reverse(sourceArray, index, length); -``` - -`.Reverse()` takes the following parameters: - -- `sourceArray`, the array to be reversed -- `index`, an integer specifying the start of the subset -- `length`, an integer specifying the number of elements of the subset - -If the method is run without specifying and index and length, then the entire array will be reversed. - -## Example - -The following example initializes `spamLetters` with values, and reverses the sequence: - -```cs -using System; - -public class Example -{ - public static void Main(string[] args) - { - string[] spamLetters = {"S", "P", "A", "M"}; - - Array.Reverse(spamLetters); - - foreach (string s in spamLetters) - { - System.Console.Write(s + " "); - } - } -} -``` - -The code returns the following output: - -```shell -M A P S -``` - -## Codebyte Example - -The following example uses the `.Reverse()` method to flip the final 4 characters of an array. - -```codebyte/csharp -using System; - -public class Example -{ - public static void Main(string[] args) - { - string[] alphaBit = {"L", "M", "N", "O", "P"}; - - Array.Reverse(alphaBit, 1, 4); - - foreach (string a in alphaBit) - { - System.Console.Write(a + " "); - } - } -} -``` diff --git a/content/c-sharp/concepts/arrays/terms/sort/sort.md b/content/c-sharp/concepts/arrays/terms/sort/sort.md deleted file mode 100644 index 73522ecf9ee..00000000000 --- a/content/c-sharp/concepts/arrays/terms/sort/sort.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -Title: '.Sort()' -Description: 'Arranges the elements of an array in ascending or alphabetical order.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arrays' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Sort()`** array method arranges the elements of an array in ascending or alphabetical order. - -## Syntax - -```pseudo -Array.Sort(myArray); -``` - -`.Sort()` is a static method of the `Array` object. It takes one parameter, `myArray`, a one-dimensional zero-based array. - -## Example - -The following example initializes the `letters` array with strings, then uses the `.Sort()` method to arrange the strings alphabetically. Finally, a `foreach` loop passes each element of the sorted array to the `Console.Write()` method to be printed: - -```cs -using System; - -public class Example -{ - public static void Main(string[] args) - { - string[] letters = {"M", "Y", "E", "T", "P"}; - - Array.Sort(letters); - - foreach (string letter in letters) - { - System.Console.Write(letter + " "); - } - } -} -``` - -This example results in the following output: - -```shell -E M P T Y -``` - -## Codebyte Example - -The following example is runnable and returns the numbers in the `numbers` array in ascending order: - -```codebyte/csharp -using System; - -public class Example -{ - public static void Main(string[] args) - { - int[] numbers = {5895, 4810, 5364}; - - Array.Sort(numbers); - - foreach (int number in numbers) - { - System.Console.Write(number + " "); - } - } -} -``` diff --git a/content/c-sharp/concepts/classes/classes.md b/content/c-sharp/concepts/classes/classes.md deleted file mode 100644 index 053ff4cf9e2..00000000000 --- a/content/c-sharp/concepts/classes/classes.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -Title: 'Classes' -Description: 'A blueprint or template for creating objects.' -Subjects: - - 'Computer Science' -Tags: - - 'Objects' - - 'Data Types' - - 'Properties' - - 'Methods' - - 'OOP' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -In C#, a **class** serves as a blueprint or template for creating objects. It plays a fundamental role in defining the structure, behavior, and attributes of these objects. A class can be thought of as a user-defined data type that encapsulates both data (attributes) and the actions (methods) that are applied to that data. - -## Syntax for Declaring Classes - -To declare a class in C#, use the `class` keyword, followed by the class name. Class names should follow C# naming conventions (typically using PascalCase). The class definition is enclosed within curly braces `{}`. - -```cs -public class MyClass { - // Fields, properties, and methods go here -} -``` - -## Properties and Methods - -- `Properties`: Properties are used to define the attributes or data members of a class. They are defined within the class and provide access to the class's internal state. -- `Methods`: Methods are functions defined within the class that perform actions or operations. They can modify the class's state or provide functionality. - -## Access Modifiers - -C# provides access modifiers to control the visibility and accessibility of class members. Common access modifiers include: - -- `public`: Members are accessible from any code. -- `private`: Members are only accessible within the class. -- `protected`: Members are accessible within the class and derived classes. -- `internal`: Members are accessible within the same assembly (a group of related classes in the same project). -- `protected internal`: Members are accessible within the same assembly and derived classes. -- `private protected`: Members are accessible only from derived classes within the current assembly. This access modifier has been available since C# 7.2 and later. - -## Example - -Here is a simple example featuring a class with properties and methods. By employing various access modifiers in C#, this example illustrates the use of public methods, such as `GetBalance`, to access private properties like the `current balance`. Meanwhile, it showcases that private methods like `PerformAudit()` are inaccessible from external code. - -```cs -using System; - -public class Program { - public static void Main() { - // Create a BankAccount instance with an initial balance of $1000. - BankAccount account = new BankAccount(1000); - - // Use the GetBalance method to get the current balance. - double currentBalance = account.GetBalance(); - Console.WriteLine("Current Balance: $" + currentBalance); - - // Attempt to call the private method PerformAudit (won't compile). - // This will result in a compilation error because private methods cannot be accessed from outside the class. - // account.PerformAudit(); - } -} - -public class BankAccount { - // Keeping track of current balance. - private double balance; - - // Constructor - public BankAccount(double initialAmount) { - balance = initialAmount; - } - - // Accessor method for balance. - public double GetBalance() { - return balance; - } - - // Private method to perform a transaction audit. - private void PerformAudit() { - // In a real application, this method would perform auditing. - // For this example, we'll just print a message. - Console.WriteLine("Audit complete."); - } -} -``` - -## Static Classes - -Static classes are defined using the `static` keyword and exclusively contain static members, such as methods, properties, and fields. Unlike regular classes, static classes cannot be instantiated with the `new` keyword. Instead, their members are accessed using the class name itself. These classes are commonly used for utility functions or to group related functionalities. - -The `static` keyword forces all fields, methods, and properties to require this keyword. This means that if a user tries to create any of these without the `static` keyword, the code will not run and will produce a compile-time error. The reason behind this is that the user can not create an instance of a static class without using this keyword. Any methods, properties and fields that are not marked as `static` would be unreachable. - -### Example - -In the example below, a static class called `MyStaticClass` is created. The commented out code shows what a user can not do with static classes. If these commented out pieces of code were to be uncommented, the code would not compile. The example also shows how properties and methods in the `MyStaticClass` class are created and used in the `CallingClass` class: - -```cs -using System; - -public class CallingClass -{ - public static void Main() - { - Console.WriteLine(MyStaticClass.StaticField); - - // The following will produce a compile-time error - // MyStaticClass NonStaticError = new MyStaticClass(); - - int DoubleFive = MyStaticClass.GetDouble(5); - Console.WriteLine(DoubleFive); - } -} - -public static class MyStaticClass -{ - // The following will produce a compile-time error - // public int NonStaticField = 5; - - public static int StaticField = 20; - - // Returns double of the value given - public static int GetDouble(int value) { - return value * 2; - } -} -``` - -The above code produces the following output: - -```shell -20 -10 -``` - -## Partial classes - -Partial classes in C# enable class definitions to be split across multiple files. Each part of the class is defined in a separate file and combined at compile time to create a single class. This is valuable for scenarios where a class becomes too large or complex, or when multiple developers need to work on different aspects of the class simultaneously. - -![Partial Classes](https://raw.githubusercontent.com/Codecademy/docs/main/media/c-sharp-partial-class.png) - -In the image above, the `Calculator` class is depicted as a partial class structure, allowing independent development of class components. In the code below, the application's entry point, the `Main` method, creates an instance of the `Calculator` class and utilizes its methods for addition and subtraction operations. - -```cs -using System; - -class Program { - static void Main() { - Calculator calculator = new Calculator(); - int result1 = calculator.Add(5, 3); - int result2 = calculator.Subtract(10, 4); - - Console.WriteLine("Addition: " + result1); // Output: Addition: 8 - Console.WriteLine("Subtraction: " + result2); // Output: Subtraction: 6 - } -} -``` diff --git a/content/c-sharp/concepts/comments/comments.md b/content/c-sharp/concepts/comments/comments.md deleted file mode 100644 index 03b6610c3d6..00000000000 --- a/content/c-sharp/concepts/comments/comments.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -Title: 'Comments' -Description: 'A comment is a piece of text within a program that is not executed.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Syntax' - - 'Comments' - - 'Documentation' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -A **comment** is a piece of text within a program that is not executed. It can be used to provide additional information to aid in understanding the code. - -### Single-line Comments - -For single-line comments, the compiler ignores any text after two consecutive forward slashes (`//`) on the same line. - -```cs -// Comment goes here -executing code // Comment goes here -``` - -### Multi-line Comments - -Multi-line comments begin with `/*` and end with `*/`. The compiler ignores any text in between. - -```cs -/* -This is all commented out. -None of it is going to run! -*/ -``` - -### Example - -The following examples show various comment styles: - -```cs -// This line will denote a comment in C-sharp. -Console.WriteLine("Hello World!"); // This is a comment. -/* -This is a multi-line -comment. -*/ -``` - -### XML Comments - -[XML](https://www.codecademy.com/resources/docs/general/xml) comments are structured comments that produce [API](https://www.codecademy.com/resources/docs/general/api) documentation. The C# compiler produces an XML file that contains structured data representing the comments. Other tools can process that XML output to create human-readable documentation in the form of web pages or PDF files, for example. - -#### Syntax - -The following is a single-line XML comment, which uses three forward slashes (`///`): - -```cs -/// XML Comment goes here -``` - -Multi-line XML comments are similar to regular multi-line comments, except that an extra asterisk `*` is used in the opening: - -```cs -/** -XML Comments go here -*/ -``` - -#### Example - -XML tags embedded in XML comments are used to signal a specific functionality of the XML comment to the compiler. The `` tag in the following example describes a type or a member, in this case, the public class `MyClass`: - -```cs -/// -/// This class performs an important function. -/// -public class MyClass {} -``` - -## Codebyte Example - -In this example, single-line comments (`//`) are used for brief notes, while multi-line comments (`/* */`) are used to explain larger blocks of code or provide more context: - -```codebyte/csharp -using System; - -class Program -{ - static void Main(string[] args) - { - // Single-line comment: This is the entry point of the program. - Console.WriteLine("Hello, World!"); // This prints a greeting to the console. - - /* - Multi-line comment: - The following code demonstrates basic addition - and prints the result to the console. - */ - int a = 5; // Declare an integer variable 'a' and assign it the value 5. - int b = 10; // Declare an integer variable 'b' and assign it the value 10. - - int sum = a + b; // Add the two numbers and store the result in 'sum'. - Console.WriteLine("The sum of a and b is: " + sum); // Output the sum to the console. - } -} -``` diff --git a/content/c-sharp/concepts/conditionals/conditionals.md b/content/c-sharp/concepts/conditionals/conditionals.md deleted file mode 100644 index d0da743053a..00000000000 --- a/content/c-sharp/concepts/conditionals/conditionals.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -Title: 'Conditionals' -Description: 'Conditionals compare inputs and return a boolean value of either true or false.' -Subjects: - - 'Computer Science' - - 'Web Development' - - 'Mobile Development' - - 'Game Development' -Tags: - - 'Booleans' - - 'Development' - - 'Script' - - 'Variables' -CatalogContent: - - 'learn-c-sharp' - - 'paths/full-stack-engineer-career-path' ---- - -In C#, **conditionals** compare inputs and return a boolean value indicating whether it evaluates to `true` or `false`. - -Conditional statements include the `if`, `else` and `else if` statements. A shorthand for the `if`/`else` statement is the conditional or ternary operator. - -## If Statement - -An `if` statement evaluates a condition that, when true, will run a code block that follows. - -In the example below, three variables are declared and assigned values. Then, an `if` statement checks for a condition; if it evaluates to true, then the variable of boolean type will change: - -```cs -var input1 = 10; -var input2 = 10; -var output = false; - -if (input1 == input2) { - output = true; // Sets the output from false to true. -} -``` - -If the code above returned `true`, the code block below will print a statement to the console: - -```cs -if (output == true) { - Console.WriteLine("I returned true"); -} -``` - -> **Note** `==` means equal and `!=` means not equal. - -### Else Statements - -An `else` statement is combined with the `if` statement. In the case that the condition following the `if` statement returns `false`, the code block following the `else` statement will run. - -In the example below, three variables are assigned values: - -```cs -var input1 = 10; -var input2 = 10; -var output = false; - -// If the input variables are not equal, the output will be set to true. -if (input1 != input2) { - output = true; -} else { - output = false; -} - -if (output == true) { - // If the output is true, the following string will be printed. - Console.WriteLine("I returned true"); -} else { - // Otherwise, the string within this else block will be printed. - Console.WriteLine("I returned false"); -} -``` - -Since the output is `false`, this will output: - -```shell -I returned false -``` - -### Else If Statements - -An `else if` statement comes after an `if` statement and is used if an extra comparison is needed before an `else` statement. - -```pseudo -// Four variables are declared here. -var input1 = 10; -var input2 = 10; -var input3 = 5; -var output = false; - -// If input1 is equal to input3 then set the variable of output to true. -if (input1 == input3) { - output = true; -// If input1 is equal to input2, then set the variable of output to true as well. -} else if (input1 == input2) { - output = true; -// If the two conditions above are false, the else code block will run. -} else { - output = false; -} - -if (output == true) { - Console.WriteLine("I returned true"); -} else if (output == false) { - Console.WriteLine("I returned false"); -} else { - Console.WriteLine("Error"); -} -``` - -Above, the `else if` condition was true so the output was reassigned a value of `true`. This would run the code block in the first `if` block which will output: - -```shell -I returned true -``` - -## Conditional Operator - -The conditional operator `?:` also known as the ternary operator, checks a boolean output and returns one of two results depending on whether the condition is true or false. The ternary operator can be read in pseudocode as follows: - -```cs -Is this condition true ? Run this if yes : Run this if no; -``` - -In the example below, the condition that is checked is if `input1` is equal to 10. If that condition is true, it returns the first string. Otherwise, it returns the second string: - -```cs -string getInput1(int input1) => input1 === 10 ? "I returned true" : "I returned false"; - -Console.WriteLine(getInput1(10)); // Output: "I returned true" -Console.WriteLine(getInput1(5)); // Output: "I returned false" -``` - -## Codebyte Example - -Run the following codebyte example to understand how conditionals work in C#: - -```codebyte/csharp -using System; - -class Program -{ - static void Main() - { - int number = 10; - - // Using if-else conditional statements - if (number > 0) - { - Console.WriteLine("The number is positive."); - } - else if (number < 0) - { - Console.WriteLine("The number is negative."); - } - else - { - Console.WriteLine("The number is zero."); - } - } -} -``` diff --git a/content/c-sharp/concepts/data-types/data-types.md b/content/c-sharp/concepts/data-types/data-types.md deleted file mode 100644 index 28a0b8e50c8..00000000000 --- a/content/c-sharp/concepts/data-types/data-types.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -Title: 'Data Types' -Description: 'C-sharp supports many data types that represent the size and kind of values being stored in memory.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Data Types' - - 'Integers' - - 'Strings' - - 'Booleans' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -C-sharp supports many data types that represent the size and kind of values stored in memory. The two main data types in C# are value and reference types. - -## Value Types - -Value types are data types that are built-in to C#. The available types and their memory sizes are as follows: - -| Data Type | Description | Memory Size | -| --------- | ----------------------- | ------------ | -| `bool` | Boolean | 1 byte | -| `byte` | Byte | 1 byte | -| `sbyte` | Signed Byte | 1 byte | -| `char` | Character | 2 bytes | -| `decimal` | Decimal | 16 bytes | -| `double` | Double | 8 bytes | -| `float` | Float | 4 bytes | -| `int` | Integer | 4 bytes | -| `uint` | Unsigned Integer | 4 bytes | -| `nint` | Native Integer | 4 or 8 bytes | -| `nuint` | Unsigned Native Integer | 4 or 8 bytes | -| `long` | Long | 8 bytes | -| `ulong` | Unsigned Long | 8 bytes | -| `short` | Short | 2 bytes | -| `ushort` | Unsigned Short | 2 bytes | - -The following code demonstrates how to instantiate a variable of each type shown above: - -```csharp -bool isOpen = true; -byte age = 45; -sbyte temperature = 58; -char grade = 'a'; -decimal numberOfAtoms = 1493867940.23m; -double weightOfHippos = 243906.12; -float heightOfGiraffe = 908.32f; -int seaLevel = -24; -uint year = 2023u; -nint pagesInBook = 412; -nuint milesToNewYork = 2597; -long circumferenceOfEarth = 25000l; -ulong depthOfOcean = 28000ul; -short tableHeight = 4; -ushort treeBranches = 33; -``` - -## Reference Types - -Reference types are objects that exist in external memory space. The reference types in C# are as follows: - -- `object` -- `string` -- `dynamic` diff --git a/content/c-sharp/concepts/deque/deque.md b/content/c-sharp/concepts/deque/deque.md deleted file mode 100644 index 3f8b76227da..00000000000 --- a/content/c-sharp/concepts/deque/deque.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -Title: 'Deque' -Description: 'Deque is a type of data structure that allows insertion and removal of elements from both the front and rear.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Deques' - - 'Data Structures' - - 'Data Types' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -`Deque` (Double-Ended Queue) is a type of data structure that allows insertion and removal of elements from both the front and rear. In `C#`, it can be implemented using `LinkedList` and `List`. - -## Creating a Deque using LinkedList Class - -To create a deque in `C#`, use `LinkedList`, where `T` defines the type of elements stored. - -```pseudo -LinkedList deque = new LinkedList(); -``` - -- `T`: Specifies the element type. - -### Example - -The below example shows how to implement deque using `LinkedList`. - -```cs -using System; -using System.Collections.Generic; - -class Program { - static void Main() { - LinkedList deque = new LinkedList(); - - // Adding elements to the front - deque.AddFirst(1); - deque.AddFirst(2); - - // Adding elements to the back - deque.AddLast(3); - deque.AddLast(4); - - // Removing elements from the front - int front = deque.First.Value; - deque.RemoveFirst(); - - // Removing elements from the back - int back = deque.Last.Value; - deque.RemoveLast(); - - foreach (int value in deque) { - Console.WriteLine(value); - } - } -} -``` - -Output: - -```shell -1 -3 -``` - -## Creating a Deque using List Class - -To create a deque in `C#`, use `List`, where `T` defines the type of elements stored. - -```pseudo -List deque = new List(); -``` - -- `T`: Specifies the element type. - -### Example - -The below example shows how to implement deque using `List`. - -```cs -using System; -using System.Collections.Generic; - -class Program { - static void Main() { - List deque = new List(); - - // Adding elements to the front - deque.Insert(0, 1); - deque.Insert(0, 2); - - // Adding elements to the back - deque.Add(3); - deque.Add(4); - - // Removing elements from the front - int front = deque[0]; - deque.RemoveAt(0); - - // Removing elements from the back - int back = deque[deque.Count - 1]; - deque.RemoveAt(deque.Count - 1); - - foreach (int value in deque) { - Console.WriteLine(value); - } - } -} -``` - -Output: - -```shell -1 -3 -``` - -## Codebyte Example - -Use this example to experiment with implementing a `Deque` using `LinkedList`. Enjoy coding! - -```codebyte/csharp -using System; -using System.Collections.Generic; - -public class Example -{ - public static void Main() - { - LinkedList deque = new LinkedList(); - - // Add elements to the front and rear - deque.AddLast(10); // Rear - deque.AddFirst(5); // Front - deque.AddLast(15); // Rear - - // Remove elements from front and rear - deque.RemoveFirst(); // Removes 5 (Front) - deque.RemoveLast(); // Removes 15 (Rear) - - // Display the remaining element - foreach (var item in deque) - { - Console.WriteLine(item); - } - } -} -``` diff --git a/content/c-sharp/concepts/enums/enums.md b/content/c-sharp/concepts/enums/enums.md deleted file mode 100644 index eab155357ae..00000000000 --- a/content/c-sharp/concepts/enums/enums.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -Title: 'Enums' -Description: 'An enum, or enumeration type, is a set of named labels that each represent a number.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Enums' - - 'Data Types' - - 'Arrays' - - 'Vectors' - - 'Pointers' - - 'Memory' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -An **enum**, or enumeration type, is a set of named labels that each represent a number. - -## Syntax - -By default, each entry in an enum is assigned a zero-indexed value. - -```cs -enum NinjaTurtle { - Leonardo, // 0 - Michelangelo, // 1 - Donatello, // 2 - Raphael // 3 -} - -Console.WriteLine((int)NinjaTurtle.Raphael == 3); // Prints "True" -``` - -However, specific number values can also be assigned. - -```cs -enum BreadCount { - Dozen = 12, - BakersDozen = 13, - Gross = 144, - GreatGross = 1728 -} -``` - -## Example - -The following example uses an enum to identify whether a given place is a city, country, or planet. - -```cs -using System.Collections.Generic; - -public enum PlaceType { - City, - Country, - Planet, -} - -public class Place { - public string name { get; set; } - public PlaceType type { get; set; } - - public Place(string n, PlaceType t) { - name = n; - type = t; - } -} - -public class Example { - public static void Main() { - List places = new List(); - places.Add(new Place("Tokyo", PlaceType.City)); - places.Add(new Place("Canada", PlaceType.Country)); - places.Add(new Place("Jupiter", PlaceType.Planet)); - } -} -``` - -## Codebyte Example - -The following example uses an enum to classify different types of log messages. - -```codebyte/csharp -using System; -using System.Collections.Generic; - -public enum LogLevel { - Info, - Warn, - Error, -} - -public class Logger { - public HashSet ShowLevels { get; set; } - - public Logger() { - ShowLevels = new HashSet(); - } - - public void Log(LogLevel level, string message) { - if (ShowLevels.Contains(level)) { - Console.WriteLine(message); - } - } -} - -public class Example -{ - public static void Main() - { - Logger logger = new Logger(); - logger.ShowLevels.Add(LogLevel.Error); - - // "b" is logged to the console but "a" is not, - // since only Error has been added to ShowLevels. - logger.Log(LogLevel.Info, "a"); - logger.Log(LogLevel.Error, "b"); - } -} -``` diff --git a/content/c-sharp/concepts/inheritance/inheritance.md b/content/c-sharp/concepts/inheritance/inheritance.md deleted file mode 100644 index 2c422119058..00000000000 --- a/content/c-sharp/concepts/inheritance/inheritance.md +++ /dev/null @@ -1,170 +0,0 @@ ---- -Title: 'Inheritance' -Description: 'Inheritance in object-oriented programming (OOP) is the concept of creating new classes based on existing classes.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Inheritance' - - 'OOP' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -**Inheritance** in object-oriented programming (OOP) is the concept of creating new classes based on existing classes. In C#, there are parent classes and child classes. - -Child classes, similar to real-life relationships, can inherit properties, methods, and behaviors from their parent class by default and can also introduce their own unique characteristics. - -In summary, a child class in C# inherits the attributes and functionalities of its parent class, while also having the flexibility to define its specific characteristics. A child class can modify or override the characteristics of its parent class, providing a new implementation for methods already defined in the parent class. This process is known as polymorphism, another fundamental concept in OOP. - -The `:` symbol is used in C# within the declaration of the child class to specify the parent or origin class. - -## Syntax - -```cs -public class Phone -{ - public string Brand { get; set; } - public string Model { get; set; } - - public void Call(string phoneNumber) - { - Console.WriteLine($"Calling {phoneNumber}..."); - } -} -public class SmartPhone : Phone - { - public void BrowseInternet() - { - Console.WriteLine("Browsing the internet..."); - } - - - public void SendMessage(string phoneNumber, string message) - { - Console.WriteLine($"Sending message to {phoneNumber}: {message}"); - } - } - -public class LandLinePhone : Phone -{ - // LandLine phones don't have internet browsing functionality or message functionality - -} -``` - -In this example there are two child classes, `SmartPhone` and `LandLinePhone`. Both inherit from the base class or parent class `Phone`. As a result, they have access to the common properties, `Brand` and `Model`, and the call method, `Call()`, defined in the `Phone` class. - -The `SmartPhone` class has two additional methods, `BrowseInternet()` and `SendMessage()`, which are specific to smartphones. These methods enable smartphones to browse the internet and send messages. Those functionalities are not present in the parent `Phone` class. - -On the other hand, the `LandLinePhone` class does not have any additional methods because landline phones are typically used only for calling, and this functionality is already inherited from the parent class. - -## Implementation - -The following example implements the classes created earlier in the main method. - -```cs -public class Program -{ - public static void Main() - { - SmartPhone cellPhone = new SmartPhone - { - Brand = "Apple", - Model = "Iphone 14" - }; - - LandLinePhone housePhone = new LandLinePhone - { - Brand = "Panasonic", - Model = "KX-TG3411SX" - }; - - cellPhone.Call("4259638547"); // Output: "Calling 4259638547..." - cellPhone.SendMessage("2589634712", "Hi! I'm a new contributor of codecademy"); // Output: "Sending message to 2589634712: Hi! I'm a new contributor of codecademy" - cellPhone.BrowseInternet(); // Output: "Browsing the internet..." - - housePhone.Call("4384938752"); // Output: "Calling 4384938752..." - } -} -``` - -## Types of Inheritance - -### Single Inheritance - -Single inheritance is when a child class inherits the characteristics of only one parent class. - -```cs -public class Vehicle { - // Vehicle class properties and methods -} - -public class Car : Vehicle { - // Vehicle class properties and methods accessible here due to inheritance - // Car class properties and methods -} -``` - -### Multilevel Inheritance - -Multilevel inheritance is when a child class inherits from a parent class which in turn inherits from another parent class. This forms a chain of inheritance. A common example in real life is the grand-parent, parent and grand-children relationship. - -```cs -public class Vehicle { - // Vehicle class properties and methods -} - -public class Car : Vehicle { - // Vehicle class properties and methods accessible here due to inheritance - // Car class properties and methods -} -public class SportsCar : Car { - // Vehicle class properties and methods accessible here due to inheritance - // Car class properties and methods accessible here due to inheritance - // SportsCar class properties and methods -} - -``` - -### Hierarchical Inheritance - -Hierarchical inheritance is when a single parent class has multiple children. - -```cs -public class Animal { - // Parent class properties and methods -} - -public class Dog : Animal{ - // Animal class properties and methods accessible here due to inheritance - // Dog class properties and methods -} - -public class Cat : Animal{ - // Animal class properties and methods accessible here due to inheritance - // Cat class properties and methods -} -public class Lion : Animal{ - // Animal class properties and methods accessible here due to inheritance - // Lion class properties and methods -} -public class Mouse : Animal{ - // Animal class properties and methods accessible here due to inheritance - // Mouse class properties and methods -} -``` - -## Access Modifiers - -In C#, access modifiers are used as keywords to determine the accessibility level (visibility) of properties, methods, or fields within a C# program. - -| Keyword | Description | -| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `public` | Available anywhere in the program. | -| `protected` | Available only to the current class or child classes that inherit from that class. | -| `internal` | Available only to the classes in the current project where it is defined. | -| `protected internal` | Available to the current class, child classes that inherit from that class, or classes in the current project where it is defined. | -| `private` | Only available within the class where it is declared. | -| `private protected` | Only available to the classes in the current project where it is defined and also to the children of all classes that inherit from the parent class within the same project. | diff --git a/content/c-sharp/concepts/interfaces/interfaces.md b/content/c-sharp/concepts/interfaces/interfaces.md deleted file mode 100644 index f9935b77152..00000000000 --- a/content/c-sharp/concepts/interfaces/interfaces.md +++ /dev/null @@ -1,216 +0,0 @@ ---- -Title: 'Interfaces' -Description: 'An interface is an abstract contract that defines methods and properties that must be implemented by any class that implements the interface.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Interface' - - 'Syntax' - - 'Abstraction' - - 'Documentation' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -An **interface** in C# is a contract that defines a set of methods, properties, events, and indexers that a class or struct must implement. Interfaces cannot be instantiated directly, but they can be implemented by classes and structs. They are one of several tools for implementing object-oriented design in C#. - -## Syntax - -An interface in C# is created using the `interface` keyword. The syntax for defining an interface in C# is: - -``` -interface MyInterface -{ - void MyMethod(); - string MyProperty { get; set; } - event EventHandler MyEvent; -} -``` - -To implement an interface in C#, you use the `:` symbol, followed by the name of the interface. The syntax for implementing an interface is as follows: - -``` -class MyClass : MyInterface -{ - public void MyMethod() - { - // implementation of MyMethod() - } - - public string MyProperty - { - get { return "MyValue"; } - set { } - } - - public event EventHandler MyEvent; -} -``` - -## Example - -The following example defines an interface with default implementations. This feature is available from C# 8.0 version onwards: - -```cs -using System; - -public interface IAnimal -{ - string Name { get; set; } - void MakeSound(); - void Move(); -} - -public class Dog : IAnimal -{ - public string Name { get; set; } - - public Dog(string name) - { - Name = name; - } - - public void MakeSound() - { - Console.WriteLine("The dog barks when he is happy to see me."); - } - - public void Move() - { - Console.WriteLine("The dog moves when he sees his best friend."); - } -} - -public class Cat : IAnimal -{ - public string Name { get; set; } - - public Cat(string name) - { - Name = name; - } - - public void MakeSound() - { - Console.WriteLine("The cat purrs when I scratch his head."); - } - - public void Move() - { - Console.WriteLine("The cat only moves when there is food in his bowl."); - } -} - -public class Program -{ - public static void Main() - { - IAnimal myDog = new Dog("Spot"); - IAnimal myCat = new Cat("Mittens"); - - Console.WriteLine($"Dog's name: {myDog.Name}"); - myDog.MakeSound(); - myDog.Move(); - - Console.WriteLine($"Cat's name: {myCat.Name}"); - myCat.MakeSound(); - myCat.Move(); - } -} -``` - -The code above results in the following output: - -```shell -Dog's name: Spot -The dog barks when he is happy to see me. -The dog moves when he sees his best friend. -Cat's name: Mittens -The cat purrs when I scratch his head. -The cat only moves when there is food in his bowl. -``` - -## Codebyte Example - -Here is a codebyte example that defines an interface with default implementations: - -```codebyte/csharp -using System; - -public interface IAnimal -{ - void MakeSound(); - string Name { get; set; } - - void Move() - { - Console.WriteLine("This is a default animal movement."); - } -} - -public class Dog : IAnimal -{ - public string Name { get; set; } - - public Dog(string name) - { - Name = name; - } - - public void MakeSound() - { - Console.WriteLine("The dog barks when he is happy to see me."); - } - - public void Move() - { - Console.WriteLine("The dog moves when he sees his best friend."); - } -} - -public class Cat : IAnimal -{ - public string Name { get; set; } - - public Cat(string name) - { - Name = name; - } - - public void MakeSound() - { - Console.WriteLine("The cat purrs when I scratch his head"); - } - public void Move() - { - Console.WriteLine("The cat only moves when there is food in his bowl."); - } -} - -public class Program -{ - public static void Main() - { - IAnimal dog = new Dog("Spot"); - IAnimal cat = new Cat("Mittens"); - - Console.WriteLine($"{dog.Name} actions:"); - dog.MakeSound(); - dog.Move(); - - Console.WriteLine($"{cat.Name} actions:"); - cat.MakeSound(); - cat.Move(); // Uses default implementation - } -} -``` - -## Use of Interfaces - -Interfaces can be used in C# to achieve a number of different goals, including: - -- `Abstraction`: Interfaces can be used to abstract away the implementation details of a class or struct. This can make code more modular and easier to understand. -- `Multiple inheritance`: C# does not support multiple inheritance of classes, but it does support multiple inheritance of interfaces. This allows a class to inherit the functionality of multiple different interfaces. -- `Plug-and-play`: Interfaces can be used to create a "plug-and-play" architecture. This means that different classes or structs can be easily swapped in and out, as long as they implement the same interfaces. diff --git a/content/c-sharp/concepts/loops/loops.md b/content/c-sharp/concepts/loops/loops.md deleted file mode 100644 index 60c86a18638..00000000000 --- a/content/c-sharp/concepts/loops/loops.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -Title: 'Loops' -Description: 'A loop is a logical structure that allows for the repeated execution of a block of code.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Loops' - - 'For' - - 'Control Flow' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -A **loop** is a logical structure used to repeatedly execute a block of code. This repetition can either iterate an exact number of times (definite) or continuously until a condition is met (indefinite). - -## For Loop - -In C# the `for` loop uses definite repetition to run a block of code a specified number of times and consists of three statements separated by semicolons. - -- Statement 1 executes only once, before the code block runs for the first time, and is commonly used to set the initial value of a variable. - -- Statement 2 is a conditional statement that must return `true` for the code block to execute. - -- Statement 3 runs after each repetition of the loop and is typically used to alter the value of the variable set in Statement 1. - -```cs -for (int i = 5; i > 0; i--) -{ - // Repeated code here -} -``` - -> **Note:** Be careful to avoid creating an infinite loop, which occurs if the stop condition never returns `false`. - -## While Loop - -The `while` loop in C# executes an unspecified number of times until the given condition returns `false`. The condition is tested before each iteration of the loop. If the condition is `false` when it is tested the first time, the code block is never run. - -```cs -int i = 0; -while (i > -5) -{ - // Repeated code here - i--; -} -``` - -> **Note:** The variable tested in the condition should be updated within the code block to avoid an infinite loop. - -## Do While Loop - -This form of loop uses the `do` keyword, followed by the code block, followed by the `while` keyword and condition. Unlike the `while` loop it checks the condition after the code block is executed. This means the loop will always iterate at least once, but the condition must be `true` for it to continue. - -```cs -int i = 1; -do -{ - // Repeated code here - i++; -} while (i <= 3); -``` - -> **Note:** The loop in the last example will still run once even though the condition returns `false`. - -## For Each Loop - -The `foreach` loop in C# executes a block of code for each element in a given array or collection. The block is run with each element of the array in turn until the array has been exhausted. - -It is declared with the `foreach` keyword, followed by, in parentheses, a variable type, a variable name, the keyword `in` and the collection to iterate over. - -```cs -// Array to loop over -int[] numbersArray = {0, 1, 2, 3}; - -foreach (int number in numbersArray) -{ - System.Console.WriteLine(number); -} -``` - -This example outputs the following: - -```shell -0 -1 -2 -3 -``` - -## Nested Loop - -`Nested loop` is a concept where one loop is put inside another. For every iteration of the outer loop, all iterations of the inner loop are executed. - -```cs -// Outer loop -for (int i = 0; i < 3; i++) -{ - // Inner loop - for (int j = 0; j < 2; j++) - { - System.Console.WriteLine("i = " + i + ", j = " + j); - } -} -``` - -This example outputs the following: - -```shell -i = 0, j = 0 -i = 0, j = 1 -i = 1, j = 0 -i = 1, j = 1 -i = 2, j = 0 -i = 2, j = 1 -``` - -Inner and outer loops do not require being the same type. For instance, A `while` loop can be placed inside a `for` loop, or a `do-while` loop inside a `foreach` loop. - -```cs -int[] numbersArray = { 0, 1, 2, 3 }; -// Outer loop -foreach (int number in numbersArray) -{ - // Inner loop - for (int k = 0; k < 2; k++) - { - System.Console.WriteLine("number = " + number + ", k = " + k); - } -} -``` - -This example outputs the following: - -```shell -number = 0, k = 0 -number = 0, k = 1 -number = 1, k = 0 -number = 1, k = 1 -number = 2, k = 0 -number = 2, k = 1 -number = 3, k = 0 -number = 3, k = 1 -``` - -There is no upper limit on nesting levels. The examples above used two loops, but one can nest even more loops. However, it's a good practice to avoid deep nesting, as it complicates programs. diff --git a/content/c-sharp/concepts/math-functions/math-functions.md b/content/c-sharp/concepts/math-functions/math-functions.md deleted file mode 100644 index 7b777e41cac..00000000000 --- a/content/c-sharp/concepts/math-functions/math-functions.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -Title: 'Math Functions' -Description: 'Common mathematical functions can be performed using the System.Math class.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Libraries' - - 'Arithmetic' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/build-web-apps-with-asp-net' ---- - -**Mathematical functions** can be performed using the `System.Math` class. `System.Math` is a static class that is included within .NET as part of the `System` namespace. [.NET](https://dotnet.microsoft.com/en-us/learn/dotnet/what-is-dotnet) is a free, cross-platform, open source developer platform created by Microsoft. - -## Syntax - -The `Math` class can be accessed by including the `System` namespace within a `.cs` file by adding the following line: - -```pseudo -// Include the System namespace -using System; -``` - -The `Math` class is static and is accessed without needing to create an instance. - -## Example - -The following example uses the `Math.Pow()` method to return the result of `4` raised to the power of `2`: - -```cs -// Include the System namespace -using System; - -public class Example -{ - public static void Main(string[] args) - { - // Raise 4 to power of 2 - double x = Math.Pow(4,2); - - System.Console.WriteLine("x = {0}", x); - // Output: x = 16 - } -} -``` - -In cases where access to `System.Math` is required but access to the entire `System` namespace is not, an alternative syntax can be used instead. The following example uses an alternative syntax and returns the floor of `3/2` using the `System.Math.Floor()` method: - -```cs -public class Example -{ - public static void Main(string[] args) - { - // Round down the result of 3/2 - double x = System.Math.Floor((double)3/2); - - System.Console.WriteLine("x = {0}", x); - // Output: x = 1 - } -} -``` - -Below are a selected list of `System.Math` methods: diff --git a/content/c-sharp/concepts/math-functions/terms/abs/abs.md b/content/c-sharp/concepts/math-functions/terms/abs/abs.md deleted file mode 100644 index 063d5da7779..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/abs/abs.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -Title: '.Abs()' -Description: 'Returns the absolute value of a given number.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Methods' - - 'Numbers' - - 'Arithmetic' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Abs()`** class method returns the absolute value of a given number. - -## Syntax - -```pseudo -Math.Abs(number); -``` - -The `Math.Abs()` method takes only one parameter, `number`, a `decimal`, `double` or `integer` type number. The method returns the absolute value of the `number` with the same type as the `number`, except if the value of `number` equals: - -- `NaN` (not a number), then it returns `NaN` -- `NegativeInfinity`, then it returns `PositiveInfinity` -- `PositiveInfinity`, then it also returns `PositiveInfinity` - -## Example - -The following example uses the `Math.Abs()` method to return the absolute value of a `decimal` and a `double` type number. Then, the `Console.WriteLine()` function prints the results to the console: - -```cs -using System; - -public class Example { - public static void Main() { - decimal num1 = -1.23M; - double num2 = 6.674E-11; - - decimal abs1 = Math.Abs(num1); - double abs2 = Math.Abs(num2); - - Console.WriteLine("The absolute value of " + num1 + " is: " + abs1); - Console.WriteLine("The absolute value of " + num2 + " is: " + abs2); - } -} -``` - -The example will result in the following output: - -```shell -The absolute value of -1.23 is: 1.23 -The absolute value of 6.674E-11 is: 6.674E-11 -``` - -## Codebyte Example - -The following example is runnable and returns the absolute value of a `double` type number: - -```codebyte/csharp -using System; - -public class Example { - - public static void Main() { - double number = 299792458; - - Console.WriteLine("The absolute value of " + number + " is: " + Math.Abs(number)); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/acos/acos.md b/content/c-sharp/concepts/math-functions/terms/acos/acos.md deleted file mode 100644 index 78b6a10d1b1..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/acos/acos.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -Title: '.Acos()' -Description: 'Returns the inverse cosine of the argument.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arithmetic' - - 'Numbers' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Acos()`** method returns the absolute value of the inverse cosine of the argument, measured in radians. In other words, it returns the positive angle whose cosine is the specified number. - -## Syntax - -```pseudo -Math.Acos(x); -``` - -The method takes one parameter `x` of the type `double`. It will return a positive value of type `double` except in the following cases: - -- If `x` is less than -1, it will return `NaN` (not a number). -- If `x` is greater than 1, it will return `NaN`. -- If `x` is `NaN`, it will return `NaN`. - -## Example - -The following example prints the results of the `Math.Acos()` method for five different values. - -```cs -using System; - -namespace MyMathExample -{ - public class Example - { - public static void Main(string[] args) - { - double a = Math.Acos(0.5); - double b = Math.Acos(1); - double c = Math.Acos(-2); - double d = Math.Acos(4); - double e = Math.Acos(0); - - Console.WriteLine(a); - Console.WriteLine(b); - Console.WriteLine(c); - Console.WriteLine(d); - Console.WriteLine(e); - } - } -} -``` - -This results in the following output: - -```shell -1.0471975511966 -0 -NaN -NaN -1.5707963267949 -``` - -## Codebyte Example - -The example below uses `Math.Acos()` to calculate the arc cosine of `x`. The result is stored in the `result` variable. - -```codebyte/csharp -using System; - -class Program -{ - static void Main() - { - double x = -1.0; - double result = Math.Acos(x); - - Console.WriteLine($"The arc cosine of {x} is {result} radians."); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/asin/asin.md b/content/c-sharp/concepts/math-functions/terms/asin/asin.md deleted file mode 100644 index 6d9159ee4f7..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/asin/asin.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -Title: '.Asin()' -Description: 'Returns an angle in radians whose sine is a specified number.' -Subjects: - - 'Computer Science' -Tags: - - 'Libraries' - - 'Arithmetic' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **Math.Asin()** method computes an angle in radians whose sine is a specified number. In Math, this is known as the inverse sine function. - -## Syntax - -```pseudo -Math.Asin(value); -``` - -`value` is the input value of type double, which must be in the range -1 <= `value` <= 1. - -Returns an angle measured in radians, of type `double`, whose sine is `value`. If an invalid value is passed to the function, or no value is passed at all, `NaN` is returned. - -## Example - -The following example prints the results of the `Math.Asin()` method for three different values: - -```cs -using System; - -public class Example -{ - static void Main() - { - double a = Math.Asin(0.5); - double b = Math.Asin(1); - double c = Math.Asin(-2); - - Console.WriteLine(a); - Console.WriteLine(b); - Console.WriteLine(c); - } -} -``` - -This results in the following output: - -```shell -0.523598775598299 -1.5707963267949 -NaN -``` - -## Codebyte Example - -```codebyte/csharp -using System; - -class CodecademyDemo -{ - static void Main() - { - Double result = Math.Asin(0); - System.Console.WriteLine("Asin(0) = "+ result + " radians"); - - Double result1 = Math.Asin(1); - System.Console.WriteLine("Asin(1) = "+ result1 + " radians"); - - Double result2 = Math.Asin(-1); - System.Console.WriteLine("Asin(-1) = "+ result2 + " radians"); - - Double result3 = Math.Asin(2); - System.Console.WriteLine("Asin(2) = "+ result3); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/atan/atan.md b/content/c-sharp/concepts/math-functions/terms/atan/atan.md deleted file mode 100644 index 804715a1e9d..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/atan/atan.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -Title: '.Atan()' -Description: 'Returns the inverse tangent of the argument.' -Subjects: - - 'Computer Science' -Tags: - - 'Arithmetic' - - 'Methods' - - 'Numbers' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -**`Math.Atan()`** is a static method that calculates the inverse tangent of a given number, in radians. - -## Syntax - -```pseudo -Math.Atan(x); -``` - -- The `Math.Atan()` method takes one double as an argument and returns a double. -- Using this method requires the `System` namespace. - -## Example - -This example first uses the `Math.Atan()` method to compute the arctangent of an angle in radians and then converts it to degrees: - -```cs -using System; - -class sample -{ - public static void Main() - { - double value = 1.0; // The tangent of an angle - double angleInRadians = Math.Atan(value); - Console.WriteLine("The arctangent of the angle in radians: {0}",angleInRadians); - double angleInDegrees = angleInRadians * (180 / Math.PI); - Console.WriteLine("The arctangent of the angle in degrees: {0}",angleInDegrees); - } -} -``` - -The above code creates the following output: - -```shell -The arctangent of the angle in radians: 0.7853981633974483 -The arctangent of the angle in degrees: 45 -``` - -## Codebyte Example - -The following example uses `Math.Atan()` to return the arctangent of a right angled triangle, where the side opposite the angle is equal to 7, and the side adjacent is 5: - -```codebyte/csharp -namespace AtanExample { - class Example { - static void Main(string[] args) { - double oppSide = 7; - double adjSide = 5; - double tangentValue = oppSide / adjSide; - double arctangentValue = System.Math.Atan(tangentValue); - System.Console.WriteLine($"Arcangent = {arctangentValue}"); - } - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/atan2/atan2.md b/content/c-sharp/concepts/math-functions/terms/atan2/atan2.md deleted file mode 100644 index 213112afecd..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/atan2/atan2.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -Title: '.Atan2()' -Description: 'Returns the angle, in radians, between the positive x-axis and the vector to point (x, y).' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Arithmetic' - - 'Functions' - - 'Geometry' - - 'Methods' - - 'Numbers' - - 'Trigonometry' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **Math.Atan2()** function returns the angle, in radians, between the positive x-axis and a vector to the point with the given (x, y) coordinates in the Cartesian plane. - -## Syntax - -```pseudo -Math.Atan2(y, x) -``` - -The function takes two arguments `y` and `x` of type `double`, representing the `y` and `x` coordinates of a point (x, y). - -The return value is the angle θ, measured in radians, for which tan(θ) = `y` / `x`. The resulting angle is between -π and π. - -- When `x` > 0 and `y` > 0, in quadrant 1, 0 < θ < π/2. -- When `x` < 0 and `y` > 0, in quadrant 2, π/2 < θ < π. -- When `x` < 0 and `y` < 0, in quadrant 3, -π < θ < -π/2. -- When `x` > 0 and `y` < 0, in quadrant 4, -π/2 < θ < 0. - -For points (x, y) on the boundaries of the quadrants: - -- When `x` >= 0 and `y` = 0, θ = 0. -- When `x` = 0 and `y` > 0, θ = π/2. -- When `x` < 0 and `y` = 0, θ = π. -- When `x` = 0 and `y` < 0, θ = -π/2. - -## Example - -The following is an example of the `Math.Atan2()` function: - -```cs -using System; - -public class Program -{ - public static void Main() - { - double x = 4.0; - double y = 3.0; - - double angleRadians = Math.Atan2(y, x); - double angleDegrees = angleRadians * (180/Math.PI); - - Console.WriteLine("The angle in radians between the positive x-axis and"); - Console.WriteLine($"a vector to the point ({x}, {y}) is: {angleRadians},"); - Console.WriteLine($"which is equivalent to {angleDegrees} degrees."); - } -} -``` - -This example produces the following output: - -``` -The angle in radians between the positive x-axis and -a vector to the point (4, 3) is: 0.643501108793284, -which is equivalent to 36.869897645844 degrees. -``` - -## Codebyte Example - -The following is a runnable example. Changing the values of the variables will yield different results: - -```codebyte/csharp -using System; - -class Sample { - static void Main() { - double x = -5; - double y = 0; - - double angleRadians = Math.Atan2(y, x); - double angleDegrees = angleRadians * (180/Math.PI); - - Console.WriteLine($"point ({x}, {y})"); - Console.WriteLine($"angle in radians: {angleRadians}"); - Console.WriteLine($"angle in degrees: {angleDegrees}"); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/ceiling/ceiling.md b/content/c-sharp/concepts/math-functions/terms/ceiling/ceiling.md deleted file mode 100644 index 9f51a7a07ce..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/ceiling/ceiling.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -Title: '.Ceiling()' -Description: 'Returns the smallest integer which is greater than or equal to a given number.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Libraries' - - 'Arithmetic' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -**`Math.Ceiling()`** is a class method that always rounds up to the next full integer. It is used to return the smallest integer greater than or equal to the specified number. - -## Syntax - -```pseudo -Math.Ceiling(val); -``` - -- The method takes only one parameter, `val`, the number to be rounded (as a `decimal` or `double` type). - -## Example - -The following example uses `Math.Ceiling()` to return the next full integer. - -```cs -// Include the System namespace -using System; -public class Demo { - public static void Main(){ - decimal val1 = 6.64M; - decimal val2 = -9.02M; - Console.WriteLine("Solution = " + Math.Ceiling(val1)); - Console.WriteLine("Solution = " + Math.Ceiling(val2)); - } -} -``` - -The example will result in the following output: - -```shell -Solution = 7 -Solution = -9 -``` - -## Codebyte Example - -The following example is runnable and uses the `Math.Ceiling()` method to return the smallest whole number that is greater than or equal to the given `double` type `number`: - -```codebyte/csharp -using System; - -public class Example { - public static void Main() { - double number = 3.14159; - double ceiling = Math.Ceiling(number); - - Console.WriteLine("The ceiling value of " + number + " is " + ceiling); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/cos/cos.md b/content/c-sharp/concepts/math-functions/terms/cos/cos.md deleted file mode 100644 index c2e9b1f8d39..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/cos/cos.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -Title: '.Cos()' -Description: 'Returns the cosine of a given angle.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Methods' - - 'Numbers' - - 'Arithmetic' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Cos()`** class method returns the cosine of a given angle. - -## Syntax - -```pseudo -Math.Cos(angle); -``` - -The `Math.Cos()` method takes only one parameter, `angle`, an angle in radians of type `double`. The method returns the cosine of the `angle` as a `double` value or `NaN` (not a number) if the value of `angle` equals: - -- `NaN` -- `NegativeInfinity` -- `PositiveInfinity` - -## Example - -The following example first converts `60` degrees to radians, then uses the `Math.Cos()` method to return the sine of that angle. Finally, the `Console.WriteLine()` function prints the result to the console: - -```cs -using System; - -public class Example { - public static void Main(string[] args) { - double degrees = 60; - double radians = degrees * Math.PI/180; - - double cosine = Math.Cos(radians); - - Console.WriteLine("The cosine of " + degrees + " degrees is: " + cosine); - } -} -``` - -The example will result in the following output: - -```shell -The cosine of 60 degrees is: 0.5 -``` - -## Codebyte Example - -The following example is runnable and returns the cosine of the `angle` given in degrees: - -```codebyte/csharp -using System; - -public class Example { - - public static void Main(string[] args) { - // Angle in degrees - double angle = 0; - - Console.WriteLine("The cosine of " + angle + " degrees is: " + Math.Cos(angle * Math.PI/180)); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/cosh/cosh.md b/content/c-sharp/concepts/math-functions/terms/cosh/cosh.md deleted file mode 100644 index ed0f3e79531..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/cosh/cosh.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -Title: '.Cosh()' -Description: 'Returns the hyperbolic cosine of a given angle.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Methods' - - 'Numbers' - - 'Arithmetic' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Cosh()`** class method returns the hyperbolic cosine of a given angle. - -## Syntax - -```pseudo -Math.Cosh(angle); -``` - -The `Math.Cosh()` method takes only one parameter, `angle`, an angle in radians of type `double`. The method returns the hyperbolic cosine of the `angle` as a `double` value, except if the value of `angle` equals: - -- `NaN` (not a number), then it returns `NaN`. -- `NegativeInfinity`, then it returns `PositiveInfinity`. -- `PositiveInfinity`, then it also returns `PositiveInfinity`. - -> **Note:** Depending on the operating system or architecture, the exact result or the input range of the `Math.Cosh()` method may differ due to the differences in the C runtime environment. - -## Example - -The following example first converts `45` degrees to radians, then uses the `Math.Cosh()` method to return the hyperbolic cosine of that angle. `Math.Round()` rounds up the result to five decimals. Finally, the result is printed using `Console.WriteLine()`: - -```cs -using System; - -public class Example { - public static void Main(string[] args) { - double degrees = 45; - double radians = degrees * Math.PI/180; - - double hyperbolicCosine = Math.Round(Math.Cosh(radians), 5); - - Console.WriteLine("The hyperbolic cosine of " + degrees + " degrees is: " + hyperbolicCosine); - } -} -``` - -The example will result in the following output: - -```shell -The hyperbolic cosine of 45 degrees is: 1.32461 -``` - -## Codebyte Example - -The following example is runnable and returns the hyperbolic cosine of the `angle` given in degrees: - -```codebyte/csharp -using System; - -public class Example { - public static void Main(string[] args) { - // Angle in degrees - double angle = 0; - - Console.WriteLine("The hyperbolic cosine of " + angle + " degrees is: " + Math.Round(Math.Cosh(angle * Math.PI/180), 5)); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/exp/exp.md b/content/c-sharp/concepts/math-functions/terms/exp/exp.md deleted file mode 100644 index cc1fb6bf90a..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/exp/exp.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -Title: '.Exp()' -Description: 'Returns the result of raising e to the power of a specific number.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arithmetic' - - 'Numbers' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Exp()`** method returns the value of raising `e` to the power of a given number. - -`e` stands for Euler's number, an irrational number, with an approximate constant value of 2.71828. It provides a constant base to the natural logarithm or log and can be understood as a limit of a given progression. - -![e Formula](https://raw.githubusercontent.com/Codecademy/docs/main/media/e-formula.jpg) - -Consequently, the `Math.Exp()` method is the inverse of the `Math.Log()` method. - -## Syntax - -```pseudo -Math.Exp(double n); -``` - -The method takes only one parameter; the variable `n` (number) of type `double`. The function will return a positive value of type `double` unless the value passed is one of the following: - -- If `n` is `0`, the function will return `1`. -- If `n` is `PositiveInfinity`, the function will return `PositiveInfinity`. -- If `n` is `NegativeInfinity`, the function will return `0`. -- If `n` is `NaN`, the function will return `NaN`. - -## Example - -The following example applies the `Math.Exp()` method for six different values. The return values are printed with the `Console.WriteLine()` method. - -```cs -using System; - -namespace MathExpMethod -{ - public class Example - { - public static void Main(string[] args) - { - double firstCase = Math.Exp(1); - double secondCase = Math.Exp(-1); - double thirdCase = Math.Exp(0); - double fourthCase = Math.Exp(double.PositiveInfinity); - double fifthCase = Math.Exp(double.NegativeInfinity); - double sixthCase = Math.Exp(double.NaN); - - Console.WriteLine(firstCase); - Console.WriteLine(secondCase); - Console.WriteLine(thirdCase); - Console.WriteLine(fourthCase); - Console.WriteLine(fifthCase); - Console.WriteLine(sixthCase); - } - } -} -``` - -This example results in the following output: - -```shell -2.71828182845905 -0.367879441171442 -1 -Infinity -0 -NaN -``` - -## Codebyte Example - -The following example is runnable and uses the `Math.Exp()` method to return the value of raising `e` to the power of the given `double` type `number`: - -```codebyte/csharp -using System; - -public class Example { - public static void Main() { - double number = 0; - double exponential = Math.Exp(number); - - Console.WriteLine("The value of e raised to the power of " + number + " is " + exponential); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/floor/floor.md b/content/c-sharp/concepts/math-functions/terms/floor/floor.md deleted file mode 100644 index 02f480fa8f4..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/floor/floor.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -Title: '.Floor()' -Description: 'Returns the largest whole integer which is less than or equal to the given number.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Libraries' - - 'Arithmetic' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -**`Math.Floor()`** is a static method that rounds down and returns the largest whole integer that is less than or equal to the given number. - -## Syntax - -```pseudo -Math.Floor(x); -``` - -- The `Math.Floor()` method is used to find the largest whole integer that is less than or equal to the argument, `x`, passed in. The argument can be of a `float` or `double` type. -- The `System` namespace is required to access this method. - -## Example - -The following example uses `Math.Floor()` to return the largest whole number. - -```cs -// Include the System namespace -using System; - -public class Floor { - public static void Main() { - Console.WriteLine(Math.Floor(5.05)); - } -} -``` - -The example will result in the following output: - -```shell -5 -``` - -## Codebyte Example - -The following example is runnable and uses the `Math.Floor()` method to return the largest whole number that is less than or equal to the given `double` type `number`: - -```codebyte/csharp -using System; - -public class Example { - public static void Main() { - double number = 3.14159; - double floor = Math.Floor(number); - - Console.WriteLine("The floor value of " + number + " is " + floor); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/max/max.md b/content/c-sharp/concepts/math-functions/terms/max/max.md deleted file mode 100644 index 15de4e39d3e..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/max/max.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -Title: '.Max()' -Description: 'Returns the greater of two specified numbers.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Methods' - - 'Numbers' - - 'Arithmetic' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Max()`** method returns the greater of two specified numbers. - -## Syntax - -```pseudo -Math.Max(num1, num2) -``` - -`Math.Max()` returns the greater value from `num1` and `num2`. - -## Example - -The following example compares two integers `i1` and `i2` and writes the greater integer to the console. - -```cs -using System; - -public class Example { - public static void Main (string[] args) { - int i1 = -234, i2 = 345; - - Console.WriteLine("Math.Max (int) = " + Math.Max(i1,i2)); - } -} -``` - -This example results in the following output: - -```shell -Math.Max (int) = 345 -``` - -## Codebyte Example - -The following example is runnable and uses the `Math.Max()` method to return the greater number from the given two `integer` type numbers, `number1` and `number2`: - -```codebyte/csharp -using System; - -public class Example { - public static void Main() { - int number1 = 12756, number2 = 12104; - int max = Math.Max(number1, number2); - - Console.WriteLine("The max value of " + number1 + " and " + number2 + " is " + max); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/min/min.md b/content/c-sharp/concepts/math-functions/terms/min/min.md deleted file mode 100644 index 614410c8aaf..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/min/min.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -Title: '.Min()' -Description: 'Returns the smaller of two specified numbers.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Methods' - - 'Numbers' - - 'Arithmetic' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Min()`** method returns the lesser of two specified numbers. - -## Syntax - -```pseudo -Math.Min(num1, num2) -``` - -`Math.Min()` returns the lesser value from `num1` and `num2`. - -## Example - -The following example compares two integers `i1` and `i2` and writes the lesser integer to the console. - -```cs -using System; - -public class Example { - public static void Main (string[] args) { - int i1 = -134, i2 = 268; - - Console.WriteLine("Math.Min (int) = " + Math.Min(i1,i2)); - } -} -``` - -This example results in the following output: - -```shell -Math.Min (int) = -134 -``` - -## Codebyte Example - -Try changing the values of xint1 and xint2 to see the results. - -```codebyte/csharp -string str = "{0}: The lesser of {1,3} and {2,3} is {3}."; - -int xInt1 = 267, xInt2 = -39; - -Console.WriteLine("Display the lesser of two values:\n"); -Console.WriteLine(str,"--> ", xInt1, xInt2, Math.Min(xInt1, xInt2)); -``` diff --git a/content/c-sharp/concepts/math-functions/terms/pow/pow.md b/content/c-sharp/concepts/math-functions/terms/pow/pow.md deleted file mode 100644 index 1eea469f1a9..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/pow/pow.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -Title: '.Pow()' -Description: 'Returns the result of a given number raised to the power of a second number.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Methods' - - 'Numbers' - - 'Arithmetic' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Pow()`** method returns a number raised to the power of a second number. - -## Syntax - -```pseudo -Math.Pow(num1, num2) -``` - -`Math.Pow()` takes two values of type `double`. It will return a `double` that is the result of the value `num1` raised to the power of value `num2`. - -## Example - -The following example demonstrates the `Math.Pow()` method and writes the result to the console. - -```cs -using System; - -public class Example { - public static void Main (string[] args) { - double d1 = 8, d2 = 3; - - Console.WriteLine("8^3 = " + Math.Pow(d1,d2)); - } -} -``` - -This example results in the following output: - -```shell -8^3 = 512 -``` - -## Codebyte Example - -The following example is runnable and uses the `Math.Pow()` method to return a `double` type value of `2` raised to the power of `10`: - -```codebyte/csharp -using System; - -public class Example { - public static void Main() { - double number = 2, power = 10; - double value = Math.Pow(number, power); - - Console.WriteLine("The value of " + number + " raised to the power of " + power + " is " + value); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/round/round.md b/content/c-sharp/concepts/math-functions/terms/round/round.md deleted file mode 100644 index 17c5771c162..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/round/round.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -Title: '.Round()' -Description: 'Returns a value rounded to the nearest integer.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Methods' - - 'Numbers' - - 'Arithmetic' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Round()`** class method returns a value rounded to the nearest integer. - -## Syntax - -```pseudo -Math.Round(value1, value2, value3); -``` - -The `Math.Round()` method takes up to three parameters: - -- `value1` is the only required parameter and is either a decimal or double. -- `value2` would be an integer ranging from -2,147,483,648 to 2,147,483,647 (int32), or it could be a specific mode that is called from the `MidpointRounding` `enum`. -- `value3` would be the mode if `value2` was of type int32. The modes include: `ToEven`, `AwayFromZero`, `ToZero`, and `TowardZero`. - -## Example - -The following example passes one argument as a parameter: - -```cs -using System; - -public class Example { - public static void Main(string[] args) { - decimal val1 = 10.2m; - val1 = Math.Round(val1); - - Console.WriteLine("Rounded value is " + val1); - } -} -``` - -The example will result in the following output: - -```shell -Rounded value is 10 -``` - -## Codebyte Example - -The following example passes three arguments into the method: - -```codebyte/csharp -using System; - -public class Example { - - public static void Main(string[] args) { - decimal val1 = 20.5m; - int val2 = 0; - MidpointRounding mode = MidpointRounding.ToEven; - - Console.WriteLine("Rounded value is " + Math.Round(val1, val2, mode)); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/sin/sin.md b/content/c-sharp/concepts/math-functions/terms/sin/sin.md deleted file mode 100644 index 3eedf463737..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/sin/sin.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -Title: '.Sin()' -Description: 'Returns the sine of a given angle.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Methods' - - 'Numbers' - - 'Arithmetic' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Sin()`** class method returns the sine of a given angle. - -## Syntax - -```pseudo -Math.Sin(angle); -``` - -The `Math.Sin()` method takes only one parameter, `angle`, an angle in radians of type `double`. The method returns the sine of the `angle` as a `double` value or `NaN` (not a number) if the value of `angle` equals: - -- `NaN` -- `NegativeInfinity` -- `PositiveInfinity` - -## Example - -The following example first converts `30` degrees to radians, then uses the `Math.Sin()` method to return the sine of that angle. Finally, the `Console.WriteLine()` function prints the result to the console: - -```cs -using System; - -public class Example { - public static void Main(string[] args) { - double degrees = 30; - double radians = degrees * Math.PI/180; - - double sine = Math.Sin(radians); - - Console.WriteLine("The sine of " + degrees + " degrees is: " + sine); - } -} -``` - -The example will result in the following output: - -```shell -The sine of 30 degrees is: 0.5 -``` - -## Codebyte Example - -The following example is runnable and returns the sine of the `angle` given in degrees: - -```codebyte/csharp -using System; - -public class Example { - - public static void Main(string[] args) { - // Angle in degrees - double angle = -90; - - Console.WriteLine("The sine of " + angle + " degrees is: " + Math.Sin(angle * Math.PI/180)); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/sinh/sinh.md b/content/c-sharp/concepts/math-functions/terms/sinh/sinh.md deleted file mode 100644 index 61fb7d1094f..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/sinh/sinh.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -Title: '.Sinh()' -Description: 'Returns the hyperbolic sine of a given angle.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Methods' - - 'Numbers' - - 'Arithmetic' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Sinh()`** class method returns the hyperbolic sine of a given angle. - -## Syntax - -```pseudo -Math.Sinh(angle); -``` - -The `Math.Sinh()` method takes only one parameter: an `angle` in radians of type `double`. The method returns the hyperbolic sine of the angle as a `double` value, except if the value of `angle` equals: - -- `NaN` (not a number), then it returns `NaN`. -- `NegativeInfinity`, then it returns `NegativeInfinity`. -- `PositiveInfinity`, then it returns `PositiveInfinity`. - -> **Note:** Depending on the operating system or architecture, the exact result or the input range of the `Math.Sinh()` method may differ due to the differences in the C runtime environment. - -## Example - -The following example first converts `88` degrees to radians, then uses the `Math.Sinh()` method to return the hyperbolic sine of that angle. `Math.Round()` rounds up the result to five decimals. Finally, the `Console.WriteLine()` function prints the result to the console: - -```cs -using System; - -public class Example { - public static void Main(string[] args) { - double degrees = 88; - double radians = degrees * Math.PI/180; - double hyperbolicSine = Math.Round(Math.Sinh(radians), 5); - - Console.WriteLine("The hyperbolic sine of " + degrees + " degrees is: " + hyperbolicSine); - } -} -``` - -The example will result in the following output: - -```shell -The hyperbolic sine of 88 degrees is: 2.2151 -``` - -## Codebyte Example - -The following example is runnable and returns the hyperbolic sine of the `angle` given in degrees: - -```codebyte/csharp -using System; - -public class Example { - public static void Main(string[] args) { - // Angle in degrees - double angle = 0; - - Console.WriteLine("The hyperbolic sine of " + angle + " degrees is: " + Math.Round(Math.Sinh(angle * Math.PI/180), 5)); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/sqrt/sqrt.md b/content/c-sharp/concepts/math-functions/terms/sqrt/sqrt.md deleted file mode 100644 index 5f047510941..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/sqrt/sqrt.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -Title: '.Sqrt()' -Description: 'Returns the square root of the given number.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arithmetic' - - 'Numbers' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Sqrt()`** method returns the square root of the number given. - -## Syntax - -```pseudo -Math.Sqrt(x); -``` - -The method takes only one parameter, the variable `x`, of type `double`. The function will return a positive value of type `double` unless the value passed is one of the following: - -- If `x` is negative, the function will return `NaN` (not a number). -- If `x` is `NaN`, the function will return `NaN`. -- If `x` is `PositiveInfinity`, the function will return `PositiveInfinity`. - -## Example - -The following example demonstrates the `Math.Sqrt()` method. Four different values are passed to the method, and the return values are printed with the `Console.WriteLine()` method. - -```cs -using System; - -namespace MySquareRoot { - public class Example { - public static void Main(string[] args) { - double a = Math.Sqrt(256); - double b = Math.Sqrt(-256); - double c = Math.Sqrt(500); - double d = Math.Sqrt(0.144); - - Console.WriteLine(a); - Console.WriteLine(b); - Console.WriteLine(c); - Console.WriteLine(d); - } - } -} -``` - -This example results in the following output: - -```shell -16 -NaN -22.3606797749979 -0.379473319220205 -``` - -## Codebyte Example - -The following example is runnable and uses the `Math.Sqrt()` method to return a `double` type value of the square root of `100`: - -```codebyte/csharp -using System; - -public class Example { - public static void Main() { - double number = 100; - double squareRoot = Math.Sqrt(number); - - Console.WriteLine("The square root of " + number + " is " + squareRoot); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/tan/tan.md b/content/c-sharp/concepts/math-functions/terms/tan/tan.md deleted file mode 100644 index ca54086b595..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/tan/tan.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -Title: '.Tan()' -Description: 'Returns the tangent of a given angle.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Methods' - - 'Numbers' - - 'Arithmetic' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -In C#, the **`Math.Tan()`** method returns the tangent of a given angle. - -## Syntax - -```pseudo -Math.Tan(angle); -``` - -The `Math.Tan()` method takes only one parameter, `angle`, an angle in radians of type `double`. The method returns the tangent of the `angle` as a `double` value or `NaN` (not a number) if the value of `angle` equals: - -- `NaN` -- `NegativeInfinity` -- `PositiveInfinity` - -## Example - -The following example converts 30 degrees to radians and then uses the `Math.Tan()` method to calculate the tangent of that angle. Finally, `Console.WriteLine()` outputs the result to the console: - -```cs -using System; - -public class Example { - public static void Main(string[] args) { - // Define an angle in degrees - double degrees = 30; - - // Convert the angle to radians - double radians = degrees * Math.PI/180; - - // Calculate the tangent of the angle - double tangent = Math.Tan(radians); - - // Display the result - Console.WriteLine("The tangent of " + degrees + " degrees is: " + tangent); - } -} -``` - -The above example will result in the following output: - -```shell -The tangent of 30 degrees is: 0.5773502691896257 -``` - -## Codebyte Example - -The following example is runnable and returns the tangent of the `angle` given in degrees: - -```codebyte/csharp -using System; -public class Example { - public static void Main(string[] args) { - double degrees = 45; - double radians = degrees * Math.PI/180; - double tangent = Math.Tan(radians); - Console.WriteLine("The tangent of " + degrees + " degrees is: " + tangent); - } -} -``` diff --git a/content/c-sharp/concepts/math-functions/terms/tanh/tanh.md b/content/c-sharp/concepts/math-functions/terms/tanh/tanh.md deleted file mode 100644 index d5d67313315..00000000000 --- a/content/c-sharp/concepts/math-functions/terms/tanh/tanh.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -Title: '.Tanh()' -Description: 'Computes the hyperbolic tangent of a given angle in radians.' -Subjects: - - 'Computer Science' - - 'Data Science' -Tags: - - 'Arithmetic' - - 'Numbers' - - 'Classes' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`Math.Tanh()`** method returns the hyperbolic tangent of a given angle in radians. - -## Syntax - -```pseudo -Math.Tahn(x); -``` - -This method accepts a single parameter,`x`, which is the angle in radians. It returns the hyperbolic tangent value of `x`. - -## Example - -The example below declares two double values, `x` and `y`, and then calculates the hyperbolic tangent of `x` using the `Math.Tanh()` function. The resulting value is stored in `y`. Finally, the value of `y` is printed to the console. - -```cs -using System; - -public class Program -{ - public static void Main() - { - double x = 2; - double y = Math.Tanh(x); - - Console.WriteLine(y); - // Output: 0.9640275800758169 - } -``` - -## Codebyte Example - -This example is runnable and demonstrates the `Math.tanh()` function: - -```codebyte/csharp -using System; -public class program -{ - public static void Main(string[] args) - { - double num1 = 60.0, num2 = 0.0, num3 = 1.0; - double tanhvalue = Math.Tanh(num1); - Console.WriteLine("The tanh of num1 = " + tanhvalue); - - tanhvalue = Math.Tanh(num2); - Console.WriteLine("The tanh of num2 = " + tanhvalue); - - tanhvalue = Math.Tanh(num3); - Console.WriteLine("The tanh of num3 = " + tanhvalue); - } - } -``` diff --git a/content/c-sharp/concepts/methods/methods.md b/content/c-sharp/concepts/methods/methods.md deleted file mode 100644 index 91e0e0f9bf4..00000000000 --- a/content/c-sharp/concepts/methods/methods.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -Title: 'Methods' -Description: 'Methods are blocks of code that can be called elsewhere in the program.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -**Methods** are blocks of code that can be reused elsewhere in a C# application. Each application has at least one `Main()` method that acts as the starting point. Methods are used to avoid the repetition of code and make it maintainable and readable. Usually, a method has one or multiple dedicated purposes. - -A function inside a class is called a method. As C# is an [object-oriented](https://www.codecademy.com/resources/docs/general/programming-paradigms/object-oriented-programming) programming language, all functions are declared inside classes, making them methods. Thus, methods and functions are synonymous. - -## Syntax - -```pseudo -// Declare a public method without return type and no parameters: -public void PrintString() -{ - Console.WriteLine("Hello, World!"); -} - -// Declare a private method which returns an object and takes no parameters: -private int ReturnNumber() -{ - return 7; -} - -// Declare a public method which returns an integer and takes an input parameter: -public int CalculateWithParameter(int x) -{ - return ReturnNumber() - x; -} -``` - -Methods begin with a signature made of the following parts: - -- An access level of `public` or `private` (`private` is the default) -- Optional modifiers (e.g., `abstract` and `sealed`) -- The method return value (`string`, `int`, `object`, etc.) or `void` -- The method name (starting with a capital letter; usually a verb) -- Zero, one, or more (optional) parameters - -## Codebyte Example - -In the following example, two methods are separate defined: `Main()` and `GetSquare()`. When the program is run, the `Main()` is executed first which, in turn, executes the `GetSquare()` method with an `int` parameter passed to it. The returned value is saved to a [variable](https://www.codecademy.com/resources/docs/c-sharp/variables) and printed to the console: - -```codebyte/csharp -using System; - -public class Example -{ - public static void Main(string[] args) - { - var squared = new Example().GetSquare(5); - Console.WriteLine(squared.ToString()); - } - - private int GetSquare(int i) - { - return i * i; - } -} -``` diff --git a/content/c-sharp/concepts/operators/operators.md b/content/c-sharp/concepts/operators/operators.md deleted file mode 100644 index 8810908d32d..00000000000 --- a/content/c-sharp/concepts/operators/operators.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -Title: 'Operators' -Description: 'Operators are used to perform various operations on variables and values.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Operators' - - 'Arithmetic' - - 'Comparison' - - 'Logical' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -**Operators** are used to perform various operations on variables and values. - -## Syntax - -The following code snippet uses the assignment operator, `=`, to set `myVariable` to the value of `num1` and `num2` with an arithmetic operator operating on them. For example, if `operator` represented `*`, `myVariable` would be assigned a value of `num1 * num2`. - -```pseudo -myVariable = num1 operator num2; -``` - -Operators can be organized into the following groups: - -- Arithmetic operators for performing traditional math evaluations. -- Assignment operators for assigning values to variables. -- Comparison operators for comparing two values. -- Logical operators for combining `Boolean` values. -- [Bitwise operators](https://www.codecademy.com/resources/docs/general/bitwise-operator) for manipulating the bits of a number. - -## Arithmetic Operators - -C# has the following arithmetic operators: - -- Addition, `+`, returns the sum of two numbers. -- Subtraction, `-`, returns the difference between two numbers. -- Multiplication, `*`, returns the product of two numbers. -- Division, `/`, returns the quotient of two numbers. -- Modulus, `%`, returns the remainder of one number divided by another. - -The ones above operate on two values. C# also has two unary operators: - -- Increment, `++`, which increments its single operand by one. -- Decrement, `--`, which decrements its single operand by one. - -Unlike the other arithmetic operators, the increment and decrement operators change the value of their operand as well as return a value. They also return different results depending on if they precede or follow the operand. Preceding the operand returns the value of the operand before the operation. Following the operand returns the value of the operand after the operation. - -```cs -int x = 5; -int y = x++; // x now equals 6, y equals 5 -int z = --x; // x now equals 5, z equals 5 -``` - -## Logical Operators - -C# has the following logical operators: - -- The `&` (and) operator returns `true` if both operands are `true`. -- The `|` (or) operator returns `true` if either operand is `true`. -- The `^` (xor) operator returns `true` if only one of its operands are `true` -- The `!` (not) operator returns `true` if its single operand is `false`. - -> **Note:** `&`,`|`, and `^` are logical operators when the operands are `bool` types. When the operands are numbers they perform bitwise operations. See **Bitwise Operators** below. - -The above operators always evaluate both operands. There are also these conditional "short circuiting" operators: - -- The `&&` (conditional and) operator returns `true` if both operands are `true`. If the first operand is `false`, the second operand is not evaluated. -- The `||` (conditional or) operator returns `true` if either operand is `true`. If the first operand is `true` the second operand is not evaluated. - -## Assignment Operators - -C# includes the following assignment operators: - -- The `=` operator assigns the value on the right to the variable on the left. -- The `+=` operator updates a variable by incrementing its value and reassigning it. -- The `-=` operator updates a variable by decrementing its value and reassigning it. -- The `*=` operator updates a variable by multiplying its value and reassigning it. -- The `/=` operator updates a variable by dividing its value and reassigning it. -- The `%=` operator updates a variable by calculating its modulus against another value and reassigning it. - -The assignment operators of the form `op=`, where `op` is a binary arithmetic operator, is a shorthand. The expression `x = x op y;` can be shortened to `x op= y;`. This compound assignment also works with the logical operators `&`, `|` and `^`. - -- The `??=` operator assigns the value on the right to the variable on the left if the variable on the left is `null`. - -## Comparison Operators - -C# has the following comparison operators: - -- Equal, `==`, for returning `true` if two values are equal. -- Not equal, `!=`, for returning `true` if two values are not equal. -- Less than, `<`, for returning `true` if the left value is less than the right value. -- Less than or equal to, `<=`, for returning `true` if the left value is less than or equal to the right value. -- Greater than, `>`, for returning `true` if the left value is greater than the right value. -- Greater than or equal to, `>=`, for returning `true` if the left value is greater than or equal to the right value. - -> **Note:** for these comparison operators, if any operand is not a number (`Double.NaN` or `Single.NaN`) the result of the operation is `false`. - -## Bitwise Operators - -C# has the following operators that perform operations on the individual bits of a number. - -- Bitwise complement, `~`, inverts each bit in a number. -- Left-shift, `<<`, shifts its left operand left by the number of bits specified in its right operand. New right positions are zero-filled. -- Right-shift, `>>`, shifts its left operand right by the number of bits specified in its right operand. For signed integers, left positions are filled with the value of the high-order bit. For unsigned integers, left positions are filled with zero. -- Unsigned right-shift, `>>>`, same as `>>` except left positions are always zero-filled. -- Logical AND, `&`, performs a bitwise logical AND of its operands. -- Logical OR, `|`, performs a bitwise logical OR on its operands. -- Logical XOR, `^`, performs a bitwise logical XOR on its operands. diff --git a/content/c-sharp/concepts/strings/strings.md b/content/c-sharp/concepts/strings/strings.md deleted file mode 100644 index a75c1e1b502..00000000000 --- a/content/c-sharp/concepts/strings/strings.md +++ /dev/null @@ -1,214 +0,0 @@ ---- -Title: 'Strings' -Description: 'A string is an instance of the System.String object in C# and represents an immutable sequence of Char objects.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Data Types' - - 'Strings' - - 'Objects' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -A **`string`** is an instance of the `System.String` object in C# and represents an immutable sequence of `Char` objects. Unlike other languages, there's no null-terminating character at the end of a C# string, so a C# string can contain embedded null characters. The `string` keyword in C# is an alias for `System.String` and can be used even without `using System;`. - -> **Note:** Strings are immutable, which means they do not change once created. Methods and operators that appear to change a string in a variable really assign a new string to the variable and release the old string for garbage collection. This is important to realize when using references, since a reference pointing to a string that's subsequently "modified" will continue to point to the original unmodified string. - -## Declaring and Initializing - -There are many different ways to declare and initialize a string in C#. The following example lists a number of them: - -```cs -// Declare without initializing. -string myString1; - -// Declare using System.String. -System.String myString2; - -// Initialize with a string literal. -string myString3 = "Hello World!"; - -// Local variables can use implicit typing. -var localString = "Still a strongly-typed string."; - -// The string constructor can create a string from a char*, char[] or sbyte*. -char[] source = {'1','2','3','A','B','C'}; -string myString4 = new string(source); -``` - -The `new` operator is only used to create a string when initializing with an array of `char`. - -> **Note:** It is best practice to initialize an empty string with the `System.String.Empty` constant value or the `""` string literal rather than with `null` to avoid an unwanted `NullReferenceException`. - -## String Literals - -C# has three different types of string literals. - -### Quoted String Literals - -Quoted string literals are contained within a pair of double quote characters (`"`) on a single line. They require escape characters to include special characters and line breaks. - -```cs -string myString1 = "I'm a quoted string literal."; - -string myString2 = "I have an embedded\r\nline break."; -/* The resulting string: -I have an embedded -line break. -*/ -``` - -These are some of the escape sequences used in string literals: - -| Escape Sequence | Character Name | -| --------------- | ------------------------------------------------------------ | -| `\'` | Single quote | -| `\"` | Double quote | -| `\\` | Backslash | -| `\0` | Null | -| `\n` | New line | -| `\r` | Carriage return | -| `\t` | Horizontal tab | -| `\uNNNN` | UTF-16 Unicode character (range `\u0000` - `\uFFFF`) | -| `\U00NNNNNN` | UTF-32 Unicode character (range `\U00000000` - `\U0010FFFF`) | - -### Verbatim String Literals - -Verbatim string literals are a convenience used for multi-line strings, strings that contain backslashes, or embedded double quotes. Verbatim string literals begin with `@"` rather than just `"` as with a quoted literal string. - -> **Note:** Use two double quotes (`""`) to include a double quote in a verbatim string literal. - -```cs -string msPath = @"C:\Users\JSmith\Documents\Readme.txt"; -/* The resulting string: -C:\Users\JSmith\Documents\Readme.txt -*/ - -string myString1 = @"I have an embedded -line break"; -/* The resulting string: -I have an embedded -line break. -*/ - -string myString2 = @"This string says, ""Hello World!""."; -/* The resulting string: -This string says, "Hello World!". -*/ -``` - -### Raw String Literals - -Raw string literals were introduced with C# 11. It preserves whitespace, allows the use of embedded line breaks, and can include any character that would otherwise require an escape sequence. It allows the raw string literal to appear in code exactly how it will be stored and/or displayed. - -Raw string literals obey the following rules: - -- They begin and end with at least three quote characters (`"""`). More than three can be used in instances where there are three consecutive quote characters in the string itself. -- A single line string requires the opening and closing character sequences on the same line. -- Multi-line strings require the opening and closing character sequences to each be on their own line. -- In multi-line strings, whitespace to the right of the opening character sequence is omitted. -- In multi-line strings, whitespace to the left of the closing character sequence is removed from every line of the string. - -```cs -string myString1 = """Using "Hello World!" as an example."""; -/* The resulting string: -Using "Hello World!" as an example. -*/ - -string myString2 = """ -Using - "Hello - World." - as a - Example. -"""; -/* The resulting string: -Using - "Hello - World." - as a - Example. -*/ - -string myString3 = """" -Raw string literal example: -string temp = """text."""; -""""; -/* The resulting string: -Raw string literal example: -string temp = """text."""; -*/ - -``` - -## String Interpolation - -Interpolated strings contain expressions delimited by curly braces (`{...}`) that are evaluated when the string literal is evaluated and used in place of the whole expression. It can improve the readability and maintainability of code. An interpolated quoted string literal is identified by a preceding `$` character. - -```cs -string name = "John"; -string greet = @"""Hello World!"""; -string myString = $"{name} says, {greet}"; -/* The resulting string: -John says, "Hello World!" -*/ -``` - -Interpolation can be used with verbatim string literals, preceding them with `@$` or `$@`. - -```cs -string name = "John"; -string greet = @"""Hello World!"""; -string myString = @$"{name} - says, - {greet}"; -/* The resulting string: -John - says, - "Hello World!" -*/ -``` - -Interpolation can also be used with raw string literals. They are preceded by one or more `$` characters. The number of `$` used indicates the number of curly braces used to enclose interpolated expressions, sequences of curly braces less than that number will be included in the output. - -```cs -string name = "John"; -string greet = @"""Hello World!"""; -string myString = $"""" -{name} - says, - {greet} -""""; -/* The resulting string: -John - says, - "Hello World!" -*/ -``` - -## Codebyte Example - -The following is a runnable example showing string interpolation and verbatim string literals. - -> **Note:** When editing this codebyte, be aware that the version of C# being used does not permit raw string literals. - -```codebyte/csharp -using System; - -public class Program -{ - public static void Main() - { - string name = "John"; - string greet = @"""Hello World!"""; - string myString = @$"{name} - says, - {greet}"; - - Console.WriteLine(myString); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/compare/compare.md b/content/c-sharp/concepts/strings/terms/compare/compare.md deleted file mode 100644 index 11afd15fd8f..00000000000 --- a/content/c-sharp/concepts/strings/terms/compare/compare.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -Title: '.Compare()' -Description: 'Compares the alphabetical order of two strings and returns an integer that represents their relative ranking.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Strings' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Compare()`** method is a string method that compares the alphabetical order of two specified [`strings`](https://www.codecademy.com/resources/docs/c-sharp/strings) and returns an integer that represents their relative ranking. - -## Syntax - -```pseudo -String.Compare(string1, string2, ignoreCase); -``` - -- The `.Compare()` method is called on the `String` class. It takes two `string` type arguments, `string1` and `string2`, and compares them alphabetically. -- `ignoreCase` is an optional `boolean` type argument. By default the `.Compare()` method is case-sensitive. Passing `true` as the third argument makes the `.Compare()` method case-insensitive. - -The `.Compare()` method returns an `integer` that represents the relative order of `string1` and `string2` in the alphabet: - -- `-1` if `string1` comes before `string2` -- `0` if their position is the same (`string1` and `string2` are identical) -- `1` if `string2` comes before `string1` - -## Example - -In the following example, the `.Compare()` method compares `"Pizza"` with `"pizza"` and `"waffle"`. Then the `.WriteLine()` method prints the returned integer to the console: - -```cs -using System; - -public class Example { - public static void Main (string[] args) { - string str1 = "Pizza", str2 = "pizza", str3 = "waffle"; - - Console.WriteLine(String.Compare(str1, str2)); - Console.WriteLine(String.Compare(str1, str3)); - } -} -``` - -In the first case, `"pizza"` comes before `"Pizza"` in alphabetical order, as it is lowercase and the method is case-sensitive. In the second case, `"Pizza"` comes before `"waffle"` in alphabetical order. This example results in the following output: - -```shell -1 --1 -``` - -## Codebyte Example - -In the following runnable example, the `.Compare()` method determines the alphabetical order of `string1` and `string2`, while the letter casing is ignored. Finally, the `.WriteLine()` method prints the returned integer to the console. - -```codebyte/csharp -using System; - -public class Example { - public static void Main (string[] args) { - string string1 = "SUPERCALIFRAGILISTICEXPIALIDOCIOUS", string2 = "supercalifragilisticexpialidocious"; - - Console.WriteLine(String.Compare(string1, string2, true)); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/concat/concat.md b/content/c-sharp/concepts/strings/terms/concat/concat.md deleted file mode 100644 index f6ee8142195..00000000000 --- a/content/c-sharp/concepts/strings/terms/concat/concat.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -Title: '.Concat()' -Description: 'Combines two or more strings together into a single string.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Methods' - - 'Lists' - - 'Loops' - - 'Strings' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Concat()`** [method](https://www.codecademy.com/resources/docs/c-sharp/methods) combines strings by appending one string to the end of another. This method is similar in function to using the `+` or `+=` [operator](https://www.codecademy.com/resources/docs/c-sharp/operators) to concatenate strings, though the compiler handles those operators differently for optimization in certain scenarios. - -## Syntax - -```pseudo -string.Concat(string1, string2, ...) -``` - -- `string1, string2, ...`: The strings that will be concatenated together. - -## Example - -The following example uses the `.Concat()` method to combine three strings: - -```cs -using System; - -public class ConcatMethod -{ - public static void Main() - { - string firstString = "Hello"; - string secondString = "World!"; - string fullSentence = string.Concat(firstString, " ", secondString); - Console.WriteLine(fullSentence); - } -} -``` - -This results in the following output: - -```shell -Hello World! -``` - -## Codebyte Example - -The below codebyte example demonstrates how `.Concat()` can be used with a `foreach` [loop](https://www.codecademy.com/resources/docs/c-sharp/loops) to iterate through a list and output multiple concatenated strings: - -```codebyte/csharp -using System; -using System.Collections.Generic; - -public class ConcatMethod -{ - public static void Main() - { - List usernames = new List { "Alice", "Bob", "Charlie" }; - foreach (string user in usernames) - { - string greeting = string.Concat("Hi there ", user, ", how can I help you?"); - Console.WriteLine(greeting); - } - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/contains/contains.md b/content/c-sharp/concepts/strings/terms/contains/contains.md deleted file mode 100644 index 37cf3e436ba..00000000000 --- a/content/c-sharp/concepts/strings/terms/contains/contains.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -Title: '.Contains()' -Description: 'Determines whether a character or subset of characters is present within a given string' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Characters' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Contains()`** method determines whether a `string` includes a particular character or substring. It returns `true` if the character is included, otherwise the method returns `false`. There are additional parameters that can modify the comparison rules. - -## Syntax - -```pseudo -// Determines whether the String includes a given character -String.Contains(char); - -// Determines whether the String includes a given string -String.Contains(string); - -// Determines whether the String includes a given character considering the type of comparison -String.Contains(char, comparisonType) - -// Determines whether the String includes a given string considering the type of comparison -String.Contains(string, comparisonType) -``` - -`.Contains()` takes the following arguments: - -- `char` is a single character. -- `string` is a sequence of characters. -- `comparisonType` is an enumeration value that allows to add specific rules to compare strings such as culture, case, and sort. Passing as an additional argument: - - `CurrentCulture` determines whether strings match culture-sensitive criteria using the current system culture for comparison. - - `CurrentCultureIgnoreCase` does the same as above and ignores the case. - - `InvariantCulture` determines whether strings match using a fixed, culture-independent set of rules that remain consistent across all systems and regions. - - `InvariantCultureIgnoreCase` does the same as above and ignores the case. - - `Ordinal` determines whether strings match using binary sort rules. This is the fastest comparison method, performing a simple byte-by-byte comparison of Unicode values. - - `OrdinalIgnoreCase` does the same as above and ignores the case. - -## Example - -The following example shows how we can use `.Contains()` method - -```cs -using System; - -public class Example -{ - public static void Main() - { - string stringToSeek = "The distance is nothing when one has a motive."; - string substring = "motive"; - char character = 'l'; - - bool result; - - // String.Contains(string) - result = stringToSeek.Contains(substring); - Console.WriteLine(result); - - // String.Contains(char) - result = stringToSeek.Contains(character); - Console.WriteLine(result); - } -} -``` - -Here is the following output: - -```shell -True -False -``` - -Now, let's see how we can use the `comparisonType` parameter to modify the comparison rules: - -```cs -using System; -using System.Globalization; - -public class Example -{ - public static void Main() - { - // Turkish culture handles 'i' and 'İ' differently - CultureInfo turkishCulture = new CultureInfo("tr-TR"); - string turkishString = "İstanbul"; - string searchText = "istanbul"; - - // Default culture comparison (typically en-US) - bool defaultResult = turkishString.Contains(searchText, StringComparison.CurrentCultureIgnoreCase); - - // Turkish culture comparison - CultureInfo.CurrentCulture = turkishCulture; - bool turkishResult = turkishString.Contains(searchText, - StringComparison.CurrentCultureIgnoreCase); - - Console.WriteLine($"Default culture result: {defaultResult}"); - Console.WriteLine($"Turkish culture result: {turkishResult}"); - } -} -``` - -Here is the output: - -```shell -Default culture result: True -Turkish culture result: False -``` - -## Codebyte Example - -The example below determines whether the word `helpful` is included in the particular string. - -```codebyte/csharp -using System; - -public class CodeByte -{ - public static void Main() - { - string exampleString = "Codecademy is very helpful"; - string stringToFind = "helpful"; - - if (exampleString.Contains(stringToFind)) - { - Console.WriteLine("The example string contains the word \"{0}\"", stringToFind); - } - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/endswith/endswith.md b/content/c-sharp/concepts/strings/terms/endswith/endswith.md deleted file mode 100644 index 31be5bad7e4..00000000000 --- a/content/c-sharp/concepts/strings/terms/endswith/endswith.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -Title: '.EndsWith()' -Description: 'Determines if the end of the string instance matches the specified string and returns a boolean.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Characters' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.EndsWith()`** method determines whether the end of the `string` instance matches the specified character or string. Additional parameters may be supplied to define the criteria for a match. - -## Syntax - -```pseudo -// Determines whether the String instance's last character matches the specified character -String.EndsWith(char); - -// Determines whether the end of String instance matches the specified string -String.EndsWith(string); - -// Same as above but uses additional case-sensitive and culture-sensitive -String.EndsWith(string, ignoreCase, culture) - -// Same as above but uses an enumeration to determine the case- and culture-sensitive criteria -String.EndsWith(string, comparisonType) -``` - -`.EndsWith()` is a static method of the `String` object. It takes the following arguments: - -- `char` is an instance of the `Char` structure; represents a single letter. -- `string` is an instance of the `String` object. -- `ignoreCase` is a boolean; if `true` then case is ignored for comparison (e.g., 'a' == 'A'). -- `culture` is an instance of the `System.Globalization.CultureInfo` class which includes culture-specific sort order rules. -- `comparisonType` is an element of the `StringComparison` enumeration which encapsulates the case- and culture-specific criteria; available fields include: - - `CurrentCulture` sets the current culture rules. - - `CurrentCultureIgnoreCase` sets the current culture rules but ignores case. - - `InvariantCulture` sets the invariant culture's sorting rules (it's a culture that doesn't change based on the user's location). - - `InvariantCultureIgnoreCase` sets the invariant culture rules but ignores case. - - `Ordinal` sets ordinal (binary) sort rules to compare strings. - - `OrdinalIgnoreCase` sets ordinal (binary) sort rules to compare strings but ignores case. - -## Example - -The following example illustrates a few of the ways the `String.EndsWith()` method may be used to evaluate the end of a `string`. - -```cs -using System; -using System.Threading; - -public class Example -{ - public static void Main() - { - string baseString = "AbCdEfG"; - string compareEnd = "efg"; - - bool result; - - // String.EndsWith(string) - result = baseString.EndsWith(compareEnd); - Console.WriteLine("Simple compare: {0}", result.ToString()); - - // String.EndsWith(string, ignoreCase, culture) - result = baseString.EndsWith(compareEnd, true, Thread.CurrentThread.CurrentCulture); - Console.WriteLine("Compare using Case/Culture: {0}", result.ToString()); - - // String.EndsWith(string, comparisonType) - result = baseString.EndsWith(compareEnd, StringComparison.InvariantCulture); - Console.WriteLine("Compare using Enumeration: {0}", result.ToString()); - } - -} -``` - -This is what is printed to the console: - -```shell -Simple compare: False -Compare using Case/Culture: True -Compare using Enumeration: False -``` - -## Codebyte Example - -In this example, the `months` array is populated with the months of the year, and the `.EndsWith()` method is used to determine the number of months that end in the letter 'y': - -```codebyte/csharp -using System; - -public class CodeByteExample -{ - public static void Main() - { - string[] months = new string[] {"January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December"}; - - int y_count = 0; - - foreach (string month in months) - { - if (month.EndsWith('y')) - { - y_count++; - } - } - - Console.WriteLine("{0} months end in the letter 'y'", y_count); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/equals/equals.md b/content/c-sharp/concepts/strings/terms/equals/equals.md deleted file mode 100644 index 8392997c33d..00000000000 --- a/content/c-sharp/concepts/strings/terms/equals/equals.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -Title: '.Equals()' -Description: 'Determines whether two string objects have the same value or not.' -Subjects: - - 'Computer Science' -Tags: - - 'Libraries' - - 'Arithmetic' - - 'Strings' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Equals()`** method determines whether two string objects have the same value or not. - -## Syntax - -```pseudo -String.Equals(string1, string2) - -string1.Equals(string2) -``` - -`.Equals()` is a method of class `String`. This method will take two parameters in the form of string objects and check their values for equality. - -This method returns a boolean value of `true` or `false`. - -## Example - -The following example demonstrates the `.Equals()` method. Two parameters are passed to the method and the return value is printed with the `Console.WriteLine()` method. - -```cs -using System; - -class EqualsMethod { - - public static void Main(string[] args) - { - string s1 = "Codecademy"; - string s2 = "Codecademy"; - - Console.WriteLine(s1.Equals(s2)); - } -} -``` - -This example results in the following output: - -```shell -True -``` - -## Codebyte Example - -In this executable example, the string variables can be modified. The output will be the result of the `.Equals()` method: - -```codebyte/csharp -using System; - -class EqualsMethod { - - public static void Main(string[] args) - { - string string1 = "Codecademy"; - string string2 = "codecademy!"; - - Console.WriteLine(string1.Equals(string2)); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/format/format.md b/content/c-sharp/concepts/strings/terms/format/format.md deleted file mode 100644 index a2830328621..00000000000 --- a/content/c-sharp/concepts/strings/terms/format/format.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -Title: '.Format()' -Description: 'Creates a new string by replacing placeholders in a format string with the string representation of specified values.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Formatting' - - 'Methods' - - 'Strings' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Format()`** method creates a new string by replacing placeholders in a format string with the string representation of specified values. Non-string values are converted to strings by calling their `.ToString()` method. - -The string representation of each value is also based on: - -- Additional format details specified in each placeholder, such as specific number or date formats, or alignment settings. -- A specific culture or regional style which affects how numbers and dates are formatted. - -## Syntax - -```pseudo -String.Format(formatString, value_1, value_2, ..., value_n); - -String.Format(culture, formatString, value_1, value_2, ..., value_n); -``` - -The `.Format()` method is a static method of the `String` class that defines the following parameters: - -- `formatString`: A string containing plain text and placeholders to be replaced by the specified values. For example, `"My name is {0}."` where `{0}` is a placeholder to be replaced by a value representing the name. -- `value_1`, `value_2`, ..., `value_n`: The values that replace the placeholders in `formatString`. They can be objects of any type. Each placeholder requires a corresponding value argument. -- `culture`: This specifies how numbers and dates should be formatted based on the rules of a specific culture (like language or region). If not provided, it will use the default settings of your system. - -Each placeholder in the format string must be enclosed in curly braces and follow this syntax: - -```pseudo -{parameter_specifier[,alignment_specifier][:format_specifier]} -``` - -Where: - -- A **parameter specifier** (mandatory) is a number starting from `0`, which indicates the position of the replacing value among those passed to the method. For example, `{0}` for the first value, `{1}` for the second, etc.. -- An **alignment specifier** (optional) is a number, separated by a comma, that indicates the minimum number of characters for the value's string representation, which is padded with spaces only if too short. The padding occurs on the right if the specifier is negative (left alignment) or on the left if positive (right alignment). For example, `{0, 15}` right-aligns the first passed value taking up at least 15 characters. -- A **format specifier** (optional) is a character or a group of characters preceded by a colon that applies a specific format to the value. It is only supported by numeric, date, and enum values and defaults to the general format (`G`) if not provided. It depends on the value type and indicates either: - - A standard format that consists of a single character corresponding to a predefined format (e.g., `C` for currency, `D` for a long date, or a decimal, depending on the value type). - - A custom format that consists of multiple characters that define specific formatting rules for the value (e.g., `yyyy-MM-dd` for dates). - -To display a literal curly brace in the result string, you need to double it (`{{`). - -The same parameter specifier can be used multiple times in the format string if the same value needs to appear more than once. - -## Example 1 - -The following example uses two values (a string and a date) to create a new string by applying the `.Format()` method to a format string. The string value (`name`) is inserted into the `{0}` placeholder. The date value (`loginDate`) is used in two placeholders with the same parameter specifier (`{1:d}` and `{1:t}`) to display the date and time parts separately. Here, `d` and `t` specify standard short date and short time formats, respectively. Since no culture argument is provided, the date and the time are formatted according to the rules of the current culture (`en-US`, in this case). - -```cs -using System; - -public class Example { - public static void Main (string[] args) - { - string name = "John"; - DateTime loginDate = new DateTime(2024, 9, 2, 17, 45, 0); - - // Using String.Format to create the message based on the current culture: - string message = String.Format("Hi {0}, your last login was on {1:d} at {1:t}.", name, loginDate); - - Console.WriteLine(message); - } -} -``` - -This example results in the following output: - -```shell -Hi John, your last login was on 9/2/24 at 5:45 PM. -``` - -## Example 2 - -The following example is a variation of the previous one which shows how to format `loginDate` using the rules of the British culture (`en-GB`). - -```cs -using System; -using System.Globalization; - -public class Example { - - public static void Main (string[] args) - { - string name = "John"; - DateTime loginDate = new DateTime(2024, 9, 2, 17, 45, 0); - - // Using String.Format to create the message based on the British culture: - CultureInfo culture = CultureInfo.CreateSpecificCulture("en-GB"); - string message = String.Format(culture, "Hi {0}, your last login was on {1:d} at {1:t}.", name, loginDate); - -    Console.WriteLine(message); - } -} -``` - -This example results in the following output: - -```shell -Hi John, your last login was on 02/09/2024 at 17:45. -``` - -## Codebyte Example - -The following example uses the `.Format()` method to create a string with a name, a date, and a number, where the date displays only the month and day, and the number is rounded to a single digit after the decimal point. - -```codebyte/csharp -using System; - -public class Example { - - static void Main() - { - DateTime date = new DateTime(2024, 8, 4); - string name = "John"; - double temperature = 102.68; - - // Using String.Format to create a formatted string - string formattedString = String.Format("On {0:M}, {1} recorded a temperature of {2:0.0}°F.", date, name, temperature); - - Console.WriteLine(formattedString); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/indexof/indexof.md b/content/c-sharp/concepts/strings/terms/indexof/indexof.md deleted file mode 100644 index dfadc40acc2..00000000000 --- a/content/c-sharp/concepts/strings/terms/indexof/indexof.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -Title: '.IndexOf()' -Description: 'Returns the index of a specified character or substring in a string.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Methods' - - 'Strings' - - 'Search' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.IndexOf()`** method is a string method that returns the index of the first occurrence of a specified character or substring in a given string. If the character or substring is not found, it returns `-1`. - -## Syntax - -```pseudo -IndexOf(char value); -IndexOf(string value); -IndexOf(char value, int startIndex); -IndexOf(string value, int startIndex); -IndexOf(string value, int startIndex, int count); -``` - -- `value` : The substring or character to search for. -- `startIndex` (optional): The index from where the search should start. -- `count` (optional): Maximum number of characters to search. - -## Example - -The following example uses the `IndexOf()` method to find the index of the first occurrence of the character "d" in the string "Codecademy docs". - -```cs -string str = "Codecademy docs"; -int index = str.IndexOf('d'); - -Console.WriteLine("Index: " + index); -``` - -This example results in the following output: - -``` -Index: 2 -``` - -## Codebyte Example - -The following codebyte is runnable and shows the usage of the `.IndexOf()` method on a string. - -```codebyte/csharp -using System; - -public class IndexOfExample -{ - public static void Main() - { - string sentence = "The cat in the hat wears a red and white striped hat"; - - Console.WriteLine(sentence); - - int index1 = sentence.IndexOf('h'); - Console.WriteLine($"Index of 'h': {index1}"); - - int index2 = sentence.IndexOf("cat"); - Console.WriteLine($"Index of 'cat': {index2}"); - - int index3 = sentence.IndexOf('a', 10); - Console.WriteLine($"Index of 'a' starting from index 10: {index3}"); - - int index4 = sentence.IndexOf("dog"); - Console.WriteLine($"Index of 'dog': {index4}"); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/join/join.md b/content/c-sharp/concepts/strings/terms/join/join.md deleted file mode 100644 index 9cb8518d94d..00000000000 --- a/content/c-sharp/concepts/strings/terms/join/join.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -Title: '.Join()' -Description: 'Joins elements of a collection into a single string with a specified separator.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Methods' - - 'Characters' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Join()`** method concatenates an array or a collection of strings into a single string, with a specified separator inserted between each element. - -This method is particularly useful for formatting lists, such as comma-separated values or readable sentences. - -## Syntax - -```pseudo -string.Join(string separator, IEnumerable values) -``` - -- `separator`: A string to insert between each element. If empty, elements are joined with no separator. -- `values`: An array or collection of strings to concatenate. `null` values in the collection are replaced with empty strings. - -## Example - -This example demonstrates how `.Join()` uses a comma and space (`,`) as the separator to create a formatted to-do list. - -```cs -using System; - -class Program -{ - static void Main() - { - string[] studyTasks = { "Complete C# lesson", "Review notes", "Practice coding exercises", "Read documentation" }; - - // Using .Join() to create a sequential to-do list with ", " as the separator - string toDoList = string.Join(", ", studyTasks); - - Console.WriteLine("Today's Codecademy study plan: " + toDoList); - } -} -``` - -This example results in the following output: - -```shell -Today's Codecademy study plan: Complete C# lesson, Review notes, Practice coding exercises, Read documentation -``` - -## Codebyte Example - -The following example demonstrates how `.Join()` combines a collection of course names using an ampersand (`&`) to produce a readable list. - -```codebyte/csharp -using System; - -public class Program -{ - public static void Main() - { - string[] languages = { "C#", "Python", "Java" }; - string codecademyCourses = string.Join(" & ", languages); - - Console.WriteLine("Popular Codecademy courses: " + codecademyCourses); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/lastindexof/lastindexof.md b/content/c-sharp/concepts/strings/terms/lastindexof/lastindexof.md deleted file mode 100644 index 619cf4dca07..00000000000 --- a/content/c-sharp/concepts/strings/terms/lastindexof/lastindexof.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -Title: '.LastIndexOf()' -Description: 'Finds the last occurrence of a specified character or substring within a string.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Characters' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.LastIndexOf()`** method returns the last occurrence of a specified character or substring within a `string`. - -The method returns `-1` if there's no such match. - -Additional parameters may be supplied to define the criteria for the search. - -## Syntax - -```pseudo -// Determines the zero-based index of the last occurrence of char within the string -String.LastIndexOf(char); - -// Same as above but uses an additional starting position parameter. The search starts at the startIndex and proceeds backward toward the beginning of the string. -String.LastIndexOf(char, startIndex); - -// Same as above but uses an additional searching length parameter. The search starts at the startIndex and proceeds backward toward the beginning of the string for a specified number of character positions. -String.LastIndexOf(char, startIndex, length); - -// Determines the zero-based index of the last occurrence of substring within the string -String.LastIndexOf(substring); - -// Same as above but uses an additional starting position parameter. The search starts at the startIndex and proceeds backward toward the beginning of the string. -String.LastIndexOf(substring, startIndex); - -// Same as above but uses an additional searching length parameter. The search starts at the startIndex and proceeds backward toward the beginning of the string for a specified number of character positions. -String.LastIndexOf(string, startIndex, length); - -// Determines the zero-based index of the last occurrence of substring within the string, using the stringComparison method. -String.LastIndexOf(substring, stringComparison); - -// Same as above but uses an additional startIndex parameter. The search starts at the startIndex and proceeds backward toward the beginning of the string, using the stringComparison method. -String.LastIndexOf(substring, startIndex, stringComparison); - -// Same as above but uses an additional searching length parameter. The search starts at the startIndex and proceeds backward toward the beginning of the string for a specified number of character positions, using the stringComparison method. -String.LastIndexOf(substring, startIndex, length, stringComparison); -``` - -`.LastIndexOf()` is a method of the `String` object. It may take following parameters: - -- `char` is an instance of the Char structure; represents a single letter. -- `string` is an instance of the String object. -- `startIndex` is an Int32 object. -- `length` is an Int32 object. -- `stringComparison` is an enumeration which encapsulates the case- and culture-specific criteria; available fields include: - - `CurrentCulture` sets the current culture rules. - - `CurrentCultureIgnoreCase` sets the current culture rules but ignores case. - - `InvariantCulture` sets the invariant culture's sorting rules (it's a culture that doesn't change based on the user's location). - - `InvariantCultureIgnoreCase` sets the invariant culture rules but ignores case. - - `Ordinal` sets ordinal (binary) sort rules to compare strings. - - `OrdinalIgnoreCase` sets ordinal (binary) sort rules to compare strings but ignores case. - -## Example - -The following example illustrates a few of the ways the `String.LastIndexOf()` method may be used to determine the last occurrence of a specified character or substring within a `string`. - -```cs -using System; - -public class HelloWorld -{ - public static void Main(string[] args) - { - string baseString = "Hello, I'm Codecademy"; - string compareStr = "m"; - int startIndex = 17; - int searchLength = 4; - int result; - - // String.LastIndexOf(string) - result = baseString.LastIndexOf(compareStr); - Console.WriteLine("Simple search: {0}", result.ToString()); - - // String.LastIndexOf(string, startIndex) - result = baseString.LastIndexOf(compareStr, startIndex); - Console.WriteLine("Search using starting position: {0}", result.ToString()); - - // String.LastIndexOf(string, startIndex, length) - result = baseString.LastIndexOf(compareStr, startIndex, searchLength); - Console.WriteLine("Search using starting position & searching length: {0}", result.ToString()); - - // String.LastIndexOf(string, startIndex, length, stringComparison) - compareStr = "C"; - StringComparison strCmp = StringComparison.InvariantCultureIgnoreCase; - result = baseString.LastIndexOf(compareStr, startIndex, strCmp); - Console.WriteLine("Search using starting position & string comparison: {0}", result.ToString()); - } -} -``` - -This is what is printed to the console: - -```shell -Simple search: 19 -Search using starting position: 9 -Search using starting position & searching length: -1 -Search using starting position & string comparison: 15 -``` - -## Codebyte Example - -In this example, the `String.LastIndexOf()` is used with `compareStr`, `startIndex` and `strCmp` parameters to determine the last occurrence of a substring within the string: - -```codebyte/csharp -using System; - -public class HelloWorld -{ - public static void Main(string[] args) - { - string baseString = "Hello, I'm Codecademy"; - string compareStr = "C"; - int startIndex = 17; - StringComparison strCmp = StringComparison.InvariantCultureIgnoreCase; - - int result = baseString.LastIndexOf(compareStr, startIndex, strCmp); - Console.WriteLine("Search using starting position & string comparison: {0}", result.ToString()); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/padleft/padleft.md b/content/c-sharp/concepts/strings/terms/padleft/padleft.md deleted file mode 100644 index 1bbfab0bb0f..00000000000 --- a/content/c-sharp/concepts/strings/terms/padleft/padleft.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -Title: '.PadLeft()' -Description: 'Pads the beginning of a string with spaces or a specified character to reach a specified total length.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Characters' - - 'Methods' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -In C#, the **`.PadLeft()`** [method](https://www.codecademy.com/resources/docs/cpp/methods) adds padding to the start of a string until it reaches the specified total length. If a padding character is not specified, it defaults to spaces. This method returns a new string, leaving the original string unchanged. - -## Syntax - -```pseudo -string.PadLeft(int totalWidth); -``` - -Or, alternatively: - -```pseudo -string.PadLeft(int totalWidth, char paddingChar); -``` - -- `totalWidth`: The desired total length of the string after padding. -- `paddingChar` (Optional): The character used for padding. If not specified, a space is used by default. - -## Example - -The following example illustrates the usage of `.PadLeft()` in various scenarios: - -```cs -using System; - -class Program -{ - static void Main() - { - string str = "Codecademy"; // Length: 10 - Console.WriteLine($"String: '{str}'"); - - // Case 1: Padding with default space character - string paddingDefault = str.PadLeft(15); - Console.WriteLine($"Case 1: '{paddingDefault}'"); - - // Case 2: Padding with a specific character - char paddingChar = '.'; - string paddingWithChar = str.PadLeft(15, paddingChar); - Console.WriteLine($"Case 2: '{paddingWithChar}'"); - - // Case 3: Total width is less than string length - string noPadding = str.PadLeft(1); - Console.WriteLine($"Case 3: '{noPadding}'"); - } -} -``` - -The above example gives the following output: - -```shell -String: 'Codecademy' -Case 1: ' Codecademy' -Case 2: '.....Codecademy' -Case 3: 'Codecademy' -``` - -## Codebyte Example - -The following runnable example demonstrates different use cases for `.PadLeft()`, including padding with spaces by default and padding with a specified character: - -```codebyte/csharp -using System; - -class Program { - static void Main() { - string str = "Hello World"; - int totalLength = 15; - char padChar = '.'; - - Console.WriteLine($"Original string: '{str}'"); - - // Default padding with spaces to reach the specified total length - string paddingDefault = str.PadLeft(totalLength); - Console.WriteLine($"Padded with spaces to length {totalLength}: '{paddingDefault}'"); - - // Padding with a specific character to reach the specified total length - string paddingWithChar = str.PadLeft(totalLength, padChar); - Console.WriteLine($"Padded with '{padChar}' to length {totalLength}: '{paddingWithChar}'"); - - // No padding applied if the specified length is less than the string's length - int shorterLength = 5; - string noPadding = str.PadLeft(shorterLength); - Console.WriteLine($"Specified length ({shorterLength}) less than string length: '{noPadding}'"); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/padright/padright.md b/content/c-sharp/concepts/strings/terms/padright/padright.md deleted file mode 100644 index 01809e59ad0..00000000000 --- a/content/c-sharp/concepts/strings/terms/padright/padright.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -Title: '.PadRight()' -Description: 'Adds padding to the right side of a string to ensure it reaches a specified total length.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Characters' - - 'Methods' - - 'Functions' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.PadRight()`** method in C# is used to add padding characters to the right of a string to achieve a specified total length. By default, it uses spaces as the padding character, but a custom character can also be specified. - -## Syntax - -```pseudo -string.PadRight(int totalWidth, char paddingChar) -``` - -- `totalWidth`: The desired total length of the string, including padding. If the specified width is less than the string's length, no padding is added. -- `paddingChar`(Optional): The character to use for padding. Defaults to a space character (`' '`). - -> **Note**: The `.PadRight()` method does not modify the original string. It generates and returns a new string with padding applied to achieve the specified total width. - -## Example - -### Default Padding with Spaces - -```cs -using System; -class Program -{ - static void Main() - { - string name = "John"; - string paddedName = name.PadRight(10); - Console.WriteLine($"'{paddedName}'"); - } -} -``` - -The above code generates the output as follows: - -```shell -'John ' -``` - -### Custom Padding Character - -```cs -using System; - -class NameFormatter -{ - public static void Main(string[] args) - { - string name = "John"; - string paddedName = name.PadRight(10, '-'); - Console.WriteLine($"'{paddedName}'"); - } -} -``` - -The output of the above code will be: - -```shell -'John------' -``` - -### Handling Shorter Total Width - -If the specified `totalWidth` is less than the length of the string, the original string is returned: - -```cs -using System; - -class NamePaddingExample -{ - public static void Main(string[] args) - { - string name = "John"; - string result = name.PadRight(3); - Console.WriteLine($"'{result}'"); - } -} -``` - -Here's what the output of this code will be: - -```shell -'John' -``` - -## Codebyte Example - -Run the following example to understand how the `.PadRight()` method works: - -```codebyte/csharp -using System; - -class Program -{ - static void Main() - { - string word = "Align"; - // Pad with spaces to a total width of 15 - Console.WriteLine("'" + word.PadRight(15) + "'"); - - // Pad with asterisks to a total width of 15 - Console.WriteLine("'" + word.PadRight(15, '*') + "'"); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/remove/remove.md b/content/c-sharp/concepts/strings/terms/remove/remove.md deleted file mode 100644 index 5adec1b5844..00000000000 --- a/content/c-sharp/concepts/strings/terms/remove/remove.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -Title: '.Remove()' -Description: 'Removes a specified number of characters from a string starting at a defined index and returns the modified string.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Elements' - - 'Methods' - - 'Strings' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -In C#, the **`.Remove()`** method removes characters from a specific position in a string, starting at a given index. The original string remains unchanged, and the modified string is returned. - -## Syntax - -```pseudo -// Removes characters from startIndex to the end of the string. -string.Remove(int startIndex); -``` - -Or, alternatively: - -```pseudo -// Removes a specified number of characters starting at startIndex. -string.Remove(int startIndex, int count); -``` - -- `startIndex`: The zero-based position in the string where removal begins. -- `count` (Optional): The number of characters to remove from the specified `startIndex`. - -## Example - -The following example shows how to use the `.Remove()` method: - -```cs -using System; - -public class RemoveExample -{ - public static void Main() - { - string baseStr = "ABCDEFGHIJ"; - - string newStr1 = baseStr.Remove(5); - string newStr2 = baseStr.Remove(2, 5); - - Console.WriteLine("New string1: " + newStr1); - Console.WriteLine("New string2: " + newStr2); - - } -} -``` - -This example results in the following output: - -```shell -New string1: ABCDE -New string2: ABHIJ -``` - -## Codebyte Example - -Run the following codebyte example to understand how the `.Remove()` method works: - -```codebyte/csharp -using System; - -class RemoveMethod { - - public static void Main(string[] args) - { - string baseStr1 = "Codecademy helps you grow"; - string baseStr2 = "Improve skills with Codecademy"; - - string removedStr1 = baseStr1.Remove(10); - Console.WriteLine("Removed string1: " + removedStr1); - - string removedStr2 = baseStr2.Remove(8, 7); - Console.WriteLine("Removed string2: " + removedStr2); - - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/replace/replace.md b/content/c-sharp/concepts/strings/terms/replace/replace.md deleted file mode 100644 index 3ad35506e0b..00000000000 --- a/content/c-sharp/concepts/strings/terms/replace/replace.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -Title: '.Replace()' # Required; the file name should be the same as the title, but lowercase, with dashes instead of spaces, and all punctuation removed -Description: 'Returns a new string where every instance of a certain character or substring in the original string is swapped with a different specified character or substring.' # Required; ideally under 150 characters and starts with a noun (used in search engine results and content previews) -Subjects: # Please only use Subjects in the subjects.md file (https://github.com/Codecademy/docs/blob/main/documentation/subjects.md). If that list feels insufficient, feel free to create a new Subject and add it to subjects.md in your PR! - - 'Computer Science' - - 'Web Design' - - 'Web Development' -Tags: # Please only use Tags in the tags.md file (https://github.com/Codecademy/docs/blob/main/documentation/tags.md). If that list feels insufficient, feel free to create a new Tag and add it to tags.md in your PR! - - 'Strings' - - 'Methods' - - 'Characters' -CatalogContent: # Please use course/path landing page slugs, rather than linking to individual content items. If listing multiple items, please put the most relevant one first - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Replace()`** method returns a new string where every instance of a certain character or substring in the original string is swapped with a different specified character or substring. - -## Syntax - -```pseudo -// Replaces old character with new character. -myString.Replace(char oldChar, char newChar); - -// Replaces old string with new string. -myString.Replace(string oldString, string newString); -``` - -The `.Replace()` method takes the original string returns a new string with the following changes in it: - -- All occurrences of indicated character are replaced with another one. -- All occurrences of indicated string are replaced with another one. - -> **Note:** If `oldChar` or `oldString` is not found in the original string, than the method returns the string without changes. - - - -> **Note:** If `newChar` or `newString` is `null`, than all occurrences of `oldChar` or `oldString` are removed. - - - -> **Note:** The `.Replace()` method does not modify the original `string`, it always produces a new string. - -## Example 1 - -The following example takes the `string` named `oldString`, replaces all the hyphen characters `-` with comma characters `,`, and returns the new `string` named `newString`. - -```cs -using System; - -public class Example -{ - public static void Main(string[] args) - { - string oldString = "A-B-C-D-E-F-G-H-I"; - string newString = oldString.Replace('-', ','); - Console.WriteLine($"Old string: \"{oldString}\""); - Console.WriteLine($"New string: \"{newString}\""); - } -} -``` - -It produces the following output to the console: - -```shell -Old string: "A-B-C-D-E-F-G-H-I" -New string: "A,B,C,D,E,F,G,H,I" -``` - -## Example 2 - -The following example takes the `string` named `wrongString`, replaces the word `fourth` with the word `third`, and returns the new `string` named `rightString`. - -```cs -using System; - -public class Example -{ - public static void Main(string[] args) - { - string wrongString = "Earth is the fourth planet from the Sun."; - string rightString = wrongString.Replace("fourth", "third"); - Console.WriteLine($"False statement: {wrongString}"); - Console.WriteLine($"True statement: {rightString}"); - } -} -``` - -It produces the following output to the console: - -```shell -False statement: Earth is the fourth planet from the Sun. -True statement: Earth is the third planet from the Sun. -``` - -## Codebyte Example - -In the following runnable example, the `.Replace()` method is used to create a `replacedString` from the `originalString`. Then both strings are printed to the console: - -```codebyte/csharp -using System; - -class Program -{ - static void Main() - { - string originalString = "Hello, world!"; - string replacedString = originalString.Replace("world", "universe"); - - Console.WriteLine("Original string: " + originalString); - Console.WriteLine("Replaced string: " + replacedString); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/split/split.md b/content/c-sharp/concepts/strings/terms/split/split.md deleted file mode 100644 index 3cb8301f86e..00000000000 --- a/content/c-sharp/concepts/strings/terms/split/split.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -Title: '.Split()' -Description: 'Divides a string into an array of substrings based on specified delimiter(s).' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Strings' - - 'Libraries' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Split()`** method divides a string into an array of substrings based on specified delimiter(s), which can be a character, an array of characters, or a string. - -## Syntax - -Splits a string into a maximum number of substrings based on the characters in an array. - -`.Split()` takes three parameters - - -- _separator_: Delimiters for splitting, which can be a character, an array of characters, or strings. -- _count_: Maximum number of substrings to return. -- _options_: Specifies whether to include empty substrings `(StringSplitOptions.None)` or exclude them `(StringSplitOptions.RemoveEmptyEntries)`. - -It can be used in the following ways: - -```pseudo -Split(String[], Int32, StringSplitOptions) -``` - -Splits a string into a maximum number of substrings using the strings in an array as delimiters. - -```pseudo -Split(Char[], Int32, StringSplitOptions) -``` - -Splits a string into a maximum number of substrings using the characters in an array as delimiters. - -```pseudo -Split(String[], StringSplitOptions) -``` - -Splits a string into substrings based on the strings in an array. - -```pseudo -Split(Char[]) -``` - -Splits a string into substrings based on the characters in an array. - -```pseudo -Split(Char[], StringSplitOptions) -``` - -Splits a string into substrings based on the characters in an array. - -```pseudo -Split(Char[], Int32) -``` - -## Example - -The following examples demonstrates the use of `.Split()` method: - -```cs -using System; - -class EqualsMethod { - - public static void Main(string[] args) - { - string s1 = "Rivers, Mountains, Oceans"; - - string[] subs = s1.Split(','); - foreach (var sub in subs) - { - Console.WriteLine($"Substring: {sub}"); - } - - // To remove spaces alongwith the comma, specify ', ' as the delimiter. - subs = s1.Split(", "); - foreach (var sub in subs) - { - Console.WriteLine($"Substring: {sub}"); - } - - // To limit the number of substrings to 2, specify the optional parameter - subs = s1.Split(", ", 2); - foreach (var sub in subs) - { - Console.WriteLine($"Substring: {sub}"); - } - } -} -``` - -This example results in the following output: - -```shell -Substring: Rivers -Substring: Mountains -Substring: Oceans -Substring: Rivers -Substring: Mountains -Substring: Oceans -Substring: Rivers -Substring: Mountains, Oceans -``` - -## Codebyte Example - -This example demonstrates how the `.Split()` method works in C# for splitting a string based on delimiters (in this case, commas and spaces). - -```codebyte/csharp -using System; - -class SplitExample -{ - public static void Main(string[] args) - { - // A sample CSV string - string csv = "John,25,Developer,New York,,john@example.com"; - - // Split by comma - string[] fields = csv.Split(','); - Console.WriteLine("Fields after splitting by comma:"); - foreach (var field in fields) - Console.WriteLine($"'{field}'"); - - // Split by comma and remove empty entries - string[] fieldsWithoutEmpty = csv.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - Console.WriteLine("\nFields after removing empty entries:"); - foreach (var field in fieldsWithoutEmpty) - Console.WriteLine($"'{field}'"); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/startswith/startswith.md b/content/c-sharp/concepts/strings/terms/startswith/startswith.md deleted file mode 100644 index 03dd34a54a2..00000000000 --- a/content/c-sharp/concepts/strings/terms/startswith/startswith.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -Title: '.StartsWith()' -Description: 'Determines if the start of the string instance matches the specified string and returns a boolean.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Methods' - - 'Characters' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.StartsWith()`** method determines whether the start of the `string` instance matches the specified character or string. Additional parameters may be supplied to define the criteria for a match. - -## Syntax - -```pseudo -// Determines whether the String instance's first character matches the specified character. -String.StartsWith(char); - -// Determines whether the start of String instance matches the specified string. -String.StartsWith(string); - -// Same as above but uses additional case-sensitive and culture-sensitive criteria. -String.StartsWith(string, ignoreCase, culture) - -// Same as above but uses an enumeration to determine the case- and culture-sensitive criteria. -String.StartsWith(string, comparisonType) -``` - -`.StartsWith()` is a static method of the `String` object. It takes the following arguments: - -- `char` is an instance of the `Char` structure; represents a single letter. -- `string` is an instance of the `String` object. -- `ignoreCase` is a boolean; if `true` then case is ignored for comparison (e.g., 'a' == 'A'). -- `culture` is an instance of the `System.Globalization.CultureInfo` class which includes culture-specific sort order rules. -- `comparisonType` is an element of the `StringComparison` enumeration which encapsulates the case- and culture-specific criteria; available fields include: - - `CurrentCulture` sets the current culture rules. - - `CurrentCultureIgnoreCase` sets the current culture rules but ignores case. - - `InvariantCulture` sets the invariant culture's sorting rules (it's a culture that doesn't change based on the user's location). - - `InvariantCultureIgnoreCase` sets the invariant culture rules but ignores case. - - `Ordinal` sets ordinal (binary) sort rules to compare strings. - - `OrdinalIgnoreCase` sets ordinal (binary) sort rules to compare strings but ignores case. - -## Example - -The following example illustrates a few of the ways the `String.StartsWith()` method may be used to evaluate the start of a `string`. - -```cs -using System; -using System.Threading; - -public class Example -{ - public static void Main() - { - string baseString = "AbCdEfG"; - string compareStart = "abc"; - - bool result; - - // String.StartsWith(string) - result = baseString.StartsWith(compareStart); - Console.WriteLine("Simple compare: {0}", result.ToString()); - - // String.StartsWith(string, ignoreCase, culture) - result = baseString.StartsWith(compareStart, true, Thread.CurrentThread.CurrentCulture); - Console.WriteLine("Compare using Case/Culture: {0}", result.ToString()); - - // String.StartsWith(string, comparisonType) - result = baseString.StartsWith(compareStart, StringComparison.InvariantCulture); - Console.WriteLine("Compare using Enumeration: {0}", result.ToString()); - } - -} -``` - -This is what is printed to the console: - -```shell -Simple compare: False -Compare using Case/Culture: True -Compare using Enumeration: False -``` - -## Codebyte Example - -In this example, the `months` array is populated with the months of the year, and the `.StartsWith()` method is used to determine the number of months that start in the letter 'J': - -```codebyte/csharp -using System; - -public class CodeByteExample -{ - public static void Main() - { - string[] months = new string[] {"January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December"}; - - int j_count = 0; - - foreach (string month in months) - { - if (month.StartsWith('J')) - { - j_count++; - } - } - - Console.WriteLine("{0} months starts in the letter 'J'", j_count); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/substring/substring.md b/content/c-sharp/concepts/strings/terms/substring/substring.md deleted file mode 100644 index 2e41afca218..00000000000 --- a/content/c-sharp/concepts/strings/terms/substring/substring.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -Title: '.Substring()' -Description: 'Returns the substring of a string instance starting at a given index.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Methods' - - 'Strings' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.Substring()`** method is a string method that returns a substring of a string starting at the specified index. It will return all characters from that index to the end unless a maximum length is specified. If the starting index equals the string length, it returns an empty string (`""`). If the index is greater than the string length, it throws an `ArgumentOutOfRangeException`. - -## Syntax - -```pseudo -.Substring(int startIndex) -``` - -Or, alternatively: - -```pseudo -.Substring(int startIndex, int length) -``` - -- `startIndex`: The index from where the substring starts. -- `Length` (Optional): The number of characters to include in the substring.. - -## Example - -In this example, `.Substring()` is used to return the substring of "Codecademy" starting at index `4` and includes all characters from that position to the end of the string: - -```cs -using System; - -public class Program -{ - public static void Main() - { - string str = "Codecademy"; - Console.WriteLine(str.Substring(4)); - } -} -``` - -The above example results in the following output: - -```shell -cademy -``` - -## Example 2 - -In this example, `.Substring()` is used with the optional `length` parameter to return a substring of 6 characters starting from index `2` of the string `"Codecademy"`. - -```cs -using System; - -public class Program -{ - public static void Main() - { - string str = "Codecademy"; - Console.WriteLine(str.Substring(2, 6)); - } -} -``` - -The above code generates the following output: - -````shell -decade - -## Codebyte Example - -The below code demonstrates how to use the Substring method: - -```codebyte/csharp -using System; - -public class Example -{ - public static void Main(string[] args) - { - string Name1 = "Brad"; - string Name2 = "Angelina"; - - Console.WriteLine(Name1.Substring(1)); - Console.WriteLine(Name2.Substring(1)); - } -} -```` diff --git a/content/c-sharp/concepts/strings/terms/tochararray/tochararray.md b/content/c-sharp/concepts/strings/terms/tochararray/tochararray.md deleted file mode 100644 index 3733476f2e1..00000000000 --- a/content/c-sharp/concepts/strings/terms/tochararray/tochararray.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -Title: '.ToCharArray()' -Description: 'Converts a string into an array of characters.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Strings' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.ToCharArray()`** method in C# converts a string into an array of characters, where each character in the string becomes an element in the resulting array. This allows for the manipulation or iteration of individual characters. - -## Syntax - -```pseudo -char[] arrayName = stringName.ToCharArray(); -``` - -- `stringName`: The string to be converted into a character array. -- `arrayName`: The resulting array containing individual characters from the string. - -### Optional Parameters - -The `.ToCharArray()` method can also take optional parameters to convert a specific substring into a character array: - -```pseudo -char[] substringArray = stringName.ToCharArray(startIndex, length); -``` - -- `startIndex`: The zero-based index where the substring starts. -- `length`: The number of characters to include in the resulting array, starting from `startIndex`. - -## Examples - -### Split into Individual Characters - -Here's an example of using `.ToCharArray()` to split a string into individual characters: - -```cs -using System; - -class Program -{ - static void Main() - { - string greeting = "Hello, World!"; - char[] charArray = greeting.ToCharArray(); - - foreach (char c in charArray) - { - Console.WriteLine(c); - } - } -} -``` - -The output of the above code will be as follows: - -```shell -H -e -l -l -o -, - -W -o -r -l -d -! -``` - -### Converting a Substring to a Character Array - -```cs -using System; - -class Program -{ - static void Main() - { - string phrase = "Convert this string!"; - char[] partialArray = phrase.ToCharArray(8, 4); - - foreach (char c in partialArray) - { - Console.WriteLine(c); - } - } -} -``` - -The output of the above code will be as follows: - -```shell -t -h -i -s -``` - -## Codebyte Example - -Run the following codebyte example to see how `.ToCharArray()` works in C#: - -```codebyte/csharp -using System; - -class Program -{ - static void Main() - { - string example = "Learn C#"; - char[] charArray = example.ToCharArray(); - - Console.WriteLine("Character Array:"); - foreach (char c in charArray) - { - Console.Write(c + " "); - } - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/tolower/tolower.md b/content/c-sharp/concepts/strings/terms/tolower/tolower.md deleted file mode 100644 index 98535cce563..00000000000 --- a/content/c-sharp/concepts/strings/terms/tolower/tolower.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -Title: '.ToLower()' -Description: 'Converts all the characters in a given string to lowercase.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Strings' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -The **`.ToLower()`** method is a string method in C# that returns a new string in which all the characters are converted to lowercase. - -The method does not modify the original string, but rather returns a new one. This method is helpful in normalizing user input or comparing strings in a case-insensitive manner. - -## Syntax - -```pseudo -myString.ToLower(); -``` - -`myString` is the string being converted to lowercase. - -## Example - -In the following example, the `.ToLower()` method is called on a string `originalString`, and is printed to the console: - -```cs -using System; - -string originalString = "HELLO WORLD"; - -Console.WriteLine(originalString.ToLower()); // Output: "hello world" -``` - -## Codebyte Example - -In following runnable example, a new string `originalString` is created that contains some text. Then, the `.ToLower()` method is called on this string and the result is stored in a new string variable `lowerCaseString`. Finally, both the original and the lowercase strings are printed to the console. - -```codebyte/csharp -using System; - -class Program { - static void Main(string[] args) { - string originalString = "THIS IS A TEST STRING"; - string lowerCaseString = originalString.ToLower(); - - Console.WriteLine("Lowercase string: " + originalString.ToLower();); - Console.WriteLine("Original string: " + originalString); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/toupper/toupper.md b/content/c-sharp/concepts/strings/terms/toupper/toupper.md deleted file mode 100644 index 78aec40a1c2..00000000000 --- a/content/c-sharp/concepts/strings/terms/toupper/toupper.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -Title: '.ToUpper()' -Description: 'Returns a new string with all uppercase characters.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Strings' - - 'Methods' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -In C#, the **`.ToUpper()`** method returns a new string with all the characters converted to uppercase. Numbers and symbols are not changed. - -This method does not modify the original string, but instead, it creates a new string that contains the uppercase version of the original string. - -## Syntax - -```pseudo -somestring.ToUpper() -``` - -This method will not change the input string. - -## Example - -In the following example, `originalString` is the string being converted to uppercase, and `uppercaseString` is the new string that contains the uppercased characters. The original string remains unchanged: - -```cs -using System; - -class Program -{ - static void Main(string[] args) - { - originalString = "Hello World" - string uppercaseString = originalString.ToUpper(); - - Console.WriteLine(originalString); - Console.WriteLine(uppercaseString); - } -} -``` - -This will output: - -```shell -Hello World -HELLO WORLD -``` - -## Codebyte Example - -The example below converts a given string to uppercase and stores this value in a new string variable named `uppercaseString`: - -```codebyte/csharp -using System; - -class Program -{ - static void Main(string[] args) - { - originalString = "Hello World" - string uppercaseString = originalString.ToUpper(); - - Console.WriteLine(originalString); - Console.WriteLine(uppercaseString); - } -} -``` diff --git a/content/c-sharp/concepts/strings/terms/trim/trim.md b/content/c-sharp/concepts/strings/terms/trim/trim.md deleted file mode 100644 index d1e7971ef97..00000000000 --- a/content/c-sharp/concepts/strings/terms/trim/trim.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -Title: '.Trim()' -Description: 'Trims starting and ending whitespaces from a given string.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Methods' - - 'Functions' - - 'Strings' - - 'Characters' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -In C#, the **`.Trim()`** [method](https://www.codecademy.com/resources/docs/c-sharp/methods) trims starting and ending whitespaces from a given string. - -## Syntax - -```pseudo -str.Trim() -``` - -- `str`: The string from which starting and ending whitespaces are to be removed. - -## Example - -The following example demonstrates the usage of the `.Trim()` method: - -```cs -using System; - -public class Example -{ - public static void Main() - { - string str = " Codecademy "; - - // Using the Trim() method - string trimmedStr = str.Trim(); - - // Printing the results - Console.WriteLine($"Original: '{str}'"); - Console.WriteLine($"Trimmed: '{trimmedStr}'"); - } -} -``` - -The above code produces the following output: - -```shell -Original: ' Codecademy ' -Trimmed: 'Codecademy' -``` - -## Codebyte Example - -The following codebyte example shows the use of the `.Trim()` method: - -```codebyte/csharp -using System; - -public class CodebyteExample -{ - public static void Main() - { - string str = " Programming "; - - // Using the Trim() method - string trimmedStr = str.Trim(); - - // Printing the results - Console.WriteLine($"Original: '{str}'"); - Console.WriteLine($"Trimmed: '{trimmedStr}'"); - } -} -``` diff --git a/content/c-sharp/concepts/switch/switch.md b/content/c-sharp/concepts/switch/switch.md deleted file mode 100644 index d091d77c5dd..00000000000 --- a/content/c-sharp/concepts/switch/switch.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -Title: 'Switch' -Description: 'Switch statements execute a code block from a list of conditions if a condition is true.' -Subjects: - - 'Code Foundations' - - 'Web Development' - - 'Mobile Development' -Tags: # Please only use Tags in the tags.md file (https://github.com/Codecademy/docs/blob/main/documentation/tags.md). If that list feels insufficient, feel free to create a new Tag and add it to tags.md in your PR! - - 'Control Flow' - - 'Switch' -CatalogContent: # Please use course/path landing page slugs, rather than linking to individual content items. If listing multiple items, please put the most relevant one first - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -**Switch** statements execute a code block from a list of `case` conditions for which the `expression` validates as `true`. Switch statements are similar to if/else statements. - -## Syntax - -```pseudo -switch (expression) -{ - case alpha: - // Code block - break; - case beta: - // Code block - break; - default: - // Code block - break; -} -``` - -A `switch` statement includes one or more `case` conditions. The `case` conditions are evaluated in top-to-bottom order. If none of the `case` conditions evaluate to `true`, the `default` condition is executed. If no `default` is defined, the switch statement is bypassed. - -Common Switch syntax definitions: - -- `switch`: Definition of the `switch` statement. -- `expression`: The logic each `case` will be evaluated against. -- `case`: A value the `expression` is matched against. If the `case` matches the result of the `expression`, the code block within the `case` will be executed. -- `break` (recommended): Terminates the switch statement. Recommended at the end of each `case` and `default` to terminate the switch once the case has been fulfilled. A switch statement tests all cases unless a `break`, `throw`, or `return` statement is used to direct control out of the switch. If no `break` statement exists in a case, C# will throw a compile time error. -- `default` (optional): The behavior executed if no `case` condition matches the `expression`. - -## Codebyte Example - -The following example creates a string variable named `favoriteTurtle` with the value of `"Donatello"`. A switch statement is defined that evaluates the value of `favoriteTurtle`. If a case matches the value of `favoriteTurtle`, a corresponding message is printed to the console. If none of the cases in the switch statement match the value of `favoriteTurtle`, a default message is printed to the console. - -```codebyte/csharp -using System; - -public class Example -{ - public static void Main(string[] args) - { - string favoriteTurtle = "Donatello"; - - switch (favoriteTurtle) - { - case "Leonardo": - Console.WriteLine("Leads!"); - break; - case "Donatello": - Console.WriteLine("Does machines!"); - break; - case "Raphael": - Console.WriteLine("Cool, but rude!"); - break; - case "Michelangelo": - Console.WriteLine("Party dude!"); - break; - default: - Console.WriteLine($"{favoriteTurtle} sounds cool, but I'll bet they're not a ninja!"); - break; - } - } -} - -// Output: "Does machines!" -``` diff --git a/content/c-sharp/concepts/variables/variables.md b/content/c-sharp/concepts/variables/variables.md deleted file mode 100644 index 219219b3352..00000000000 --- a/content/c-sharp/concepts/variables/variables.md +++ /dev/null @@ -1,173 +0,0 @@ ---- -Title: 'Variables' -Description: 'Variables are used to store and manipulate data. In C#, each variable has a type that determines the values it can store.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Variables' - - 'Data Types' -CatalogContent: - - 'learn-c-sharp' - - 'paths/computer-science' ---- - -**Variables** are used to store and manipulate data. In C#, each variable has a type that determines the values it can store. - -## Types of variables - -In C#, there are five distinct types of variables: - -| Name | Description | -| ------------------ | -------------------------------------------------------------------------------------------------------------------------------- | -| Local variables | Variables declared within a method, constructor, or code block, accessible only within that scope. | -| Instance variables | Non-static fields in a class, storing data unique to each instance of the class. | -| Static Variables | Variables shared across all instances of a class, belonging to the class itself. | -| Constant Variables | Immutable values initialized at the time of declaration, typically declared with const and behaving similarly to static members. | -| Readonly Variables | Values that can be assigned during declaration or in a constructor but cannot be modified afterward. | - -## Syntax - -```pseudo -type name = value; -``` - -- `type`: The data type of a variable, defining the kind of data it can hold. -- `name`: The identifier for the variable, used to reference it in the code. -- `value`: An optional initial value for the variable. If omitted, it must be assigned a value before use. - -## Examples - -### Local variables - -In this example, `localVariable` can only be used within the `MyMethod()` function: - -```cs -void MyMethod() -{ - int localVariable = 10; // This variable is only accessible inside MyMethod -} -``` - -### Instance variables - -The example demonstrates an instance variable (`name`) within a class (`Person`). Each instance of `Person` will have its own copy of `name`: - -```cs -class Person -{ - public string name; // Instance variable - - public Person(string personName) - { - name = personName; // Initialize instance variable - } -} -``` - -### Static Variables - -Here, `wheels` is a static variable, meaning it belongs to the `Car` class and is shared by all instances. Note that static variables can be modified unless marked as `const`: - -```cs -class Car { - public static int wheels = 4; // Static variable -} -``` - -### Constant Variables - -In this example, `Pi` is a constant variable, meaning its value cannot be changed after declaration and is shared across all instances: - -```cs -class Circle -{ - public const double Pi = 3.14159; // Constant variable - - public double CalculateArea(double radius) - { - return Pi * radius * radius; // Using the constant variable - } -} -``` - -### Readonly Variables - -In this example, `length` and `width` are readonly variables assigned in the `Rectangle` constructor. Their values cannot be changed after the instance is created: - -```cs -class Rectangle -{ - public readonly double length; // Readonly variable - public readonly double width; // Readonly variable - - public Rectangle(double l, double w) - { - length = l; // Assigning value in the constructor - width = w; // Assigning value in the constructor - } -} -``` - -## Codebyte Example - -Here’s an example showcasing the use of various types of variables: - -```codebyte/csharp -using System; - -class Car -{ - // Instance variable - public string model; - - // Static variable - public static int wheels = 4; // Shared across all instances - - // Constant variable - public const string fuelType = "Gasoline"; // Cannot be changed - - // Readonly variable - public readonly string vin; // Must be assigned in constructor - - // Constructor to initialize instance and readonly variables - public Car(string model, string vin) - { - this.model = model; - this.vin = vin; // Assigning the readonly variable - } - - public void DisplayInfo() - { - // Local variable - string message = $"Car Model: {model}, VIN: {vin}, Wheels: {wheels}, Fuel Type: {fuelType}"; - - // Displaying the message - Console.WriteLine(message); - } -} - -class Factory -{ - static void Main() - { - // Creating instances of Car - Car car1 = new Car("Toyota Camry", "1HGCM82633A123456"); - Car car2 = new Car("Honda Accord", "1HGCM82633A654321"); - - // Displaying info for each car - car1.DisplayInfo(); - car2.DisplayInfo(); - - // Modifying static variable - Car.wheels = 5; // All instances will see this change - - // Displaying info again to see the updated static variable - car1.DisplayInfo(); - car2.DisplayInfo(); - - // Trying to modify readonly variable (will cause compile-time error) - // car1.vin = "1HGCM82633A111111"; // Uncommenting this line will cause an error - } -} -``` diff --git a/content/c/c.md b/content/c/c.md deleted file mode 100644 index 351ed5c44bc..00000000000 --- a/content/c/c.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -Title: 'C' -Description: 'C is a powerful mid to low-level compiled programming language used in operating systems, as the base for higher level languages like C++ and Python, and in high-performance applications. It excels in speed and performance giving the programmer great control over the system. The C language was created by Dennis Ritchie in Bell Labs in the 1970s. It was designed to be a system implementation language for the nascent Unix operating system.' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -C is a powerful mid to low-level compiled programming language used in operating systems, as the base for higher level languages like C++ and Python, and in high-performance applications. It excels in speed and performance giving the programmer great control over the system. - -The C language was created by Dennis Ritchie in Bell Labs in the 1970s. It was designed to be a system implementation language for the nascent Unix operating system. diff --git a/content/c/concepts/arrays/arrays.md b/content/c/concepts/arrays/arrays.md deleted file mode 100644 index 6f95c561a9b..00000000000 --- a/content/c/concepts/arrays/arrays.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -Title: 'Arrays' -Description: 'In the C language, an array is a data structure of a fixed length that stores a list of values.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Arrays' - - 'Lists' - - 'Variable Types' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -In the C language, an array is a list of values, with a fixed length. - -Being able to store multiple pieces of related information in the same structure is very useful when writing C programs. - -## Declaring an Array - -The syntax for declaring an array is first specify the data type, then a descriptive array name, followed by square brackets surrounding the array's length (number of items): - -```pseudo -type name[length]; -``` - -To declare an `int` array named `grades` with a length of 6: - -```c -int grades[6]; // An array to hold six integers -``` - -Alternatively, the length can be omitted and the array's initial values can be assigned to it instead. Values are assigned inside of the curly brackets and separated by commas. - -```c -int grades[] = {96, 90, 78, 84, 88, 92}; -``` - -## Accessing Values with Indexes - -The values in arrays are accessed using their index, or their position in the array. They can either be assigned or used this way. - -```c -char vowels[] = {'a', 'e', 'i', 'o', 'u'}; -``` - -Note that in C, an array's indexes start at 0 instead of 1: - -```pseudo - +-------------------------+ -Value | 'a' 'e' 'i' 'o' 'u' | - +-------------------------+ -Index | 0 1 2 3 4 | - +-------------------------+ -``` - -An element can be accessed by referring to the array name and the element's index number: - -- `vowels[0]` will give the value `'a'` -- `vowels[1]` will give the value `'e'` -- `vowels[2]` will give the value `'i'` -- `vowels[3]` will give the value `'o'` -- `vowels[4]` will give the value `'u'` - -```c -char vowels[] = {'a', 'e', 'i', 'o', 'u'}; - -putchar(vowels[3]); -// Output: o -``` - -## Example - -Creating an array that holds the snowfall measurements (in the nearest inch) from the past 7 days: - -```c -#include - -int main() { - int snowfall[] = {10, 13, 14, 11, 9, 8, 6}; - printf("%d\n", snowfall[0]); - - snowfall[2] = 16; // Update an element - printf("%d\n", snowfall[2]); - - return 0; -} -``` - -The output would be: - -```shell -10 -16 -``` diff --git a/content/c/concepts/arrays/terms/dynamic-arrays/dynamic-arrays.md b/content/c/concepts/arrays/terms/dynamic-arrays/dynamic-arrays.md deleted file mode 100644 index 7e849d64da6..00000000000 --- a/content/c/concepts/arrays/terms/dynamic-arrays/dynamic-arrays.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -Title: 'Dynamic Arrays' -Description: 'A dynamic array in C refers to an array whose size can be adjusted during runtime.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Arrays' - - 'Lists' - - 'Variable Types' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -A **dynamic array** in C refers to an array whose size can be adjusted during runtime. Unlike static arrays, whose size must be fixed at compile time, dynamic arrays offer flexibility by utilizing memory allocation functions from the `stdlib.h` library, such as [`malloc()`](https://www.codecademy.com/resources/docs/c/memory-management/malloc), [`calloc()`](https://www.codecademy.com/resources/docs/c/memory-management/calloc), [`realloc()`](https://www.codecademy.com/resources/docs/c/memory-management/realloc), and [`free()`](https://www.codecademy.com/resources/docs/c/memory-management/free). - -Dynamic arrays are useful when the required size of an array cannot be determined in advance. They allow efficient memory management by allocating or freeing memory as needed, avoiding wastage or insufficient allocation. - -## How to Implement a Dynamic Array - -To implement a dynamic array, the following steps are involved: - -### 1. **Allocate Memory** - -Use `malloc()` or `calloc()` to allocate memory for the array dynamically. - -#### `malloc()` - -This function allocates a block of memory on the heap at runtime. It takes a single argument specifying the size of the memory block in bytes. However, the memory allocated by `malloc()` is not initialized, meaning it contains garbage values. - -The syntax for using `malloc()` is as follows: - -```pseudo -int *arr = (int *)malloc(size * sizeof(int)); -``` - -#### `calloc()` - -This function also allocates memory dynamically, but unlike `malloc()`, it initializes the allocated memory to zero. It takes two arguments: the number of elements and the size of each element. - -The syntax for using `calloc()` is as follows: - -```pseudo -int *arr = (int *)calloc(size, sizeof(int)); -``` - -> **Note**: Both functions `malloc()` and `calloc()` return a pointer to the allocated memory. If memory allocation fails, they return `NULL`, so it's important to check if the allocation was successful. - -### 2. **Access and Modify** - -Once memory is allocated, use the pointer like a normal array to store and modify values. - -### 3. **Resize the Array** - -Use `realloc()` to adjust the array size if necessary. - -The syntax for using `realloc()` is as follows: - -```pseudo -arr = (int *)realloc(arr, new_size * sizeof(int)); -``` - -### 4. **Free Memory** - -When the dynamically allocated memory is no longer needed, use [`free()`](https://www.codecademy.com/resources/docs/c/memory-management/free) to release it and prevent memory leaks. - -The syntax for using `free()` is as follows: - -```psuedo -free(arr); -``` - -## Example - -Here is an example that shows how to initialize and use a dynamic array: - -```c -#include -#include - -int main() { - int n = 5; - int *arr_malloc, *arr_calloc; - - // Dynamically allocate memory using malloc - arr_malloc = (int *)malloc(n * sizeof(int)); - - if (arr_malloc == NULL) { - printf("Memory allocation failed using malloc\n"); - return 1; - } - - // Initialize the array using a loop - for (int i = 0; i < n; i++) { - arr_malloc[i] = i + 1; // Assigning values 1 to 5 - } - - printf("Array allocated using malloc:\n"); - for (int i = 0; i < n; i++) { - printf("%d ", arr_malloc[i]); - } - printf("\n"); - - // Dynamically allocate memory using calloc - arr_calloc = (int *)calloc(n, sizeof(int)); - - if (arr_calloc == NULL) { - printf("Memory allocation failed using calloc\n"); - free(arr_malloc); // Free previously allocated memory - return 1; - } - - // Since calloc initializes all elements to 0, we don't need to initialize the array - printf("Array allocated using calloc (initialized to 0):\n"); - for (int i = 0; i < n; i++) { - printf("%d ", arr_calloc[i]); - } - printf("\n"); - - // Free the dynamically allocated memory - free(arr_malloc); - free(arr_calloc); - - return 0; -} -``` - -The output of the above code will be as follows: - -```shell -Array allocated using malloc: -1 2 3 4 5 -Array allocated using calloc (initialized to 0): -0 0 0 0 0 -``` diff --git a/content/c/concepts/basic-output/basic-output.md b/content/c/concepts/basic-output/basic-output.md deleted file mode 100644 index 629b7aaf154..00000000000 --- a/content/c/concepts/basic-output/basic-output.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -Title: 'Basic Output' -Description: 'Basic console output is managed by the standard header file for input and output in C.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Print' - - 'Output' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -In the C language, **basic console output** is achieved using functions from the "standard input output" header file (`stdio.h`). - -## Header File - -C itself has no ability to output any information. In order to so, the `stdio.h` header file must be included in the program, which commonly happens at the top of the file: - -```c -#include -``` - -Once this is done, the functions included in it can be used. diff --git a/content/c/concepts/basic-output/terms/printf/printf.md b/content/c/concepts/basic-output/terms/printf/printf.md deleted file mode 100644 index 6ce6614c586..00000000000 --- a/content/c/concepts/basic-output/terms/printf/printf.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -Title: 'printf()' -Description: 'Print a string in the console.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Print' - - 'Functions' - - 'Console' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`printf()`**, or "print formatted", function can print a string to the console, including variables within the string. - -## Syntax - -```pseudo -printf(string, value1, value2 ... valueN) -``` - -The `printf()` function takes a string with variable placeholders, also known as format specifiers, followed by any number of values to format in the string. - -## Example - -```c -#include - -int main(void) { - printf("%d is a number\n", 5); - printf("%d is after %d\n", 2, 1); - return 0; -} -``` - -The output would be: - -```shell -5 is a number -2 is after 1 -``` - -## Format Specifiers - -As seen above, the string given contains a `%` character followed by a letter to indicate what type of value will be formatted there. Some common ones are shown below: - -| Format Specifier(s) | Type(s) | -| ------------------- | --------------- | -| `%c` | char | -| `%f` or `%g` | float or double | -| `%d` or `%i` | int | -| `%p` | pointer | -| `%s` | string | - -## Decimal Precision - -When using format specifiers for decimal numbers, the number of decimal places to be printed can be specified. - -For example, to print two digits after the decimal place with `printf()`, `0.2f` can be used: - -```c -#include - -int main() { - float pi = 3.14159; - - // Print 2 digits after the decimal place - printf("%0.2f", pi); - - return 0; -} -``` - -The output would be: - -```shell -3.14 -``` diff --git a/content/c/concepts/basic-output/terms/putchar/putchar.md b/content/c/concepts/basic-output/terms/putchar/putchar.md deleted file mode 100644 index c22a97ea52a..00000000000 --- a/content/c/concepts/basic-output/terms/putchar/putchar.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -Title: 'putchar()' -Description: 'Print a char in the console.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Char' - - 'Console' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`putchar()`**, or "put character", function prints a single character to `stdout` (normally the console). - -## Syntax - -```pseudo -putchar(char) -``` - -The **`putchar()`** takes a single `char` as an argument and prints it. - -## Example - -```c -#include - -int main(void) { - putchar('a'); - return 0; -} -``` - -The output would be: - -```shell -a -``` diff --git a/content/c/concepts/basic-output/terms/puts/puts.md b/content/c/concepts/basic-output/terms/puts/puts.md deleted file mode 100644 index e3980c51122..00000000000 --- a/content/c/concepts/basic-output/terms/puts/puts.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -Title: 'puts()' -Description: 'Print a string in the console.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'String' - - 'Console' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`puts()`**, or "put string", function prints a [string](https://www.codecademy.com/resources/docs/c/strings) to `stdout`, normally the console, followed by a newline character. - -## Syntax - -```pseudo -puts(str) -``` - -The `puts()` function takes a `str` argument and prints it, adding a newline character at the end of it. - -## Example - -```c -#include - -int main(void) { - puts("Hello World!"); - return 0; -} -``` - -The output would be: - -```shell -Hello World! -``` diff --git a/content/c/concepts/basic-output/terms/scanf/scanf.md b/content/c/concepts/basic-output/terms/scanf/scanf.md deleted file mode 100644 index 0d362a51f38..00000000000 --- a/content/c/concepts/basic-output/terms/scanf/scanf.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -Title: 'scanf()' -Description: 'Reads a user input and assigns it to a variable.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Functions' - - 'Input' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`scanf()`** function (short for 'scan formatted') reads user input, interprets it according to the specified format, and assigns the converted value to a variable. - -## Syntax - -```pseudo -int scanf(const char *format, &variable1, &variable2, ..., &variableN); -``` - -- `format`: A string containing format specifiers (e.g., `%d`, `%f`, `%s`) that define the type of input expected. -- `&variable1, &variable2, ..., &variableN`: Pointers to variables where the values from the input will be stored. Each pointer corresponds to a format specifier in the `format` string. - -For a short list of format specifiers you can use in the input string, see the 'Format Specifiers' table in the [`printf`](https://www.codecademy.com/resources/docs/c/basic-output/printf) documentation. - -> **Note:** `scanf()` does not have any intrinsic validation of the user input. This can cause errors if the user input does not match the format specifiers in the string. - -## Example 1 - -In the following example, the format specifier `%d` tells the function to expect an integer, then assigns it to the variable `yourNumber`: - -```c -#include - -int main(void) { - int yourNumber; - - printf("Type your favorite number:"); - scanf("%d", &yourNumber); - printf("Your favorite number is: %d", yourNumber); -} -``` - -If the user typed in `3`, the output would be: - -```shell -Your favorite number is: 3 -``` - -## Example 2 - -Here is another example using two variables: - -```c -#include - -int main(void) { - int yourNumber; - char yourLetter; - - printf("Type your favorite number and letter:"); - scanf("%d%c", &yourNumber, &yourLetter); - printf("Your favorite number is: %d and your favorite letter is: %c", yourNumber, yourLetter); -} -``` - -If the user typed in `4Bh`, the output would be: - -```shell -Type your favorite number and letter:Your favorite number is: 48 and your favorite letter is: h -``` diff --git a/content/c/concepts/comments/comments.md b/content/c/concepts/comments/comments.md deleted file mode 100644 index f8996627b6d..00000000000 --- a/content/c/concepts/comments/comments.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -Title: 'Comments' -Description: 'Comments are a piece of text within a program that are not executed. They are used to provide additional information to aid in understanding the code. In C, there are single and multi-line comments.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Comments' - - 'Documentation' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -A comment is a piece of text within a program that is not executed. It can be used to provide additional information to aid in understanding the code. - -## Single-line Comments - -Single-line comments are created using two consecutive forward slashes. The compiler ignores any text after `//` on the same line. - -```c -// This line will denote a comment in C -``` - -## Multi-line Comments - -Multi-line comments are created using `/*` to begin the comment, and `*/` to end the comment. The compiler ignores any text in between. - -```c -/* -This is all commented out. -None of it is going to run! -*/ -``` - -## Header Comment - -Multi-line comments can be used to create a header comment at the top of the file. File header comments are used to identify the author of the code, the date the code was written, a description of the program, etc. This is a common convention in the C language. - -```c -/*************************************************************** -* FILENAME: hello.c -* DESCRIPTION: This program prints a message to the screen. -* AUTHOR: Gilfoyle -* DATE: 04/20/2023 -* MODIFICATION: Dinesh -* CHANGES: N/A -****************************************************************/ -``` - -## Example - -Here's a program with a multi-line comment and three single-line comments: - -```c -/* Tip Calculator -Written by Sonny */ - -#include - -int main() { - // Calculate the tip - double total = 18.75; - double tip = total * 0.2; - - // Display the tip - printf("The tip is $%.2f\n", tip); // Show two decimal places - - return 0; -} -``` diff --git a/content/c/concepts/compiling/compiling.md b/content/c/concepts/compiling/compiling.md deleted file mode 100644 index f31673025a3..00000000000 --- a/content/c/concepts/compiling/compiling.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -Title: 'Compiling' -Description: 'A compiler translates the C program (source code) into machine language (machine code) which it stores on the disk as a file.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Command Line' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -A compiler translates the C program (source code) into machine language (machine code) which it stores on the disk as a file. - -This process of converting the source code into machine code is known as compilation. - -## Stages of Compiling a C Program - -There are 4 stages in the process of compilation of a C Program. - -### 1. Preprocessing - -[Preprocessing](https://www.codecademy.com/resources/docs/c/preprocessors) is the first stage in the process of compilation. In this stage: - -- Preprocessor commands that begin with `#` are interpreted. -- Comments are removed from the source code. -- Macros are expanded. - -### 2. Compiling - -In this stage, the preprocessed code is translated into assembly code and syntax errors are checked by the compiler. - -### 3. Assembly - -In this stage, an assembler is used to translate the assembly code into object code (machine code). - -### 4. Linking - -Linking is the final stage in the process of compilation. In this stage, all the object code from multiple modules is merged (linked) together and creates an executable image which is also saved on the disk, usually as a file with the file name without any extension (e.g. **hello**), so that it can finally be executed by the processor. - -## Compile Command - -```shell -gcc –Wall hello.c -``` - -This compiles a file named **hello.c** and the output file will be named **a.out**. - -```shell -gcc –Wall hello.c –o hello -``` - -This compiles a file named **hello.c** and specifies the output file name as **hello**. The option `-o` is used to name the output file. - -## Execute Command - -```shell -./hello -``` - -The executable file **hello** is loaded from the disk to memory and the computer’s CPU (Central Processing Unit) executes the program one instruction at a time. - -![xkcd comic](https://imgs.xkcd.com/comics/compiling.png) - -([xkcd](https://xkcd.com/303/): Compiling) diff --git a/content/c/concepts/control-statements/control-statements.md b/content/c/concepts/control-statements/control-statements.md deleted file mode 100644 index b5a9536e8b5..00000000000 --- a/content/c/concepts/control-statements/control-statements.md +++ /dev/null @@ -1,264 +0,0 @@ ---- -Title: 'Control Statements' -Description: 'In C, control statements direct program flow using conditions, loops, and branches for decision-making and repetition.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Algorithms' - - 'Booleans' - - 'Conditionals' - - 'Control Flow' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -In C, [**control statements**](https://www.codecademy.com/resources/docs/general/control-flow) are fundamental constructs that use loops and conditions to determine how a program should execute. They give programmers the ability to deliberately, frequently, or in reaction to certain scenarios run individual code blocks. - -C supports two main types of control statements: - -## Conditional Statements - -Conditional statements in C are used to make decisions and execute specific blocks of code depending on whether a condition evaluates to `true` or `false`. Some of the conditional statement constructs supported in C are `if`,`else`, `else if`, and `switch` statement. - -### if Statement - -The `if` statement is used to execute a code block only if a specified condition evaluates to `true`: - -```pseudo -if (condition) { - // Code to execute if condition is true -} -``` - -Here's an example code snippet demonstrating the use of `if` statement in C: - -```c -#include - -int main() { - int number = 10; - - // Check if the number is greater than 5 - if (number > 5) { - printf("Greater than 5\n"); - } - - return 0; -} -``` - -The output for the code would be: - -```shell -Greater than 5 -``` - -### if-else Statement - -The `if-else` statement is used for executing a code block only if a specified condition comes `true` and another if it comes `false`: - -```pseudo -if (condition) { - // Code to execute if condition is true -} else { - // Code to execute if condition is false -} -``` - -Here's an example code snippet demonstrating the use of `if-else` statement in C: - -```c -#include -int main() { - int number = 3; - - // Check if the number is greater than 5 - if (number > 5) { - printf("Greater than 5\n"); - } else { - printf("5 or less\n"); - } - - return 0; -} -``` - -The output for the code would be: - -```shell -5 or less -``` - -### switch Statement - -The `switch` statement executes one of several blocks of code based on the value of a variable: - -```pseudo -switch (variable) { - case value1: - // Code for case value1 - break; - case value2: - // Code for case value2 - break; - default: - // Code if no cases match -} -``` - -Here's an example code snippet demonstrating the use of `switch` statement in C: - -```c -#include -int main() { - int day = 6; - -// Determine the day of the week - switch (day) { - case 1: - printf("Monday\n"); - break; - case 2: - printf("Tuesday\n"); - break; - case 3: - printf("Wednesday\n"); - break; - case 4: - printf("Thursday\n"); - break; - case 5: - printf("Friday\n"); - break; - case 6: - printf("Saturday\n"); - break; - case 7: - printf("Sunday\n"); - break; - default: - printf("Invalid day\n"); - } - - return 0; -} -``` - -The output for the code would be: - -```shell -Saturday -``` - -## Looping Statements - -Looping statements in C are used to repeatedly execute a code block until a specific condition comes `false`. This helps developers avoid the repetition of tasks and minimizes the duplication of code in their programs. - -### for loop - -In C, the `for` loop allows users to run a block of code multiple times, making it ideal for situations where they know exactly how many iterations are needed: - -```pseudo -for (initialization; condition; update) { - // Code to execute in each iteration -} -``` - -Here's an example code snippet demonstrating the use of `for` statement in C: - -```c -#include - -int main() { - // Using a for loop to print numbers 1 to 5 - for (int i = 1; i <= 5; i++) { - printf("Iteration: %d\n", i); - } - return 0; -} -``` - -The output for the code would be: - -```shell -Iteration: 1 -Iteration: 2 -Iteration: 3 -Iteration: 4 -Iteration: 5 -``` - -### while loop - -The `while` loop in C executes a code block repeatedly until a specific condition comes `false`. It's mostly used when the number of iterations needed are not known: - -```pseudo -while (condition) { - // Code to execute while condition is true -} -``` - -Here's an example code snippet demonstrating the use of `while` loop in C: - -```c -#include -int main() { - int i = 1; - - // While loop will execute as long as i is less than or equal to 5 - while (i <= 5) { - printf("%d\n", i); // Print the value of i - i++; // Increment i by 1 - } - return 0; -} -``` - -The output for the code would be: - -```shell -1 -2 -3 -4 -5 -``` - -### do-while loop - -A `do-while` loop in C resembles a `while` loop with a difference. The condition is tested after the loop body is executed and not before, which is how it's executed at least once regardless of the condition. In a `do-while` loop, execution continues as long as the given condition is met: - -```pseudo -do { - // Block of code to be executed -} while (condition); -``` - -Here's an example code snippet demonstrating the use of `do-while` loop in C: - -```c -#include -int main() { - int count = 1; - - // do-while loop to print numbers 1 to 5 - do { - printf("Count: %d\n", count); - count++; - } while (count <= 5); - - return 0; -} -``` - -The output for the code would be: - -```shell -Count: 1 -Count: 2 -Count: 3 -Count: 4 -Count: 5 -``` diff --git a/content/c/concepts/data-types/data-types.md b/content/c/concepts/data-types/data-types.md deleted file mode 100644 index 4672cb5c868..00000000000 --- a/content/c/concepts/data-types/data-types.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -Title: 'Data Types' -Description: 'Data types are units of value stored in memory through variables, each with different functionalities and size-ranges.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Booleans' - - 'Variable Types' - - 'Variables' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -In C, **data types** are units of value stored in [memory](https://www.codecademy.com/resources/docs/c/memory-management) through [variables](https://www.codecademy.com/resources/docs/c/variables). Different kinds of data types determine their size and functionality. - -## Static Typing - -Like with C++ and Java, C is a statically-typed language where variable types are known at compile time instead of the [runtime](https://www.codecademy.com/resources/docs/general/runtime). In this case, types must be expressly indicated by the programmer. - -Data type classifications supported in C include the following: - -- Primitive data types -- User-defined data types -- Derived data types - -Types also differ in the amount of memory they occupy and the range of values they can hold. This will depend on the compiler of the computer. An integer, for example, might take up 32 bits on one computer, or perhaps it might be stored in 64 bits on another. - -## Primitive Types - -These data types are mostly numeric (integers, doubles, floating-point numbers, etc.) and can be used for arithmetic operations like subtraction and division. Values that use the `void` keyword (for no data) are also regarded as primitive data types. - -## Derived Data Types - -These data types derive from primitive or fundamental data types. In C, these can be of three types: - -- [Arrays](https://www.codecademy.com/resources/docs/c/arrays) -- [Functions](https://www.codecademy.com/resources/docs/c/functions) -- [Pointers](https://www.codecademy.com/resources/docs/c/pointers) - -## User-defined Types - -These are a collection of data with values that have fixed meanings that extend the primitive types already available. Users define them based on requirements. C consists of the following user-defined types: - -- Enum -- [Structures](https://www.codecademy.com/resources/docs/c/structures) -- Typedef -- Union - -## Memory Size - -| Type | Size | Value Range | -| ------ | ------- | ------------------------------ | -| Char | 1 byte | -128 - 127 or 0 - 255 | -| Int | 4 bytes | -2,147,483,648 - 2,147,483,647 | -| Float | 4 bytes | 1.2E-38 - 3.4E+38 | -| Double | 8 bytes | 1.7E-308 - 1.7E+308 | - -### Int - -Ints contain only integral values. A minus sign preceding the data type indicates that the value is negative. They can be expressed in hexadecimal notation (base 16). - -> **Note:** Hexadecimal integer literals begin always with the `0` followed by either an `x` or `X`, followed by different combinations of digits (`0` - `9`) and letters (`a` - `f` or `A` - `F`). - -```c -int = 0; -int = -5; -int = 20; -int rgbColor = 0XFFEF0D; // Hexadecimal -``` - -Spaces aren't allowed between digits and the values larger than 999 don't use commas. - -```c -int hundreds = 12,000; // This is wrong -int hundreds2 = 12000; // This is correct -``` - -### Float and Double - -Floating-point values are non-whole numbers that contain decimal places. They can have up to 6 decimal digits of precision and can be expressed in scientific notation. - -> **Note:** Scientific notation is a form of expressing numbers that are too large or too small to be conveniently written in decimal form (e.g., `6.022E23`). - -Doubles are like floats but more precise with up to 15 decimal digits. The following is an example of `float` and `double` type values: - -```c -float salary = 523.45; -double bankTransaction = 245.2518; -float counterFactor = 15.87E4; -``` - -### Char - -Chars use single quotations marks `'` to represent single characters such as letters, [numbers](https://www.codecademy.com/resources/docs/general/data-types/number), [whitespace](https://www.codecademy.com/resources/docs/general/whitespace), special characters, and symbols. Each char only occupies one byte in memory. In C, sequences of chars are called [strings](https://www.codecademy.com/resources/docs/c/strings). - -```c -char a = 'a'; -``` diff --git a/content/c/concepts/enums/enums.md b/content/c/concepts/enums/enums.md deleted file mode 100644 index eec452e323e..00000000000 --- a/content/c/concepts/enums/enums.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -Title: 'Enums' -Description: 'An enum is used to assign custom names to integral constants.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Enum' - - 'Variable Types' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -An **enum** (enumeration) is a user-defined data type in C. It is used to assign names to integral constants. The principal purpose of these names is to create a program that is easy to read and maintain. It is defined using the `enum` keyword. - -## Syntax - -```pseudo -enum name -{ - memberName1 = , - memberName2, - memberName3, - ... - memberNameN -}; -``` - -An enum is made up of members where each `memberName` can have a defined integral constant (e.g. 0, 10, 2) or just the `memberName`. - -## Examples - -If we do not explicitly assign values to `enum` `day`, the compiler by default assigns values starting from 0. For instance, `sunday` gets a value of 0, `monday` gets 1, and so on. - -```c -#include -enum fruits {apple, orange, banana, peach, grape}; - -int main() -{ - enum fruits d = banana; - printf("The fruit number stored in d is %d", d); - return 0; -} -``` - -This example results in the following output: - -```shell -The fruit number stored in d is 2 -``` - -Two `enum` names can have the same value. For instance, both `Running` and `In_Progress` have the same value of 1. - -```c -#include -enum State {Todo = 0, Running = 1, In_Progress = 1}; -int main() -{ - printf("%d, %d, %d", Todo, Running, In_Progress); - return 0; -} -``` - -This example results in the following output. - -```shell -0, 1, 1 -``` - -We can assign values to a particular name in any order. All unassigned names get value as the value of the previous name plus one. - -```c -#include -enum day {sunday = 1, monday, tuesday = 20, - wednesday, thursday = 10, friday, saturday}; - -int main() -{ - printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, - wednesday, thursday, friday, saturday); - return 0; -} -``` - -This example results in the following output: - -```shell -1 2 20 21 10 11 12 -``` - -> **Note:** All `enum` constants must be unique in their scope. diff --git a/content/c/concepts/functions/functions.md b/content/c/concepts/functions/functions.md deleted file mode 100644 index 0a57f5aef21..00000000000 --- a/content/c/concepts/functions/functions.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -Title: 'Functions' -Description: 'Functions are blocks of code that can be reused within a program.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Functions' - - 'Arguments' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -Functions are blocks of code that can be reused within a program. They are stored under a name similar to a variable and can be called using this name. - -## Syntax - -```pseudo -return_type name(parameters) { - // Code goes here -} -``` - -Functions are declared with the following pieces: - -- A `return_type` that denotes the specific type of data output. -- The `name` of the functions. -- The `parameters` are used for processing data in the function body, and the code for it to run in curly brackets. - -A function named `greet()` that prints a greeting to the console can be declared like this: - -```c -void greet(void) { - puts("Howdy!"); -} -``` - -The `greet()` function uses a [`void`](https://www.codecademy.com/resources/docs/general/data-types/void) type to indicate that no output is returned after execution. - -## Calling a Function - -After a function is declared, it can be called in the program. The syntax for this is the variables name followed by parenthesis. - -```c -#include - -// Declaring the function - -void greet(void) { - puts("Howdy!"); -} - -// Calling the function inside main() - -int main() { - greet(); -} -``` - -The output would be: - -```shell -Howdy! -``` - -## Arguments - -The values passed to a function are known as arguments. They represent the actual input values that can be used within the function. - -```c -#include - -void max(int x, int y) { - if (x > y) - printf("%d is the bigger number\n", x); - else - printf("%d is the bigger number\n", y); -} - -int main() { - int a = 20; - int b = 30; - - max(a, b); - - return 0; -} -``` - -Here's another example: - -```c -#include - -void greet(char* name) { - printf("Howdy %s!\n") -} - -int main() { - greet("John Doe"); // Output: Howdy John Doe! - return 0; -} -``` - -## Returning Values - -A function is also capable of returning a value back to were it was called using the `return` keyword. This is useful for computing values within a function. Notice that the word proceeding the function name indicates the type of value returned. - -```c -#include - -int add(int a, int b) { - return a + b; -} - -int main(void) { - int num = add(1, 1); - printf("%d\n", num); -} -``` - -Here, the `add()` function has a return value of `int`. diff --git a/content/c/concepts/header-files/header-files.md b/content/c/concepts/header-files/header-files.md deleted file mode 100644 index 2a94c677b1b..00000000000 --- a/content/c/concepts/header-files/header-files.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -Title: 'Header Files' -Description: 'Allow common functions to be used across multiple files without copying their declarations and definitions.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Functions' - - 'Conceptual' - - 'Constructors' - - 'Programming' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -**Header files**, typically denoted by a **`.h`** suffix, are used to provide forward declarations of functions, data types, macros, and more, but they do not contain the definitions. This prevents multiple definitions across the codebase, adhering to the _One Definition Rule_. While simple functions and data types may occasionally defy this rule, the general best practice is to separate declarations and definitions, with exceptions covered in more advanced topics beyond this summary. - -These files are usually paired with a source file that defines the terms declared in the header, allowing them to be reused across multiple source files without redeclaring each function. - -Header files come in two forms: _user-defined_ and those from _the standard library_. The developer creates user-defined headers, which are typically situated in the same directory as the source file being worked on (though this can vary depending on the configuration and tools used). Standard library headers like `stdio.h` are found in system directories. - -## Syntax - -A header file is included in a source file using the `#include` preprocessor directive, followed by the header file's name. For example: - -```pseudo -#include -``` - -This allows the use of functions from the `stdio.h` file, such as `printf`, as shown below: - -```c -#include - -int main() -{ - printf("Hello World!"); - - return 0; -} -``` - -For user-defined header files, the syntax is slightly different; instead of ``, `"filename.h"` is used. For example: - -```pseudo -#include "myHeader.h" -``` - -If the header file is not in the same directory as the source file, it can be included using a relative (recommended) or absolute (not recommended) path, like this: - -```pseudo -#include "../myHeaders/myHeader.h" -``` - -A better approach is to configure the compiler to include the directory containing the header files, allowing the header to be included without specifying the full path. Check your Integrated Development Environment (IDE) documentation for specific instructions on configuring this, as the process may vary. - -## Header File Construction - -A proper header file should only contain declarations, not definitions. The corresponding source file contains the definitions, which generally share the same name as the header. For example, a header file named `myHeader.h` is typically paired with a source file named `myHeader.c`. The header file should also include a header guard and a preprocessor macro that prevents multiple file inclusions. If the contents are not already defined (based on the unique name of the macro), they are included; otherwise, the compiler skips the file. A header guard for `myHeader.h` looks like this: - -```pseudo -#ifndef UNIQUE_NAME -#define UNIQUE_NAME - -// Declarations here - -#endif -``` - -`UNIQUE_NAME` can be any unique identifier, but the convention is to use the full filename of the header file. - -The accompanying C file will include the header file itself (as this is where the functions are declared) and the function definitions. For example: - -```pseudo -#include "myHeader.h" - -// Function definitions -``` - -## Example - -Here's a simple program that adds two integers and prints the result. - -First, the `add.h` header file is defined with the following code: - -```c -#ifndef ADD -#define ADD - -// Header that declares an addition function - -int add(int x, int y); - -#endif -``` - -Next, the paired `add.c` source file is defined with the following code: - -```c -#include "add.h" - -int add(int x, int y) -{ - return x + y; -} -``` - -Now, here's the program that calls the `add.h` header, computes a simple addition and prints the answer: - -```c -#include // Used for printing; notice the angle brackets for standard library headers -#include "add.h" // Double quotes for user-defined headers - -int main() { - int x = 3; - int y = 5; - int result = 0; // Initialize to zero - - // Compute the addition - result = add(x, y); - - // Display the result - printf("%d + %d = %d\n", x, y, result); - - return 0; -} -``` - -The above code produces the following output: - -```shell -3 + 5 = 8 -``` diff --git a/content/c/concepts/keywords/keywords.md b/content/c/concepts/keywords/keywords.md deleted file mode 100644 index c7e7ed87ecd..00000000000 --- a/content/c/concepts/keywords/keywords.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -Title: 'Keywords' -Description: 'Reserved words with predefined meanings and purposes in the C programming language and cannot be used as identifiers.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Data Types' - - 'Variables' - - 'Keywords' - - 'Functions' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -In C programming, **keywords** are fundamental building blocks. They are predefined and reserved by the language for specific functionalities, making it easier for programmers to write efficient and standard code. Keywords are part of the syntax and convey the compiler how to interpret a piece of code. Since they are reserved, they cannot be redefined or used for any other purpose. - -C provides a small set of keywords compared to modern programming languages, ensuring simplicity and performance. Understanding keywords is essential for learning the language and using its features effectively. - -## Key points about keywords - -- Keywords are case-sensitive in C. For example, `if` and `If` are treated differently. -- There are 32 standard keywords in C. -- Keywords cannot be used as variable names, function names, or any other identifiers. -- They provide specific instructions to the compiler to perform operations like branching, looping, data type definition, and memory management. -- Some compilers may introduce additional keywords as extensions, but these are non-standard. - -## Table of Keywords - -| Keyword | Description | -| ---------- | --------------------------------------------------- | -| `auto` | Declares an automatic variable | -| `break` | Exits a loop or switch statement | -| `case` | Defines a branch in a switch statement | -| `char` | Declares a character variable | -| `const` | Declares a constant value | -| `continue` | Skips the current iteration of a loop | -| `default` | Defines the default branch in a switch | -| `do` | Starts a do-while loop | -| `double` | Declares a double-precision floating point | -| `else` | Provides an alternative branch in an if | -| `enum` | Defines an enumeration | -| `extern` | Declares an external variable | -| `float` | Declares a floating-point variable | -| `for` | Starts a for loop | -| `goto` | Transfers control to a labeled statement | -| `if` | Starts a conditional statement | -| `int` | Declares an integer variable | -| `long` | Declares a long integer variable | -| `register` | Declares a register variable | -| `return` | Exits from a function | -| `short` | Declares a short integer variable | -| `signed` | Declares a signed variable | -| `sizeof` | Determines the size of a data type | -| `static` | Declares a static variable | -| `struct` | Declares a structure | -| `switch` | Starts a switch statement | -| `typedef` | Defines a new type name | -| `union` | Declares a union | -| `unsigned` | Declares an unsigned variable | -| `void` | Declares a void type | -| `volatile` | Declares a variable that can be modified externally | -| `while` | Starts a while loop | - -Keywords in C are indispensable for writing efficient and functional programs. They form the backbone of the language's syntax and provide instructions to the compiler for various operations. Understanding these reserved words is crucial for any programmer learning C, as it helps in creating structured and standard-compliant code. By mastering the use of keywords, you can unlock the full potential of the C programming language. diff --git a/content/c/concepts/keywords/terms/typedef/typedef.md b/content/c/concepts/keywords/terms/typedef/typedef.md deleted file mode 100644 index f7d44dede21..00000000000 --- a/content/c/concepts/keywords/terms/typedef/typedef.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -Title: 'typedef' -Description: 'Defines a new name for an existing data type in C to improve code readability and maintainability.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Alias' - - 'Data Types' - - 'Variables' - - 'Keywords' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`typedef`** keyword in C is used to create a new name (alias) for an existing data type, primarily to simplify complex data types. This improves code readability and maintainability. It does not create a new type but assigns a new name to the existing type. - -## Syntax - -Here's the basic syntax for `typedef`: - -```pseudo -typedef existing_data_type new_data_type; -``` - -- `existing_type`: The data type that will be assigned a new name. -- `new_name`: The new alias given to the existing data type. - -## Example - -Here’s a simple example demonstrating the use of `typedef` to create a new name for an existing data type in C: - -```c -#include -// Using typedef to create a new name for int -typedef int Integer; - -int main() { - Integer age = 25; // Integer is now an alias for int - printf("Age: %d\n", age); - return 0; -} -``` - -In this example, `Integer` is created as a new alias for the `int` data type, making the code easier to read and maintain by using a more descriptive name: - -```shell -Age: 25 -``` diff --git a/content/c/concepts/linked-list/linked-list.md b/content/c/concepts/linked-list/linked-list.md deleted file mode 100644 index 06350722013..00000000000 --- a/content/c/concepts/linked-list/linked-list.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -Title: 'Linked List' -Description: 'Linked list is a type of data structure in which elements are not sequentially stored but are randomly spread in memory.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Data Structures' - - 'Linked Lists' - - 'Memory' - - 'Pointers' - - 'Variables' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -A **linked list** is a type of linear data structure in which elements are not stored sequentially but are dynamically allocated in memory, consisting of small units called nodes. These units connect and point to other nodes to create a linked list. - -The structure of a node is illustrated below: - -![Linked list node](https://raw.githubusercontent.com/Codecademy/docs/main/media/linked-list-node.png) - -Each node in a linked list has two parts: - -- `data`: It stores the value, which can be of any data type. -- `next`: A pointer that stores the memory address of the next node in the sequence. - -When nodes are connected to one other, a linked list is formed, as shown below: - -![Singular linked list](https://raw.githubusercontent.com/Codecademy/docs/main/media/singular-linked-list.png) - -A linked list consists of two key components: - -- `Head`: The first node in the linked list. -- `Tail`: The last node in the linked list, which points to `NULL` in a singly linked list. - -There are four types of linked list: - -- Singly Linked List: Each node points to the next node and the last node points to NULL. -- Doubly Linked List: Each node has two pointers, one to the next node and one to the previous node. -- Circular Linked List: The last node points back to the first node, forming a circular structure. -- Doubly Circular Linked List: Combines the features of both doubly and circular linked lists, where each node has two pointers and the last node points back to the first node, forming a circular structure. diff --git a/content/c/concepts/loops/loops.md b/content/c/concepts/loops/loops.md deleted file mode 100644 index e5bc3f7a265..00000000000 --- a/content/c/concepts/loops/loops.md +++ /dev/null @@ -1,139 +0,0 @@ ---- -Title: 'Loops' -Description: 'A loop is a programming tool that is used to repeat a set of instructions.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Loops' - - 'While' - - 'For' - - 'Control Flow' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -A **loop** is a programming tool that is used to repeat a set of instructions. Iterate is a generic term that means “to repeat” in the context of loops. A loop will continue to iterate until a specified condition, commonly known as a stopping condition, is met. - -## For Loop - -A `for` loop begins with the `for` keyword and a statement declaring the three parameters governing the iteration, all separated by semicolons`;`: - -- The `initialization` defines where to begin the loop by declaring (or referencing) the iterator variable. -- The `condition` determines when to stop looping (when the expression evaluates to false). -- The `increment` statement updates the iterator each time the loop is completed. - -```pseudo -for (initialization; condition; increment) { - // Code to be executed repeatedly -} -``` - -For example: - -```c -for (int i = 0; i < 4; i++) { - printf("%d\n", i); -} -``` - -The output would be: - -```shell -0 -1 -2 -3 -``` - -## While Loop - -The `while` loop creates a loop that is executed as long as a specified condition evaluates to true. The loop will continue to run until the condition evaluates to false. The condition is specified before the loop, and usually, some variable is incremented or altered in the while loop body to determine when the loop should stop. - -```pseudo -while (condition) { - // Code block to be executed -} -``` - -For example: - -```c -int i = 0; - -while (i < 5) { - printf("%d\n", i); - i++; -} -``` - -The output would be: - -```shell -0 -1 -2 -3 -4 -``` - -## Do…While Loop - -A `do`...`while` statement creates a loop that executes a block of code once, checks if a condition is true, and then repeats the loop as long as the condition remains true. They are used when the loop body needs to be executed at least once. The loop ends when the condition evaluates to false. - -```pseudo -do { - // Code to be executed at least once -} while (condition); -``` - -For example: - -```c -int x = 0; -int i = 0; - -do { - x = x + i; - printf("%d\n", x); - i++; -} while (i < 5); -``` - -The output would be: - -```shell -0 -1 -3 -6 -10 -``` - -## Nested For Loop - -A nested `for` loop is when a `for` loop runs inside another `for` loop. - -The inner loop will run all its iterations for each iteration of the outer loop. - -For example: - -```c -for (int outer = 0; outer < 2; outer++) { - for (int inner = 0; inner < 3; inner++) { - printf("%d-%d\n", outer, inner); - } -} -``` - -The output would be: - -```shell -0-0 -0-1 -0-2 -1-0 -1-1 -1-2 -``` diff --git a/content/c/concepts/macros/macros.md b/content/c/concepts/macros/macros.md deleted file mode 100644 index eb68596a001..00000000000 --- a/content/c/concepts/macros/macros.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -Title: 'Macros' -Description: 'A macro is a label defined in the source code that is replaced by its value by the preprocessor before compilation.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Command Line' - - 'Developer Tools' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -A **macro** is a label defined in the source code that is replaced by its value by the [preprocessor](https://www.codecademy.com/resources/docs/c/preprocessors) before [compilation](https://www.codecademy.com/resources/docs/c/compiling). Macros are initialized with the `#define` preprocessor command and can be undefined with the `#undef` command. - -There are two types of macros: object-like macros and function-like macros. - -## Object-Like Macros - -These macros are replaced by their value in the source code before compilation. Their primary purpose is to define constants to be used in the code. - -**Note**: Macro definitions are not followed by a semicolon `;`. - -### Example - -In the following example, `PI` is defined as an object-like macro: - -```c -#include -#define PI 3.1416 - -int main() { - float radius = 3; - float area; - area = PI * radius * radius; - printf("Area is: %f",area); - return 0; -} -``` - -This example outputs the following: - -```shell -Area is: 28.274401 -``` - -## Function-Like Macros - -These macros behave like [functions](https://www.codecademy.com/resources/docs/c/functions), in that they take arguments that are used in the replaced code. Note that in defining a function-like macro, there cannot be a space between the macro name and the opening parenthesis. - -### Example - -In the following example, `AREA` is defined as a function-like macro. Note that other macros can be used in defining a subsequent macro. The inner macro is replaced by its value before the outer macro is replaced. - -```c -#include -#define PI 3.1416 -#define AREA(r) r * r * PI - -int main() { - float radius = 5; - float result; - result = AREA(radius); - printf("Area is: %f",result); - return 0; -} -``` - -This example outputs the following: - -```shell -Area is: 78.540001 -``` - -## Predefined Macros - -C has a number of predefined macros, including the following: - -- `__DATE__`: Current date formatted as `MMM DD YYYY`. -- `__TIME__`: Current time formatted as `HH:MM:SS`. -- `__FILE__`: Current filename. -- `__LINE__`: Current line number. - -### Example - -The following example uses the above predefined macros: - -```c -#include -int main() { - -char file[] = __FILE__; -char date[] = __DATE__; -char time[] = __TIME__; -int line = __LINE__; - -printf("File name: %s\n", file); -printf("Date: %s\n", date); -printf("Time: %s\n", time); -printf("Line number: %d\n", line); -} -``` - -The output resembles the following: - -```shell -File name: main.c -Date: Jun 25 2022 -Time: 14:05:33 -Line number: 7 -``` - -## Undefining a Macro - -Once defined, a macro can be undefined with the `#undef` command. Using the macro after that point will result in a compile error. - -### Example - -```c -#include -#define TEST 1 - -int main() { - #ifdef TEST - printf("TEST defined\n"); - #else - printf("TEST undefined\n"); - #endif - - #undef TEST - - #ifdef TEST - printf("TEST defined\n"); - #else - printf("TEST undefined\n"); - #endif - -} -``` - -This results in the output: - -```shell -TEST defined -TEST undefined -``` diff --git a/content/c/concepts/memory-management/memory-management.md b/content/c/concepts/memory-management/memory-management.md deleted file mode 100644 index 3f6a03b5964..00000000000 --- a/content/c/concepts/memory-management/memory-management.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -Title: 'Memory Management' -Description: 'Memory management is the process by which computer programs are assigned to physical or virtual memory space.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Memory' - - 'Memory Management' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -**Memory management**, or memory allocation, is the process by which computer programs are assigned to physical or virtual memory space. Computer memory is a finite resource that must be efficiently managed. - -The memory allocation can be done either before or at the time of program implementation. There are two techniques for memory allocation: static memory allocation and dynamic memory allocation. - -## Static Memory Allocation - -In this type of allocation, the compiler allocates a fixed amount of memory during compile time and the operating system internally uses a data structure known as stack to manage the memory. - -Exact memory requirements must be known in advance as once memory is allocated it can not be changed. - -```c -int days; // Needs to be initialized or assigned some value at run time -int snowfall = 0; // Normal variable -const int maxScore = 10; // Constant, can not be changed -``` - -## Dynamic Memory Allocation - -In this type of allocation, system memory is managed at runtime. Dynamic memory management in C programming language is performed using the `malloc()`, `calloc()`, `realloc()`, and `free()` functions. These four functions are defined in the `` C standard library header file. It uses the heap space of the system memory. More can be learned about these functions below: diff --git a/content/c/concepts/memory-management/terms/calloc/calloc.md b/content/c/concepts/memory-management/terms/calloc/calloc.md deleted file mode 100644 index dac178c442f..00000000000 --- a/content/c/concepts/memory-management/terms/calloc/calloc.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -Title: 'calloc()' -Description: 'Dynamically allocates an array of memory blocks of a specified type.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Memory' - - 'Memory Management' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`calloc()`** function is used to dynamically allocate an [array](https://www.codecademy.com/resources/docs/c/arrays) of memory blocks of a specified type. Each block has a default value of `0`. - -## Syntax - -```pseudo -calloc(numberofblocks, size); -``` - -Both `numberofblocks` and `size` are of type `size_t`. - -## Example - -The following example showcases the `calloc()` function: - -```c -int *ptr; - -// The pointer ptr holds the address of the first byte in the allocated memory -ptr = (int*) calloc(5, sizeof(int)); -``` - -The above statement allocates contiguous space in memory for 5 elements each with the size of the `int`. diff --git a/content/c/concepts/memory-management/terms/free/free.md b/content/c/concepts/memory-management/terms/free/free.md deleted file mode 100644 index e5ed598a0c0..00000000000 --- a/content/c/concepts/memory-management/terms/free/free.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -Title: 'free()' -Description: 'Dynamically de-allocates memory at runtime.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Memory' - - 'Memory Management' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`free()`** function is used to dynamically de-allocate the memory at runtime. Memory allocated by the `malloc()` and `calloc()` functions must be manually de-allocated when not in use. Freeing it helps to reduce memory wastage. - -## Syntax - -```pseudo -free(memoryblock); -``` - -The `memoryblock` must exist beforehand in order to be de-allocated by the `free()` function. - -## Example - -The following example showcases the `free()` function: - -```c -int *ptr; - -// Memory allocated using malloc() function -ptr = (int*) malloc(5 * sizeof(int)); - -// Memory de-allocated using free() function -free(ptr); -``` diff --git a/content/c/concepts/memory-management/terms/malloc/malloc.md b/content/c/concepts/memory-management/terms/malloc/malloc.md deleted file mode 100644 index 407d960b071..00000000000 --- a/content/c/concepts/memory-management/terms/malloc/malloc.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -Title: 'malloc()' -Description: 'Allocates a block of memory in the heap, but does not initialize.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Memory' - - 'Memory Management' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`malloc()`** function is used to allocate a block of memory in the heap. It allocates the user a specified number of bytes but does not initialize. Once allocated, the program accesses this block of memory via a [pointer](https://www.codecademy.com/resources/docs/c/pointers) that `malloc()` returns. - -## Syntax - -```pseudo -malloc(size); -``` - -The `size` parameter is of type `size_t`. - -The default pointer returned by `malloc()` is of the type `void` but can be cast into a pointer of any data type. However, if the space is insufficient for the amount of memory requested by `malloc()`, then the allocation fails and a `NULL` pointer is returned. - -## Example - -The following example showcases the `malloc()` function: - -```c -int *ptr; - -// The pointer ptr holds the address of the first byte in the allocated memory -ptr = (int*) malloc(5 * sizeof(int)); -``` - -Since the size of `int` is 4 bytes, the above statement will allocate 20 bytes (4 \* 5) of memory. diff --git a/content/c/concepts/memory-management/terms/realloc/realloc.md b/content/c/concepts/memory-management/terms/realloc/realloc.md deleted file mode 100644 index d8329ab387b..00000000000 --- a/content/c/concepts/memory-management/terms/realloc/realloc.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -Title: 'realloc()' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Description: 'Reallocates a block of memory that was previously allocated.' -Tags: - - 'Memory' - - 'Memory Management' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`realloc()`** function is used to reallocate a block of memory. If the memory that was previously allocated using the `malloc()` or `calloc()` function is not sufficient, it can be reallocated using the `realloc()` function. - -## Syntax - -```pseudo -realloc(memoryblock, size); -``` - -The `memoryblock` must exist beforehand. The `size` is of type `size_t`. - -## Example - -The following example showcases the `realloc()` function: - -```c -int *ptr; - -// Memory allocated using malloc() function -ptr = (int*) malloc(5 * sizeof(int)); - -// ptr is reallocated with 40 bytes (4 * 10) of memory -ptr = realloc(ptr, 10 * sizeof(int)); -``` diff --git a/content/c/concepts/operators/operators.md b/content/c/concepts/operators/operators.md deleted file mode 100644 index 8fabfd677a4..00000000000 --- a/content/c/concepts/operators/operators.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -Title: 'Operators' -Description: 'Operators are used to perform operations on variables and values.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Operators' - - 'Arithmetic' - - 'Comparison' - - 'Logical' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -**Operators** are used to perform operations on variables and values. They are symbols that tell the compiler to perform specific mathematical or logical functions. The C language provides the following types of operators: - -- Arithmetic Operators -- Relational Operators -- Logical Operators -- Bitwise Operators -- Assignment Operators -- Misc Operators - -## Arithmetic Operators - -C has the following basic arithmetic operators to perform common mathematical operations: - -| Operator | Name | Description | -| :------: | :------------: | ----------------------------------------------------------- | -| `+` | Addition | `x + y` returns the sum of `x` and `y` | -| `-` | Subtraction | `x - y` returns the difference of `x` and `y` | -| `*` | Multiplication | `x * y` returns the product of `x` and `y` | -| `/` | Division | `x / y` returns the quotient of `x` and `y` | -| `%` | Modulo | `x % y` returns the integer remainder of `x` divided by `y` | -| `++` | Increment | `x++` returns `x + 1` | -| `--` | Decrement | `x--` returns `x - 1` | - -```c -int x = 0; -x = x + 4; // x is now 4 -x = x - 1; // x is now 3 -x = x * 8; // x is now 24 -x = x / 4; // x is now 6 -x = x % 4; // x is now 2 -x++; // x is now 3 -x--; // x is now 2 -``` - -## Relational Operators - -Relational operators compare two values and return `true` or `false`. - -| Operator | Name | Description | -| :------: | :----------------------: | ---------------------------------------------------------- | -| `==` | Equal | `x == y` is `true` if `x` and `y` are equal. | -| `!=` | Not Equal | `x != y` is `true` if `x` and `y` are not equal. | -| `<` | Less Than | `x < y` is `true` if `x` is less than `y`. | -| `>` | Greater Than | `x > y` is `true` if `x` is greater than `y`. | -| `<=` | Less Than or Equal to | `x <= y` is `true` if `x` is less than or equal to `y`. | -| `>=` | Greater Than or Equal to | `x >= y` is `true` if `x` is greater than or equal to `y`. | - -```c -int x = 7; -int y = 5; - -if (x > y) { - // This code will run. -} - -if (x == y) { - // This code won't run. -} -``` - -## Logical Operators - -Logical operators operate on boolean values and return boolean values. - -| Operator | Name | Description | -| :------: | :--: | ------------------------------------------------------------------ | -| `!` | Not | `!x` is `true` when `x` is `false` and `false` when `x` is `true`. | -| `&&` | And | `x && y` is `true` only if `x` and `y` are both `true`. | -| `\|\|` | Or | `x \|\| y` is `true` if either `x` or `y` is `true`. | - -```c -int x = 7; -int y = 5; - -if (x > y \|\| x == y) { - // This code will run. -} - -if (x == y && x < 0) { - // This code won't run. -} -``` - -## Bitwise Operators - -Bitwise operators manipulate individual bits in an integer. - -| Operator | Name | Description | -| :------: | :---------: | -------------------------------------------------------------- | -| `&` | And | Result has bit set only where both operands have that bit set. | -| `\|` | Or | Result has bit set if either operand has that bit set. | -| `^` | Xor | Result has bit set only if only one operand has that bit set. | -| `~` | Not | Takes a single operand and inverts each bit in it. | -| `<<` | Left shift | `a << b` means `a`'s bits are shifted to the left `b` spaces. | -| `>>` | Right shift | `a >> b` means `a`'s bits are shifted to the right `b` spaces. | - -```c -int x; - -x = 19 & 7; -// x is 3 : 10011 & 00111 = 00011 - -x = 19 | 7; -// x is 23 : 10011 | 00111 = 10111 - -x = 19 ^ 7; -x is 20 : 10011 ^ 00111 = 10100 - -x = 7 << 2; -// x is 28 : 00111 << 2 = 11100 - -x = 19 >> 2; -// x is 4 : 10011 >> 2 = 00100 -``` - -## Assignment Operators - -Assignment operators assign the value on the right to the variable on the left. - -| Operator | Name | Description | -| :------: | :-----------------------: | ------------------------------------------ | -| `=` | Assignment | `a = 3` assigns value `3` to variable `a`. | -| `+=` | Addition Assignment | `a += 3` is short for `a = a + 3`. | -| `-=` | Subtraction Assignment | `a -= 3` is short for `a = a - 3`. | -| `*=` | Multiplication Assignment | `a *= 3` is short for `a = a * 3`. | -| `/=` | Division Assignment | `a /= 3` is short for `a = a / 3`. | -| `%=` | Modulo Assignment | `a %= 3` is short for `a = a % 3`. | -| `&=` | And Assignment | `a &= 3` is short for `a = a & 3`. | -| `\|=` | Or Assignment | `a \|= 3` is short for `a = a \| 3`. | -| `^=` | Xor Assignment | `a ^= 3` is short for `a = a ^ 3`. | -| `<<=` | Left Shift Assignment | `a <<= 3` is short for `a = a << 3`. | -| `>>=` | Right Shift Assignment | `a >>= 3` is short for `a = a >> 3`. | - -## Misc Operators - -Misc operators don't fit into a particular category. - -| Operator | Name | Description | -| :--------: | :------------------: | ------------------------------------------------------------------------------- | -| `sizeof()` | Addition Assignment | `sizeof(x)` returns the size of variable `x`. | -| `&` | Address | `&x` returns the address of variable `x`. | -| `*` | Pointer | `*x` returns a pointer to variable `x`. Not to be confused with multiplication. | -| `?:` | Conditional Operator | `expression?x:y` returns `x` when `expression` is `true`, `y` otherwise. | diff --git a/content/c/concepts/operators/terms/sizeof/sizeof.md b/content/c/concepts/operators/terms/sizeof/sizeof.md deleted file mode 100644 index e31152aad66..00000000000 --- a/content/c/concepts/operators/terms/sizeof/sizeof.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -Title: 'sizeof()' -Description: 'Determines the memory size (in bytes) of a given data type or variable and returns it as an integer.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Arithmetic' - - 'Operators' - - 'Data Types' - - 'Variables' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -In C, the **`sizeof()`** operator returns an integer representing the memory size of a [data type](https://www.codecademy.com/resources/docs/c/data-types) or [variable](https://www.codecademy.com/resources/docs/c/variables) in bytes. - -## Syntax - -```pseudo -sizeof(input) -``` - -- `input`: The data type or variable whose memory size is to be calculated. - -## Example - -The following example demonstrates the usage of the `sizeof()` operator: - -```c -#include - -int main() { - // Calculate the memory size of the 'int' data type - int res = sizeof(int); - - // Print the result - printf("Size of int: %d bytes\n", res); - - return 0; -} -``` - -The above code produces the following output: - -```shell -Size of int: 4 bytes -``` diff --git a/content/c/concepts/operators/terms/ternary-operator/ternary-operator.md b/content/c/concepts/operators/terms/ternary-operator/ternary-operator.md deleted file mode 100644 index 95cd284f2ad..00000000000 --- a/content/c/concepts/operators/terms/ternary-operator/ternary-operator.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -Title: 'Ternary operator' -Description: 'Provides a concise way to write conditional expressions in C.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Arithmetic' - - 'Comparison' - - 'Logical' - - 'Operators' - - 'Ternary' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **ternary operator** in C, also known as the conditional operator (**`?:`**), provides a shorthand way to perform conditional assignments or expressions. It is an alternative to [`if-else`](https://www.codecademy.com/resources/docs/c/control-statements) statements and is primarily used to simplify code by reducing the number of lines required for simple condition-based decisions. - -## Syntax - -```pseudo -condition ? expression_if_true : expression_if_false; -``` - -- `condition`: A boolean expression that evaluates to either true or false. -- `expression_if_true`: The value or operation executed if the condition is true. -- `expression_if_false`: The value or operation executed if the condition is false. - -## Example - -In this example, the ternary operator is used to determine the maximum of two numbers by evaluating whether `a` is greater than `b`: - -```c -#include - -int main() { - int a = 10, b = 20; - int max; - max = (a > b) ? a : b; - printf("The maximum value is: %d\n", max); - return 0; -} -``` - -The code above produces the following output: - -```shell -The maximum value is: 20 -``` diff --git a/content/c/concepts/operators/terms/unary-operators/unary-operators.md b/content/c/concepts/operators/terms/unary-operators/unary-operators.md deleted file mode 100644 index 810235ab2fd..00000000000 --- a/content/c/concepts/operators/terms/unary-operators/unary-operators.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -Title: 'Unary operators' -Description: 'Perform operations on a single operand.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Arithmetic' - - 'Comparison' - - 'Logical' - - 'Operators' - - 'Unary' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -**Unary operators** in C operate on a single operand to perform various operations such as incrementing, decrementing, negating, or manipulating bits. They are frequently used for modifying values, checking conditions, and optimizing calculations in expressions. - -## Syntax - -```pseudo -operator operand; -``` - -- `operator`: A unary operator that performs an operation on a single operand. -- `operand`: The variable or value on which the operator acts. - -> **Note:** In postfix notation, the operator is placed after the operand, and the original value is used before the operation takes effect. - -## Types of Unary operators - -### Increment (`++`) - -Increases the value of the operand by 1. Can be used in prefix (`++x`) or postfix (`x++`) notation. - -### Decrement (`--`) - -Decreases the value of the operand by 1. Can be used in prefix (`--x`) or postfix (`x--`) notation. - -### Unary Plus (`+`) - -Indicates a positive value. Rarely used explicitly, as numbers are positive by default. - -### Unary Minus (`-`) - -Negates the value of the operand. - -### Logical NOT (`!`) - -Reverses the truth value of the operand. If the operand is nonzero, it returns `0`; otherwise, it returns `1`. - -### Bitwise NOT (`~`) - -Inverts all bits of the operand. - -### Indirection (`*`) - -Accesses the value stored at a memory address (used with pointers). - -### Addressof (`&`) - -Retrieves the memory address of a variable. - -### Sizeof (`sizeof()`) - -Determines the size (in bytes) of a variable or data type. - -## Example - -In this example, various unary operators are demonstrated, such as negation, increment, decrement, bitwise operations, and the `sizeof` operator to show their effects on integer values: - -```c -#include - -int main() { - int number = 5; - int negation = -number; // Unary minus - int logicalNot = !number; // Logical NOT - int bitwiseNot = ~number; // Bitwise NOT - int preIncrement = ++number; // Pre-increment - int postDecrement = number--; // Post-decrement - int sizeInBytes = sizeof(number); // Sizeof operator - - printf("Unary minus: %d\n", negation); - printf("Logical NOT: %d\n", logicalNot); - printf("Bitwise NOT: %d\n", bitwiseNot); - printf("Pre-increment: %d\n", preIncrement); - printf("Post-decrement: %d\n", postDecrement); - printf("Sizeof operator: %d\n", sizeInBytes); - - return 0; -} -``` - -The code produces the output as: - -```shell -Unary minus: -5 -Logical NOT: 0 -Bitwise NOT: -6 -Pre-increment: 6 -Post-decrement: 6 -Sizeof operator: 4 -``` diff --git a/content/c/concepts/pointers/pointers.md b/content/c/concepts/pointers/pointers.md deleted file mode 100644 index 4a345ed4b2b..00000000000 --- a/content/c/concepts/pointers/pointers.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -Title: 'Pointers' -Description: 'A pointer is a variable that stores a memory address, which typically represents the location of another variable.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Pointers' - - 'Memory' - - 'Variables' - - 'Arrays' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -A **pointer** is a [variable](https://www.codecademy.com/resources/docs/c/variables) that stores a memory address, which typically represents the location of another variable. Pointers are useful because they allow the efficient creation and manipulation of complex data structures. - -## Understanding Pointers - -Data is stored in a computer's [memory](https://www.codecademy.com/resources/docs/general/computer-hardware/ram). A variable represents a specific location within that memory and consists of three parts: - -- An identifier (name) -- A value -- An address - -The address is a value that describes _where_ in memory a variable is located. - -To understand pointers, it may be helpful to think of variables as boxes on a shelf. Each box has a label (the identifier), a unique serial number that allows one to locate it (the address), and possibly something inside of it (the value). - -Following this analogy, a pointer can be described as a box that contains the serial number of another box within it. - -## Declaring and Assigning a Pointer - -A pointer is declared similarly to how a variable is — by specifying its type, identifier, and value. However, an asterisk character `*` is inserted in front of the identifier. - -```pseudo -type *name = value; -``` - -In order to obtain the address of a variable, the identifier is prefixed with an ampersand symbol `&`. This is known as the address operator. - -```c -int year = 1986; -int *pointer_to_year = &year; -``` - -The left-hand side of this declaration may be read in reverse order — "`pointer_to_year` is a pointer to an integer." - -If the value of `year` were to be printed, the output would read "1986". However, if the value of `pointer_to_year` were to be printed, the output would be an address such as `0x2aba1c0cf890`. - -The dereference operator (also known as the indirection operator), represented by an asterisk (`*`), allows one to access the value of the variable that a pointer points to. - -```c -int year = 1986; // Value of year: 1986 - -int *pointer_to_year = &year; // Value of pointer_to_year: 0x2aba1c0cf890 - -int another_year = *(pointer_to_year) - 33; // Value of another_year: 1953 - -*(pointer_to_year) = 2019; // This sets the value of year to 2019 -``` - -## Functions and Pointers - -Like other data types, pointers can be passed to and returned from [functions](https://www.codecademy.com/resources/docs/c/functions). One scenario in which this might be useful is "returning" two values from a function. - -```c -#include -#include - -int divide(int a, int b, bool *d) { - int c = a / b; - - if (c * b == a) { - *(d) = true; - } else { - *(d) = false; - } - return c; -} - -int numerator = 10; -int denominator = 5; -bool divisible; - -int main() { - int result = divide(numerator, denominator, &divisible); - - printf("%d", result); - - return 0; -} -``` - -In the example above, the `divide()` function returns the result of `a / b` and sets the variable that `d` points at to represent whether or not `a` is divisible by `b`. When this function is called on the last line, `result` is assigned a value of 2 and `divisible` becomes true. diff --git a/content/c/concepts/pointers/terms/double-pointer/double-pointer.md b/content/c/concepts/pointers/terms/double-pointer/double-pointer.md deleted file mode 100644 index 019dcd18374..00000000000 --- a/content/c/concepts/pointers/terms/double-pointer/double-pointer.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -Title: 'Double Pointer' -Description: 'Holds the memory address of a pointer.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Pointers' - - 'Memory' - - 'Variables' - - 'Arrays' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -In C, a **double pointer** is a [pointer](https://www.codecademy.com/resources/docs/c/concepts/pointers/terms/pointer/pointer) that holds the memory address of another pointer. It allows indirect access to the value of a variable. - -## Syntax - -A double pointer is declared using two asterisks (`**`) before the pointer variable name: - -```pseudo -type **name -``` - -- `type`: The type of data the double pointer will point to (e.g., `int`, `char`, etc.). -- `name`: The identifier for the double pointer. - -## Example - -The following example demonstrates how a double pointer is declared and used: - -```c -# include - -int main() { - int value = 35; - int *pointer = &value; // Pointer to an integer (stores the address of 'value') - int **doublePointer = &pointer; // Double pointer to an integer pointer (stores the address of 'pointer') - - // Printing the values - printf("Value of value: %d\n", value); // Direct access to value - printf("Value of *pointer: %d\n", *pointer); // Dereferencing pointer to access value - printf("Value of **doublePointer: %d\n", **doublePointer); // Dereferencing double pointer twice to access value - - // Printing the addresses - printf("Address of value: %p\n", (void*)&value); // Address of the variable 'value' - printf("Address of pointer: %p\n", (void*)&pointer); // Address of the pointer 'pointer' - printf("Address of doublePointer: %p\n", (void*)&doublePointer); // Address of the double pointer 'doublePointer' - - return 0; -} -``` - -The above code will give the following output: - -```shell -Value of value: 35 -Value of *pointer: 35 -Value of **doublePointer: 35 -Address of value: 0x7ffcbffdcc14 -Address of pointer: 0x7ffcbffdcc18 -Address of doublePointer: 0x7ffcbffdcc20 -``` - -In the example: - -- `value` is an integer variable. -- `pointer` is a pointer tha stores the address of `value`. -- `doublePointer` is a double pointer that stores the address of the pointer. diff --git a/content/c/concepts/pointers/terms/null-pointer/null-pointer.md b/content/c/concepts/pointers/terms/null-pointer/null-pointer.md deleted file mode 100644 index 19566f66238..00000000000 --- a/content/c/concepts/pointers/terms/null-pointer/null-pointer.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -Title: 'Null Pointer' -Description: 'A NULL pointer in C is a pointer that does not point to any valid memory location.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Pointers' - - 'Memory' - - 'Variables' - - 'Arrays' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -A **`NULL` pointer** in C is a pointer that doesn't point to any valid memory location. It acts as a special value to show that a pointer is either not initialized yet or is pointing to an invalid or unavailable memory address. - -## Syntax - -In C, the `NULL` pointer is defined in the `` header file. It is typically assigned to a pointer to indicate that it is not pointing to any valid memory. - -```pseudo -#include - -pointer_type *pointer_name = NULL; -``` - -- `pointer_type`: The data type of the pointer . -- `pointer_name`: The name of the pointer. - -## Example - -In the example, we declare an integer pointer `ptr` and initialize it to `NULL`, indicating that it doesn't point to any valid memory location: - -```c -#include -#include - -int main() { - int *ptr = NULL; // Initialize pointer to NULL - - if (ptr == NULL) { - printf("Pointer is NULL\n"); - } - - return 0; -} -``` - -The `if` statement checks if `ptr` is `NULL`, if true, it prints "Pointer is NULL" to the screen. This ensures the pointer is not used before properly initialising to a valid memory address. - -## Usage - -### 1. Initializing Pointers - -It is a common practice to initialize pointers to `NULL` to avoid them pointing to random or undefined memory locations. This helps prevent undefined behavior caused by dereferencing uninitialized or dangling pointers. - -```c -int *ptr = NULL; -``` - -### 2. Pointer Checking - -Before dereferencing a pointer, it is a good practice to check whether it is `NULL`. Dereferencing a `NULL` pointer will cause a **segmentation fault**, leading to runtime errors. - -```c -if (ptr != NULL) { - // Safe to dereference ptr - printf("%d", *ptr); -} else { - printf("Pointer is NULL\n"); -} -``` - -### 3. Return Value for Failure - -Functions that involve memory allocation or searching operations often return a `NULL` pointer to indicate failure. For example, when using [`.malloc()`](https://www.codecademy.com/resources/docs/c/memory-management/malloc) to allocate memory, if the allocation fails, it returns `NULL`. - -```c -int *ptr = malloc(sizeof(int)); -if (ptr == NULL) { - printf("Memory allocation failed!\n"); -} -``` - -### 4. NULL vs. 0 - -In C, `NULL` is often defined as `((void \*)0)`. While `NULL` and `0` can be used interchangeably in many contexts, using `NULL` improves code readability, making it clear that the value is a pointer rather than an integer. - -## Best Practices - -1. Always initialize pointers to `NULL` to avoid pointing to garbage memory. -2. Always check for `NULL` before dereferencing pointers. -3. Use `NULL` as a return value for functions that encounter errors or failure in memory allocation. -4. Avoid using pointer arithmetic on `NULL`. diff --git a/content/c/concepts/pointers/terms/pointer-arithmetics/pointer-arithmetics.md b/content/c/concepts/pointers/terms/pointer-arithmetics/pointer-arithmetics.md deleted file mode 100644 index 8c751fdad7b..00000000000 --- a/content/c/concepts/pointers/terms/pointer-arithmetics/pointer-arithmetics.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -Title: 'Pointer Arithmetics' -Description: 'Pointer arithmetic in C enables operations on pointers, such as incrementing, decrementing, or finding the difference between two pointers.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Pointers' - - 'Memory' - - 'Variables' - - 'Arrays' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -**Pointer arithmetic** in C allows for performing operations on pointers, such as incrementing, decrementing, or calculating the difference between two pointers. Since pointers store memory addresses, pointer arithmetic enables efficient traversal through arrays and manipulation of memory locations. - -## Syntax - -In C, a pointer can be modified using arithmetic operations. The type of data the pointer points to determines how much the pointer moves in memory with each operation. For example, adding 1 to a pointer doesn't simply add 1 to its value but rather advances it by the size of the data type it points to. - -### 1. Incrementing a Pointer - -```pseudo -pointer_name++; -``` - -This moves the pointer to the next element in the array it points to. - -### 2. Decrementing a Pointer - -```pseudo -pointer_name--; -``` - -This moves the pointer to the previous element. - -### 3. Adding an Integer to a Pointer - -```pseudo -pointer_name += n; -``` - -This moves the pointer `n` elements ahead, where `n` is an integer. - -### 4. Subtracting an Integer from a Pointer - -```pseudo -pointer_name -= n; -``` - -This moves the pointer `n` elements back. - -### 5. Subtracting Two Pointers - -```pseudo -ptr1 - ptr2; -``` - -This gives the number of elements between the two pointers, assuming both point to elements of the same array. - -## Example - -```c -#include - -int main() { - int arr[] = {10, 20, 30, 40, 50}; - int *ptr = arr; - - // Accessing elements using pointer arithmetic - printf("First element: %d\n", *ptr); // Access arr[0] - ptr++; // Increment pointer - printf("Second element: %d\n", *ptr); // Access arr[1] - - ptr += 2; // Move pointer 2 elements ahead - printf("Fourth element: %d\n", *ptr); // Access arr[3] - - ptr--; // Move pointer 1 element back - printf("Third element: %d\n", *ptr); // Access arr[2] - - // Subtracting pointers - int *ptr2 = &arr[4]; - printf("Difference between pointers: %ld\n", ptr2 - ptr); // Output: 4 - - return 0; -} -``` - -The output of above code will the following output: - -```shell -First element: 10 -Second element: 20 -Fourth element: 40 -Third element: 30 -Difference between pointers: 4 -``` - -## Important Considerations - -- **Pointer Out-of-Bounds**: Pointer arithmetic should never be used to go out of bounds of an array or memory block. This results in undefined behavior. -- **Pointer Type Matters**: When performing pointer arithmetic, the data type of the pointer determines the increment/decrement amount. For instance, if the pointer is of type `double*`, each pointer increment will add the size of `double` (typically 8 bytes) to the pointer. -- **Array and Pointer Relationship**: In C, an array name is essentially a pointer to the first element of the array. Pointer arithmetic works seamlessly with arrays, allowing traversal and access to elements. - -## Best Practices - -- Use pointer arithmetic for efficient memory traversal, especially in large arrays or buffers. -- Avoid out-of-bounds access by carefully ensuring that pointer arithmetic does not go past the limits of arrays. -- Use pointer arithmetic when working with low-level memory manipulation, but ensure the code is clear and maintainable by adding comments or using named constants when possible. diff --git a/content/c/concepts/preprocessors/preprocessors.md b/content/c/concepts/preprocessors/preprocessors.md deleted file mode 100644 index 51f7c4caeee..00000000000 --- a/content/c/concepts/preprocessors/preprocessors.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -Title: 'Preprocessors' -Description: 'A preprocessor scans the C program source code before it is compiled, allowing the source code to expand macros, include other files, and conditionally compile blocks of source code.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Command Line' - - 'Developer Tools' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -Preprocessors in C scan the source code before it is [compiled](https://www.codecademy.com/resources/docs/c/compiling) and transform it with tools like macros. - -Preprocessor commands and macros are included in the source code file and are interpreted before the source code is passed to the compiler. - -The preprocessor can modify the final code that is compiled or provide messages to the developer during preprocessing. - -## Common Uses of Preprocessor Commands - -### Including Additional Files - -One of the most common preprocessor commands is `#include` which is used to include the text contents of some other file into the one being compiled. - -```c -#include -``` - -The preprocessor will replace `#include ` with the text contents of the file **stdio.h**. - -### Conditional Compilation - -The preprocessor includes several statements used for conditional compilation: - -- `#if` -- `#elif` -- `#else` -- `#endif` -- `#ifdef`: shorthand for `#if defined(...)` -- `#ifndef`: shorthand for `#if !defined(...)` - -```c -#if HELLO > 0 - printf("Hello world!"); -#endif -``` - -If the macro `HELLO` is greater than zero, then the `printf("Hello world!")` command will be compiled. If not, then the command will be omitted from the final code being compiled. - -```c -#ifdef _WIN32 - // Compile for 32-bit Windows system -#elif defined(_WIN64) - // Compile for a 64-bit Windows system -#else - // Compile for something else -#endif -``` - -The example above will compile different code for different operating systems based on if the macros `_WIN32` or `_WIN64` exist. - -### Defining Macros - -When the preprocessor encounters a [macro](https://www.codecademy.com/resources/docs/c/macros) in the source code, it will replace the macro with the value it has been assigned. Macros are defined by using `#define` and can be undefined using `#undef`. - -```c -#define PI 3.1416 -``` - -After this line, every time the preprocessor encounters the macro `PI`, it will replace it with 3.1416 in the source code. - -```c -#undef PI -``` - -After this line, trying to use the macro PI will result in a compilation error. diff --git a/content/c/concepts/scope/scope.md b/content/c/concepts/scope/scope.md deleted file mode 100644 index 2086fb74aae..00000000000 --- a/content/c/concepts/scope/scope.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -Title: 'Scope' -Description: 'Scope defines the region in a program where a variable can be accessed.' -Subjects: - - 'Computer Science' - - 'Developer Tools' - - 'Web Development' -Tags: - - 'Control Flow' - - 'Memory' - - 'Programming' - - 'Variables' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -In C, [**scope**](https://www.codecademy.com/resources/docs/general/scope) defines the region of a program where a [variable](https://www.codecademy.com/resources/docs/c/variables) can be accessed. Variables in C are categorized into local and global scopes based on their accessibility. - -## Local Scope - -Variables declared inside a [function](https://www.codecademy.com/resources/docs/c/functions) or block have local scope, meaning they are accessible only within that function or block. - -## Syntax for local scope - -```pseudo -return_type function_name() { - // Variable with local scope - data_type variable_name = value; - - // Code that uses the variable - ... -} -``` - -- `data_type`: Represents the type of the variable. -- `variable_name`: Name of the variable used in the code. -- `value`: Value assigned to the variable. - -## Global Scope - -Variables declared outside of any function have global scope and can be accessed and modified from any function within the program. - -## Syntax for global scope - -```pseudo - -data_type variable_name = value; -// Global variable (declared outside any function) -return_type function_name() { - // Code that can access the global variable -} -``` - -## Example - -The example demonstrates variable scope in C, where `globalVar` has global scope (accessible throughout the program), while `localVar` has local scope (accessible only within `myFunction`): - -```c -#include -// Global variable -int globalVar = 100; -void myFunction() { - // Local variable - int localVar = 10; - - // Accessing both local and global variables - printf("Local variable inside myFunction: %d\n", localVar); - printf("Global variable inside myFunction: %d\n", globalVar); -} -int main() { - // Accessing the global variable - printf("Global variable inside main: %d\n", globalVar); - - // Calling the function which accesses both local and global variables - myFunction(); - - return 0; -} -``` - -The code above produces this output: - -```shell -Global variable inside main: 100 -Local variable inside myFunction: 10 -Global variable inside myFunction: 100 -``` diff --git a/content/c/concepts/static-variables/static-variables.md b/content/c/concepts/static-variables/static-variables.md deleted file mode 100644 index c1ed6929719..00000000000 --- a/content/c/concepts/static-variables/static-variables.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -Title: 'Static Variables' -Description: 'Static variables retain their value across function calls and exist for the lifetime of the program, providing persistent storage.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Booleans' - - 'Variable Types' - - 'Variables' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -In C, a **static variable** is a special type of variable that retains its value across function calls. Unlike local variables, which are recreated every time a function is called, static variables are initialized only once and maintain their value for the lifetime of the program. Static variables can be declared inside functions, blocks, or globally, but their behavior differs based on their scope. - -Static variables are often used to store data that needs to persist, like counters or state information. - -## Syntax - -```pseudo -static data_type variable_name = value; -``` - -- `static`: A keyword that declares the variable as static, ensuring it retains its value across function calls and persists for the program's lifetime. -- `data_type`: Specifies the type of the variable (e.g., `int`, `float`, `char`). -- `variable_name`: The name of the variable, used to access it. -- `value` (Optional): The initial value assigned to the variable. If not provided, static variables are automatically initialized to zero. - -## Example - -Here’s an example demonstrating the use of static variables: - -```c -#include - -void counter() { - static int count = 0; // Static variable retains its value - count++; - printf("Count: %d\n", count); -} - -int main() { - counter(); // Output: Count: 1 - counter(); // Output: Count: 2 - counter(); // Output: Count: 3 - return 0; -} -``` - -The output of the above code will be: - -```shell -Count: 1 -Count: 2 -Count: 3 -``` - -The code demonstrates the use of a static variable `count` inside the `counter` function, which retains its value across multiple function calls. Each time `counter()` is called, `count` increments and prints its updated value, showcasing the persistence of static variables. diff --git a/content/c/concepts/storage-classes/storage-classes.md b/content/c/concepts/storage-classes/storage-classes.md deleted file mode 100644 index 60535216706..00000000000 --- a/content/c/concepts/storage-classes/storage-classes.md +++ /dev/null @@ -1,149 +0,0 @@ ---- -Title: 'Storage Classes' -Description: 'Define the lifetime, visibility, and scope of variables.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Classes' - - 'Storage' - - 'Scope' - - 'Objects' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -In C, **storage classes** determine where and for how long a variable is stored in memory, as well as its default value and scope. C provides four storage classes: - -1. `auto` -2. `register` -3. `static` -4. `extern` - -Each storage class has a specific role in how variables behave in a program. - -## 1. `auto` Storage Class - -The `auto` storage class acts as the default class for local variables. Variables declared with `auto` are automatically created when the block of code (such as a function) is entered, and they are destroyed when the block is exited. These variables have automatic storage duration. - -Here is how a variable can be declared using the `auto` storage class: - -```pseudo -auto type variable_name; -``` - -Let's look at an example that demonstrates the behavior of the `auto` storage class: - -```c -#include - -int main() { - auto int num = 5; // 'auto' is optional here as it's the default for local variables - printf("%d\n", num); // Output: 5 - return 0; -} -``` - -In this case, the `num` variable is created and destroyed within the `main` function. - -## 2. `register` Storage Class - -The `register` storage class suggests the compiler that a variable can be stored in a CPU register instead of RAM. This can improve the speed of access, but it is just a suggestion and not a guarantee. The `register` keyword can only be used for local variables. - -Here is how a variable can be declared using the `register` storage class: - -```pseudo -register type variable_name; -``` - -Below is an example demonstrating the `register` storage class: - -```c -#include - -int main() { - register int count; - for (count = 0; count < 5; count++) { - printf("%d ", count); - } - return 0; -} -``` - -In this example, the `count` variable is suggested to be stored in a register for faster access during the loop. - -## 3. `static` Storage Class - -The `static` storage class is used to maintain the value of a variable across function calls. A static variable retains its value even after the function in which it is declared finishes executing. Additionally, static variables are initialized only once, and their lifetime is the entire program runtime. - -Here is how a variable can be declared using the `static` storage class: - -```pseudo -static type variable_name; -``` - -Let's see an example where a `static` variable retains its value across multiple function calls: - -```c -#include - -void counter() { - static int count = 0; // This variable retains its value across function calls - count++; - printf("Count: %d\n", count); -} - -int main() { - counter(); // Output: Count: 1 - counter(); // Output: Count: 2 - counter(); // Output: Count: 3 - return 0; -} -``` - -In this example, the `count` variable retains its value across multiple calls to the `counter` function, and its value continues from where it was left off in the previous call. - -## 4. `extern` Storage Class - -The `extern` storage class helps declare a variable that is defined in another file or elsewhere in the program. It tells the compiler that the variable exists, but its definition will be provided later. It is used for sharing variables between files. - -Here is how a variable can be declared using the `extern` storage class: - -```pseudo -extern type variable_name; -``` - -Below is an example demonstrating how the `extern` storage class is used across files: - -```c -// file1.c -#include - -int count = 10; // Definition of count - -void display() { - printf("Count: %d\n", count); -} - -// file2.c -extern int count; // Declaration of count from file1.c - -int main() { - display(); // Output: Count: 10 - return 0; -} -``` - -In this example, the `extern` keyword in `file2.c` allows access to the `count` variable defined in `file1.c`. - -Each of these storage classes provides different advantages, depending on how and where the variable is used in the program. - -The table below provides a concise comparison of the four storage classes in C, outlining their lifetime, scope, initialization behavior, and typical use case: - -| Storage Class | Lifetime | Scope | Initialization | Use Case | -| ------------- | ---------------------- | ------------------------------ | ---------------------------- | -------------------------------------------- | -| `auto` | Local function/block | Local function/block | Automatic | Default for local variables | -| `register` | Local function/block | Local function/block | Automatic | Suggests variable to be stored in a register | -| `static` | Entire program runtime | Local function/block or global | Zero (if not initialized) | Retains value between function calls | -| `extern` | Entire program runtime | Global | External (defined elsewhere) | Access variables from other files | diff --git a/content/c/concepts/strings/strings.md b/content/c/concepts/strings/strings.md deleted file mode 100644 index 501aa4c4b39..00000000000 --- a/content/c/concepts/strings/strings.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -Title: 'Strings' -Description: 'Strings are character sequences that are either expressed in double quotes or as arrays that end with a null character \0.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Data Types' - - 'Characters' - - 'Arrays' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -**Strings** are character sequences that are either expressed in double quotes or as [arrays](https://www.codecademy.com/resources/docs/c/arrays) that end with a `null` character `'\0'`. - -## Syntax - -```pseudo -char string-name[]; -char string_name[] = "abcd"; -char string_name[size] = {'a', 'b', 'c', 'd', '\0'}; -``` - -Strings in C are first declared with the `char` data type, followed by the `string_name`, and then immediately followed by square brackets `[]`. The snippet above showcases the two ways that string values are initialized: - -- Zero or more characters, digits, and escape sequences surrounded in double quotes. -- An array of comma-separated characters, surrounded in curly brackets `{ }`, and ending with a `null` character `'\0'`\*. - -\* This is required when an optional `size` is passed to square brackets to specify the number of characters in the string. - -## Example - -The following declaration and initialization create a string of `"Howdy"`: - -```c -char message[6] = {'H', 'o', 'w', 'd', 'y', '\0'}; -``` - -Even though `"Howdy"` has only 5 characters, `message` has 6 characters due to the `null` character at the end of the `message` array. - -The above statement can be rewritten as: - -```c -char message[] = "Howdy"; -``` - -### Memory - -Here's the memory presentation: - -```pseudo -Character | 'H' 'o' 'w' 'd' 'y' '\0' -Index | 0 1 2 3 4 5 -Address | 23451 23452 23453 23454 23455 23456 -``` - -## Displaying a String - -To display a string in C, the [`printf()`](https://www.codecademy.com/resources/docs/c/basic-output) function from the **stdio.h** header file can be used along with the `%s` character to format strings, followed by the string name. - -### Display Example - -The following is an example of displaying a string in C: - -```c -#include - -int main() { - char message[] = "Hi y'all!"; - printf("Bot: %s\n", message); - - return 0; -} - -``` - -The output would be: - -```shell -Bot: Hi y'all! -``` - -## String Functions - -The **string.h** header defines a handful of string functions for manipulating arrays of characters. diff --git a/content/c/concepts/strings/terms/strchr/strchr.md b/content/c/concepts/strings/terms/strchr/strchr.md deleted file mode 100644 index fe5ba4e4a66..00000000000 --- a/content/c/concepts/strings/terms/strchr/strchr.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -Title: 'strchr()' -Description: 'Finds the first occurrence of a given character.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Data Types' - - 'Characters' - - 'Arrays' - - 'Functions' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The `strchr()` string function finds the first occurrence of a given character. - -## Syntax - -The **string.h** header file needs to be included at the top of the file: - -```c -#include -``` - -`strchr()` function searches `string` for the character `'c'`: - -```c -strchr(string, 'c') -``` - -## Example - -Using `strchr()` function to find a specific character in the alphabet: - -```c -#include -#include - -int main() { - char alphabet[] = "abcdefghijklmnopqrstuvwxyz"; - printf("%s", strchr(alphabet, 's')); - return 0; -} -``` - -The output would be: - -```shell -stuvwxyz -``` diff --git a/content/c/concepts/strings/terms/strcmp/strcmp.md b/content/c/concepts/strings/terms/strcmp/strcmp.md deleted file mode 100644 index 87bd14a6de2..00000000000 --- a/content/c/concepts/strings/terms/strcmp/strcmp.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -Title: 'strcmp()' -Description: 'Compares two strings and returns an integer value.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Data Types' - - 'Characters' - - 'Arrays' - - 'Functions' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`strcmp()`** function compares two strings and returns an integer value. - -## Syntax - -```pseudo -#include - -strcmp(string1, string2); -``` - -At the top of the file, the `` header file needs to be included. The `strcmp()` function compares strings `string1` and `string2` and returns an integer value. - -- If the two strings are the same, return 0. -- If `string1` > `string2`, return positive value. -- If `string1` < `string2` or `string1` is a substring of `string2`, return negative value. - -## Example - -```c -#include -#include - -int main() { - char address1[20] = "575 Broadway"; - char address2[20] = "576 Broadway"; - - if (strcmp(address1, address2) == 0) { - printf("Address 1 and address 2 are equal."); - } - else { - printf("Address 1 and address 2 are different."); - } - return 0; -} -``` diff --git a/content/c/concepts/strings/terms/strcpy/strcpy.md b/content/c/concepts/strings/terms/strcpy/strcpy.md deleted file mode 100644 index 416636bdefb..00000000000 --- a/content/c/concepts/strings/terms/strcpy/strcpy.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -Title: 'strcpy()' -Description: 'Copies one string into another string, and returns the newly copied string' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Data Types' - - 'Characters' - - 'Arrays' - - 'Functions' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`strcpy()`** function copies one string into another string, and returns the newly copied string. - -## Syntax - -```pseudo -#include - -strcpy(string1, string2); -``` - -At the top of the file, the `` header file needs to be included. The `strcpy()` copies `string2` parameter into `string1`, including the terminating `null` character (`'\0'`). - -## Example - -Suppose we have two strings, `pokemon1` and `pokemon2`: - -```c -#include -#include - -int main() { - char pokemon1[30] = "Ditto"; - char pokemon2[30] = "Pikachu"; - - // This function has copied pokemon2 into pokemon1 - strcpy(pokemon1, pokemon2); - - printf("pokemon1 is now: %s", pokemon1); - return 0; -} -``` - -The output would be: - -``` -Pikachu -``` diff --git a/content/c/concepts/strings/terms/strlen/strlen.md b/content/c/concepts/strings/terms/strlen/strlen.md deleted file mode 100644 index c47136d42d3..00000000000 --- a/content/c/concepts/strings/terms/strlen/strlen.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -Title: 'strlen()' -Description: 'Returns the length of the string without including the terminating character.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Data Types' - - 'Characters' - - 'Functions' - - 'Methods' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`strlen()`** string function returns the length of the string without including the terminating character, `'\n'`. - -## Syntax - -```pseudo -strlen(string) -``` - -It takes in the `string` and returns an unsigned short. - -## Example - -```c -#include -#include - -int main() { - char spell[20] = "Abracadabra"; - printf("Length: %i", strlen(spell)); - return 0; -} -``` - -The output would be: - -```shell -Length: 11 -``` - -Notice how it didn't count the terminating character. diff --git a/content/c/concepts/strings/terms/strtok/strtok.md b/content/c/concepts/strings/terms/strtok/strtok.md deleted file mode 100644 index 8da7cef700d..00000000000 --- a/content/c/concepts/strings/terms/strtok/strtok.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -Title: 'strtok()' -Description: 'Breaks a string into a series of tokens using a list of delimiters.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Data Types' - - 'Characters' - - 'Arrays' - - 'Functions' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The **`strtok()`** function breaks a string into a series of tokens using a list of delimiters. - -## Syntax - -```pseudo -char *token = strtok(string, delimiters); - -token = strtok(NULL, delimiters); -``` - -The `strtok()` function splits the `string` parameter into tokens based on one or more `delimiters`, and returns the [pointer](https://www.codecademy.com/resources/docs/c/pointers) to the first token. - -Subsequent calls to `strtok()`, with `string` set to `NULL`, return a pointer to the next tokenized string. When there are no tokens left to retrieve, a `NULL` pointer is returned. - -## Example - -The following example splits up a comma-delimited list and prints out the result: - -```c -#include -#include - -int main () { - char str[] = "Comma,Delimited,List"; - const char s[] = ","; - char *token = strtok(str, s); - - while( token != NULL ) { - printf( "%s\n", token ); - token = strtok(NULL, s); - } -} -``` - -This results in the following output: - -```shell -Comma -Delimited -List -``` diff --git a/content/c/concepts/structures/structures.md b/content/c/concepts/structures/structures.md deleted file mode 100644 index a3917a6d0e6..00000000000 --- a/content/c/concepts/structures/structures.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -Title: 'Structures' -Description: 'A structure is used to group different types of data together.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Arrays' - - 'Lists' - - 'Structure' - - 'Variable Types' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -A **structure** is used to group different types of data together. It is defined using the `struct` keyword. - -## Syntax - -```pseudo -struct Name{ - type1 memberName1; - type2 memberName2; - type3 memberName3; - ... - typeN memberNameN; -}; -``` - -A structure is made up of members where each `memberName` has to be declared with a `type`. - -## Example - -The following example uses the `struct` keyword to create a `Patient` structure: - -```c -struct Patient{ - char name[30]; - int age; - int weight; - int heightInInches; -}; -``` - -`name`, `age`, `weight`, and `heightInInches` are members of the `Patient` structure. - -## Structure Variables - -[Variables](https://www.codecademy.com/resources/docs/c/variables) can be created in order to work with the `Patient` structure above. The following example declares and initializes a structure variable: - -```c -#include -#include - -struct Patient { - char name[30]; - int age; - int weight; - int heightInInches; -}; - -int main() { - // Variable initialization at declaration - struct Patient patientA = {"Douglas Franklin", 62, 280, 74}; - return 0; -} -``` - -## Accessing Members - -Members can be accessed using the member operator `.`: - -```c -#include -#include - -struct Patient { - char name[30]; - int age; - int weight; - int heightInInches; -}; - -int main() { - // Variable initialization at declaration - struct Patient patientA = {"Douglas Franklin", 62, 280, 74}; - - // Accessing members - printf("Name: %s \nAge: %d \nWeight: %d \nHeight: %d\n", - patientA.name, patientA.age, patientA.weight, patientA.heightInInches); - - return 0; -} -``` - -This will output the following: - -```shell -Name: Douglas Franklin -Age: 62 -Weight: 280 -Height: 74 -``` - -## Nested Structures - -A structure can be within another structure. Nested structure members can be accessed using the member operator `.`. The example below shows a `Hospital` structure member variable being declared within the `Patient` structure: - -```c -#include -#include - -struct Hospital { - char department[30]; - int roomNum; -}; - -struct Patient { - char name[30]; - int age; - int weight; - int heightInInches; - struct Hospital roomDetails; -}; - -int main() { - // Variable initialization at declaration - struct Patient patientA = {"Douglas Franklin", 62, 280, 74, "oncology", 526}; - - // Accessing nested structure members - printf("Department: %s \nRoom: %d \n", patientA.roomDetails.department, patientA.roomDetails.roomNum); - - return 0; -} -``` - -The output is as follows: - -```shell -Department: oncology -Room: 526 -``` diff --git a/content/c/concepts/switch/switch.md b/content/c/concepts/switch/switch.md deleted file mode 100644 index c1197dbecfb..00000000000 --- a/content/c/concepts/switch/switch.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -Title: 'Switch' # Required; the file name should be the same as the title, but lowercase, with dashes instead of spaces, and all punctuation removed -Description: 'Evaluates several case conditions, and executes a code block if the case value is a match.' # Required; ideally under 150 characters and starts with a present-tense verb (used in search engine results and content previews) -Subjects: # Please only use Subjects in the subjects.md file (https://github.com/Codecademy/docs/blob/main/documentation/subjects.md). If that list feels insufficient, feel free to create a new Subject and add it to subjects.md in your PR! - - 'Code Foundations' - - 'Computer Science' -Tags: # Please only use Tags in the tags.md file (https://github.com/Codecademy/docs/blob/main/documentation/tags.md). If that list feels insufficient, feel free to create a new Tag and add it to tags.md in your PR! - - 'Control Flow' - - 'If' - - 'Else' -CatalogContent: # Please use course/path landing page slugs, rather than linking to individual content items. If listing multiple items, please put the most relevant one first - - 'learn-c' - - 'paths/computer-science' ---- - -In C, the **`switch case`** statement provides a structure for supporting several options or conditions to execute a block of code, similar to the `if..else-if..else` statement. A main difference here, though, is that this statement is much easier to read and write. - -However, it can only evaluate one expression or variable at a time. - -## Syntax - -``` -switch(expression) { - case value1: - // Enter code here - break; - case value2: - // Enter code here - break; - case value_n: - // Enter code here - break; - default: - // Enter code here -} -``` - -Here's how the switch (aka switch-case) statement works: - -1. The switch `expression` is evaluated only once. -2. The value of the expression will be compared with the values of each `case`, and if there is a match the corresponding block of code is executed. If there is no code block provided in the `case`, the control moves on to the next `case` until it finds one with a code block, and executes the code block there. -3. The `break` keyword breaks out of the switch block, and does not evaluate any additional statements in the switch. (Without the `break`, execution would continue with the next `case` statement.) The program now exits the switch. -4. The code inside the `default` case is executed if none of the above cases are matched with the resulting value of the expression. This case is optional, and acts just like the `else` in an `if..else-if..else` statement. It serves as a "catch-all" case. - -The expression or variable's resulting value must be of an integral or enumerated type. Examples of valid result types for switch-case expressions are `int`, `double`, `float`, and `char`. (Remember that characters, which have type `char`, are integral, because they have integer ASCII codes.) This statement will not be valid for expressions or variables that, for example, result in a string value. - -## Example 1: Evaluating a variable - -The following prints out some statements to a student based on a grade they got on a test or quiz. - -```c -#include - -int main(){ - char grade = 'B'; - switch(grade){ - case 'A': - printf("Excellent!\n"); - break; - case 'B': - case 'C': - printf("Good job!\n"); - break; - case 'D': - printf("Okay, you passed.\n"); - break; - case 'F': - printf("Better try again...\n"); - break; - default: - printf("Invalid grade!!!\n"); - } - - printf("Your grade is %c\n", grade); - - return 0; -} -``` - -This example will output: - -```shell -Good job! -Your grade is B -``` - -## Example 2: Evaluating an expression - -The following determines if the addition of two numbers results in either a total of 5 or 4. - -```c -#include - -int main(){ - int num1 = 1; - int num2 = 3; - - switch(num1 + num2){ - case 5: - printf("The addition of %d and %d results in 5\n", num1, num2); - break; - case 4: - printf("The addition of %d and %d results in 4\n", num1, num2); - break; - default: - printf("The addition of %d and %d does not result in either 4 or 5\n", num1, num2); - } - return 0; -} -``` - -This example will output: - -```shell -The addition of 1 and 3 results in 4 -``` - -Just as aforementioned, a switch-case statement can be used to evaluate the value of not just a variable, but also an expression, as long as the expression results in one value that is either a number or something containing a numerical value. diff --git a/content/c/concepts/union/union.md b/content/c/concepts/union/union.md deleted file mode 100644 index 2dfe74b8132..00000000000 --- a/content/c/concepts/union/union.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -Title: 'Union' -Description: 'A user-defined data type that allows storing different data types in the same memory location.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Input' - - 'Print' - - 'Variables' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -A **union** in C is a user-defined data type that allows storing different data types in the same memory location. - -Unlike [structures](https://www.codecademy.com/resources/docs/c/structures), which allocate separate memory for each member, a union uses the same memory block for all its members. This means that at any given time, only one member of a union can hold a value, making unions memory-efficient but requiring careful handling. - -## Syntax - -```pseudo -union union_name { - data_type member1; - data_type member2; - ... - data_type memberN; -}; -``` - -**Parameters:** - -Unions do not take parameters directly, but their members can be of different data types: - -- `union_name`: The name given to the union. -- `data_type`: It can be any valid C data type (`int`, `float`, `char`, etc.). -- `member`: The names given to the union members. - -**Return Value:** - -A union does not hold a value itself, but its members can hold values. The memory is shared among all members, so assigning a value to one member overwrites the value of the others. - -## Memory Allocation - -In C unions, memory is allocated based on the largest member. For example, if a union contains an integer (4 bytes) and a character (1 byte), the union will occupy 4 bytes. This is because all members share the same memory space – when one member is modified, it affects the memory of other members. - -## Accessing Members - -Union members are accessed using the dot (`.`) operator for regular union variables or the arrow (`->`) operator for pointers to unions. However, it is important to remember that only the last member assigned a value should be accessed. Accessing an uninitialized or overwritten member leads to undefined behavior due to shared memory. - -```c -union Data { - int number; - char letter; -} data; - -data.number = 65; -printf("%d\n", data.number); // Prints 65 -printf("%c\n", data.letter); // Prints 'A' (ASCII 65) -``` - -Here, `data.number = 65` stores the integer 65 in the shared memory. Since `data.letter` uses the same memory, interpreting the value as a character (`char`) results in `'A'`, which is the ASCII representation of 65. - -## Example - Memory Optimization in Unions - -The following code demonstrates the use of a union in C, where different data types (integer, float, and string) share the same memory location: - -```c -#include -#include - -union Data { - int i; - float f; - char str[20]; -}; - -int main() { - union Data data; - - data.i = 10; - printf("Integer: %d\n", data.i); - - data.f = 3.14; - printf("Float: %.2f\n", data.f); - - strcpy(data.str, "Hello"); - printf("String: %s\n", data.str); - - printf("Memory size: %lu\n", sizeof(data)); - return 0; -} -``` - -The output of the above code will be: - -```shell -Integer: 10 -Float: 3.14 -String: Hello -Memory size: 20 -``` - -## Difference Between Structure and Union - -Structures and unions are both user-defined data types in C, but they serve different purposes. The following table highlights the key differences between structures and unions, making it easier to choose the appropriate data type based on memory usage and accessibility requirements. - -| Feature | Structure | Union | -| --------------------- | ----------------------------------------------- | --------------------------------------------- | -| **Memory Allocation** | Allocates memory for all members | Shares memory among members | -| **Accessibility** | All members can hold values simultaneously | Only one member holds a value at a time | -| **Use Case** | Suitable when all data fields need to be stored | Suitable for memory-efficient operations | -| **Data Integrity** | Stores all data without overwriting | Only the last assigned value is retained | -| **Memory Usage** | Uses more memory as all members exist | Uses less memory as only one member is active | diff --git a/content/c/concepts/user-input/user-input.md b/content/c/concepts/user-input/user-input.md deleted file mode 100644 index 659f087c865..00000000000 --- a/content/c/concepts/user-input/user-input.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -Title: 'User Input' -Description: 'In the C language, the scanf function stands for scan format and handles user input. It reads a formatted string from the standard input stream, which is usually the user keyboard.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Input' - - 'Print' - - 'Variables' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -The `scanf()` function, which stands for “scan format", reads a formatted string from the standard input stream, which is usually the user keyboard. - -## Syntax - -```pseudo -scanf("formatted string", &variable); -``` - -Here, the user can enter a value in the terminal, press Enter, and that number will get stored in the `pinNumber` variable. - -```c -scanf("%d", &pinNumber); -``` - -**Note:** There's an ampersand `&` before the variable names in the arguments. The program will crash if there's a missing `&` sign. - -## Example - -In this example, the program will prompt the user to enter a number with `"Add tip amount: "`. Then the user can enter a number in the terminal, press Enter, and the number will get stored in the variable `tip`. - -```c -#include - -int main() { - float tip = 0.0; - - printf("Add tip amount: "); - scanf("%f", &tip); - - printf("You gave a tip of $%.2f", tip); - - return 0; -} -``` diff --git a/content/c/concepts/variables/variables.md b/content/c/concepts/variables/variables.md deleted file mode 100644 index e16b04157f7..00000000000 --- a/content/c/concepts/variables/variables.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -Title: 'Variables' -Description: 'A variable is a location in computer memory used to store data.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Variables' - - 'Data Types' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -A **variable** is a location in computer memory used to store data, usually for use in a program. - -## Syntax - -```pseudo -type name = value; -``` - -When declaring a variable in C, the `type` of variable goes first, followed by the name, and then the value. - -But if a variable does not yet need a value assigned to it, this can be omitted and assigned later. - -```pseudo -type name; -name = value; -``` - -Variables in C are static and can only have one type (e.g., an `int` variable can only hold an integer value). - -## Example - -To display a variable in C, the `printf()` function from the **stdio.h** header file can be used along with the `%` character to format values, followed by the variable name: - -```c -#include - -int main(void) { - int number = 5; - char letter = 'a'; - - printf("%d\n", number); - printf("%c\n", letter); - - return 0; -} -``` - -The output would be: - -```shell -5 -a -``` diff --git a/content/cloud-computing/cloud-computing.md b/content/cloud-computing/cloud-computing.md deleted file mode 100644 index c65c7745dff..00000000000 --- a/content/cloud-computing/cloud-computing.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -Title: 'Cloud Computing' -Description: 'Cloud computing refers to an architecture where computing resources and hardware are maintained and managed remotely by an entity other than the user.' -Codecademy Hub Page: 'https://www.codecademy.com/catalog/subject/cloud-computing' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'paths/back-end-engineer-career-path' ---- - -**Cloud computing** refers to an architecture where computing resources and hardware are maintained and managed remotely by an entity other than the user. This is becoming popular with businesses and ubiquitous in personal computing. For example, whenever a person sets up a website on GoDaddy, plays World of Warcraft, or streams a movie on Netflix, they are using a cloud computing solution. - -## Advantages - -Cloud computing offers the following advantages to the user: - -- **Scalability:** Adding additional capacity is quicker and easier in a cloud environment then when a user runs their own data center. When a user manages a data center themselves, additional capacity involves purchasing, installing, and configuring new hardware. A cloud solution provides access to many more resources than would otherwise be possible. -- **Security:** A cloud solution often provides more security than a business, especially a small business, can manage on their own. -- **Availability:** Cloud solutions are able to provide services that are guaranteed to stay available, leading to better uptime for users and clients. -- **Performance:** A cloud solution will provide more powerful hardware than a business could afford in its own data center. -- **Cost:** A cloud solution is typically more affordable than an on-premises solution offering the same capabilities. - -Generally, cloud computing removes the necessity of a business to maintain a dedicated data center. This frees the business from the cost of all the personnel and hardware that a data center requires. diff --git a/content/cloud-computing/concepts/aws-management-console/aws-management-console.md b/content/cloud-computing/concepts/aws-management-console/aws-management-console.md deleted file mode 100644 index 52050fd10e3..00000000000 --- a/content/cloud-computing/concepts/aws-management-console/aws-management-console.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -Title: 'AWS Management Console' -Description: 'The AWS Management Console is a web application that is home to all the various other consoles used to manage AWS services.' -Subjects: - - 'Computer Science' -Tags: - - 'Cloud Computing' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'paths/back-end-engineer-career-path' ---- - -The **AWS Management Console** is a web application that is home to all the various other consoles used to manage AWS services. The console's customizable home page is what's first seen when a user logs into AWS. - -![AWS Management Console home page](https://raw.githubusercontent.com/Codecademy/docs/main/media/aws-console-home.png) - -The home page provides access to each service console and provides information needed to perform AWS-related tasks. - -The AWS Management Console provides the following: - -- Unified settings for all service consoles, such as region and screen display. -- The ability to add, remove, and resize widgets that display information about the AWS environment and provide shortcuts to AWS services. -- The ability to set favorites to access frequently-used services. -- A unified search tool to find services, features, and documentation. -- AWS CloudShell, a browser-based shell that allows CLI commands against services in Bash, PowerShell, or Z shell. - -In addition to the web application, the AWS Management Console is available as a mobile app for Android and iOS. The app is intended to provide mobile-relevant tasks as a companion to the full web application. diff --git a/content/cloud-computing/concepts/cloud-services/cloud-services.md b/content/cloud-computing/concepts/cloud-services/cloud-services.md deleted file mode 100644 index 2359d67ff76..00000000000 --- a/content/cloud-computing/concepts/cloud-services/cloud-services.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -Title: 'Cloud Services' -Description: 'There are many different cloud-computing services, but the big three are Microsoft Azure, Amazon Web Services (AWS) and Google Cloud Platform (GCP).' -Subjects: - - 'Computer Science' -Tags: - - 'Cloud Computing' - - 'Networking' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'paths/back-end-engineer-career-path' ---- - -There are many different **cloud-computing services**, but the big three are [Amazon Web Services (AWS)](https://aws.amazon.com/), [Microsoft Azure](https://azure.microsoft.com/), and [Google Cloud Platform (GCP)](https://cloud.google.com/). All three offer services to cover the most significant cloud-computing needs: - -- [Infrastructure as a service (IaaS)](https://www.codecademy.com/resources/docs/cloud-computing/iaas) -- [Platform as a service (PaaS)](https://www.codecademy.com/resources/docs/cloud-computing/paas) -- [Function as a service (FaaS)](https://www.codecademy.com/resources/docs/cloud-computing/faas) -- [Software as a service (SaaS)](https://www.codecademy.com/resources/docs/cloud-computing/saas) - -## AWS - -AWS is the largest cloud computing platform, and the most mature, introducing its first public cloud services in 2006. It serves millions of users, from individuals to large enterprises, to governments. - -- AWS offers more than 200 services to its customers. -- As of 2021, AWS has 25 geographic regions and 218+ edge locations. - -The advantages of AWS include: - -- The widest array of services; from networking to quantum computing. -- The most mature, reliable and secure platform. -- The most compute capability. - -Disadvantages include: - -- If Dev/Enterprise support is needed, users must pay for it separately. -- The number of services and options can be overwhelming. -- A complex and hard-to-understand pricing structure. -- There are limited options to run a [hybrid cloud](https://www.codecademy.com/resources/docs/cloud-computing/types-of-cloud) solution. - -## Azure - -Azure is the second largest cloud platform, introduced by Microsoft in 2008. It is also currently among the fastest growing cloud platforms. - -- Azure offers more than 200 products and services, a wide array of which are tailored to enterprises already using Microsoft products. -- In addition to Microsoft products, Azure supports [open-source](https://www.codecademy.com/resources/docs/open-source) languages, technologies and platforms. -- As of 2021, Azure has 60+ geographic regions with 116 edge locations. - -The advantages of Azure include: - -- The ease of integration and migration for existing Microsoft users. -- Lower cost for users of Microsoft products such as Windows, Active Directory and SQL Server. -- Significant support for hybrid cloud solutions. -- The broadest geographic reach of the three platforms. - -Disadvantages include: - -- Fewer service offerings than AWS. -- Predominantly supports enterprise customers. -- High level of expertise and maintenance required. - -## GCP - -GCP was introduced by Google in 2010 and is the smallest of the big three cloud-computing platforms. - -- GCP offers over 100 services including computing, networking, and [big data](https://www.codecademy.com/resources/docs/general/data-science/big-data). -- GCP services include Google Workspace, enterprise Android, and Chrome OS. -- As of 2021 GCP has 27 geographic regions and 146 edge locations. - -The advantages of GCP include: - -- Easily integrates with other Google products and services. -- Excellent integrations with open-source projects and third-party services. -- Easily accommodates growth by offering considerable scaling and load-balancing capabilities. -- Cutting edge [AI](https://www.codecademy.com/resources/docs/ai) and [machine learning](https://www.codecademy.com/resources/docs/ai/machine-learning) services. - -The disadvantages include: - -- Limited services compared to AWS and Azure. -- Limited support for enterprise users. diff --git a/content/cloud-computing/concepts/containerization/containerization.md b/content/cloud-computing/concepts/containerization/containerization.md deleted file mode 100644 index 5e47fa2d0b7..00000000000 --- a/content/cloud-computing/concepts/containerization/containerization.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -Title: 'Containerization' -Description: 'Containerization is a type of virtualization that bundles code with its required environment.' -Subjects: - - 'Computer Science' - - 'Data Science' - - 'Cybersecurity' -Tags: - - 'Cloud Computing' - - 'Infrastructure' - - 'Docker' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'paths/back-end-engineer-career-path' ---- - -**Containerization** is a type of virtualization that bundles code with its required environment. These bundles are called “containers”. Containers can be run in nearly all computing environments and are widely used in cloud computing. - -## How do Containers Work? - -Containers work by providing a self-contained and isolated environment for software to run. They are typically managed in container orchestration systems, such as Kubernetes or Docker Swarm. These systems automate the work of managing and scheduling individual containers across clusters of servers. - -Containers are built from container images, which provide specifications for the container and how it is instantiated. A container image can be thought of as a recipe, and the container is the dish made from following that recipe. Docker is a common platform for building, packaging, and distributing container images. - -## Containers vs. Virtual Machines - -Containers and [virtual machines](https://www.codecademy.com/resources/docs/general/virtual-machines) are both types of virtualization technology that are used for similar purposes. However, a main difference is that containers virtualize at the operating system-level, and virtual machines virtualize at the hardware-level. This means that multiple containers can run on a single, shared operating system kernel, such as the [Linux kernel](https://www.codecademy.com/resources/docs/open-source/linux-kernel). Virtual machines do not traditionally use a shared operating system, although some hypervisors now support container-like virtualization which can allow multiple virtual machines to use a single operating system kernel. Because multiple containers share the same kernel, they are typically considered less secure than virtual machines. - -## Benefits of Containerization - -Containerization provides many benefits, such as: - -### Portability - -Containers can be easily moved to different environments and operating systems. They can also be moved to different cloud providers, or different cloud or on-premise infrastructures without significant reconfiguration. This portability makes it easier to switch between cloud providers or adopt hybrid cloud infrastructures. - -### Scalability - -Containers can easily be scaled to handle changes in demand. For example, if a containerized web application had a sudden surge in web traffic, additional container instances can easily be added to handle the increased demand. - -### Efficiency - -Containers are designed to be lightweight, and they are typically faster and more efficient than other forms of virtualization. One major reason for this is because containers do not have to boot an entire operating system, unlike traditional virtual machines. Additionally, because containers are designed to be small and efficient, more containers can be run on a single host. - -## Containerization Uses - -Many software companies use containers and other virtualization technology. Containerization is a fundamental part of [cloud computing](https://www.codecademy.com/resources/docs/cloud-computing), [data science](https://www.codecademy.com/resources/docs/data-science), [cybersecurity](https://www.codecademy.com/resources/docs/cybersecurity), and more. diff --git a/content/cloud-computing/concepts/faas/faas.md b/content/cloud-computing/concepts/faas/faas.md deleted file mode 100644 index 6c5d6eb2844..00000000000 --- a/content/cloud-computing/concepts/faas/faas.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -Title: 'FaaS' -Description: 'Function as a Service (FaaS) is a serverless cloud computing model that enables developers to build and deploy applications without managing infrastructure.' -Subjects: - - 'Computer Science' -Tags: - - 'Cloud' - - 'Functions' - - 'Development' - - 'Infrastructure' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'paths/back-end-engineer-career-path' ---- - -**Function as a service (FaaS)** is a serverless cloud computing model that enables developers to build and deploy applications without managing infrastructure. It supports event-driven execution, auto-scaling, and cost-efficient cloud application development. - -## History - -FaaS was first offered by start-ups like PiCloud around 2010. It has since been offered by large vendors such as Amazon (AWS Lambda), Google (Google Cloud Functions), and Microsoft (Microsoft Azure Functions). - -## Key Concepts of FaaS - -- **Event-driven execution** – Functions trigger based on events like API calls or message queues. -- **Auto-scaling** – Functions scale automatically based on demand. -- **Stateless** – Each function instance is independent and does not maintain session data. -- **Short-lived execution** – Functions typically run within seconds. -- **Cost-efficiency** – Billing is based on execution time and usage, not idle time. - -## FaaS Architecture and Components - -FaaS architecture consists of several key components that enable event-driven execution, scalability, and seamless integration. - -### Components of FaaS - -- **Function Execution Environment**: The runtime that executes functions on demand. -- **Event Sources**: Triggers such as HTTP requests, database updates, or message queues. -- **Function Deployment and Management**: Services that manage and deploy functions. -- **Monitoring and Logging**: Tools for tracking function execution and performance. -- **Security and Permissions**: Identity and access management controls. - -## Real-World Applications of FaaS - -FaaS is widely used across industries for different use cases: - -- **Web Applications** – Handles backend logic for web apps (e.g., authentication, payments). -- **Data Processing** – Processes streams of data in real time (e.g., IoT sensor data, log analysis). -- **Chatbots and AI** – Executes AI-based processing for chatbots and virtual assistants. -- **Automation and Orchestration** – Automates workflows, scheduling, and CI/CD pipelines. -- **Multimedia Processing** – Manages image/video processing dynamically. -- **Streaming Services** – Companies like Netflix use FaaS for real-time video processing and personalization. -- **E-commerce** – Handles transaction processing, fraud detection, and inventory management. - -## Advantages and Disadvantages - -The main difference between the FaaS and platform as a service (PaaS) models is that FaaS services hide the server details from the user. This results in the following advantages: - -- Instead of paying for server processes being run on the cloud, the user is only paying for function execution time. -- Because a server process is not being constantly run, the user does not pay for any process idle time. -- This results in a lower cost and higher scalability. - -The disadvantages include: - -- Initial requests to the server might take several seconds to respond, though [caching](https://www.codecademy.com/resources/docs/general/cache) may reduce subsequent requests to milliseconds. -- It requires giving up substantial control. Things like the server, security or database the application uses are handled by the service provider. -- There may be difficulty switching service providers after the application is developed. - -## FaaS vs Other Cloud Service Models - -FaaS is often compared with **PaaS (Platform as a Service)** and **IaaS (Infrastructure as a Service)**. For a deeper dive into these concepts, refer to their respective entries: - -- [Platform as a Service (PaaS)](https://www.codecademy.com/resources/docs/cloud-computing/paas) -- [Infrastructure as a Service (IaaS)](https://www.codecademy.com/resources/docs/cloud-computing/iaas) - -By understanding these models, developers can choose the right approach for their cloud applications. diff --git a/content/cloud-computing/concepts/iaas/iaas.md b/content/cloud-computing/concepts/iaas/iaas.md deleted file mode 100644 index 6d1c5a3951e..00000000000 --- a/content/cloud-computing/concepts/iaas/iaas.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -Title: 'IaaS' -Description: 'Infrastructure as a service (IaaS) is a cloud computing model that offers remote computer, storage, and networking resources that are available on demand.' -Subjects: - - 'Computer Science' - - 'Networking' -Tags: - - 'Networking' - - 'Cloud' - - 'Infrastructure' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'paths/back-end-engineer-career-path' ---- - -**Infrastructure as a service (IaaS)** is a cloud computing model that offers remote computer, storage, and networking resources that are available on demand. These services are typically offered on a pay-as-you-go basis. The user is given control of [virtual machines](https://www.codecademy.com/resources/docs/general/virtual-machines) (software running on a cloud server that acts as its own independent computer). These virtual machines are managed by another piece of software running on the cloud server, known as a hypervisor. Examples of this type of software include Oracle VirtualBox or VMware ESXi. The user is allowed to run arbitrary software on these virtual machines, including operating systems. - -IaaS provides an [API](https://www.codecademy.com/resources/docs/general/api) to control the low-level details of the underlying network infrastructure (e.g., backups, partitioning, security, and physical resources). While they do not have direct access to the infrastructure, users can configure: - -- Operating systems -- Storage -- Deployed applications -- Networking components (e.g., host firewalls) - -The user's responsibilities include the following: - -- Maintaining the virtual machines. - - This includes keeping operating systems and applications patched and up-to-date. -- Paying the cloud service only for the number of resources allocated and consumed. diff --git a/content/cloud-computing/concepts/paas/paas.md b/content/cloud-computing/concepts/paas/paas.md deleted file mode 100644 index 61e4e287c9a..00000000000 --- a/content/cloud-computing/concepts/paas/paas.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -Title: 'PaaS' -Description: 'Platform as a service (PaaS) is a service model that offers developers a platform to create, manage, and deploy their applications.' -Subjects: - - 'Computer Science' - - 'Networking' -Tags: - - 'Cloud Computing' - - 'Platform' - - 'Development' - - 'Infrastructure' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'paths/back-end-engineer-career-path' ---- - -**Platform as a service (PaaS)** is a service model offered to simplify the process of developing and deploying apps. With PaaS, developers don't need to worry about the underlying software and hardware their applications depend upon. When using a PaaS, the service provider provides and maintains the following: - -- Operating systems -- Software development kits (SDK) -- Frameworks -- Libraries -- APIs -- Any other relevant software needed for application development - -In addition to the software, the service provider also provides the infrastructure needed for the application. PaaS includes the services provided by an infrastructure-as-a-service ([IaaS](https://www.codecademy.com/resources/docs/cloud-computing/saas)) offering. Compared to the other two cloud services available - IaaS and software as a service ([SaaS](https://www.codecademy.com/resources/docs/cloud-computing/iaas)) - On the service provider, PaaS places more responsibility than IaaS and less responsibility than SaaS. - -## Advantages of PaaS - -Since a PaaS relieves developers of many maintenance tasks, an application can be developed and deployed much more quickly. - -Using a PaaS is often cheaper than building and maintaining the necessary software and hardware in-house. PaaS applications scale based on how much they are being used. Without using PaaS, developers risk paying for more than what they need. - -Since it is a web service, PaaS allows a team of developers to collaborate on a project regardless of each developer's geographic location. - -## Disadvantages of PaaS - -When using a PaaS, developers are limited to the use of the software technologies (languages, frameworks, libraries, etc...) that are available from the vendor. Before selecting a vendor for PaaS, developers should make sure that they are comfortable using what the vendor provides. Another disadvantage of PaaS is migration. It is possible for a vendor's technology stack to not be compatible with another vendor's technology stack; therefore if a team of developers wishes to change vendor, they may be required to completely rework everything for things to work on the new vendor's platform. - -## Providers of PaaS - -Many of the major tech firms have a PaaS offering. Examples: - -- Google App Engine -- Amazon Elastic Beanstalk -- Microsoft App Services - -These are just a few of them. There are also open-source versions of PaaS (such as Cloud Foundry, Dokku, and OKD) that are offered by some smaller tech firms or independent developers. - -## Conclusion - -Platform as a service is a widely available solution for developers looking to streamline the development of a project. Since many of the responsibilities are handled by a PaaS vendor, it can be a cheaper option than creating an in-house platform. Before committing to a PaaS solution, it is critical to consider the advantages and disadvantages of each vendor's offering. diff --git a/content/cloud-computing/concepts/root-user/root-user.md b/content/cloud-computing/concepts/root-user/root-user.md deleted file mode 100644 index fdbaef5d42b..00000000000 --- a/content/cloud-computing/concepts/root-user/root-user.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -Title: 'Root User' -Description: 'The root user of a cloud computing account is the identity that has access to all services and settings available to that account.' -Subjects: - - 'Computer Science' -Tags: - - 'Cloud' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'back-end-engineer-career-path' ---- - -The **root user** of a cloud computing account is the identity that has access to all services and resources available to that account. The root user is typically created when the cloud computing account is first set up, and it is used to initialize the services and settings used by that account. - -After this initial setup, it is best practice to not use the root user for everyday tasks, even administrative ones. It is recommended that the root user is only used to create the first limited access users to perform day-to-day maintenance. The root user credentials should be kept safe and only be used for the few account and service management tasks for which it is necessary. diff --git a/content/cloud-computing/concepts/saas/saas.md b/content/cloud-computing/concepts/saas/saas.md deleted file mode 100644 index 316959eab83..00000000000 --- a/content/cloud-computing/concepts/saas/saas.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -Title: 'SaaS' -Description: 'SaaS is a cloud computing service delivery model that makes software and applications available over the internet.' -Subjects: - - 'Computer Science' - - 'Networking' -Tags: - - 'Networking' - - 'Cloud' - - 'Infrastructure' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'back-end-engineer-career-path' ---- - -**Software as a service (SaaS)** is a cloud computing service delivery model that makes software and applications available over the Internet. - -Some examples of SaaS include Google Workspace, Dropbox, and Microsoft 365. - -## Architecture - -SaaS services typically use a multi-tenant approach, where multiple customers share access to cloud resources. Each customer has their own space to store data. The data is isolated and will remain invisible to other tenants. - -## Advantages - -With its flexibility and low costs, SaaS services have several advantages including: - -- **Accessibility**: Requires only an internet connection and can be accessed from an internet-enabled device (e.g., a computer, smartphone or tablet) within a location that has internet service. -- **Management**: Customers do not have to maintain anything; all maintenance and updates are provided by the service provider. -- **Scalability**: Customers can use as much of the service as they want and are charged for the amount used. - -## Challenges - -Since they are not in direct control of the service, customers could face challenges such as: - -- **Service Issues**: Disruptions like security breaches, server outages, or service changes are beyond the customer's control. -- **Switching Providers**: Depending on the amount of data being stored, it may be difficult to transfer the data to a different provider. -- **Updates**: If the service provider issues a new version of the product, the customer may have to allocate time to learn the newer version. diff --git a/content/cloud-computing/concepts/shared-responsibility-model/shared-responsibility-model.md b/content/cloud-computing/concepts/shared-responsibility-model/shared-responsibility-model.md deleted file mode 100644 index 11b6c3faee8..00000000000 --- a/content/cloud-computing/concepts/shared-responsibility-model/shared-responsibility-model.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -Title: 'Shared Responsibility Model' -Description: 'The shared responsibility model pertains to the security of a cloud account and how the responsibility is split between the cloud provider and the customer.' -Subjects: - - 'Computer Science' -Tags: - - 'Cloud Computing' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'paths/back-end-engineer-career-path' ---- - -The **shared responsibility model** means that cloud providers maintain some responsibility for security, but some security responsibilities are borne by the customer. To provide a secure environment using cloud services, the customer must be cognizant of where the provider's responsibilities end, and where their responsibilities start. - -The line between customer and provider responsibilities can vary between service providers, and can change depending on what type of service is being provided. For instance, the responsibilities may differ between [infrastructure as a service (IaaS)](https://www.codecademy.com/resources/docs/cloud-computing/iaas) and [platform as a service (PaaS)](https://www.codecademy.com/resources/docs/cloud-computing/paas). - -In general, the customer is always responsible for securing what's under their direct control, such as: - -- Information and Data -- User Access -- Configuration of the cloud platform -- The resources used to connect to the cloud - -In general, the cloud provider is always responsible for securing the physical hosts, network, and data centers. diff --git a/content/cloud-computing/concepts/types-of-cloud/types-of-cloud.md b/content/cloud-computing/concepts/types-of-cloud/types-of-cloud.md deleted file mode 100644 index 717e5e53143..00000000000 --- a/content/cloud-computing/concepts/types-of-cloud/types-of-cloud.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -Title: 'Types of Cloud' -Description: 'The types of cloud computing implementations include public, private, hybrid, and multicloud.' -Subjects: - - 'Computer Science' -Tags: - - 'Cloud Computing' - - 'Networking' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'paths/back-end-engineer-career-path' ---- - -There are several **types of cloud** computing implementation: - -## Public Cloud - -Public clouds are owned and operated by third-party cloud service providers that deliver computing resources such as servers and storage over the Internet. Examples include the following: - -- [Amazon Web Services (AWS)](https://aws.amazon.com/) -- [Google Cloud Platform (GCP)](https://cloud.google.com/gcp) -- [Microsoft Azure](https://azure.microsoft.com/en-us/) - -## Private Cloud - -Private cloud refers to cloud computing resources used exclusively by a single business or organization. A private cloud can be physically located on the company’s on-site data center. Some companies also pay third-party service providers to host their private cloud. - -## Hybrid Cloud - -Hybrid clouds are a combination of both private and public clouds. Data and applications are allowed to be shared between the private and public clouds. Allowing data and applications to move between private and public clouds provides businesses: - -- Greater flexibility. -- More deployment options. -- Optimization existing infrastructure, security, and compliance. - -## Multicloud - -Multicloud is a combination of the above, referring to any implementation that utilizes more than one cloud solution. While it includes all hybrid clouds, multicloud also includes solutions that involve two or more public clouds, or two or more private clouds. diff --git a/content/data-science/concepts/big-data/big-data.md b/content/data-science/concepts/big-data/big-data 2.md similarity index 100% rename from content/data-science/concepts/big-data/big-data.md rename to content/data-science/concepts/big-data/big-data 2.md diff --git a/content/data-science/concepts/data-distributions/data-distributions.md b/content/data-science/concepts/data-distributions/data-distributions 2.md similarity index 100% rename from content/data-science/concepts/data-distributions/data-distributions.md rename to content/data-science/concepts/data-distributions/data-distributions 2.md diff --git a/content/data-science/concepts/data-distributions/terms/binomial-distribution/binomial-distribution.md b/content/data-science/concepts/data-distributions/terms/binomial-distribution/binomial-distribution 3.md similarity index 100% rename from content/data-science/concepts/data-distributions/terms/binomial-distribution/binomial-distribution.md rename to content/data-science/concepts/data-distributions/terms/binomial-distribution/binomial-distribution 3.md diff --git a/content/data-science/concepts/data-distributions/terms/chi-square-distribution/chi-square-distribution.md b/content/data-science/concepts/data-distributions/terms/chi-square-distribution/chi-square-distribution 2.md similarity index 100% rename from content/data-science/concepts/data-distributions/terms/chi-square-distribution/chi-square-distribution.md rename to content/data-science/concepts/data-distributions/terms/chi-square-distribution/chi-square-distribution 2.md diff --git a/content/data-science/concepts/data-distributions/terms/exponential-distribution/exponential-distribution.md b/content/data-science/concepts/data-distributions/terms/exponential-distribution/exponential-distribution 2.md similarity index 100% rename from content/data-science/concepts/data-distributions/terms/exponential-distribution/exponential-distribution.md rename to content/data-science/concepts/data-distributions/terms/exponential-distribution/exponential-distribution 2.md diff --git a/content/data-science/concepts/data-distributions/terms/geometric-distribution/geometric-distribution.md b/content/data-science/concepts/data-distributions/terms/geometric-distribution/geometric-distribution 2.md similarity index 100% rename from content/data-science/concepts/data-distributions/terms/geometric-distribution/geometric-distribution.md rename to content/data-science/concepts/data-distributions/terms/geometric-distribution/geometric-distribution 2.md diff --git a/content/data-science/concepts/data-distributions/terms/hypergeometric-distribution/hypergeometric-distribution.md b/content/data-science/concepts/data-distributions/terms/hypergeometric-distribution/hypergeometric-distribution 2.md similarity index 100% rename from content/data-science/concepts/data-distributions/terms/hypergeometric-distribution/hypergeometric-distribution.md rename to content/data-science/concepts/data-distributions/terms/hypergeometric-distribution/hypergeometric-distribution 2.md diff --git a/content/data-science/concepts/data-distributions/terms/lognormal-distribution/lognormal-distribution.md b/content/data-science/concepts/data-distributions/terms/lognormal-distribution/lognormal-distribution 3.md similarity index 100% rename from content/data-science/concepts/data-distributions/terms/lognormal-distribution/lognormal-distribution.md rename to content/data-science/concepts/data-distributions/terms/lognormal-distribution/lognormal-distribution 3.md diff --git a/content/data-science/concepts/data-distributions/terms/normal-distribution/normal-distribution.md b/content/data-science/concepts/data-distributions/terms/normal-distribution/normal-distribution 2.md similarity index 100% rename from content/data-science/concepts/data-distributions/terms/normal-distribution/normal-distribution.md rename to content/data-science/concepts/data-distributions/terms/normal-distribution/normal-distribution 2.md diff --git a/content/data-science/concepts/data-distributions/terms/poisson-distribution/poisson-distribution.md b/content/data-science/concepts/data-distributions/terms/poisson-distribution/poisson-distribution 2.md similarity index 100% rename from content/data-science/concepts/data-distributions/terms/poisson-distribution/poisson-distribution.md rename to content/data-science/concepts/data-distributions/terms/poisson-distribution/poisson-distribution 2.md diff --git a/content/data-science/concepts/data-distributions/terms/weibull-distribution/weibull-distribution.md b/content/data-science/concepts/data-distributions/terms/weibull-distribution/weibull-distribution 2.md similarity index 100% rename from content/data-science/concepts/data-distributions/terms/weibull-distribution/weibull-distribution.md rename to content/data-science/concepts/data-distributions/terms/weibull-distribution/weibull-distribution 2.md diff --git a/content/data-science/concepts/data-mining/data-mining.md b/content/data-science/concepts/data-mining/data-mining 2.md similarity index 100% rename from content/data-science/concepts/data-mining/data-mining.md rename to content/data-science/concepts/data-mining/data-mining 2.md diff --git a/content/data-science/concepts/data-warehouse/data-warehouse.md b/content/data-science/concepts/data-warehouse/data-warehouse 2.md similarity index 100% rename from content/data-science/concepts/data-warehouse/data-warehouse.md rename to content/data-science/concepts/data-warehouse/data-warehouse 2.md diff --git a/content/data-science/concepts/hypothesis-testing/hypothesis-testing.md b/content/data-science/concepts/hypothesis-testing/hypothesis-testing 2.md similarity index 100% rename from content/data-science/concepts/hypothesis-testing/hypothesis-testing.md rename to content/data-science/concepts/hypothesis-testing/hypothesis-testing 2.md diff --git a/content/data-science/concepts/hypothesis-testing/terms/t-table/t-table.md b/content/data-science/concepts/hypothesis-testing/terms/t-table/t-table.md deleted file mode 100644 index a47c52e7cf5..00000000000 --- a/content/data-science/concepts/hypothesis-testing/terms/t-table/t-table.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -Title: 'T-table' -Description: 'A statistical tool used in hypothesis testing to determine critical values for t-distributions and assess the significance of test results.' -Subjects: - - 'Data Science' - - 'Data Visualization' -Tags: - - 'Database' - - 'Queries' -CatalogContent: - - 'r-for-programmers' - - 'paths/data-science' ---- - -The **t-table**, also known as the Student's t-distribution table, is a critical reference tool in statistical analysis. It helps researchers determine whether to reject or fail to reject their null hypothesis, particularly in cases where sample sizes are small or the population standard deviation is unknown. The table provides critical values based on degrees of freedom (df) and significance levels (α), making it essential for statistical inference. - -The t-distribution is bell-shaped like the normal distribution but has heavier tails, which account for variability in smaller samples. As df increases, the t-distribution gradually approaches the normal distribution. - -## One-Tailed T-Test Critical Values - -| Degrees of Freedom (df) | α = 0.10 | α = 0.05 | α = 0.025 | α = 0.01 | α = 0.005 | -| ----------------------- | -------- | -------- | --------- | -------- | --------- | -| 1 | 3.078 | 6.314 | 12.706 | 31.821 | 63.657 | -| 2 | 1.886 | 2.920 | 4.303 | 6.965 | 9.925 | -| 3 | 1.638 | 2.353 | 3.182 | 4.541 | 5.841 | -| 4 | 1.533 | 2.132 | 2.776 | 3.747 | 4.604 | -| 5 | 1.476 | 2.015 | 2.571 | 3.365 | 4.032 | -| 6 | 1.440 | 1.943 | 2.447 | 3.143 | 3.707 | -| 7 | 1.415 | 1.895 | 2.365 | 2.998 | 3.499 | -| 8 | 1.397 | 1.860 | 2.306 | 2.896 | 3.355 | -| 9 | 1.383 | 1.833 | 2.262 | 2.821 | 3.250 | -| 10 | 1.372 | 1.812 | 2.228 | 2.764 | 3.169 | -| 11 | 1.363 | 1.796 | 2.201 | 2.718 | 3.106 | -| 12 | 1.356 | 1.782 | 2.179 | 2.681 | 3.055 | -| 13 | 1.350 | 1.771 | 2.160 | 2.650 | 3.012 | -| 14 | 1.345 | 1.761 | 2.145 | 2.624 | 2.977 | -| 15 | 1.341 | 1.753 | 2.131 | 2.602 | 2.947 | -| 16 | 1.337 | 1.746 | 2.120 | 2.583 | 2.921 | -| 17 | 1.333 | 1.740 | 2.110 | 2.567 | 2.898 | -| 18 | 1.330 | 1.734 | 2.101 | 2.552 | 2.878 | -| 19 | 1.328 | 1.729 | 2.093 | 2.539 | 2.861 | -| 20 | 1.325 | 1.725 | 2.086 | 2.528 | 2.845 | -| 21 | 1.323 | 1.721 | 2.080 | 2.518 | 2.831 | -| 22 | 1.321 | 1.717 | 2.074 | 2.508 | 2.819 | -| 23 | 1.319 | 1.714 | 2.069 | 2.500 | 2.807 | -| 24 | 1.318 | 1.711 | 2.064 | 2.492 | 2.797 | -| 25 | 1.316 | 1.708 | 2.060 | 2.485 | 2.787 | -| 26 | 1.315 | 1.706 | 2.056 | 2.479 | 2.779 | -| 27 | 1.314 | 1.703 | 2.052 | 2.473 | 2.771 | -| 28 | 1.313 | 1.701 | 2.048 | 2.467 | 2.763 | -| 29 | 1.311 | 1.699 | 2.045 | 2.462 | 2.756 | -| 30 | 1.310 | 1.697 | 2.042 | 2.457 | 2.750 | - -## Two-Tailed T-Test Critical Values - -| Degrees of Freedom (df) | α = 0.20 | α = 0.10 | α = 0.05 | α = 0.02 | α = 0.01 | -| ----------------------- | -------- | -------- | -------- | -------- | -------- | -| 1 | 3.078 | 6.314 | 12.706 | 31.821 | 63.657 | -| 2 | 1.886 | 2.920 | 4.303 | 6.965 | 9.925 | -| 3 | 1.638 | 2.353 | 3.182 | 4.541 | 5.841 | -| 4 | 1.533 | 2.132 | 2.776 | 3.747 | 4.604 | -| 5 | 1.476 | 2.015 | 2.571 | 3.365 | 4.032 | -| 6 | 1.440 | 1.943 | 2.447 | 3.143 | 3.707 | -| 7 | 1.415 | 1.895 | 2.365 | 2.998 | 3.499 | -| 8 | 1.397 | 1.860 | 2.306 | 2.896 | 3.355 | -| 9 | 1.383 | 1.833 | 2.262 | 2.821 | 3.250 | -| 10 | 1.372 | 1.812 | 2.228 | 2.764 | 3.169 | -| 11 | 1.363 | 1.796 | 2.201 | 2.718 | 3.106 | -| 12 | 1.356 | 1.782 | 2.179 | 2.681 | 3.055 | -| 13 | 1.350 | 1.771 | 2.160 | 2.650 | 3.012 | -| 14 | 1.345 | 1.761 | 2.145 | 2.624 | 2.977 | -| 15 | 1.341 | 1.753 | 2.131 | 2.602 | 2.947 | -| 16 | 1.337 | 1.746 | 2.120 | 2.583 | 2.921 | -| 17 | 1.333 | 1.740 | 2.110 | 2.567 | 2.898 | -| 18 | 1.330 | 1.734 | 2.101 | 2.552 | 2.878 | -| 19 | 1.328 | 1.729 | 2.093 | 2.539 | 2.861 | -| 20 | 1.325 | 1.725 | 2.086 | 2.528 | 2.845 | -| 21 | 1.323 | 1.721 | 2.080 | 2.518 | 2.831 | -| 22 | 1.321 | 1.717 | 2.074 | 2.508 | 2.819 | -| 23 | 1.319 | 1.714 | 2.069 | 2.500 | 2.807 | -| 24 | 1.318 | 1.711 | 2.064 | 2.492 | 2.797 | -| 25 | 1.316 | 1.708 | 2.060 | 2.485 | 2.787 | -| 26 | 1.315 | 1.706 | 2.056 | 2.479 | 2.779 | -| 27 | 1.314 | 1.703 | 2.052 | 2.473 | 2.771 | -| 28 | 1.313 | 1.701 | 2.048 | 2.467 | 2.763 | -| 29 | 1.311 | 1.699 | 2.045 | 2.462 | 2.756 | -| 30 | 1.310 | 1.697 | 2.042 | 2.457 | 2.750 | - -### How to Use These Tables - -1. **Determine the Test Type**: - - - **One-tailed test**: Used when testing for an effect in a specific direction (greater than or less than). - - **Two-tailed test**: Used when testing for any significant difference, regardless of direction. - -2. **Calculate degrees of freedom (df)**: - - - For a single-sample test: \( df = n - 1 \) - -3. **Choose the significance level (\(\alpha\))**: - - - Common values: 0.05 (5%), 0.01 (1%), 0.10 (10%) - -4. **Find the critical value** where the `df` row intersects with the chosen \(\alpha\) column. - -5. **Compare with the t-statistic**: - - If the calculated t-statistic exceeds the critical value, reject the null hypothesis. - - If it does not exceed the critical value, fail to reject the null hypothesis. - -**Note:** - -- For one-tailed tests, use the one-tailed table directly. -- For two-tailed tests, use the two-tailed table or double the α value in the one-tailed table. -- If the df isn't listed, interpolate between the closest values or use the more conservative (larger) critical value. - -## Example - -Given: - -- Degrees of freedom (df) = 15 -- Significance level (α) = 0.05 (for 95% confidence level) -- Two-tailed test - -### Steps to find critical t-value - -- Find degrees of freedom (df = 15) in the leftmost column -- Move right to the α = 0.05 column -- Read the t-value where the row and column intersect - -From the t-table: - -| Degrees of Freedom (df) | α = 0.05 | -| ----------------------- | -------- | -| 15 | 2.131 | - -Therefore, the critical t-value for df = 15 at α = 0.05 is 2.131 diff --git a/content/data-science/concepts/hypothesis-testing/terms/z-table/z-table.md b/content/data-science/concepts/hypothesis-testing/terms/z-table/z-table.md deleted file mode 100644 index 2de28c0896f..00000000000 --- a/content/data-science/concepts/hypothesis-testing/terms/z-table/z-table.md +++ /dev/null @@ -1,153 +0,0 @@ ---- -Title: 'Z-table' -Description: 'A Z-table shows the cumulative probabilities of a standard normal distribution, helping find the probability of a value occurring below a given z-score.' -Subjects: - - 'Data Science' - - 'Data Visualization' - - 'Machine Learning' -Tags: - - 'Data Science' - - 'Deep Learning' -CatalogContent: - - 'learn-python-3' - - 'paths/data-science' ---- - -The **Z-table** is a statistical reference that shows cumulative probabilities for z-scores in a standard normal distribution (which has a mean of _0_ and standard deviation of _1_). The table helps find probabilities associated with z-scores, where: - -- **Positive z-values** represent values **above** the mean. -- **Negative z-values** represent values **below** the mean. - -## Types of Z-Tables - -Z-tables come in different formats depending on how probabilities are calculated: - -- **Cumulative Z-table (Left-Tail)**: The most commonly used table, showing the probability of a value occurring below a given Z-score (area to the left). -- **Right-Tail Z-table**: Displays the probability of a value occurring above a given Z-score (area to the right). It is used when focusing on upper-tail probabilities. -- **Two-Tailed Tests**: Used in hypothesis testing, where deviations in both directions are considered. To find probabilities, sum the areas in both tails or subtract from _1_ accordingly. - -## Z-Distribution Table for Positive Z-Values - -Shows the cumulative probabilities of values occurring below positive Z-scores in a standard normal distribution: - -| Z | 0.00 | 0.01 | 0.02 | 0.03 | 0.04 | 0.05 | 0.06 | 0.07 | 0.08 | 0.09 | -| --- | ------- | ------- | ------- | ------- | ------- | ------- | ------- | ------- | ------- | ------- | -| 0.0 | 0.5000 | 0.50399 | 0.50798 | 0.51197 | 0.51595 | 0.51994 | 0.52392 | 0.52790 | 0.53188 | 0.53586 | -| 0.1 | 0.53983 | 0.54380 | 0.54776 | 0.55172 | 0.55567 | 0.55962 | 0.56356 | 0.56749 | 0.57142 | 0.57535 | -| 0.2 | 0.57926 | 0.58317 | 0.58706 | 0.59095 | 0.59483 | 0.59871 | 0.60257 | 0.60642 | 0.61026 | 0.61409 | -| 0.3 | 0.61791 | 0.62172 | 0.62552 | 0.62930 | 0.63307 | 0.63683 | 0.64058 | 0.64431 | 0.64803 | 0.65173 | -| 0.4 | 0.65542 | 0.65910 | 0.66276 | 0.66640 | 0.67003 | 0.67364 | 0.67724 | 0.68082 | 0.68439 | 0.68793 | -| 0.5 | 0.69146 | 0.69497 | 0.69847 | 0.70194 | 0.70540 | 0.70884 | 0.71226 | 0.71566 | 0.71904 | 0.72240 | -| 0.6 | 0.72575 | 0.72907 | 0.73237 | 0.73565 | 0.73891 | 0.74215 | 0.74537 | 0.74857 | 0.75175 | 0.75490 | -| 0.7 | 0.75804 | 0.76115 | 0.76424 | 0.76730 | 0.77035 | 0.77337 | 0.77637 | 0.77935 | 0.78230 | 0.78524 | -| 0.8 | 0.78814 | 0.79103 | 0.79389 | 0.79673 | 0.79955 | 0.80234 | 0.80511 | 0.80785 | 0.81057 | 0.81327 | -| 0.9 | 0.81594 | 0.81859 | 0.82121 | 0.82381 | 0.82639 | 0.82894 | 0.83147 | 0.83398 | 0.83646 | 0.83891 | -| 1.0 | 0.84134 | 0.84375 | 0.84614 | 0.84849 | 0.85083 | 0.85314 | 0.85543 | 0.85769 | 0.85993 | 0.86214 | -| 1.1 | 0.86433 | 0.86650 | 0.86864 | 0.87076 | 0.87286 | 0.87493 | 0.87698 | 0.87899 | 0.88098 | 0.88296 | -| 1.2 | 0.88493 | 0.88686 | 0.88877 | 0.89065 | 0.89251 | 0.89435 | 0.89617 | 0.89796 | 0.89973 | 0.90147 | -| 1.3 | 0.90320 | 0.90490 | 0.90658 | 0.90824 | 0.90988 | 0.91149 | 0.91308 | 0.91466 | 0.91621 | 0.91774 | -| 1.4 | 0.91924 | 0.92073 | 0.92220 | 0.92364 | 0.92507 | 0.92647 | 0.92785 | 0.92922 | 0.93056 | 0.93189 | -| 1.5 | 0.93319 | 0.93448 | 0.93574 | 0.93699 | 0.93822 | 0.93943 | 0.94062 | 0.94179 | 0.94295 | 0.94408 | -| 1.6 | 0.94520 | 0.94630 | 0.94738 | 0.94845 | 0.94950 | 0.95053 | 0.95154 | 0.95254 | 0.95352 | 0.95449 | -| 1.7 | 0.95543 | 0.95637 | 0.95728 | 0.95818 | 0.95907 | 0.95994 | 0.96080 | 0.96164 | 0.96246 | 0.96327 | -| 1.8 | 0.96407 | 0.96485 | 0.96562 | 0.96638 | 0.96712 | 0.96784 | 0.96856 | 0.96926 | 0.96995 | 0.97062 | -| 1.9 | 0.97128 | 0.97193 | 0.97257 | 0.97320 | 0.97381 | 0.97441 | 0.97500 | 0.97558 | 0.97614 | 0.97669 | -| 2.0 | 0.97725 | 0.97778 | 0.97831 | 0.97882 | 0.97932 | 0.97982 | 0.98030 | 0.98077 | 0.98124 | 0.98169 | -| 2.0 | 0.97725 | 0.97778 | 0.97831 | 0.97882 | 0.97932 | 0.97982 | 0.98030 | 0.98077 | 0.98124 | 0.98169 | -| 2.1 | 0.98214 | 0.98257 | 0.98300 | 0.98341 | 0.98382 | 0.98422 | 0.98461 | 0.98499 | 0.98537 | 0.98574 | -| 2.2 | 0.98610 | 0.98645 | 0.98679 | 0.98713 | 0.98746 | 0.98778 | 0.98810 | 0.98840 | 0.98870 | 0.98899 | -| 2.3 | 0.98928 | 0.98956 | 0.98983 | 0.99010 | 0.99036 | 0.99061 | 0.99086 | 0.99111 | 0.99134 | 0.99158 | -| 2.4 | 0.99180 | 0.99202 | 0.99224 | 0.99245 | 0.99266 | 0.99286 | 0.99305 | 0.99324 | 0.99343 | 0.99361 | -| 2.5 | 0.99379 | 0.99396 | 0.99413 | 0.99430 | 0.99446 | 0.99461 | 0.99477 | 0.99492 | 0.99506 | 0.99520 | -| 2.6 | 0.99534 | 0.99547 | 0.99560 | 0.99573 | 0.99585 | 0.99597 | 0.99609 | 0.99620 | 0.99631 | 0.99642 | -| 2.7 | 0.99653 | 0.99664 | 0.99674 | 0.99683 | 0.99693 | 0.99702 | 0.99711 | 0.99720 | 0.99728 | 0.99736 | -| 2.8 | 0.99744 | 0.99752 | 0.99760 | 0.99767 | 0.99774 | 0.99781 | 0.99788 | 0.99795 | 0.99801 | 0.99807 | -| 2.9 | 0.99813 | 0.99819 | 0.99824 | 0.99830 | 0.99834 | 0.99839 | 0.99844 | 0.99849 | 0.99854 | 0.99858 | -| 3.0 | 0.99865 | 0.99869 | 0.99874 | 0.99878 | 0.99882 | 0.99886 | 0.99889 | 0.99893 | 0.99896 | 0.99899 | -| 3.1 | 0.99903 | 0.99906 | 0.99909 | 0.99912 | 0.99915 | 0.99918 | 0.99920 | 0.99923 | 0.99925 | 0.99927 | -| 3.2 | 0.99929 | 0.99931 | 0.99934 | 0.99936 | 0.99938 | 0.99940 | 0.99942 | 0.99944 | 0.99946 | 0.99947 | -| 3.3 | 0.99949 | 0.99951 | 0.99952 | 0.99954 | 0.99955 | 0.99957 | 0.99958 | 0.99959 | 0.99961 | 0.99962 | -| 3.4 | 0.99963 | 0.99964 | 0.99965 | 0.99966 | 0.99967 | 0.99968 | 0.99969 | 0.99970 | 0.99971 | 0.99972 | -| 3.5 | 0.99973 | 0.99974 | 0.99975 | 0.99975 | 0.99976 | 0.99977 | 0.99977 | 0.99978 | 0.99978 | 0.99979 | -| 3.6 | 0.99980 | 0.99980 | 0.99981 | 0.99981 | 0.99982 | 0.99982 | 0.99983 | 0.99983 | 0.99983 | 0.99984 | -| 3.7 | 0.99984 | 0.99985 | 0.99985 | 0.99985 | 0.99986 | 0.99986 | 0.99986 | 0.99986 | 0.99987 | 0.99987 | -| 3.8 | 0.99987 | 0.99987 | 0.99988 | 0.99988 | 0.99988 | 0.99988 | 0.99988 | 0.99989 | 0.99989 | 0.99989 | -| 3.9 | 0.99989 | 0.99989 | 0.99989 | 0.99990 | 0.99990 | 0.99990 | 0.99990 | 0.99990 | 0.99990 | 0.99991 | - -## Z-Distribution Table for Negative Z-Values - -Displays the cumulative probabilities of values occurring below negative Z-scores, representing values to the left of the mean: - -| Z | 0.00 | 0.01 | 0.02 | 0.03 | 0.04 | 0.05 | 0.06 | 0.07 | 0.08 | 0.09 | -| ---- | ------- | ------- | ------- | ------- | ------- | ------- | ------- | ------- | ------- | ------- | -| -3.9 | 0.00005 | 0.00005 | 0.00004 | 0.00004 | 0.00004 | 0.00004 | 0.00004 | 0.00004 | 0.00003 | 0.00003 | -| -3.8 | 0.00007 | 0.00007 | 0.00007 | 0.00006 | 0.00006 | 0.00006 | 0.00006 | 0.00005 | 0.00005 | 0.00005 | -| -3.7 | 0.00011 | 0.00010 | 0.00010 | 0.00010 | 0.00009 | 0.00009 | 0.00008 | 0.00008 | 0.00008 | 0.00008 | -| -3.6 | 0.00016 | 0.00015 | 0.00015 | 0.00014 | 0.00014 | 0.00013 | 0.00013 | 0.00012 | 0.00012 | 0.00011 | -| -3.5 | 0.00023 | 0.00022 | 0.00022 | 0.00021 | 0.00020 | 0.00019 | 0.00019 | 0.00018 | 0.00017 | 0.00017 | -| -3.4 | 0.00034 | 0.00032 | 0.00031 | 0.00030 | 0.00029 | 0.00028 | 0.00027 | 0.00026 | 0.00025 | 0.00024 | -| -3.3 | 0.00048 | 0.00047 | 0.00045 | 0.00043 | 0.00042 | 0.00040 | 0.00039 | 0.00038 | 0.00036 | 0.00035 | -| -3.2 | 0.00069 | 0.00066 | 0.00064 | 0.00062 | 0.00060 | 0.00058 | 0.00056 | 0.00054 | 0.00052 | 0.00050 | -| -3.1 | 0.00097 | 0.00094 | 0.00090 | 0.00087 | 0.00084 | 0.00082 | 0.00079 | 0.00076 | 0.00074 | 0.00071 | -| -3.0 | 0.00135 | 0.00131 | 0.00126 | 0.00122 | 0.00118 | 0.00114 | 0.00111 | 0.00107 | 0.00104 | 0.00100 | -| -2.9 | 0.00187 | 0.00181 | 0.00175 | 0.00169 | 0.00164 | 0.00159 | 0.00154 | 0.00149 | 0.00144 | 0.00139 | -| -2.8 | 0.00256 | 0.00248 | 0.00240 | 0.00233 | 0.00226 | 0.00219 | 0.00212 | 0.00205 | 0.00199 | 0.00193 | -| -2.7 | 0.00347 | 0.00336 | 0.00326 | 0.00317 | 0.00307 | 0.00298 | 0.00289 | 0.00280 | 0.00272 | 0.00264 | -| -2.6 | 0.00466 | 0.00453 | 0.00440 | 0.00427 | 0.00415 | 0.00402 | 0.00391 | 0.00379 | 0.00368 | 0.00357 | -| -2.5 | 0.00621 | 0.00604 | 0.00587 | 0.00570 | 0.00554 | 0.00539 | 0.00523 | 0.00508 | 0.00494 | 0.00480 | -| -2.4 | 0.00820 | 0.00798 | 0.00776 | 0.00755 | 0.00734 | 0.00714 | 0.00695 | 0.00676 | 0.00657 | 0.00639 | -| -2.3 | 0.01072 | 0.01049 | 0.01026 | 0.01004 | 0.00982 | 0.00961 | 0.00940 | 0.00919 | 0.00899 | 0.00879 | -| -2.2 | 0.01390 | 0.01361 | 0.01321 | 0.01297 | 0.01255 | 0.01222 | 0.01191 | 0.01160 | 0.01130 | 0.01101 | -| -2.1 | 0.01786 | 0.01743 | 0.01700 | 0.01659 | 0.01618 | 0.01578 | 0.01539 | 0.01500 | 0.01463 | 0.01426 | -| -2.0 | 0.02275 | 0.02222 | 0.02169 | 0.02118 | 0.02068 | 0.02018 | 0.01969 | 0.01921 | 0.01873 | 0.01831 | -| -1.9 | 0.02872 | 0.02807 | 0.02743 | 0.02680 | 0.02619 | 0.02559 | 0.02500 | 0.02442 | 0.02385 | 0.02330 | -| -1.8 | 0.03593 | 0.03515 | 0.03438 | 0.03362 | 0.03288 | 0.03216 | 0.03145 | 0.03076 | 0.03008 | 0.02941 | -| -1.7 | 0.04457 | 0.04363 | 0.04272 | 0.04182 | 0.04093 | 0.04006 | 0.03920 | 0.03836 | 0.03754 | 0.03673 | -| -1.6 | 0.05480 | 0.05370 | 0.05262 | 0.05156 | 0.05050 | 0.04947 | 0.04846 | 0.04746 | 0.04648 | 0.04552 | -| -1.5 | 0.06681 | 0.06552 | 0.06426 | 0.06301 | 0.06178 | 0.06057 | 0.05938 | 0.05821 | 0.05705 | 0.05592 | -| -1.4 | 0.08076 | 0.07927 | 0.07778 | 0.07636 | 0.07493 | 0.07352 | 0.07215 | 0.07078 | 0.06944 | 0.06811 | -| -1.3 | 0.09680 | 0.09510 | 0.09342 | 0.09176 | 0.09012 | 0.08851 | 0.08693 | 0.08536 | 0.08380 | 0.08226 | -| -1.2 | 0.11507 | 0.11314 | 0.11123 | 0.10935 | 0.10749 | 0.10565 | 0.10383 | 0.10204 | 0.10027 | 0.09853 | -| -1.1 | 0.13567 | 0.13360 | 0.13136 | 0.12924 | 0.12714 | 0.12507 | 0.12302 | 0.12099 | 0.11899 | 0.11702 | -| -1.0 | 0.15866 | 0.15625 | 0.15386 | 0.15151 | 0.14917 | 0.14686 | 0.14457 | 0.14231 | 0.14007 | 0.13786 | -| -0.9 | 0.18406 | 0.18141 | 0.17879 | 0.17621 | 0.17361 | 0.17106 | 0.16850 | 0.16600 | 0.16354 | 0.16109 | -| -0.8 | 0.21186 | 0.20897 | 0.20611 | 0.20327 | 0.20045 | 0.19766 | 0.19489 | 0.19215 | 0.18943 | 0.18673 | -| -0.7 | 0.24196 | 0.23885 | 0.23576 | 0.23272 | 0.22962 | 0.22655 | 0.22352 | 0.22055 | 0.21770 | 0.21476 | -| -0.6 | 0.27425 | 0.27093 | 0.26763 | 0.26435 | 0.26109 | 0.25785 | 0.25463 | 0.25143 | 0.24825 | 0.24510 | -| -0.5 | 0.30854 | 0.30503 | 0.30153 | 0.29806 | 0.29460 | 0.29116 | 0.28774 | 0.28434 | 0.28096 | 0.27760 | -| -0.4 | 0.34458 | 0.34090 | 0.33724 | 0.33360 | 0.32997 | 0.32636 | 0.32276 | 0.31918 | 0.31561 | 0.31207 | -| -0.3 | 0.38209 | 0.37828 | 0.37448 | 0.37070 | 0.36693 | 0.36317 | 0.35942 | 0.35569 | 0.35197 | 0.34827 | -| -0.2 | 0.42074 | 0.41683 | 0.41294 | 0.40905 | 0.40517 | 0.40129 | 0.39743 | 0.39358 | 0.38974 | 0.38591 | -| -0.1 | 0.46017 | 0.45620 | 0.45224 | 0.44828 | 0.44433 | 0.44038 | 0.43644 | 0.43251 | 0.42858 | 0.42464 | -| 0.0 | 0.50000 | 0.49601 | 0.49202 | 0.48803 | 0.48405 | 0.48006 | 0.47608 | 0.47210 | 0.46812 | 0.46414 | - -## How to Use the Z-Table - -1. **Calculate the Z-Score**: Determine the z-score based on the data point’s distance from the mean. -2. **Locate the Z-Score**: Find the first decimal in the left column and the second decimal in the top row; their intersection gives the probability. -3. **Interpret the Probability**: - - **Left-tail table**: The value represents the probability to the left of Z. - - **Right-tail**: Subtract from 1 to get the probability to the right. - - **Between two z-scores**: Subtract the smaller probability from the larger one to find the probability of a value falling between two z-scores. - -## Example 1 - -To find the z-value corresponding to a cumulative probability, locate the probability in the table and find the associated z-score. - -To find the z-score for a cumulative probability of 0.975: - -- Look for 0.975 in the table. -- The closest value is 0.9750, which corresponds to z = 1.96 (row 1.9, column 0.06). - -Thus, the z-score for a cumulative probability of 0.975 is 1.96. - -## Example 2 - -To find the cumulative probability (p-value) for a given z-score, locate the z-score in the table and read the corresponding probability. - -To find the cumulative probability for z = -1.5: - -- Locate z = -1.5 in the table (row -1.5). -- Find the probability under column 0.00, which is 0.0668. - -Thus, the cumulative probability (p-value) for z = -1.5 is 0.0668. diff --git a/content/data-science/concepts/jupyter-magic-commands/jupyter-magic-commands.md b/content/data-science/concepts/jupyter-magic-commands/jupyter-magic-commands 2.md similarity index 100% rename from content/data-science/concepts/jupyter-magic-commands/jupyter-magic-commands.md rename to content/data-science/concepts/jupyter-magic-commands/jupyter-magic-commands 2.md diff --git a/content/data-science/concepts/jupyter-notebook-extensions/jupyter-notebook-extensions.md b/content/data-science/concepts/jupyter-notebook-extensions/jupyter-notebook-extensions 2.md similarity index 100% rename from content/data-science/concepts/jupyter-notebook-extensions/jupyter-notebook-extensions.md rename to content/data-science/concepts/jupyter-notebook-extensions/jupyter-notebook-extensions 2.md diff --git a/content/data-science/concepts/jupyter-notebook/jupyter-notebook.md b/content/data-science/concepts/jupyter-notebook/jupyter-notebook 2.md similarity index 100% rename from content/data-science/concepts/jupyter-notebook/jupyter-notebook.md rename to content/data-science/concepts/jupyter-notebook/jupyter-notebook 2.md diff --git a/content/data-science/concepts/one-hot-encoding/one-hot-encoding.md b/content/data-science/concepts/one-hot-encoding/one-hot-encoding 2.md similarity index 100% rename from content/data-science/concepts/one-hot-encoding/one-hot-encoding.md rename to content/data-science/concepts/one-hot-encoding/one-hot-encoding 2.md diff --git a/content/data-science/data-science.md b/content/data-science/data-science 2.md similarity index 100% rename from content/data-science/data-science.md rename to content/data-science/data-science 2.md diff --git a/content/data-science/data-science 3.md b/content/data-science/data-science 3.md new file mode 100644 index 00000000000..1d75663fbeb --- /dev/null +++ b/content/data-science/data-science 3.md @@ -0,0 +1,59 @@ +--- +Title: 'Data Science' # Required; this is the name that appears on the hub page for this language. Pay attention to capitalization and punctuation! +Description: 'Data Science is a multidisciplinary field that includes activities like data management, data collection, data analysis, and data visualization.' # Required; ideally under 150 characters and starts with the name of the topic (used in search engine results and content previews) +Codecademy Hub Page: 'https://www.codecademy.com/catalog/subject/data-science' # If codecademy.com doesn't have a hub page for this language, that's okay too. You can omit this field. +CatalogContent: # Please use course/path landing page slugs, rather than linking to individual content items. If listing multiple items, please put the most relevant one first + - 'learn-data-science' + - 'paths/data-science-foundations' +--- + +**Data Science** is a multidisciplinary field of study that includes activities like data management, data collection, data analysis, and data visualization. It incorporates skills from a broad range of disciplines that include computer science, statistics, mathematics, and visual design. + +## Applications + +Since the beginning of the 21st century, data science has been used in almost every field of industry to extract insights from data that may be leveraged in business decision-making and product development. These applications are largely related to fields of study rooted in data science, including: + +- Data Management + - Data Security + - Data Validation + - Data Cleaning + - Data Modelling + - Data Integration +- Data Use + - Data Visualization + - Data Analytics + - [Data Mining](https://www.codecademy.com/resources/docs/data-science/data-mining) + - Business Intelligence and Strategy +- [Artificial Intelligence](https://www.codecademy.com/resources/docs/ai) + - [Machine Learning](https://www.codecademy.com/resources/docs/ai/machine-learning) +- [Cloud and Distributed Computing](https://www.codecademy.com/resources/docs/cloud-computing) + +## Languages and Tools + +- [Python](https://www.codecademy.com/resources/docs/python) + - Matplotlib + - [Pandas](https://www.codecademy.com/resources/docs/pandas) + - Scikit-learn + - TensorFlow + - NLTK +- [R](https://www.codecademy.com/resources/docs/r) (ggplot2) +- [JSON](https://www.codecademy.com/resources/docs/general/json) +- Excel +- Tableau +- [RDF](https://www.codecademy.com/resources/docs/general/semantic-technologies/rdf) +- [SQL](https://www.codecademy.com/resources/docs/sql) +- [Jupyter Notebooks](https://www.codecademy.com/resources/docs/data-science/jupyter-notebook) +- MATLAB +- [XML](https://www.codecademy.com/resources/docs/general/xml) + +## History + +Many statisticians have argued that data science is not a new field, but rather another name for statistics. Considering this perspective, the history of data science would date as far back as the 5th century B.C., demonstrated by the Athenians who estimated the height of ladders needed to scale the walls of Platea by counting the bricks of the wall vertically in several areas, then multiplying the most frequent count by the height of a brick. + +In 1662, John Graunt produced _Natural and Political Observations Made Upon the Bills of Mortality_ in which he estimated the population of London by using annual funeral records, familial death rates, and average family size. + +Without the correlation to statistics involved, many consider John Tukey to be the inventor of data science where in March 1962 he published _The Future of Data Analysis_ where he described a field he called “data analysis,” which resembles modern data science. With advents in data processing and storage, applications of data science have accelerated in both complexity and popularity. + +## Concepts + +Some of the fundamental concepts and tools of data science are explored below: diff --git a/content/discrete-math/concepts/congruences/congruences.md b/content/discrete-math/concepts/congruences/congruences.md deleted file mode 100644 index 131d8035bf0..00000000000 --- a/content/discrete-math/concepts/congruences/congruences.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -Title: 'Congruences' -Description: 'Congruences refer to the relationship between two integers a and b when they have the same remainder after division by positive integer m that is greater than 1.' -Subjects: - - 'Computer Science' - - 'Discrete Math' -Tags: - - 'Arithmetic' - - 'Math' - - 'Logical' - - 'Logic' -CatalogContent: - - 'computer-science' - - 'paths/computer-science' ---- - -**Congruences** refer to the relationship between two integers, _a_ and _b_, that have the same remainder after division by a positive integer, _m_ (which is greater than 1). - -## _a_ divides _b_ - -If _a_ and _b_ are integers where a ≠ 0, then _a_ divides _b_ if an integer _c_ exists given that _b = ac_. - -Explanation: - -- When _a_ divides _b_, it is denoted as _a_ | _b_. -- _a_ is termed as a factor or divisor of _b_, while _b_ is termed as multiple of _a_. -- If _a_ | _b_ then _b_ / _a_ is an integer (According to _a_ divides _b_). -- If _a_ does not divide _b_, it is denoted with _a_ ⋮ _b_ - -## _a_ is congruent to _b_ mod _m_ - -If _a_ and _b_ are integers and _m_ is a positive integer, then _a_ is congruent to _b_ modulo _m_ if _m|(a − b)_. It is termed as Congruence Relation. - -Explanation: - -- The notation $$a \equiv b \pmod{m}$$ says that _a_ is congruent to _b_ modulo _m_. -- _m_ stands for modulus. -- Two integers are congruent `mod _m_` if and only if they have the same remainder on being divided by `_m_`. -- If _a_ is not congruent to _b_ modulo _m_ then it is denoted by $$a \not\equiv b \pmod{m}$$. - -### Example - -Suppose _a_ is 17 and _b_ is 5. To check if _a_ is congruent to _b_ modulo _m_: - -1. $$17 \equiv 5 \pmod{6}$$ -2. $$6 \text{ divides } 17 - 5 = 12$$ - -Solution: $$17 \equiv 5 \pmod{6}$$ because 6 divides $$17 - 5 = 12$$ - -## Congruence Properties - -Congruence properties pertain to the equivalence relation between integers where two numbers share the same remainder when divided by a fixed positive integer. - -### Linear Congruences - -Linear congruence is a special form of congruence denoted by $$ax \equiv b \pmod{m}$$, where _x_ denotes an integer variable. Similar to previous cases of congruence, _a_ and _b_ are integers and _m_ is modulo. - -Here, _m_ is a positive integer. Solution of congruence stands for all the values of integer _x_ which are satisfied. - -### Reflexive Property - -A congruence relation is reflexive if for any integers: - -```tex -a \equiv a \pmod{m} \text{for any integer } a \text{ and positive integer } m. -``` - -### Symmetric Property - -A congruence relation is symmetric if for any integers: - -```tex -\text{If } a \equiv b \pmod{m}, \text{ then } b \equiv a \pmod{m} \text{ for any integers } a, b \text{ and positive integer } m. -``` - -### Transitive Property - -A congruence relation is transitive if for any integers: - -```tex -\text{If } a \equiv b \pmod{m} \text{ and } b \equiv c \pmod{m}, \text{ then } a \equiv c \pmod{m} \text{ for any integers } a, b, c \text{ and positive integer } m. -``` diff --git a/content/discrete-math/concepts/enumeration/enumeration.md b/content/discrete-math/concepts/enumeration/enumeration.md deleted file mode 100644 index a7789946b49..00000000000 --- a/content/discrete-math/concepts/enumeration/enumeration.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -Title: 'Enumeration' -Description: 'Enumeration is a complete, ordered listing of all the items in a collection.' -Subjects: - - 'Computer Science' - - 'Discrete Math' -Tags: - - 'Arithmetic' - - 'Math' - - 'Logical' - - 'Logic' -CatalogContent: - - 'computer-science' - - 'paths/computer-science' ---- - -**Enumeration** is another word for count. In the context of mathematics, enumerating is a type of counting given a specified event or situation. An enumeration is a complete, ordered listing of all the items in a collection. When speaking in the context of mathematics and computer science, listing all the elements of a set comes into play. - -**Counting Theory** is a part of discrete mathematics that deals with counting the number of possible outcomes of a given event. Being an essential element of probability, it tries to answer an abstract question, "How many?" - -## Preliminaries: On Choices - -It is said that in order to combine numbers correctly, it's best to look for the words `AND` and `OR` in the description of the sequence of choices available. - -Some notes on `"AND"`: - -- Corresponds to the Cartesian product of sets. -- If one element of the set A `AND` one element of the set B is chosen, then this is equivalent to choosing one element of the `Cartesian product of A and B`. - -Some notes on `OR`: - -- Corresponds to the union of sets. -- If an element of the set A `OR` one element of the set B is chosen, then this is equivalent to choosing one element of the union of A and B. - -It is very useful to describe a choice sequence for constructing the set of objects of interest by paying close attention to the words `"AND"` and `"B"`. - -## Fundamental Counting Principle - -The fundamental counting principle states that the total number of outcomes of two or more independent events is the product of the number of outcomes of each individual event. - -## Example - -Suppose there are 3 shirts (call them `A`, `B`, and `C`), and 4 pairs of pants (call them `w`, `x`, `y`, and `z`). There will be `3x4=12` possible outfits: - -```plaintext -Aw, Ax, Ay, Az, -Bw, Bx, By, Bz, -Cw, Cx, Cy, Cz -``` - -## Principle of Inclusion and Exclusion (The Subtraction Rule) - -The principle of inclusion and exclusion is an approach that derives the method of finding the number of elements in the union of two (2) finite sets. - -In the context of combinations and probability, the necessity of finding a counting method in order to make sure that an object is not counted twice is wanting. - -The formula (ꓴ is "AND", ꓵ is "OR"): - -```tex -n(A ꓴ B) = n(A) + n(B) - n(A ꓵ B) -``` - -The exclusion of the intersection of the sets addresses the problem or question of duplication. - -## Product Rule - -The rule states that if there are `n(A)` ways to do `A` and `n(B)` ways to do `B`, then the number of ways to do `A` and `B` is `n(A) x n(B)`. This is true if the number of ways of doing `A` and `B` are independent; the number of choices for doing `B` is the same regardless of which choice is made for `A`. - -The general take, however: - -There are `n(A) x n(B) x n(C)` ways to do `A` and `B` and `C`. - -## Sum Rule - -The rule states that if there are `n(A)` ways to do `A` and, distinct from them, `n(B)` ways to do `B`, then the number of ways to do `A` or `B` is `n(A) + n(B)`. - -And, the general rule: - -There are `n(A) + n(B) + n(C)` ways to do `A` or `B` or `C`. - -## The Division Rule - -There are `n/d` ways to do a task if it can be done using a procedure that can be carried out in `n` ways, where there are `d` corresponding outcomes per group. diff --git a/content/discrete-math/concepts/number-bases/number-bases.md b/content/discrete-math/concepts/number-bases/number-bases.md deleted file mode 100644 index 3e5a078eec2..00000000000 --- a/content/discrete-math/concepts/number-bases/number-bases.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -Title: 'Number Bases' -Description: 'Number Bases are diverse systems for representing and expressing numbers.' -Subjects: - - 'Computer Science' - - 'Discrete Math' -Tags: - - 'Arithmetic' - - 'Logic' - - 'Logical' - - 'Math' - - 'Numbers' -CatalogContent: - - 'computer-science' - - 'paths/computer-science' ---- - -**Number Bases** are diverse systems for representing and expressing numbers. Each base defines the number of digits used to represent a value in that specific system. - -## Types of Bases - -A base can be any whole number greater than 1. The four most commonly used number bases in a computer system are: - -- Binary (Base 2) -- Octal (Base 8) -- Decimal (Base 10) -- Hexadecimal (Base 16) - -### Binary - -[Binary](https://www.codecademy.com/resources/docs/general/binary) is a number system that uses a base of 2. A number in binary can only be represented by `0`'s and `1`'s. In computer languages, the notation for representing binary numbers is leading `0b`. For example, `0b1010` is a binary number. - -### Octal - -Octal is a number system that uses a base of 8. A number in octal can only be represented by eight digits `0-7`. In computer languages, the notation for representing octal numbers is leading `0o`. For example, `0o0176` is an octal number. - -### Decimal - -Decimal is the most common number system that uses a base of 10. A number in decimal contains digits `0-9`. In computer languages, by default, there is no notation required to represent decimal numbers. For example, `9801` is a decimal number. - -### Hexadecimal - -[Hexadecimal](https://www.codecademy.com/resources/docs/general/hexadecimal) is a number system that uses a base of 16. The first ten digits of a hexadecimal number contain digits `0-9` and the remaining six digits contain letters `A-F` (not case sensitive). A common notation of hexadecimal numbers is prefixing with `0x`. For example, `0xA63F` is a hexadecimal number. - -## Converting Between Bases - -Converting between number bases requires two key concepts: the place value system and the digit representation. - -In the place value system, each digit's value is determined by its position within the number. Each position represents a value based on the number's base raised to an exponent. Starting from the rightmost digit, the exponent begins at zero and increases by one as we move to the left. For instance, in decimal (base 10), `999` can be represented as `9 * 10^2 + 9 * 10^1 + 9 * 10^0`. - -Digit representation refers to the symbols used to express numbers in a specific number system. For example, in hexadecimal, the number `15` is represented as `F`. - -### Binary to Other Bases - -- To convert binary (base-2) to decimal (base-10), multiply each digit by 2 raised to its respective power and sum them up. For example, `0b1001` in binary is `1 * 2^3 + 0 * 2^2 + 0 * 2^1 + 1 * 2^0 = 9` in decimal. -- To convert binary to octal (base-8), group the binary digits into sets of three (from the right) and convert each group to its octal equivalent. For example, `0b001100` in binary is grouped as `001 100`, and the octal equivalent is `0o14`. -- To convert binary to hexadecimal (base-16), group the binary digits into sets of four (from the right) and convert each group to its hexadecimal equivalent. For example, `0b10011111` in binary is grouped as `1001 1111`, and the hexadecimal equivalent is `0x9F`. - -### Octal to Other Bases - -- To convert octal (base-8) to decimal, multiply each digit by 8 raised to its respective power and sum them up. For example, `0o67` in octal is `6 * 8^1 + 7 * 8^0 = 55` in decimal. -- To convert octal to binary, convert each octal digit to its 3-bit binary equivalent. For example, `0o67` in octal is `110 111` in binary. -- To convert octal to hexadecimal, first convert the octal number to binary and then group the binary digits into sets of four and convert each group to its hexadecimal equivalent. - -### Decimal to Other Bases - -- To convert decimal (base-10) to binary, repeatedly divide the decimal number by `2`, keeping track of each remainder. The binary equivalent is obtained by reading the remainders in reverse order. - -For example, to convert `27` to binary: - -```plaintext -27 / 2 = 13 remainder 1, -13 / 2 = 6 remainder 1, -6 / 2 = 3 remainder 0, -3 / 2 = 1 remainder 1, -1 / 2 = 0 remainder 1 -``` - -The binary equivalent is `11011`. - -- To convert decimal to octal, repeatedly divide the decimal number by `8`, keeping track of each remainder. The octal equivalent is obtained by reading the remainders in reverse order. -- To convert decimal to hexadecimal, repeatedly divide the decimal number by `16`, keeping track of each remainder. The hexadecimal equivalent is obtained by reading the remainders in reverse order, with `10` represented as `A`, `11` as `B`, and so on. - -### Hexadecimal to Other Bases - -- To convert hexadecimal (base-16) to decimal, multiply each digit by 16 raised to its respective power and sum them up. For example, `0x3F` in hexadecimal is `3 * 16^1 + 15 * 16^0 = 63` in decimal. -- To convert hexadecimal to binary, convert each hexadecimal digit to its 4-bit binary equivalent. For example, `0x3F` in hexadecimal is `0011 1111` in binary. -- To convert hexadecimal to octal, first convert the hexadecimal number to binary and then group the binary digits into sets of three and convert each group to its octal equivalent. diff --git a/content/discrete-math/concepts/proofs/proofs.md b/content/discrete-math/concepts/proofs/proofs.md deleted file mode 100644 index dca7ddf67ad..00000000000 --- a/content/discrete-math/concepts/proofs/proofs.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -Title: 'Proofs' -Description: 'A proof is a series of statements intended to demonstrate some conclusion.' -Subjects: - - 'Computer Science' - - 'Discrete Math' -Tags: - - 'Arithmetic' - - 'Math' - - 'Logical' - - 'Logic' -CatalogContent: - - 'discrete-math' ---- - -A **proof** is a series of statements intended to demonstrate some conclusion. Each step in a proof must follow logically from previous steps in accordance with recognized rules of logic and mathematical reasoning. - -In discrete mathematics, proofs are used to establish the truth or falsity of important claims. When an important claim is proven, it becomes known as a theorem. - -## Conjecture - -When an important mathematical claim is suspected to be true, but has not yet been proven, it is known as a conjecture. - -Mathematical exploration and discovery are driven by the formulation and investigation of conjectures. - -## Proof Techniques - -A variety of logical and mathematical techniques are employed in proofs. A single proof may contain multiple of such techniques. Some of these techniques are described in the term pages below. diff --git a/content/discrete-math/concepts/proofs/terms/conditional-proof/conditional-proof.md b/content/discrete-math/concepts/proofs/terms/conditional-proof/conditional-proof.md deleted file mode 100644 index e6f21e9a562..00000000000 --- a/content/discrete-math/concepts/proofs/terms/conditional-proof/conditional-proof.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -Title: 'Conditional Proof' -Description: 'Proving a conditional statement by assuming the antecedent and showing that the consequent follows.' -Subjects: - - 'Computer Science' - - 'Discrete Math' -Tags: - - 'Arithmetic' - - 'Logic' - - 'Logical' - - 'Math' -CatalogContent: - - 'computer-science' - - 'paths/computer-science' ---- - -**Conditional Proof** is a technique used in mathematical proofs to prove a conditional statement. - -A conditional statement is a statement of the form 'if..., then...'. The **antecedent** (also called the hypothesis or premise) is the condition of the conditional statement: the part following 'if'. The **consequent** (also called the conclusion) is what is claimed to follow from the condition: the part following 'then'. - -Conditional proof works by assuming the antecedent of the conditional, and then showing that the consequent follows. By assuming the antecedent and then proving that the consequent follows, given that assumption, the entire conditional is shown to be true. - -## Steps for Conditional Proof - -1. Supposition for Conditional Proof: Assume that the antecedent is true. -2. Prove the consequent: Prove that the consequent is true. - -## Example - -The following statement will be proven below: If 4 is a factor of x, then 2 is a factor of x. - -### Supposition for Conditional Proof - -```plaintext -Assume, for conditional proof, that for some integer n, where n ≥ 0, x / 4 = n. -``` - -### Prove the Consequent - -```plaintext -First, perform some basic algebraic manipulation on the assumption: - -x / 4 = n [by assumption above] -x = 4n [multiplying both sides by 4] -x / 2 = 4n / 2 [dividing both sides by 2] -x / 2 = 2n [simplifying right-hand side] - -Since n is an integer value greater than or equal to 0, 2n is also an integer value greater than or equal to 0. - -It follows that x / 2 is equal to an integer value greater than or equal to 0. By definition, 2 is therefore a factor of x. -``` diff --git a/content/discrete-math/concepts/proofs/terms/proof-by-cases/proof-by-cases.md b/content/discrete-math/concepts/proofs/terms/proof-by-cases/proof-by-cases.md deleted file mode 100644 index c83b1ea6026..00000000000 --- a/content/discrete-math/concepts/proofs/terms/proof-by-cases/proof-by-cases.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -Title: 'Proof by Cases' -Description: 'Proving a statement by showing that it holds in each of a set of mutually exhaustive cases.' -Subjects: - - 'Computer Science' - - 'Discrete Math' -Tags: - - 'Arithmetic' - - 'Logic' - - 'Logical' - - 'Math' -CatalogContent: - - 'computer-science' - - 'paths/computer-science' ---- - -**Proof by Cases** is a technique used in mathematical proofs to demonstrate a statement by showing that it is true in each of a set of cases. These cases must be mutually exhaustive, meaning that they cover all possibilities, so that at least one of them must be true. By showing that the statement holds no matter which case is true, it is guaranteed that the statement is true. - -Proof by Cases is also sometimes known as **exhaustive proof**, which refers to the fact that the statement is proven in a set of mutually exhaustive cases. - -## Steps for Proof by Cases - -1. _Mutual exhaustion_: Show that there is a set of cases that is mutually exhaustive. -2. _Prove each case_: Prove that the statement is true in each of the provided cases. - -## Example - -The statement below will be demonstrated by a Proof by Cases. - -```pseudo -For any integer k, the product 3k^2 + k is even. -``` - -### Mutual Exhaustion - -```pseudo -Any integer is either odd or even. So, there are two cases to consider: (1) k is odd, and (2) k is even. -``` - -### Prove Each Case - -```pseudo -First, consider case (1), in which k is odd. - -If k is odd, then k = 2n + 1, for some integer n. - -Now, perform some algebraic manipulation on the expression 3k^2 + k: - -3k^2 + k = 3(2n+1)^2 + 2n + 1 [substitute 2n + 1 for k] - = 3(4n^2 + 4n + 1) + 2n + 1 [square (2n+1)] - = 12n^2 + 12n + 3 + 2n + 1 [multiply 3 into (4n^2 + 4n + 1)] - = 12n^2 + 14n + 4 [add like terms] - = 2(6n^2 + 7n + 2) [factor out 2] - -When n is an integer, 6n^2 + 7n + 2 is also an integer. Therefore 2(6n^2 + 7n + 2) is equal to 2 times some integer. As 2 times any integer is even, it follows that 2(6n^2 + 7n + 2) is even. Therefore 3k^2 + k is even. - -Next, consider case (2), in which k is even. - -If k is even, then k = 2n, for some integer n. - -Now, perform some algebraic manipulation on the expression 3k^2 + k: - - 3k^2 + k = 3(2n)^2 + 2 [substitute 2n for k] - = 12n^2 + 2 [simplify 3(2n)^2] - = 2(6n^2 + 1) [factor out 2] - -When n is an integer, 6n^2 + 1 is also an integer. Therefore 2(6n^2 + 1) is equal to 2 times some integer. As 2 times any integer is even, it follows that 2(6n^2 + 1) is even. Therefore 3k^2 + k is even. - -Therefore, in either case, whether k is odd or even, 3k^2 + k is even. It follows that for any integer k, the product 3k^2 + k is even. -``` diff --git a/content/discrete-math/concepts/proofs/terms/proof-by-contradiction/proof-by-contradiction.md b/content/discrete-math/concepts/proofs/terms/proof-by-contradiction/proof-by-contradiction.md deleted file mode 100644 index fb6b1468762..00000000000 --- a/content/discrete-math/concepts/proofs/terms/proof-by-contradiction/proof-by-contradiction.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -Title: 'Proof by Contradiction' -Description: 'Proving a statement by assuming that it is false and showing a contradiction follows on that assumption.' -Subjects: - - 'Computer Science' - - 'Discrete Math' -Tags: - - 'Arithmetic' - - 'Logic' - - 'Logical' - - 'Math' -CatalogContent: - - 'discrete-math' ---- - -**Proof by Contradiction** is a technique used in mathematical proofs to demonstrate a statement by assuming that it is false and then showing that a contradiction follows on that assumption. By proving that a contradiction would occur if a statement were false, the truth of that statement is thereby demonstrated. - -Proof by contradiction is also sometimes known as **indirect proof** or **reductio ad absurdum**, meaning to reduce to an absurdity. - -## Steps for Proof by Contradiction - -1. _Suppose the negation_: Assume that the statement is false. -2. _Prove a contradiction_: Prove that a contradiction follows, given the assumption. - -## Example - -The following example uses proof by contradiction to prove there are infinitely many primes. - -### Suppose the Negation - -```plaintext -Assume, for proof by contradiction, that there are only finitely many primes. -``` - -### Prove a Contradiction - -```plaintext -By assumption, there is some finite number of primes, n. Label the series of primes p1, p2, ..., pn. - -Now let P be the product of all primes plus 1: P = p1 * p2 ... * pn + 1. - -The Prime Factorization Theorem states that any integer greater than 1 is either prime or equal to a product of prime numbers. Either way, any integer greater than 1 has at least one prime factor (either itself or some combination of others). - -Let pm be an arbitrary prime factor of P. By definition, P = p1 * p2 ... * pn + 1. Therefore P / pm = (p1 * p2 ... * pn + 1) / pm. - -Since p1, p2, ..., pn contains all primes, pm equals some value in p1, p2, ..., pn. As pm equals some prime in p1, p2, ..., pn, it follows that ((p1 * p2 ... * pn + 1) / pm) is equal to some integer value plus 1/pm. Therefore ((p1 * p2 ... * pn + 1) / pm) is not equal to an integer value. Therefore pm is not a factor of P, since it does not divide P evenly. - -Therefore there is a contradiction: pm both is and is not a factor of P. - -Since assuming there are finitely many primes leads to a logical contradiction, there must be infinitely many primes. -``` diff --git a/content/discrete-math/concepts/proofs/terms/proof-by-induction/proof-by-induction.md b/content/discrete-math/concepts/proofs/terms/proof-by-induction/proof-by-induction.md deleted file mode 100644 index a448af3417e..00000000000 --- a/content/discrete-math/concepts/proofs/terms/proof-by-induction/proof-by-induction.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -Title: 'Proof by Induction' -Description: 'Proves a universal generalization using the hypothesis that the previous element in a series has some property.' -Subjects: - - 'Computer Science' - - 'Mathematics' -Tags: - - 'Algorithms' - - 'Math' - - 'Logic' -CatalogContent: - - 'discrete-math' ---- - -**Proof by induction** is a technique used in discrete mathematics to prove universal generalizations. A universal generalization is a claim which says that every element in some series has some property. For example, the following is a universal generalization: - -```plaintext -For any integer n ≥ 3, 2^n > 2n. -``` - -The above statement says that every element `n` in the series of integers beginning with `3` has the property that `2^n > 2n`. - -A proof by mathematical induction consists of two steps. The steps of a mathematical induction will be illustrated below by proving the example universal generalization just given. - -### 1. Base Step - -In the base step (also known as the base case, initial case, or basis step), the first element or elements in the series are shown to have the relevant property. For example: - -```plaintext -2^3 = 8. 2*3 = 6. 8 > 6. Therefore when n = 3, 2^n > 2n. -``` - -The first element in the series of integers beginning with `3` is `3`. Above, this element is shown to have the relevant property. - -### 2. Inductive Step - -In the inductive step (also known as the step case), it is shown that if the previous element has the relevant property, then the succeeding element has the relevant property. Generally, this is done by assuming that the previous element has the property (this assumption is known as the inductive hypothesis), and then showing that the next element must also have the property. This proof technique is known as conditional proof. Continuing the example proof: - -```plaintext -Assume for conditional proof that for some n, 2^n > 2n. Now we will prove that 2^(n+1) > 2(n+1). - -First, we perform some algebraic manipulation on the expression '2^n+1': - - 2^(n+1) = 2^n * 2^1 [Product Rule for exponents] - = 2^n * 2 [Simplify 2^1] - -So what needs to be proved is that 2^n * 2 > 2(n+1). Factoring out 2 from both sides, we need to show that 2^n > n+1. - -By the inductive hypothesis, 2^n > 2n. Now, 2n > n+1 (for any n ≥ 1). By the transitivity of '>' 2^n > n+1. This completes the inductive step. -``` - -The inductive step above shows that no matter the value of `n` in the series, if `2^n > 2n`, then `2^(n+1) > 2(n+1)`. - -### The Logic of Mathematical Induction - -Why do the base step and the inductive step together demonstrate the truth of a universal generalization? The logic of a mathematical induction can be pictured as a series of dominoes falling. In the base step, the first domino is knocked over. In the inductive step, it is shown that any successive domino will be knocked over by the domino falling behind it. Thus, once the first domino is knocked over, the second will be knocked over, then the third, and so on for all the dominoes. - -In less metaphorical terms, the base step shows that the first `n` elements have the relevant property. It then follows from the inductive step that the element at `n + 1` has that property. Now the inductive step can be applied again on the element at `n + 1` to show that the element at `n + 2` has the property. Since this can be done indefinitely, the entire series is shown to have the relevant property. - -## Proof by Induction and Recursion - -There is a close relationship between recursion and mathematical induction. A recursive function is defined by one or more base cases plus a recursive call, in which larger values of the function can be derived from smaller values. - -Similarly, mathematical induction involves one or more base cases plus an inductive step in which the properties of later values in a series can be established from earlier values. diff --git a/content/discrete-math/concepts/proofs/terms/proof-by-strong-induction/proof-by-strong-induction.md b/content/discrete-math/concepts/proofs/terms/proof-by-strong-induction/proof-by-strong-induction.md deleted file mode 100644 index 170d89cc8c0..00000000000 --- a/content/discrete-math/concepts/proofs/terms/proof-by-strong-induction/proof-by-strong-induction.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -Title: 'Proof by Strong Induction' -Description: 'Proves a universal generalization using the hypothesis that all previous elements in a series have the same property.' -Subjects: - - 'Computer Science' - - 'Discrete Math' -Tags: - - 'Arithmetic' - - 'Logic' - - 'Logical' - - 'Math' -CatalogContent: - - 'computer-science' - - 'paths/computer-science' ---- - -**Proof by strong induction** is a mathematical technique for proving universal generalizations. It differs from ordinary mathematical induction (also known as weak mathematical induction) with respect to the inductive step. - -In a weak mathematical induction, the inductive step involves showing that if some element _n_ has a property, then the successor element _n + 1_ must also have that property. In a strong mathematical induction, the inductive step involves showing that if all elements up to and including _n_ have some property, then _n + 1_ has that property as well. - -## Steps for Strong Induction - -1. _Base Step_: Prove that the first element or elements in the series have some property. -2. _Inductive Step_: Prove that if _n_ and all elements before n have the relevant property, then _n + 1_ has that property. - -## Example - -The following proposition will be proven by strong induction: - -```plaintext -For all x such that x ≥ 2, 2(x-1) - (x-2) = x. -``` - -Base Step: - -The first element is where _x = 2_. Therefore, it must be shown that _2(x - 1) - (x - 2) = x_, where _x = 2_: - -```plaintext -2(2 - 1) - (2 - 2) = 2(1) - (0) = 2 - 0 = 2 -Both sides are equal to 2. Thus, the statement is true at x = 2. -``` - -Inductive Step: - -In the inductive step, it must be shown that if, for any value _x_ between _2_ and _k_ (inclusive), _2(x - 1) - (x - 2) = x_, then at _x = k + 1, 2(x - 1) - (x - 2) = x_. - -This conditional will be proven by assuming the antecedent (this assumption is called the inductive hypothesis) and showing the consequent: - -```plaintext -Inductive Hypothesis: Suppose that for all x such that 2 ≤ x ≤ k, 2(x - 1) - (x - 2) = x. -To be proven: 2((k + 1) - 1) - ((k + 1) - 2) = k + 1. - -First, we will rearrange the left-hand of the expression above: - 2((k + 1) - 1) - ((k + 1) - 2) = 2(k + 1 - 1) - (k + 1 - 2) [removing extra parentheses] - = 2(k - 1 + 1) - (k - 2 + 1) [rearranging within parentheses] - = 2(k - 1) + 2 - (k - 2 + 1) [factoring 2 into the left parenthesis] - = 2(k - 1) + 2 - (k - 2) - 1 [rearranging the right parenthesis] - = 2(k - 1) - (k - 2) + 1 [adding numerical terms] - -Now, by the Inductive Hypothesis, 2(k - 1) - (k - 2) = k. We therefore substitute 'k' for '2(k-1) - (k-2)' in the rearranged expression above: - 2((k + 1) - 1) - ((k + 1) - 2) = k + 1 [substitution from Inductive Hypothesis] - -Having shown that 2((k + 1) - 1) - ((k + 1) - 2) = k + 1, this completes the inductive step and the proof. -``` - -Although the example above uses strong mathematical induction, the same strategy could be applied using weak mathematical induction, since the only value of the inductive hypothesis used was at _x = k_ (there was no need to use any values smaller than _k_). - -## The Logic of Strong Induction - -Why do the base step and the inductive step together demonstrate the truth of a universal generalization? - -The base step shows that the first _n_ elements in the series have the relevant property. Since all the elements prior to the element at _n + 1_ have the property, it then follows by the inductive step that the element at _n + 1_ also has the property. Similarly, since all elements prior to the element at _n + 2_ have the property, the inductive step shows that the element at _n + 2_ does as well. Since this can be done indefinitely, the entire series is shown to have the relevant property. diff --git a/content/discrete-math/discrete-math.md b/content/discrete-math/discrete-math.md deleted file mode 100644 index deb73c605b9..00000000000 --- a/content/discrete-math/discrete-math.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -Title: 'Discrete Math' -Description: 'Discrete math is a fundamental branch of mathematics that provides the foundation for various concepts and techniques used in computer science and problem-solving.' -Codecademy Hub Page: 'https://www.codecademy.com/catalog/subject/computer-science' -CatalogContent: - - 'computer-science' ---- - -**Discrete mathematics** is a fundamental branch of mathematics that provides the foundation for various concepts and techniques used in computer science and problem-solving. It encompasses a range of topics that include sets, propositions, relations, functions, proofs, logic and number theory. - -## Advantages - -Discrete mathematics offers the following advantages to the user: - -- **Efficiency:** Discrete mathematics enables the development of efficient algorithms and data structures, optimizing computational processes and reducing time complexity. This is crucial for handling large-scale data and solving complex problems in computer science and other domains. -- **Problem-solving:** Discrete mathematics equips individuals with problem-solving skills and logical reasoning. It enables the analysis and process of breaking down complex problems into smaller, more manageable components, which in turn facilitates the development of effective solutions. -- **Algorithm Design:** Discrete mathematics include techniques such as graph theory, combinatorics, and optimization, which are essential for developing algorithms that efficiently solve various computational problems. -- **Data Representation:** Discrete mathematics offers different data structures, such as arrays, lists, trees, and graphs, for organizing and representing data. These structures enable efficient storage, retrieval, and manipulation of information in computer systems. -- **Cryptography and Security:** In Discrete mathematics, concepts like number theory, modular arithmetic, and encryption algorithms form the basis of cryptographic systems used for secure transactions, data privacy, and information security. -- **Logic and Reasoning:** Discrete mathematics entails propositional and predicate logic, which are fundamental in computer science and critical for designing and verifying the correctness of software and hardware systems. -- **Foundational Knowledge:** Discrete mathematics serves as a fundamental building block for various disciplines, including computer science, information theory, operations research, and telecommunications. It provides the underlying concepts and techniques necessary for advanced study and research in these fields. diff --git a/content/emojicode/concepts/comments/comments.md b/content/emojicode/concepts/comments/comments.md deleted file mode 100644 index 41510d8f46a..00000000000 --- a/content/emojicode/concepts/comments/comments.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -Title: '💭 Comments' -Description: 'A comment is a piece of text within a program that is not executed. It can be used to provide additional information to aid in understanding the code. There are two types of comments in Emojicode. In Emojicode, single-line comments are made with 💭. Any text after the 💭 that is on the same line is not executed. shell 💭 The next line outputs "Hello" 😀 🔤Hello🔤❗️ ' -Subjects: - - 'Computer Science' -Tags: - - 'Comments' - - 'Documentation' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -A comment is a piece of text within a program that is not executed. It can be used to provide additional information to aid in understanding the code. - -There are two types of comments in Emojicode. - -## Single-line Comments - -In Emojicode, single-line comments are made with `💭`. Any text after the `💭` that is on the same line is not executed. - -```shell -💭 The next line outputs "Hello" -😀 🔤Hello🔤❗️ -``` - -## Multiline Comments - -Multiline comments are created with `💭🔜` and `🔚💭`. Any text in between is not executed. - -```shell -💭🔜 -This is a comment. -It will be ignored by the compiler. -🔚💭 -``` - -## Example - -Here's a whole Emojicode program with comments: - -```shell -💭🔜 -Emojicode is created by: -Theo Weidmann -🔚💭 - -🏁 🍇 - 😀 🔤Hello World!🔤❗️ - 💭 Output: Hello World! -🍉 -``` diff --git a/content/emojicode/concepts/conditionals/conditionals.md b/content/emojicode/concepts/conditionals/conditionals.md deleted file mode 100644 index 1ffdeece397..00000000000 --- a/content/emojicode/concepts/conditionals/conditionals.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -Title: '↪️ Conditionals' -Description: 'Conditionals take an expression, which is code that evaluates to determine a value, and checks if it is 👍 or 👎. If it’s 👍, we can tell our program to do one thing — we can even account for 👎 to do another. As we write more complex programs, conditionals allow us to address multiple scenarios and make our programs more robust. The ↪️ statement is very important. It allows for conditional execution of a code block. The whole syntax is: - If the condition evaluates to 👍, the code block will be executed. - And if it evaluates to 👎, it’ll be ignored. This example will display "a is greater than b" if the content for variable a is greater than b: shell' -Subjects: - - 'Computer Science' -Tags: - - 'If' - - 'Else' - - 'Control Flow' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -Conditionals take an expression, which is code that evaluates to determine a value, and checks if it is `👍` or `👎`. If it’s `👍`, we can tell our program to do one thing — we can even account for `👎` to do another. - -As we write more complex programs, conditionals allow us to address multiple scenarios and make our programs more robust. - -## If Statement - -The ↪️ statement is very important. It allows for conditional execution of a code block. The whole syntax is: - -- If the condition evaluates to `👍`, the code block will be executed. -- And if it evaluates to `👎`, it'll be ignored. - -This example will display "a is greater than b" if the content for variable `a` is greater than `b`: - -```shell -↪️ a ▶️ b 🍇 - 😀 🔤a is greater than b🔤❗️ -🍉 -``` - -## Else Statement - -The `🙅` extends an `↪️` statement to execute an additional code block in case the expression in the `if` statement evaluates to false. - -For example, the following code would display "a is greater than b" if `a` is greater than `b`, and `a is not greater than b` otherwise: - -```bash -↪️ a ▶️ b 🍇 - 😀 🔤a is greater than b🔤❗️ -🍉 -🙅 🍇 - 😀 🔤a is not greater than b🔤❗️ -🍉 -``` - -**Note:** The `🙅` statements is only executed if the `↪️` statement evaluated to `👎`, and if all `🙅↪️` statements evaluated to `👎` too. diff --git a/content/emojicode/concepts/data-types/data-types.md b/content/emojicode/concepts/data-types/data-types.md deleted file mode 100644 index b5d9c884a7f..00000000000 --- a/content/emojicode/concepts/data-types/data-types.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -Title: 'Data Types' -Description: 'All programming languages designate certain "types" of data. This helps the operating system and computer hardware allocate memory based on the type of data that is going to be stored. Emojicode, being a very type-safe language, takes great care to ensure that data types are understood, by both you and the compiler. Here are a few basic data types in Emojicode: 🔢, 💯, 🔡, and 👌.' -Subjects: - - 'Computer Science' -Tags: - - 'Data Types' - - 'Booleans' - - 'Integers' - - 'Strings' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -All programming languages designate certain "types" of data. This helps the operating system and computer hardware allocate memory based on the type of data that is going to be stored. - -Emojicode, being a very type-safe language, takes great care to ensure that data types are understood, by both you and the compiler. - -Here are a few basic data types in Emojicode: - -| Type | Description | -| ---- | ---------------------- | -| `🔢` | Integer numbers | -| `💯` | Decimal numbers | -| `🔡` | Text strings | -| `👌` | Truth values `👍`/`👎` | - -## 🔲 Type Casting - -Type casting is a way to determine whether a value is of a given type at run-time and to treat the value as an instance of this type. - -```emojic -🔲 value type -``` - -The `value` is the value to be casted to `type`: - -- If `value` can be casted to `type`, then `value` is returned as `type`. -- If it can't, then no value is returned. - -Type casting is implemented with the `🔲` statement: - -```emojic -🔲 hello 🔡 💭 Tries to cast txt to 🔡 -🔲 world 🐟 💭 Tries to cast a to 🐟 -``` diff --git a/content/emojicode/concepts/dictionaries/dictionaries.md b/content/emojicode/concepts/dictionaries/dictionaries.md deleted file mode 100644 index 51b1fd29bf6..00000000000 --- a/content/emojicode/concepts/dictionaries/dictionaries.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -Title: '🍯 Dictionaries' -Description: '🍯, or dictionary or hash map in other languages, is an ordered set of value pairs: pseudo 🔤key🔤 ➡️ 🔤value🔤 It provides a way to map pieces of data to each other, and allows for quick access to values associated to keys. Keys must be unique in dictionaries, but the values don’t have to be. emojic 🏁 🍇' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Dictionaries' - - 'Data Types' - - 'Arrays' - - 'Lists' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -🍯, or dictionary or hash map in other languages, is an ordered set of value pairs: - -```pseudo -🔤key🔤 ➡️ 🔤value🔤 -``` - -It provides a way to map pieces of data to each other, and allows for quick access to values associated to keys. Keys must be unique in dictionaries, but the values don’t have to be. - -## Syntax - -```emojic -🏁 🍇 - 🍿 - 🔤fr🔤 ➡️ 🔤Salut!🔤 - 🔤it🔤 ➡️ 🔤Ciao!🔤 - 🔤de🔤 ➡️ 🔤Guten Tag!🔤 - 🔤en🔤 ➡️ 🔤Hey!🔤 - 🔤es🔤 ➡️ 🔤Hola!🔤 - 🔤cn🔤 ➡️ 🔤你好!🔤 - 🔤jp🔤 ➡️ 🔤こんにちは!🔤 - 🍆 ➡️ dictionary -🍉 -``` - -`🍿` is used to list key value pairs, where each key is separated from its value with a `➡️`. This will create an instance of `🍯`, which is stored into dictionary. - -`🍯` is implemented as a hash table and is **O(1)** on average and **O(n)** in worst case. diff --git a/content/emojicode/concepts/for-in/for-in.md b/content/emojicode/concepts/for-in/for-in.md deleted file mode 100644 index ee7116da5f2..00000000000 --- a/content/emojicode/concepts/for-in/for-in.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -Title: '🔂 For In' -Description: 'The 🔂 statement allows you to quickly iterate over an instance, that is repeatedly retrieving values from it until there are no more values to provide. For example, you can iterate over an 🍨 instance and you’ll receive all elements contained in the list. emojic 🏁 🍇 🍿 🔤cookies🔤 🔤milk🔤 🔤eggs🔤 🔤blueberries🔤 🍆 ➡️ grocery 🔂 item grocery 🍇 😀 item❗️' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'For' - - 'Loops' - - 'Control Flow' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -The `🔂` statement allows you to quickly iterate over an instance, that is repeatedly retrieving values from it until there are no more values to provide. - -For example, you can iterate over an `🍨` instance and you’ll receive all elements contained in the list. - -## Syntax - -```emojic -🏁 🍇 - 🍿 🔤cookies🔤 🔤milk🔤 🔤eggs🔤 🔤blueberries🔤 🍆 ➡️ grocery - - 🔂 item grocery 🍇 - 😀 item❗️ - 🍉 -🍉 -``` - -The output would be: - -```bash -cookies -milk -eggs -blueberries -``` - -In this example, the code block will be repeated for every value of the list and the values are printed. The type of `item` is naturally `🔡`. diff --git a/content/emojicode/concepts/hello-world/hello-world.md b/content/emojicode/concepts/hello-world/hello-world.md deleted file mode 100644 index 9403c87deb2..00000000000 --- a/content/emojicode/concepts/hello-world/hello-world.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -Title: '😀 Hello World' -Description: 'We write Emojicode programs in files with the extension .emojic or .🍇. Almost all the code in an Emojicode program will live inside a 🏁 block. A block is a collection of code. The 🏁 block indicates all the code that should run when the file is executed. Within our larger program, we can indicate one or more blocks of code with 🍇 🍉 code blocks: - 🍇 to indicate the start of the code block - 🍉 to indicate the end of the code block So a basic Emojicode file will have the following structure: pseudo' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Syntax' - - 'Print' - - 'Strings' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -We write Emojicode programs in files with the extension **.emojic** or **.🍇**. - -Almost all the code in an Emojicode program will live inside a `🏁` block. A block is a collection of code. The `🏁` block indicates all the code that should run when the file is executed. - -Within our larger program, we can indicate one or more blocks of code with `🍇` `🍉` code blocks: - -- `🍇` to indicate the start of the code block -- `🍉` to indicate the end of the code block - -So a basic Emojicode file will have the following structure: - -```pseudo -🏁 🍇 - Some code go here -🍉 -``` - -To print in Emojicode, we use the `😀` `❗️` method: - -```shell -😀 🔤Hello, World!🔤❗️ -``` - -This prints "Hello, World!" to the terminal. - -- `🔤Hello, World!🔤` is a string. It holds the message we want to print to the terminal. -- We wrap the thing we want to print with a `😀` at the start and a `❗️` at the end. - -## Example - -Here's a program called **welcome.emojic** that prints a string: - -```shell -🏁 🍇 - 😀 🔤Welcome to Codecademy Docs🔤❗️ -🍉 -``` diff --git a/content/emojicode/concepts/interpolation/interpolation.md b/content/emojicode/concepts/interpolation/interpolation.md deleted file mode 100644 index 23a4766aef3..00000000000 --- a/content/emojicode/concepts/interpolation/interpolation.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -Title: '🧲 Interpolation' -Description: 'String interpolation can be used to construct a string from a mix of constants, variables, and others by including their values inside a string literal. In Emojicode, to insert a value into a string using string interpolation, we can write the variable inside two 🧲s and it will print its value. Suppose we have a constant named height with a value of 3000, and we want to use string interpolation to print out a fun fact: shell 3000 ➡️ height 😀 🔤Alex Honnold climbed El Capitan, which is 🧲height🧲 feet, without a rope!🔤❗️ ' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Interpolation' - - 'Strings' - - 'Data Types' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -String interpolation can be used to construct a string from a mix of constants, variables, and others by including their values inside a string literal. - -In Emojicode, to insert a value into a string using string interpolation, we can write the variable inside two `🧲`s and it will print its value. - -Suppose we have a constant named `height` with a value of `3000`, and we want to use string interpolation to print out a fun fact: - -```shell -3000 ➡️ height - -😀 🔤Alex Honnold climbed El Capitan, which is 🧲height🧲 feet, without a rope!🔤❗️ -``` - -It will output: - -```shell -Alex Honnold climbed El Capitan, which is 3000 feet, without a rope! -``` - -## Example - -```shell -💭 Tip Calculator - -🏁 🍇 - 3.80 ➡️ tip - - 😀 🔤The tip is $🧲tip🧲🔤❗️ -🍉 -``` - -It will output: - -```shell -The tip is 3.80 -``` diff --git a/content/emojicode/concepts/lists/lists.md b/content/emojicode/concepts/lists/lists.md deleted file mode 100644 index 90927bc8651..00000000000 --- a/content/emojicode/concepts/lists/lists.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -Title: '🍿 Lists' -Description: 'A list literal is a listing of expressions. Lists are always ordered and can contain different types of objects, such as strings, integers, booleans, etc. Lists are a mutable data type and therefore a good choice for dynamic data (adding and subtracting to lists). In Emojicode, a list is created by using 🍿 and 🍆. For instance, the example below is a list literal with integer values 18, 67, 420. emojic 🍿 18 67 420 🍆 ' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Lists' - - 'Data Types' - - 'Arrays' - - 'Dictionaries' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -A list literal is a listing of expressions. - -Lists are always ordered and can contain different types of objects, such as strings, integers, booleans, etc. Lists are a mutable data type and therefore a good choice for dynamic data (adding and subtracting to lists). - -## Syntax - -In Emojicode, a list is created by using 🍿 and 🍆. - -For instance, the example below is a list literal with integer values `18`, `67`, `420`. - -```emojic -🍿 18 67 420 🍆 -``` - -Here's another list with three strings: - -```emojic -🍿 🔤eggs🔤 🔤blueberries🔤 🔤cookies🔤 🍆 -``` - -The compiler will try to infer the type of a list literal. The default type of list literals, is the list type 🍨, an ordered mutable collections of values. diff --git a/content/emojicode/concepts/operators/operators.md b/content/emojicode/concepts/operators/operators.md deleted file mode 100644 index 7fdcfd98cca..00000000000 --- a/content/emojicode/concepts/operators/operators.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -Title: 'Operators' -Description: 'Emojicode supports arithmetic operators for: - ➕: addition - ➖: subtraction - ✖️: multiplication - ➗: division - 🚮: modulo (divides and gives the remainder) For example:' -Subjects: - - 'Computer Science' -Tags: - - 'Operators' - - 'Arithmetic' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -## Arithmetic Operations - -Emojicode supports arithmetic operators for: - -- `➕`: addition -- `➖`: subtraction -- `✖️`: multiplication -- `➗`: division -- `🚮`: modulo (divides and gives the remainder) - -For example: - -```shell -4 ➕ 2 ➡️ score1 💭 scores1 is 6 - -4 ➖ 2 ➡️ score2 💭 scores2 is 2 - -4 ✖️ 2 ➡️ score3 💭 scores3 is 8 - -4 ➗ 2 ➡️ score4 💭 scores4 is 2 - -4 🚮 2 ➡️ score5 💭 scores5 is 0 -``` diff --git a/content/emojicode/concepts/repeat-while/repeat-while.md b/content/emojicode/concepts/repeat-while/repeat-while.md deleted file mode 100644 index a31235de9f9..00000000000 --- a/content/emojicode/concepts/repeat-while/repeat-while.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -Title: '🔁 Repeat While' -Description: 'The 🔁 statement repeats a code block while as long as the given condition is 👍 (true). And if the condition is never 👍 (false), the code block will be ignored and skipped. Due to the ease of use of the 🔂 (for-in) statement, 🔁 is only used seldomly. emojic 🏁 🍇 🔁 👍 🍇 😀 🔤It goes on and on and on🔤❗️ 🍉' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'While' - - 'Loops' - - 'Control Flow' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -The 🔁 statement repeats a code block while as long as the given condition is 👍 (true). And if the condition is never 👍 (false), the code block will be ignored and skipped. - -Due to the ease of use of the 🔂 (for-in) statement, 🔁 is only used seldomly. - -## Infinite Loop - -```emojic -🏁 🍇 - 🔁 👍 🍇 - 😀 🔤It goes on and on and on🔤❗️ - 🍉 -🍉 -``` - -This program will infinitely print “It goes on and on and on”. - -```shell -It goes on and on and on -It goes on and on and on -It goes on and on and on -... -``` diff --git a/content/emojicode/concepts/strings/strings.md b/content/emojicode/concepts/strings/strings.md deleted file mode 100644 index 84a1b73086f..00000000000 --- a/content/emojicode/concepts/strings/strings.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -Title: '🔡 Strings' -Description: 'Strings are words or pieces of text that the computer treats as a single item. They provide a way to store something like a word, sentence, or whole paragraph. Technically speaking, a string is a sequence of characters. It can be of any length and contain any letters, numbers, symbols, or spaces as long as they are surrounded by 🔤s. Here are four different strings in Emojicode: shell 🔤This is a string!🔤 🔤This is also a string!!!🔤 🔤1337🔤' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Strings' - - 'Data Types' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -Strings are words or pieces of text that the computer treats as a single item. They provide a way to store something like a word, sentence, or whole paragraph. - -Technically speaking, a string is a sequence of characters. It can be of any length and contain any letters, numbers, symbols, or spaces as long as they are surrounded by `🔤`'s. - -## Syntax - -Here are four different strings in Emojicode: - -```shell -🔤This is a string!🔤 -🔤This is also a string!!!🔤 -🔤1337🔤 -🔤👆👍🔤 -``` - -It’s important to distinguish between strings and the rest of the code in our programs. Every part of a program is made up of characters, but strings are the parts we intend to keep as data—not as instructions to be executed by the computer. - -## Example - -Here's a full program that print out two strings: - -```shell -🏁 🍇 - 😀 🔤2020...🔤❗️ - 😀 🔤That was a crazy year.🔤❗️ -🍉 -``` - -## String Interpolation - -String interpolation can be used to construct a string from a mix of constants, variables, and others by including their values inside a string literal. - -In Emojicode, to insert a value into a string using string interpolation, we can write the variable inside two `🧲`s and it will print its value. - -Suppose we have a constant named `height` with a value of `3000`, and we want to use string interpolation to print out a fun fact: - -```shell -3000 ➡️ height - -😀 🔤Alex Honnold climbed El Capitan, which is 🧲height🧲 feet, without a rope!🔤❗️ -``` - -It will output: - -```shell -Alex Honnold climbed El Capitan, which is 3000 feet, without a rope! -``` diff --git a/content/emojicode/emojicode.md b/content/emojicode/emojicode.md deleted file mode 100644 index 1063391dae9..00000000000 --- a/content/emojicode/emojicode.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -# This file is used to populate the hub page for the language whose folder it's in. Be sure to create a new version if you create a folder for a new language! - -Title: 'Emojicode' # This is the name that appears on the hub page for this language. Pay attention to capitalization and punctuation! -Description: 'Emojicode is an open-source, full-blown strongly-typed programming language consisting of emojis like 🍇 and 🍉. What could be a better language than that? Learning Emojicode can bring some smiles and fun to your programming journey, as well as be an enlightening experience in which you will never look at your go-to programming language the same way again. Hopefully, it will even inspire you to create your own programming language down the road!' -CatalogContent: - - 'learn-emojicode' - - 'paths/computer-science' ---- - -Emojicode is an open-source, full-blown strongly-typed programming language consisting of emojis like `🍇` and `🍉`. What could be a better language than that? - -Learning Emojicode can bring some smiles and fun to your programming journey, as well as be an enlightening experience in which you will never look at your go-to programming language the same way again. Hopefully, it will even inspire you to create your own programming language down the road! diff --git a/content/general/concepts/algorithm/algorithm.md b/content/general/concepts/algorithm/algorithm.md deleted file mode 100644 index 1bf1e26b87c..00000000000 --- a/content/general/concepts/algorithm/algorithm.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -Title: 'Algorithm' -Description: 'An algorithm is a formal process used to solve a problem. They can be represented in several formats but are usually represented in pseudocode in order to communicate the process by which the algorithms solve the problems they were created to tackle.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Algorithms' - - 'Sort' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -An **algorithm** is a formal process used to solve a problem. Algorithms can be represented in several formats but are usually represented in pseudocode in order to communicate the process by which the algorithms solve the problems they were created to tackle. Ultimately algorithms are implemented in programming languages that allow them to manipulate data in the ways that the algorithms are intended to. Algorithms are measured in "Big O notation". - -The word algorithm comes from "Algorismus" which is a Latinized name of the influential 10th-century polymath Muhammad ibn Musa al-Khwarizmi. - -There are many ways to classify algorithms but one of the best ways to do so is by analysis of their complexity. - -## Time Complexities - -Algorithms can be categorized by their time complexities: - -- Exponential time: If the time is an exponential function of the input size. - - Brute-force search. -- Polynomial time: If the time is a power of the input size. - - Bubble sort has quadratic time complexity. -- Linear time: If the time is proportional to the input size. - - The traverse of a list. -- Logarithmic time: If the time is a logarithmic function of the input size. - - Binary search algorithm. -- Constant time: If the time needed by the algorithm is the same, regardless of the input size. - - An access to an array element. - -## Example of an Algorithm - -This is a sorting algorithm implemented in Python: - -```py -# Python implementation of Bubble Sort - -def bubbleSort(_array): - n = len(_array) - - for i in range(n-1): - for j in range(0, n-i-1): - if _array[j] > _array[j + 1]: - _array[j], _array[j + 1] = _array[j + 1], _array[j] - -_array = [3, 9, 12, 12, 100, 90] - -bubbleSort(_array) - -print ("Print sorted data:") - -for i in range(len(_array)): - print("% d" % _array[i]), -``` diff --git a/content/general/concepts/algorithm/terms/binary-search/binary-search.md b/content/general/concepts/algorithm/terms/binary-search/binary-search.md deleted file mode 100644 index 97e28b2e756..00000000000 --- a/content/general/concepts/algorithm/terms/binary-search/binary-search.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -Title: 'Binary Search Algorithm' -Description: 'An efficient searching algorithm' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Algorithms' - - 'Data Structures' - - 'Search Algorithms' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -**Binary Search** is an algorithm for searching an element within a sorted collection of items, primarily implemented with [arrays](https://www.codecademy.com/resources/docs/general/data-structures/array) or lists. The binary search algorithm follows a divide-and-conquer approach by repeatedly dividing the collection into two halves and comparing the target value with the middle element of the current search space. If there is a match, it provides the index of the middle element; otherwise, it proceeds to either side of the array, depending on the current comparison result. - -> **Note**: The collection must be sorted and have constant time indexing such as arrays to implement the binary search algorithm. Binary search is incompatible with data structures that do not support constant-time indexing. - -## The Algorithm - -The steps for the binary search algorithm are as follows: - -1. Set the `start` pointer to the beginning of the collection (index 0). -2. Set the `end` pointer to the end of the collection (length(collection) - 1). -3. While the `start` is less than or equal to the `end` pointer, repeat these steps: - 1. Calculate the middle element index: `mid = start + (end - start) / 2`. - 2. Compare the value at middle index (`mid`) with the target value. - 1. If `arr[mid]` is equal to the target value, return `mid` (search successful). - 2. If `arr[mid]` is less than the target value, set the `start` to `mid + 1`. - 3. If `arr[mid]` is greater than the target value, set the `end` to `mid - 1`. -4. If the `start` pointer becomes greater than the `end` pointer, the target value is not in the collection. Return `-1` to indicate that the target is not present. - -## Complexities for Binary Search Algorithm - -### Time Complexity - -- Average Case: `O(log n)` -- Worst Case: `O(log n)` -- Best Case: `O(1)` - -The binary search algorithm has logarithmic time complexity because it divides the array repeatedly until the target element is discovered or the search space is empty. - -In the worst-case scenario, the target element does not exist in the collection. In such cases, the algorithm keeps dividing the collection until it has exhausted the search space. - -### Space Complexity - -Binary search has a space complexity of `O(1)` as it is a space-efficient algorithm. - -## Example - -In the example below, a sorted array has elements such as `[1, 3, 4, 6, 8, 9, 11]`. The aim is to implement the binary search algorithm for searching the number `9`. - -![Sorted Array](https://raw.githubusercontent.com/Codecademy/docs/main/media/binary-search-1.png) - -In the first iteration, `start` is at 0, `end` is at 6, and `mid` becomes 3 after calculating. The algorithm compares `mid` to the target value. Since the target value (9) is greater than the middle element (6), the algorithm proceeds the search to the right half by updating the `start` index to `mid + 1`, which is 4. Now, the algorithm will focus on finding the target value in the array's right portion(index 4 to 6). - -![First Iteration of Binary Search](https://raw.githubusercontent.com/Codecademy/docs/main/media/binary-search-2.png) - -In the second iteration, `mid` becomes 5, which is the index of the target value (9). Since the target value is equal to the `mid`, the algorithm identifies the element's position. - -However, the search is not instantly completed; instead, the algorithm changes the search range. In this case, the `start` index is set to `mid + 1` which starts a narrowed search on the right part of the array. - -![Second Iteration of Binary Search](https://raw.githubusercontent.com/Codecademy/docs/main/media/binary-search-3.png) - -In the last iteration, the binary search algorithm has narrowed down the search to a single element. The middle index `mid`, `start`, and `end`, are now pointing directly to the target value (9). - -The algorithm recognizes the match, and the search concludes that the target value is found at index 5 and the binary search is successful. - -![Last Iteration of Binary Search](https://raw.githubusercontent.com/Codecademy/docs/main/media/binary-search-4.png) diff --git a/content/general/concepts/algorithm/terms/bubble-sort/bubble-sort.md b/content/general/concepts/algorithm/terms/bubble-sort/bubble-sort.md deleted file mode 100644 index 98c1bbf268b..00000000000 --- a/content/general/concepts/algorithm/terms/bubble-sort/bubble-sort.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -Title: 'Bubble Sort Algorithm' -Description: 'Illustrates a simple sorting algorithm using repeated swapping of adjacent elements.' -Subjects: - - 'Code Foundations' - - 'Computer Science' - - 'Interview Prep' -Tags: - - 'Algorithms' - - 'Bubble Sort' - - 'Sorting Algorithms' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -**Bubble sort** is a simple, comparison-based [algorithm](https://www.codecademy.com/resources/docs/general/algorithm) that repeatedly steps through an [array](https://www.codecademy.com/resources/docs/java/arrays), comparing and swapping adjacent elements if they are in the wrong order. This process continues until the array is sorted, making it an intuitive method for sorting arrays. - -## BubbleSort Method - -Bubble Sort is a straightforward algorithm that sorts an array by repeatedly comparing and swapping adjacent elements if they are in the wrong order. The steps of the Bubble Sort algorithm are as follows: - -1. **Start at the Beginning**: Begin with the first element in the array. -2. **Compare Adjacent Elements**: Compare the current element with the next element in the array. -3. **Swap if Necessary**: If the current element is greater than the next element, swap their positions. This action moves the higher element towards the end of the array. -4. **Continue Through the Array**: Move to the next pair of adjacent elements and repeat the comparison and swap process. -5. **Complete the Pass**: Continue this process until the end of the array is reached. This constitutes one complete pass through the array. -6. **Repeat the Process**: Start again with the first element for the next pass. With each pass, the number of comparisons can be reduced since the end of the array will progressively become sorted. -7. **Check for Completion**: After each pass, if no swaps have been made, it indicates that the array is now completely sorted. At this point, the algorithm can stop running. - -The process is characterized by the larger elements "bubbling" up to the end of the array with each pass, hence the name "Bubble Sort". - -### Implementation - -The following pseudocode demonstrates the Bubble Sort Algorithm: - -```plaintext -Algorithm: BubbleSort(Array) - for i from 0 to Array.length - 1 - set swapped to false - for j from 0 to Array.length - i - 1 - if Array[j] > Array[j + 1] - swap Array[j] and Array[j + 1] - set swapped to true - if not swapped - break // Array is sorted -``` - -This pseudocode outlines the logic of the Bubble Sort algorithm without being tied to any specific programming language, making it suitable for a general algorithms document. Be sure to replace the existing Java code in your markdown document with this pseudocode snippet. - -## Time Complexity - -Overall Time Complexity: O(n^2) - -- **Iterative Comparison**: Each pair of adjacent elements is compared, leading to n-1 comparisons in the first pass, n-2 in the second, and so on. -- **Best Case Scenario**: O(n) when the array is already sorted, as only one pass will be needed. -- **Worst and Average Case**: O(n^2) due to the nested loops for comparing and swapping elements. - -> **Note:** The overall time complexity of Bubble Sort is predominantly influenced by the number of passes through the array and the comparisons within each pass. - -## Characteristics of Bubble Sort - -- `Simplicity`: Bubble sort is straightforward to understand and implement. -- `Inefficiency for Large Lists`: Not suitable for large datasets due to its O(n^2) time complexity. -- `Stability`: Bubble sort is a stable algorithm, maintaining the relative order of equal elements. -- `Adaptive`: Can be optimized to stop early if the list is sorted before completing all passes, making it adaptive to the initial order of elements. - -## Example and Illustration - -The following animation visually demonstrates the Bubble Sort Algorithm in action: - -![Bubble Sort Example](https://raw.githubusercontent.com/Codecademy/docs/main/media/bubble-sort.png) - -In this example, the numbers in the array are visually represented. With each pass through the array, the largest number in the unsorted part bubbles up to its correct position at the end of the array. This process repeats, with the range of unsorted elements shrinking each time, until the entire array is sorted. diff --git a/content/general/concepts/algorithm/terms/counting-sort/counting-sort.md b/content/general/concepts/algorithm/terms/counting-sort/counting-sort.md deleted file mode 100644 index 72da705680d..00000000000 --- a/content/general/concepts/algorithm/terms/counting-sort/counting-sort.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -Title: 'Counting Sort' -Description: 'Sorts a list with duplicate values efficiently.' -Subjects: - - 'Computer Science' - - 'Interview Prep' -Tags: - - 'Algorithms' - - 'Sorting Algorithms' - - 'Java' - - 'Counting Sort' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -**Counting sort** is an out-of-place, non-comparison sorting [algorithm](https://www.codecademy.com/resources/docs/general/algorithm) that sorts a list with duplicate values efficiently. It is a helpful algorithm for sorting [arrays](https://www.codecademy.com/resources/docs/java/arrays) of small, non-negative integers, where it analyzes elements' frequency distribution and places them in their final sorted positions. - -## Explanation - -### Find the maximum value - -- Iterate through the input array `data` to find the largest element `max`. - - This determines the range of values needed to be counted. - -### Create the count array - -- Initialize a new array `count` with a `max + 1` size to hold each value's frequency. - - The size is `max + 1` so that the `max` element is accounted for. -- Set all elements in `count` to _0_ initially. - -### Count the occurrences - -- Loop through the `data` array again. -- For each element `data[i]`, increment the corresponding count in the `count` array (`count[data[i]]++`). - - This is to document the frequency distribution of elements in `data`. - -### Create the start array - -- Initialize a new array `start` of the same size as `count`. -- Set `start[0]` to _0_. -- Based on the frequency distribution found in `count`, the starting indexes can be determined and stored in the `start` array (`start[j] = start[j-1] + count[j-1]` for `j=1` to `max`). - -### Place elements in sorted order - -- Iterate through the `data` array again. -- For each element `data[a]`: - - Retrieve its corresponding position to the `temp` [variable](https://www.codecademy.com/resources/docs/java/variables) from the `start` array (`temp = start[data[a]]`). - - Place the element in the `result` array at that position (`result[temp] = data[a]`). - - Increment the `start` value for the next element with the same value (`start[data[a]]++`). - -### Return the sorted array - -- The `result` array now contains the elements of the original `data` array in sorted order. -- Return the `result` array. - -## Implementation - -The following example written in [Java](https://www.codecademy.com/resources/docs/java) shows an implementation of **counting sort**: - -```java -import java.util.Random; -import java.util.Arrays; - -public class CountingSorting { - public static void main(String[] args) { - Random rand = new Random(); - int[] arr1 = new int[10]; - for(int i =0; i < arr1.length; i++){ - arr1[i] = rand.nextInt(5); - } - System.out.println("Array Before Sort: " + Arrays.toString(arr1)); - System.out.println("Array After Sort: " + Arrays.toString(countingSort(arr1))); - } - public static int[] countingSort(int[] data){ - int[] count,start,result; - result = new int[data.length]; - //Step #1 - int max = Integer.MIN_VALUE; - for(int item:data) - { - max = Math.max(max,item); - } - //Step #2 - count = new int[max+1]; - //Step #3 - for(int i = 0; i < data.length; i++){ - count[data[i]]++; - } - //Step #4 - start = new int[max+1]; - start[0]= 0; - for(int j =1; j < start.length; j++){ - start[j] = start[j-1] + count[j-1]; - } - //Step #5 - for(int a = 0; a < result.length;a++){ - int temp = start[data[a]]; - result[temp] = data[a]; - start[data[a]]++; - } - //Step #6 - return result; - } - -} -``` - -The output for the above code is: - -```shell -Array Before Sort: [3, 2, 1, 4, 2, 4, 2, 1, 4, 2] -Array After Sort: [1, 1, 2, 2, 2, 2, 3, 4, 4, 4] -``` - -## Time Complexity - -- The first and third loops run in _O(k)_ time, where _k_ is `max`. -- The second and last loops run in _O(n)_ time. -- Therefore, the total running time is _O(n+k)_. -- If _k_ = _O(n)_, then the total time is _O(n)_. diff --git a/content/general/concepts/algorithm/terms/euclidean-algorithm/euclidean-algorithm.md b/content/general/concepts/algorithm/terms/euclidean-algorithm/euclidean-algorithm.md deleted file mode 100644 index b752c10b34e..00000000000 --- a/content/general/concepts/algorithm/terms/euclidean-algorithm/euclidean-algorithm.md +++ /dev/null @@ -1,148 +0,0 @@ ---- -Title: 'Euclidean Algorithm' -Description: 'A simple and efficient method for finding the highest common factor (HCF), also known as the greatest common divisor (GCD), of two numbers.' -Subjects: - - 'Computer Science' -Tags: - - 'Algorithms' - - 'Arithmetic' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -The **Euclidean algorithm** is a recursive algorithm that will find the highest common factor (HCF) of two numbers. The HCF is the largest value that will evenly divide (leave no remainder) both values. It is based on the observation that the HCF can be found by iteratively comparing two values, substituting the difference of the values alternatively, until the values are equivalent. This convergent value is the HCF. - -There are multiple methods to solve and find the highest common factor (HCF) of two numbers. In this explanation, let's explore a basic approach first and then move on to the Euclidean algorithm. - -## Method 1 - -In the basic approach, the purpose is to find the GCD. To do this, find the minimum value between the two given numbers. Then, divide both numbers by the minimum value. If either of the divisions results in a remainder, decrease the minimum value by one and continue dividing. This process repeats until the minimum value can divide both numbers evenly. At this point, the minimum value is the HCF. - -The following code illustrates this method in Java: - -```java -public static void main(String[] args) { - System.out.println(gcd(10,15)); - } - public static int gcd(int a,int b){ - int minValue = Math.min(a,b); - while(minValue>0){ - if(a%minValue==0 && b%minValue==0){ - break; - } - minValue--; - } - return minValue; - } -} -``` - -The output for the above code will be: - -```shell -5 -``` - -## Method 2: A Basic Euclidean Algorithm Approach - -In this method, the aim is to compare both `a` and `b`. The process begins by identifying the larger value and subtracting the smaller number from the larger number. The larger number is now replaced with the result of the subtraction. These steps repeat until the values are equal. This convergent value is the HCF. - -The following code illustrates this method in Java: - -```java -class Euclidean1 { -static int gcd(int a, int b) { - - while (a != b) { - if (a > b) - a = a - b; - else - b = b - a; - } - - return a; -} - -public static void main(String[] args) { - - int a = 15, b = 20; - - System.out.println(gcd(a, b)); -} -} -``` - -The output for the above code will be: - -```shell -5 -``` - -The step by step execution of the above code is as follows: - -- Since `b` is greater than `a` (20 > 15), here `b` is replaced with `b - a`, which gives results in `b` = 20 - 15 = 5. -- Now `a` is 15 and `b` is 5. -- The result is `a` = 15 - 5 = 10 after replacing `a` with `a - b`. -- The values are now `a` = 10 and `b` = 5. -- The process continues, `a` is replaced with `a - b`, resulting in `a` = 10 - 5 = 5. -- Now `a` and `b` are both equal to 5. -- At this point, the while loop exits, and `a` is returned. Therefore, the HCF of 15 and 20 is 5. - -## Method 3: A Recursive Euclidean Approach - -In this method, a recursive approach is used to implement the Euclidean algorithm for finding the greatest common divisor (GCD) of two integers, `a` and `b`. The method implements a function that takes `a` and `b` as integer parameters and returns an integer as the result. The algorithm begins by checking if `b` is equal to `0`. If it is, then it means that `a` is the GCD, and it returns `a` as the result. However, if `b` is not `0`, it indicates that there is a remainder when `a` is divided by `b`. In this case, the method calls itself recursively with the arguments `b` and `a % b`. This recursive call continues until `b` equals `0`, triggering the base case and yielding the GCD. - -For more information on recursion, refer to this [resource](https://www.codecademy.com/learn/java-algorithms/modules/recursion-apcs/cheatsheet). The following code illustrates this method in Java: - -```java -public class Euclidean2 { -public static void main(String[] args) { - System.out.println(EuclideanOptimized(150, 500)); - -} -static int EuclideanOptimized(int a, int b){ - if(b==0){ - return a; - } - return EuclideanOptimized(b,a%b); -} -} -``` - -The output for the above code will be: - -```shell -50 -``` - -The step by step execution of this example is as follows: - -- Given the input of two integers: `a` = 150 and `b` = 500, the code steps into the `EuclideanOptimized` function. The first `if` statement encountered checks if `b` is equal to `0`. In this particular case, `b` is not equal to `0`, resulting in the program exiting the `if` statement. -- Then the code proceeds to return `EuclideanOptimized`, but with the arguments `(b, a % b)`. -- In the first recursive cycle, the value of `a % b` will be 150. Since 150 is smaller than 500, it cannot be divided evenly by 500. Therefore, the remainder is equal to the original number, which is 150. Consequently, the next arguments for `EuclideanOptimized` are `(500, 150)`. -- The function is restarted with the arguments `(500, 150)`. Upon entering the function, the `if` statement is encountered. However, since `b` is not equal to `0`, the program moves on to the next recursive cycle with the arguments `(150, 50)` ( 500 % 150 yields 50). -- Once again, the function is initiated with arguments `(150, 50)`. As in previous iterations, `b` is not equal to `0`, and thus the program moves on to the next recursive cycle. The second argument in this case is determined by calculating the modulus 150 % 50, which yields the argument values `(50, 0)`. -- In this recursive cycle, when the code enters the `if` statement, the condition `b == 0` is satisfied. Therefore, the function will return `a`, which has a value of 50, the highest common factor for the original arguments. - -## Time Complexities - -- Method 1: - - - The first example uses a simple iterative approach to find the greatest common divisor (GCD) of two numbers. It starts by finding the minimum value between `a` and `b`, then iterates from that value down to one, checking if it divides both `a` and `b`. Therefore, the time complexity of this code is _O(min(a, b))_. - -- Method 2: - - - The second example also calculates the GCD using an iterative approach known as the Euclidean algorithm. It repeatedly subtracts the smaller number from the larger number until the two numbers become equal (the GCD). The time complexity of this algorithm depends on the number of iterations required to reach the GCD. In the worst case, where one number is a multiple of the other, the time complexity is _O(max(a, b))_. - -- Method 3: - - - The third example is an optimized version of the Euclidean algorithm that uses recursion. It calculates the GCD by repeatedly taking the modulus of `a` with `b` and calling itself with the new values (`b` and `a%b`) until `b` equals `0`. The time complexity of this optimized Euclidean algorithm is _O(log(max(a, b)))_ since the algorithm reduces the values quickly by taking the modulus. - -To summarize, the time complexities of the three codes are as follows: - -- Method 1: _O(min(a, b))_ -- Method 2: _O(max(a, b))_ -- Method 3: _O(log(max(a, b)))_ - -> **Note:** These time complexities typically represent the worst-case scenarios and assume that the `a` and `b` values are relatively large. In practice, the actual time taken by the algorithms can vary depending on the input values. diff --git a/content/general/concepts/algorithm/terms/heap-sort/heap-sort.md b/content/general/concepts/algorithm/terms/heap-sort/heap-sort.md deleted file mode 100644 index 56b52dea00b..00000000000 --- a/content/general/concepts/algorithm/terms/heap-sort/heap-sort.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -Title: 'Heap Sort' -Description: 'An efficient sorting algorithm that uses a binary heap to sort elements in O(n log n) time.' -Subjects: - - 'Computer Science' -Tags: - - 'Algorithms' - - 'Arithmetic' - - 'Sorting Algorithms' - - 'Heap Sort' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -**Heap Sort** is an efficient comparison-based sorting algorithm that outperforms simple algorithms like Bubble Sort, Insertion Sort, or Selection Sort. It builds upon the idea of Selection Sort but improves it by leveraging a binary heap to quickly find the maximum (or minimum) value. This significantly speeds up the process of sorting an array by moving the maximum element to the end in each iteration. - -The efficiency of Heap Sort comes from using a binary heap structure, a complete binary tree where every level is filled except possibly the last. In this structure, each parent node is greater than or equal to its children (max-heap). This property ensures that the root node always contains the largest element, which can then be moved to the end of the array. - -A heap can be easily represented in an array. The root node is the first element, and the rest of the tree is stored level by level, from left to right. For any node at index `i`, its left child is at `2*i + 1` and its right child is at `2*i + 2`. - -![Heap in an Array](https://raw.githubusercontent.com/Codecademy/docs/main/media/heap_in_array.jpg) - -## Explanation - -A brief explanation of the Heap Sort algorithm steps: - -- Initially, the input array needs to be heapified. That means we need to build a heap from the unsorted array. What is the heap and how can it be represented by an array is explained above. Remind that the heapified array is not sorted yet! - -- The Heapify process rests upon building a structure of parents and descendants where a parent can be calculated as **(i - 1) / 2** where _i_ is an index of a descendant and simultaneously the left descendant can be calculated as **(2\*j + 1)** and the right descendant as **(2\*j + 2)** where _j_ is the index of the parent. - -- Building of the heap itself is usually written in an **up** method which checks each node if it doesn't violate the rule mentioned in the point above (if it isn't greater than its parent). To prevent transferring the problem just a level up the check has to be called in a cycle for each node. When the checking cycle reaches the end of the array we can be sure it's heapified. - -- Heap sort is an in-place comparison sorting algorithm: This means that it doesn't require additional memory beyond the input array and elements are compared to determine their relative order. - -- The sorting of the heap is basically made by the Selection sort. The array is divided into two parts (two subarrays): the unsorted subarray at the beginning and the sorted subarray at the end. Initially, the sorted subarray is empty, and the unsorted subarray contains all the elements. The sorted subarray gradually grows and the unsorted subarray shrinks until no elements remain in the unsorted part. The main advantage compared to Selection sort is finding the maximum which takes a constant time because it lies on the index "0". Swapping of the last node to the root (mentioned below) is also constant. - -- Heap sort run on a heap tears away the maximum (the root node) and puts it to the end of the sorted subarray. Then it moves the last node to the root (as mentioned above). After such swapping the heap becomes "broken" and needs to be heapified again. For this purpose is usually used a **down** method which repairs the heap. The method is analogous to the **up** method. It is called on the root node and when it finds a descendant greater than the root it swaps it (if both descendants are greater it chooses the greater one). Again to prevent transferring the problem just a level down the check has to be called. This time we check if descendant nodes aren't greater than parents (how to find them is explained above). If they don't pass the check the swap must be made. We repeat that in each level if necessary but not for each node as in the **up** method so that is the point where the complexity is reduced. - -- Given that the algorithm has a time complexity of _O(n\*log n)_ in all cases, where _n_ is the number of elements in the array. It performs _n_ iterations of the **up** method (to build a heap) and the _log n_ factor comes from the height of the binary heap (a count of its levels). - -- This makes the algorithm efficient for large input sizes. Compared to other smart sorting algorithms Heap Sort might be better understandable because there is no need for using more advanced concepts such as recursions. Memory requirements can also be minimal (compared to Merge Sort which needs additional memory). - -- On the other hand, it is unstable (it may rearrange the relative order) and slower than the other smart sorting algorithms. Typically 2-3 times slower than well-implemented QuickSort. - -**Animation of Heap Sort:** - -![Heap Sort](https://raw.githubusercontent.com/Codecademy/docs/main/media/heap_sort_animation.gif) - -## Example - -The following example written in [Java](https://www.codecademy.com/learn/learn-java) shows an implementation of Heap sort and then uses it to sort `{3, 100, 7, 25, 1, 36, 2, 19, 17}`: - -```java -public class HeapSort { - - public static void main(String[] args) { - int[] array = {3, 100, 7, 25, 1, 36, 2, 19, 17}; - heapSort(array); - System.out.println("Sorted array: "); - for (int i : array) { - System.out.print(i + " "); - } - } - - public static void heapSort(int[] list) { - heapify(list); - int index = list.length - 1; // index of the last element - int temp; - while (index > 0) { - temp = list[0]; // swap the last element with the root - list[0] = list[index]; - list[index] = temp; - index -= 1; // the new last element - down(list, index); - } - } - - public static void heapify(int[] list) { - for (int i = 1; i < list.length; i++) - up(list, i); - } - - public static void up(int[] list, int i) { - int child = i; // index of a descendant - int parent, temp; - while (child != 0) { - parent = (child - 1) / 2; // index of a parent node - if (list[parent] < list[child]) { // swap if doesn't meet binary heap properties - temp = list[parent]; - list[parent] = list[child]; - list[child] = temp; - child = parent; // the new descendant - } else { - return; - } - } - } - - public static void down(int[] list, int last) { - int parent = 0; - int child, temp; - while (parent * 2 + 1 <= last) { - child = parent * 2 + 1; - // selection of greater descendant - if ((child < last) && (list[child] < list[child + 1])) - child++; - if (list[parent] < list[child]) { // swap if doesn't meet binary heap properties - temp = list[parent]; - list[parent] = list[child]; - list[child] = temp; - parent = child; // the new parent - } else { - return; - } - } - } -} -``` - -The output for the above code is: - -```shell -Sorted array: -1 2 3 7 17 19 25 36 100 -``` diff --git a/content/general/concepts/algorithm/terms/huffman-coding/huffman-coding.md b/content/general/concepts/algorithm/terms/huffman-coding/huffman-coding.md deleted file mode 100644 index aca611fa230..00000000000 --- a/content/general/concepts/algorithm/terms/huffman-coding/huffman-coding.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -Title: 'Huffman Coding' -Description: 'A lossless data compression algorithm that assigns variable-length codes to input characters based on their frequencies.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Algorithms' - - 'Data Structures' - - 'Search Algorithms' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -**Huffman coding** is a popular algorithm for lossless data compression that assigns variable-length codes to input characters based on their frequencies. Characters that appear more frequently in the data are assigned shorter codes, while less frequent characters receive longer codes. This approach minimizes the overall space required to represent the original data. - -The algorithm was developed by David A. Huffman in 1952 while he was a Ph.D. student at MIT. It has since become a fundamental technique in information theory and is used in many compression formats and transmission protocols. - -## How Huffman Coding Works - -Huffman coding works through the following steps: - -- Frequency Analysis: Count the frequency of each character in the input data. -- Build the Huffman Tree: - - Create a leaf node for each character and add it to a priority queue, with priority based on frequency (lower frequency = higher priority). - - While there is more than one node in the queue: - - Remove the two nodes with the highest priority (lowest frequency). - - Create a new internal node with these two nodes as children, with a frequency equal to the sum of both nodes' frequencies. - - Add the new node back to the priority queue. - - The remaining node is the root of the Huffman tree. -- Generate Huffman Codes: - - Traverse the tree from the root to each leaf. - - Assign '0' for a left branch and '1' for a right branch. - - The code for each character is the sequence of 0s and 1s on the path from the root to the character's leaf node. -- Encoding: Replace each character in the original data with its corresponding Huffman code. - -## Example - -Let's use a simple example to illustrate Huffman coding. Consider encoding the string "ABRACADABRA": - -### Step 1: Calculate Character Frequencies - -| Character | Frequency | -| --------- | --------- | -| A | 5 | -| B | 2 | -| R | 2 | -| C | 1 | -| D | 1 | - -### Step 2: Build the Huffman Tree - -Starting with leaf nodes for each character: - -```plaintext -A(5) B(2) R(2) C(1) D(1) -``` - -First, combine the two lowest frequency nodes (C and D): - -![Huffman Coding Tree Example](https://raw.githubusercontent.com/Codecademy/docs/main/media/huffman_coding_1.png) - -```plaintext -Remaining: A(5) B(2) R(2) [2] -``` - -Next, combine the [2] node with another lowest frequency node (B or R, both have 2): - -![Huffman Coding Tree Example](https://raw.githubusercontent.com/Codecademy/docs/main/media/huffman_coding_2.png) - -```plaintext -Remaining: A(5) R(2) [4] -``` - -Combine R with the [4] node: - -![Huffman Coding Tree Example](https://raw.githubusercontent.com/Codecademy/docs/main/media/huffman_coding_3.png) - -```plaintext -Remaining: A(5) [6] -``` - -Finally, combine the remaining nodes: - -![Huffman Coding Tree Example](https://raw.githubusercontent.com/Codecademy/docs/main/media/huffman_coding_4.png) - -## Step 3: Generate Huffman Codes - -Assigning 0 for left branches and 1 for right branches: - -| Character | Path from Root | Huffman Code | -| --------- | ---------------------------- | ------------ | -| A | Left | 0 | -| R | Right → Left | 10 | -| B | Right → Right → Right | 111 | -| C | Right → Right → Left → Left | 1100 | -| D | Right → Right → Left → Right | 1101 | - -## Step 4: Encode the String - -Now encode "ABRACADABRA": - -``` -A B R A C A D A B R A -0 111 10 0 1100 0 1101 0 111 10 0 -``` - -Without spaces: `01111001100011010111100` - -The encoded string is 23 bits long, compared to 88 bits if using 8-bit fixed-length encoding (11 characters × 8 bits = 88 bits), achieving approximately 74% compression. diff --git a/content/general/concepts/algorithm/terms/insertion-sort/insertion-sort.md b/content/general/concepts/algorithm/terms/insertion-sort/insertion-sort.md deleted file mode 100644 index 198f4b9dd57..00000000000 --- a/content/general/concepts/algorithm/terms/insertion-sort/insertion-sort.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -Title: 'Insertion Sort' -Description: 'Sorts an array one element at a time.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Algorithms' - - 'Sorting Algorithms' - - 'Arrays' - - 'Elements' -CatalogContent: - - 'learn-c-plus-plus' - - 'paths/computer-science' ---- - -**Insertion Sort** is a simple sorting algorithm that divides an array into two parts, sorted and unsorted. Then, it iterates through the unsorted array and places each element in the correct place in the sorted array. - -## Explanation - -- Assume that the first element in the array is already sorted. -- Iterate through the array starting from the element at the second position and compare it with the first element which is already sorted. If the first element is greater than the second, then swap them. -- Compare the third element with the two before it and if it's smaller, then swap again. -- Continue this process till the whole array is sorted. - -Here is a visual representation for the first iteration: - -![Insertion Sort](https://raw.githubusercontent.com/Codecademy/docs/main/media/insert-sort.png) - -## Implementation - -```cpp -#include -#include - -void insertionSort(std::vector& arr) { - int n = arr.size(); - for (int i = 1; i < n; ++i) { - int key = arr[i]; - int j = i - 1; - - // Move elements of arr[0..i-1] that are greater than 'key' - // to one position ahead of their current position - while (j >= 0 && arr[j] > key) { - arr[j + 1] = arr[j]; - j = j - 1; - } - arr[j + 1] = key; - } -} - -void printArray(const std::vector& arr) { - for (int i = 0; i < arr.size(); ++i) { - std::cout << arr[i] << " "; - } - std::cout << std::endl; -} - -int main() { - std::vector arr = {5, 2, 9, 1, 5, 6}; - std::cout << "Original array: "; - printArray(arr); - - insertionSort(arr); - - std::cout << "Sorted array: "; - printArray(arr); - - return 0; -} -``` - -The output for the above code is: - -```shell -Original array: 5 2 9 1 5 6 -Sorted array: 1 2 5 5 6 9 -``` - -### Time Complexity - -- Best Case: `O(n)` -- Average Case: `O(n^2)` -- Worst Case: `O(n^2)` diff --git a/content/general/concepts/algorithm/terms/kadanes-algorithm/kadanes-algorithm.md b/content/general/concepts/algorithm/terms/kadanes-algorithm/kadanes-algorithm.md deleted file mode 100644 index 353b069c743..00000000000 --- a/content/general/concepts/algorithm/terms/kadanes-algorithm/kadanes-algorithm.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -Title: "Kadane's Algorithm" -Description: 'Returns the maximum sum of a subarray within an array of numbers' -Subjects: - - 'Computer Science' -Tags: - - 'Algorithms' - - 'Arithmetic' - - 'Arrays' -CatalogContent: - - 'learn-cpp' - - 'paths/computer-science' ---- - -**`Kadane's algorithm`** is a dynamic programming approach to efficiently finding the maximum sum of a subarray in a given array of numbers. The algorithm works as follows: - -1. Initialize a current sum (variably called `maxEndingHere`) equal to the value of the element at the first position in the array (`arr[0]`). -2. Iterate through the array. At every position, set `maxEndingHere` to the maximum of the following two values: `maxEndingHere + arr[i]` or `arr[i]`, where `i` is the current position in the array. -3. Keep track of the greatest `maxEndingHere` encountered (ex: in a variable called `maxSoFar`). -4. Return `maxSoFar`. - This algorithm guarantees a time complexity of `O(n)`, making it an optimal solution for this problem. - -## Example - -**Here's how Kadane's algorithm can be applied to a problem:** - -- Consider the array {-2, -1, -3, 4, -1, 2, 1, -5, 4}. Initialize two integer variables: one named `maxEndingHere` and the other called `maxSoFar`. These variables serve to track the maximum subarray sum ending at the current position and the overall maximum subarray sum. -- The loop commences with the first element, which is -2. Therefore, both `maxEndingHere` and `maxSoFar` are initially -2. -- Proceed to the next element, -1, and compare it to the sum of itself and the previous value of `maxEndingHere`. Since -1 is greater than the sum of -2 and -1, set`maxEndingHere` to -1. Also, compare `maxSoFar` with the updated value of `maxEndingHere`. Since -2 is less than -1 set `maxSoFar` to -1. -- This process continues as we advance through the array, modifying `maxEndingHere` and `maxSoFar` at each step. -- After the loop, the variable `maxSoFar` contains the maximum subarray sum. -- Return the value of `maxSoFar`, which represents the maximum subarray sum. - -The following implementation of `Kadane's algorithm` is done in [c++](https://www.codecademy.com/resources/docs/cpp): - -```cpp -#include -using namespace std; - -int maxSubarraySum(int arr[], int size) { - int maxEndingHere = arr[0]; - int maxSoFar = arr[0]; - - for (int i = 1; i < size; i++) { - maxEndingHere = max(arr[i], maxEndingHere + arr[i]); - maxSoFar = max(maxSoFar, maxEndingHere); - } - - return maxSoFar; -} - -int main() { - int nums[] = {-2, -1, -3, 4, -1, 2, 1, -5, 4}; - int size = sizeof(nums) / sizeof(nums[0]); - - int maxSum = maxSubarraySum(nums, size); - cout << "Maximum subarray sum: " << maxSum << endl; - - return 0; -} -``` - -The output for the above code is: - -```shell -Maximum subarray sum: 6 -``` - -## Codebyte Example - -```codebyte/cpp -#include -#include -using namespace std; - -int maxSubarraySum(vector& arr) { - int maxEndingHere = arr[0]; - int maxSoFar = arr[0]; - int start = 0; - int end = 0; - int tempStart = 0; - - for (int i = 1; i < arr.size(); i++) { - if (arr[i] > maxEndingHere + arr[i]) { - maxEndingHere = arr[i]; - tempStart = i; - } else { - maxEndingHere = maxEndingHere + arr[i]; - } - - if (maxEndingHere > maxSoFar) { - maxSoFar = maxEndingHere; - start = tempStart; - end = i; - } - } - - cout << "Maximum subarray: ["; - for (int i = start; i <= end; i++) { - cout << arr[i]; - if (i != end) { - cout << ", "; - } - } - cout << "]" << endl; - - return maxSoFar; -} - -int main() { - vector nums = {-2, -1, -3, 4, -1, 2, 1, -5, 4}; - - int maxSum = maxSubarraySum(nums); - cout << "Maximum subarray sum: " << maxSum << endl; - - return 0; -} -" - -Three additional variables: `start`, `end`, and `tempStart` are added in the above code. These variables keep track of the starting and ending indices, the temporary start of the current subarray. So, in the end, the subarray itself can be printed which has the max sum with the max sum. -``` diff --git a/content/general/concepts/algorithm/terms/merge-sort/merge-sort.md b/content/general/concepts/algorithm/terms/merge-sort/merge-sort.md deleted file mode 100644 index b560d247c45..00000000000 --- a/content/general/concepts/algorithm/terms/merge-sort/merge-sort.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -Title: 'Merge Sort Algorithm' -Description: 'Returns a sorted array using divide and conquer.' -Subjects: - - 'Computer Science' - - 'Interview Prep' - - 'Code Foundations' -Tags: - - 'Sorting Algorithms' - - 'Algorithms' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -**Merge sort** is a divide-and-conquer sorting [algorithm](https://www.codecademy.com/resources/docs/general/algorithm) that breaks down an [array](https://www.codecademy.com/resources/docs/java/arrays) into smaller arrays, sorts them, and then combines the subarrays back together to return a sorted array. - -## MergeSort Method - -**Divide:** - -- `Base Case`: If the input array `data` has only one element, it's already sorted, so return. -- `Split`: Divide the array into two halves, `left` and `right`, of approximately equal size. - -**Conquer**: - -- [`Recursive Calls`](https://www.codecademy.com/learn/java-algorithms/modules/recursion-apcs/cheatsheet): Repeatedly call `mergeSort` on each half, `(left)` and `(right)`, to create subarrays so they are sorted independently. - -**Combine**: - -- `Merge`: Call the `merge` function to merge the two sorted halves (each initially of length 1) `left` and `right`, and combine them back into the original array `data` in a sorted manner. - -### Implementation Pt.1 - -The following example written in [Java](https://www.codecademy.com/learn/learn-java) shows an implementation of the first part of the Merge Sort Algorithm — splitting the main array into subarrays: - -```java -public static void mergeSort(int[] data){ - if(data.length == 1){ - return; - } - int n1 = data.length/2; - int n2 = data.length - n1; - int[] left, right; - //make left and right subarrays - left = new int[n1]; - right = new int[n2]; - System.arraycopy(data, 0, left, 0, n1); - System.arraycopy(data, n1, right, 0, n2); - //recursively split left and right arrays - mergeSort(left); - mergeSort(right); - //once array is @ length 1, the left & right array will be merged - merge(data, left, right); -} -``` - -### Merge Method - -1. **Initialize**: - - Set indices `l`, `r`, and `k` to 0 to track the positions in `left`, `right`, and `data`. -2. **Compare and Merge**: - - While both `left` and `right` have elements remaining: - - Compare the elements at `left[l]` and `right[r]`. - - Copy the smaller element into `data[k]` and increment the corresponding index (`l` or `r`). - - Increment `k` to move to the next position in `data`. -3. **Copy Remaining Elements**: - - If any elements remain in `left`, copy them directly into the remaining positions in `data`. - - Similarly, if any elements remain in `right`, copy them into the remaining positions in `data`. - -### Implementation Pt.2 - -The following example written in [Java](https://www.codecademy.com/learn/learn-java) shows an implementation of the second part of Merge Sort — sorting the subarrays and merging them back into the original array: - -```java -public static void merge(int[] data, int[] left, int[] right){ - //indexes of arrays left, right, and data - int l,r,k; - l = r = k = 0; - while(l < left.length && r < right.length && k < data.length){ - //find min between left & right element and insert it - if(left[l] < right[r]){ - data[k] = left[l]; - l++; - } - else{ - data[k] = right[r]; - r++; - } - //increment index of data after insertion - k++; - } - //if elements still remain in arrays left or right, insert them into the data - while(l < left.length){ - data[k] = left[l]; - l++; - k++; - } - while(r < right.length){ - data[k] = right[r]; - r++; - k++; - } -} - -``` - -### Time Complexity Breakdown - -Overall Time Complexity: _O(n log n)_ - -### Breakdown - -1. **Divide**: - - - The `mergeSort` function recursively divides the array into halves until each subarray has only one element. - - This splitting process has a time complexity of _O(log n)_ due to the repeated halving. - -2. **Conquer**: - - - The base case (array of size 1) requires no sorting, so its complexity is _O(1)._ - -3. **Combine**: - - The `merge` function merges two sorted subarrays into a single sorted array. - - It iterates through both subarrays once, comparing elements and copying them to the final array. - - This merging process takes _O(n)_ time, where n is the total number of merged elements. - -**Overall Time Complexity:** - -- The recursive calls to `mergeSort` create a log n-level tree. - - The number of levels in this tree directly relates to how many times the array can be divided by 2 before reaching single-element subarrays. This is equivalent to the logarithm of the array's size (log n). For example, an array of 8 elements would have 3 levels (log2 (8) = 3). _Reference the picture below for a visual understanding._ - -![Merge Sort](https://raw.githubusercontent.com/Codecademy/docs/main/media/merge.png) - -- At each level, the merging step takes O(n) time. -- Therefore, the overall time complexity is **O(n log n)**, resulting from multiplying the time complexity of each level (n) by the number of levels (log n). - -## Benefits of Merge Sort - -- `Predictable Efficiency`: Merge sort maintains a time complexity of O(n log n) regardless of the initial arrangement of elements in the input array. This means it performs equally well in best-case, average-case, and worst-case scenarios. -- `Reliable for Diverse Inputs`: This consistent performance makes merge sort a dependable choice for sorting various input sizes and datasets without unexpected slowdowns due to data arrangement. -- `Efficiency for Large Datasets`: Its O(n log n) time complexity places it among the most efficient sorting algorithms, especially for large datasets, outperforming algorithms like bubble sort and [selection sort](https://www.codecademy.com/resources/docs/general/algorithm/selection-sort) that exhibit worse-case complexities of O(n^2). diff --git a/content/general/concepts/algorithm/terms/quick-sort/quick-sort.md b/content/general/concepts/algorithm/terms/quick-sort/quick-sort.md deleted file mode 100644 index 98b5fef40a4..00000000000 --- a/content/general/concepts/algorithm/terms/quick-sort/quick-sort.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -Title: 'Quick Sort' -Description: 'Sorts an array using a divide-and-conquer approach.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Algorithms' - - 'Sorting Algorithms' - - 'Java' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -**Quick Sort** is an in-place sorting [algorithm](https://www.codecademy.com/resources/docs/general/algorithm) that sorts an [array](https://www.codecademy.com/resources/docs/java/arrays) using a divide-and-conquer approach. It starts with selecting a pivot element from the array, then partitions the array into two sub-arrays based on whether each of its elements is smaller or larger than the pivot, and finally recursively sorts those sub-arrays. - -## Explanation - -Here is a step-by-step explanation of the Quick Sort algorithm: - -Step 1. Initial Checks - -- If the array is empty or has only one element `low >= high`, then it's already sorted. So, the function returns the array itself. - - This is the reason behind not using `data.length == 1` as the stopping case for partitioning. - -Step 2. Partitioning - -- Takes the last element's index `high` as the pivot. -- Initializes two pointers, i.e., `left` at the beginning `low` and `right` at the end `high - 1` (since `high` is the pivot element). -- Iterates until `left` and `right` meet or cross. - - Moves the pointer `left` to the right when the elements at `left` are less than or equal to the pivot. - - Moves `right` to the left when the elements at `right` are greater than or equal to the pivot. - - If both the above conditions are violated and `left` and `right` haven't crossed, then swaps the numbers at indices `left` and `right`. -- If the pointers cross, swaps the pivot with the element at `left` to place the pivot element in its sorted position. - -Here is a visual representation for the first iteration: - -![Quick Sort](https://raw.githubusercontent.com/Codecademy/docs/main/media/quicksort.png) - -Step 3: Recursive Calls - -- Recursively sorts the left subarray (`data[low..left-1]`). -- Recursively sorts the right subarray (`data[left+1..high]`). - -Step 4: Helper Function - -- `swap(data, a, b)`: Swaps elements at indices `a` and `b` in the array `data`. - -## Implementation - -The following example written in [Java](https://www.codecademy.com/resources/docs/java) shows an implementation of Quick Sort: - -```java -public static void quickSort(int[] data, int low, int high) { - if(low >= high) { - return; - } - - int left = low; - int right = high; - int pivot = high; - - while(left != right) { - while(data[left] <= data[pivot] && left < right) { - left++; - } - - while(data[right] >= data[pivot] && right > left) { - right--; - } - - swap(data,left, right); - } - - swap(data, left, pivot); - quickSort(data,low,left-1); - quickSort(data,left+1, high); -} - -public static void swap(int[] data, int a, int b) { - int temp = data[a]; - data[a] = data[b]; - data[b] = temp; -} -``` - -## Time Complexity - -- Divide and Conquer: Quick Sort divides the array into smaller subarrays and recursively sorts them. -- Pivot Selection: The choice of pivot affects performance. The last element is often used, but other strategies exist that could improve runtime. -- Average-Case Time Complexity: _O(n log n)_; This occurs when the pivot element roughly divides the array into two equal halves. Randomized selection of the pivot helps achieve this on average, as it's less likely to consistently pick the smallest or largest element. -- Worst-Case Time Complexity: _O(n^2)_; This worst case scenario occurs when the pivot element is either the smallest or largest element in the array, resulting in partitioning until only one element in one of the sub-arrays. - - While Merge Sort has a worst-case time complexity of _O(n log n)_, Quick Sort has the advantage of being an in-place sorting algorithm. This means it sorts the data within the same array, avoiding the need for extra space during the sorting process. diff --git a/content/general/concepts/algorithm/terms/selection-sort/selection-sort.md b/content/general/concepts/algorithm/terms/selection-sort/selection-sort.md deleted file mode 100644 index 9a0b78f5aad..00000000000 --- a/content/general/concepts/algorithm/terms/selection-sort/selection-sort.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -Title: 'Selection-Sort Algorithm' -Description: 'Returns a sorted array.' -Subjects: - - 'Computer Science' -Tags: - - 'Algorithms' - - 'Arithmetic' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -**Selection sort** is an in-place comparison sorting algorithm. It divides the input array into two parts: the sorted subarray at the beginning and the unsorted subarray at the end. The algorithm repeatedly selects the minimum (or maximum) element from the unsorted subarray and swaps it with the first unsorted element, expanding the sorted subarray by one element. - -## Explanation - -A brief explanation of the selection sort algorithm: - -- Selection sort is an in-place comparison sorting algorithm: This means that selection sort does not require additional memory beyond the input array, and elements are compared to determine their relative order. - -- It divides the input array into two parts: Conceptually, selection sort divides the array into two subarrays: the sorted subarray at the beginning and the unsorted subarray at the end. Initially, the sorted subarray is empty, and the unsorted subarray contains all the elements. - -- The algorithm repeatedly selects the minimum (or maximum) element: In each iteration, selection sort identifies the minimum (or maximum) element from the unsorted subarray. The selection process involves scanning the unsorted subarray to find the smallest (or largest) element. - -- It swaps the selected element with the first unsorted element: Once the minimum (or maximum) element is identified, selection sort swaps it with the first element of the unsorted subarray. This action effectively expands the sorted subarray by one element and reduces the unsorted subarray by one. - -- The process continues until the entire array is sorted: Selection sort repeats the selection and swapping steps for the remaining unsorted elements until the entire array becomes sorted. The sorted subarray gradually grows, and the unsorted subarray shrinks until no elements remain in the unsorted portion. - -- Selection sort is a sorting algorithm that repeatedly finds the minimum element in the unsorted portion of an array and swaps it with the element at the beginning of the unsorted section. This process continues until the entire array is sorted. The algorithm has a time complexity of _O(n^2)_, where _n_ is the number of elements in the array. It performs _n_ iterations, each involving a comparison of each element in the unsorted section with the current minimum. As a result, the total number of comparisons is roughly _(n \* (n-1))/2_. While selection sort is inefficient for large input sizes, it can be useful for small arrays or when minimizing the number of swaps is a priority. - -**Graphical representation of Selection Sort:** - -![Selection Sort](https://raw.githubusercontent.com/Codecademy/docs/main/media/SelectionSort.png) - -## Example - -The following example written in [Java](https://www.codecademy.com/learn/learn-java) shows an implementation of selection sort and then uses it to sort `{5, 3, 4, 1, 2}`: - -```java -public class SelectionSort { - public static void selectionSort(int[] array) { - int n = array.length; - for (int i = 0; i < n - 1; i++) { - int minIndex = i; - for (int j = i + 1; j < n; j++) { - if (array[j] < array[minIndex]) { - minIndex = j; - } - } - int temp = array[minIndex]; - array[minIndex] = array[i]; - array[i] = temp; - } - } - - public static void main(String[] args) { - int[] array = {5, 3, 4, 1, 2}; - selectionSort(array); - System.out.println("Sorted array: "); - for (int i : array) { - System.out.print(i + " "); - } - } -} -``` - -The output for the above code is: - -```shell -Sorted array: 1 2 3 4 5 -``` - -The `selectionSort` function in the code takes an integer `array` as input and initializes a variable `n` with the length of the array. The outer loop iterates through the elements from the first to the second-to-last element of the array, representing the boundary of the unsorted subarray. - -Inside the outer loop, an inner loop starts from `i+1` and searches for the minimum element in the unsorted portion of the array. The index of the smallest element found is stored in the `minIndex` variable. - -After the inner loop completes, the algorithm swaps the found minimum element with the first element of the unsorted subarray using a temporary variable (`temp`). This ensures that the minimum element is correctly positioned in the sorted subarray. diff --git a/content/general/concepts/api/api.md b/content/general/concepts/api/api.md deleted file mode 100644 index 3f7b6e240d1..00000000000 --- a/content/general/concepts/api/api.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -Title: 'API' -Description: 'An API, or Application Programming Interface, is a term used to describe specifications that allow applications to communicate with one another. APIs enable exchange of information and can be a major source of value to organizations. They can be divided into three groups: Public APIs, Private APIs, and Partner APIs.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'APIs' - - 'Developer Tools' - - 'Dependency' - - 'Interface' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**API** stands for **Application Programming Interface** and is a term used to describe specifications that allow applications to communicate with one another. - -APIs enable exchange of information, and can be a major source of value (utility, market dependence and revenue) to organizations. APIs are significant components in the evolution of applications because the technical ecosystem is built on top of APIs and leverages them to function and provide many services in use today. - -## Categories - -APIs can be divided into three groups: - -- Public APIs, also known as a Open APIs, are available to users with minimal restrictions. An example of this API is Google Maps, which allows users to take advantage of Google's expansive and detailed map software in a number of ways. Developers can leverage this software and integrate with it in their applications by following the [Google Maps API documentation](https://developers.google.com/maps/apis-by-platform). - -- Private APIs, also known as Internal APIs, are used primarily within a company to share resources and facilitate the business (e.g. Company Warehouse API for managing inventory with code). - -- Partner APIs require rights or specific licenses for use. These APIs are popular in software-as-a-service platforms (e.g. [AWS API](https://docs.aws.amazon.com/general/latest/gr/aws-apis.html)). - -## Benefits and Risks of Using APIs - -The main benefits of using APIs are: - -- Cost savings through the elimination of the need to build and maintain local physical infrastructure and services. - -- Opportunities to leverage the expertise of other vendors instead of having to reinvent solutions for common problems (authentication, payment processing, maps, etc.). - -- Possibilities to build new businesses and products based on the exchange of data between users and various online services offering API access to independent developers. - -The main risks associated with using APIs are: - -- Little to no control over the impact of vendor-only changes including business infrastructure, version updates, and data collection. - -- Nonsecure APIs can become gateways to hacker attacks. As soon as they are breached, other dependent systems become vulnerable. It is commonly predicted that API abuses will become the most frequent vector of attack in the coming years. - -- APIs can be abused by the clients themselves. One example is excessive requests to the API, which is what rate limits are meant to prevent. diff --git a/content/general/concepts/argument/argument.md b/content/general/concepts/argument/argument.md deleted file mode 100644 index 9ebb7cdf390..00000000000 --- a/content/general/concepts/argument/argument.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -Title: 'Argument' -Description: 'An argument is the actual value of a variable passed into a function.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Functions' - - 'Parameters' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -An **argument** is the actual value of a variable (aka. the parameter) passed into a function. - -## Example - -Suppose we have a function called `tripleThis()`: - -```js -function tripleThis(x) { - return x * 3; -} - -tripleThis(6); -``` - -The parameter is `x` since it is the variable. The argument is `6` since it is the actual value. diff --git a/content/general/concepts/artificial-intelligence/artificial-intelligence.md b/content/general/concepts/artificial-intelligence/artificial-intelligence.md deleted file mode 100644 index 39c16b1ef09..00000000000 --- a/content/general/concepts/artificial-intelligence/artificial-intelligence.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -Title: 'Artificial Intelligence' -Description: 'Simulates human intelligence in computers, enabling learning, reasoning, and problem-solving to provide solutions across various tasks.' -Subjects: - - 'AI' - - 'Computer Science' -Tags: - - 'AI' - - 'Algorithms' - - 'Automation' -CatalogContent: - - 'paths/computer-science' - - 'paths/data-science' ---- - -**Artificial Intelligence (AI)** is described as the simulation of human intelligence in computer systems. AI technology can perform learning, reasoning, and problem-solving tasks, enabling solutions to a variety of complex problems. AI systems can range from simple algorithms, such as those making product recommendations based on purchase history, to complex systems that power self-driving cars, planning routes, and avoiding obstacles without human intervention. The demand for AI-powered solutions is growing rapidly and intersecting almost every aspect of our daily lives. - -## Types of AI - -- **Reactive Machines AI**: These are the most basic AI systems. They do not have memory or use past data to form decisions or factor into solutions. They react to specific inputs with specific outputs. -- **Limited Memory AI**: These systems can use memory and stored data to make future decisions. However, they only have temporary memory, which is stored briefly. -- **Theory of Mind AI**: These advanced AI systems involve machines that can understand emotions, behaviors, and interactions, making them more human-like in their ability to interact with humans. -- **Self-Aware AI**: This would be the most advanced type of AI system and is currently hypothetical. In this type of system, a machine would have a defined consciousness and be self-aware. It would be able to make decisions, feel emotions, and act on them based on its own intentions and desires. - -## Applications of AI - -Artificial Intelligence plays a significant role in various fields of computer science and programming. The most popular applications include: - -- **Business**: AI is playing an increasingly important role in businesses. AI-powered tools help collect, analyze, and visualize data efficiently, leading to improved decision-making, productivity, and cost reduction. -- **Healthcare**: AI assists doctors in diagnosing diseases, developing treatments, and providing personalized care to patients. -- **Education**: AI can personalize learning, enhance student engagement, and automate administrative tasks for schools and organizations. -- **Finance**: AI aids financial institutions by personalizing services and products, managing risk and fraud, ensuring compliance, and automating operations to reduce costs. -- **Manufacturing**: AI is used in manufacturing including automating tasks, such as assembly and inspection, optimizing production processes, and can be used to detect defects and improve quality control. diff --git a/content/general/concepts/augmented-reality/augmented-reality.md b/content/general/concepts/augmented-reality/augmented-reality.md deleted file mode 100644 index dce7e92a404..00000000000 --- a/content/general/concepts/augmented-reality/augmented-reality.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -Title: 'Augmented Reality' -Description: 'Augmented Reality (AR) is a digitally enhanced real world experience provided through hardware. In many instances AR provides an additional sensory experience to natural settings. A popular example of Augmented Reality in application is the video game Pokemon Go.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Augmented reality (AR)** is a digitally enhanced real world experience provided through hardware. In many instances, AR provides an additional sensory experience to natural settings. A popular example of AR in mobile applications is the video game Pokémon Go. - -An augogram is the computer generated image that is used to create an Augmented Reality experience. The term for this science and software practice is called augography. - -## Augmented Reality vs. Virtual Reality - -The difference between augmented reality (AR) and [virtual reality (VR)](https://www.codecademy.com/resources/docs/general/virtual-reality) is that augmented reality utilizes the current physical setting of the user while introducing a layer of synthetic digital, sonic or somatic presentation to enhance the user experience whereas VR involves use of a headset to facilitate an experience rooted in the graphic and sonic presentation within the VR setup as opposed to using the individuals more broad physical surroundings for interaction. - -Augmented reality is poised to grow substantially in use during the 21st century as it has many potential uses that range from entertainment, medical, commercial, military, fashion and design etc. - -## Augmented Reality Examples - -- Viewing merchandise/goods without trying them on at retail stores and shopping platforms (IKEA, Neiman Marcus, etc.) -- Flight/Combat simulation (military, commercial aviation) -- Physical markers for direction and navigation -- 3D commercial/residential design and architecture -- Training for medical procedures for nurses and doctors diff --git a/content/general/concepts/back-end/back-end.md b/content/general/concepts/back-end/back-end.md deleted file mode 100644 index 9e01c669eb5..00000000000 --- a/content/general/concepts/back-end/back-end.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -Title: 'Back-End' -Description: 'The back-end serves data to the front-end from sources like a database.' -Subjects: - - 'Web Design' - - 'Web Development' -Tags: - - 'Debugging' - - 'Development' - - 'Frameworks' - - 'Servers' -CatalogContent: - - 'learn-html' - - 'paths/back-end-engineer-career-path' ---- - - - -The **back-end** of a program or web application serves data to the [front-end](https://www.codecademy.com/resources/docs/general/front-end) from sources like a [database](https://www.codecademy.com/resources/docs/general/database). - -## Restaurant Analogy - -A common analogy for the relationship between the front-end and back-end are customers and employees at a restaurant (representation of the front-end): - -- The customer places their order (or "request") with the waiter/waitress (or [server](https://www.codecademy.com/resources/docs/general/server)). -- The order is then taken to the kitchen (representation of the back-end). -- There, the order is prepared (or "processed") with the necessary ingredients (or "data") to produce the expected food item (or "response"). -- Finally, the food item is brought back out to the dining area for the customer. - -## Common Tasks - -Back-end web development can involve a variety of tasks, including: - -- Creating, integrating, and managing databases. -- Using back-end [frameworks](https://www.codecademy.com/resources/docs/general/framework) to build [server-side](https://www.codecademy.com/resources/docs/general/server-side-rendering) software. -- Validating data to make sure it's formatted correctly before being sent to the database. -- Integrating user-facing elements with server-side elements to make sure that information is being sent to the right place so the server can retrieve it. - -## Back-End Tools - -Back-End Developers use a range of technologies and software, many of which fall into three categories: databases, programming languages, and frameworks. - -### Databases - -Databases are used to storing important data such as user information. Popular database management systems and [relational databases](https://www.codecademy.com/resources/docs/general/relational-database) include: - -- [MySQL](https://www.mysql.com/) -- [MongoDB](https://www.mongodb.com/) -- [Oracle](https://www.oracle.com/index.html) -- [PostgreSQL](https://www.postgresql.org/) - -### Languages - -Back-End Developers normally query their databases with various programming languages such as the following: - -- [SQL](https://www.codecademy.com/resources/docs/sql), which is ideal for working in relational databases. -- [Ruby](https://www.codecademy.com/resources/docs/ruby) is a beginner-friendly language that has an enthusiastic programming community behind it. -- [Python](https://www.codecademy.com/resources/docs/python) is a great choice with a concise, human-readable syntax. -- [PHP](https://www.codecademy.com/resources/docs/php) is an open-source language that is great for server-side scripting. -- [Node.js](https://www.codecademy.com/resources/docs/open-source/node-js), which brings back-end work to [JavaScript](https://www.codecademy.com/resources/docs/javascript). -- [Java](https://www.codecademy.com/resources/docs/java) is a popular choice still widely used today. - -### Frameworks - -[Frameworks](https://www.codecademy.com/resources/docs/general/framework) make all aspects of web development smoother and seamless. This saves developers time they would otherwise spend writing code. Popular frameworks include: - -- Sinatra, a lightweight Ruby framework for building web apps. -- [Ruby on Rails](https://www.codecademy.com/resources/docs/ruby/ruby-on-rails), a more robust Ruby framework that follows the model-view-controller standard. -- Django, a Python framework that offers dynamic [HTML](https://www.codecademy.com/resources/docs/html) pages. -- Flask, a lighter Python framework meant for rapid development. -- [Express](https://www.codecademy.com/resources/docs/open-source/express), a framework for building back-end APIs with JavaScript. -- Spring, a Java framework that can be used to build back-end APIs. diff --git a/content/general/concepts/big-o-notation/big-o-notation.md b/content/general/concepts/big-o-notation/big-o-notation.md deleted file mode 100644 index b58d3845276..00000000000 --- a/content/general/concepts/big-o-notation/big-o-notation.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -Title: 'Big-O Notation' -Description: 'Big-O notation is a form of measuring the algorithmic time/space complexity of a function in worst-case scenario.' -Subjects: - - 'Code Foundation' - - 'Computer Science' -Tags: - - 'Algorithms' - - 'Functions' - - 'Methods' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Big-O notation** is a form of measuring the algorithmic complexity of a [function](https://www.codecademy.com/resources/docs/general/function) or [algorithm](https://www.codecademy.com/resources/docs/general/algorithm) in the worst-case scenario. This can either analyze the maximum amount of possible time or memory space needed to solve a particular problem. Solutions can be refactored or reworked to achieve a more efficient time/space complexity with the help of Big-O notation. - -## Common Runtimes - -Here are some common runtimes: - -![Graph of the different kinds of Big-O notation](https://raw.githubusercontent.com/Codecademy/docs/main/media/big-o-graph-extended.png) - -| Runtime | Name | Description | Use Case(s) | -| :--------: | :-----------------------------------: | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| _O(1)_ | Constant time (in blue) | The time needed is the same, regardless of the input size. | Accessing an element in an array. | -| _O(ln(n))_ | Logarithmic time (in red) | The time is a logarithmic function `ln()` of the input size `n`. | Analyzing the [binary search algorithm](https://www.codecademy.com/learn/fscp-22-search-graph-search-algorithms/modules/wdcp-22-binary-search-and-search-trees/cheatsheet). | -| _O(n)_ | Linear time (in green) | The time needed is proportional to the input size `n`. | Traversing an [array](https://www.codecademy.com/resources/docs/general/data-structures/array) of `n`-size. | -| _O(n^2)_ | Polynomial/quadratic time (in purple) | The time needed is the input size, `n`, multiplied by itself. | [Bubble sort](https://www.codecademy.com/learn/sorting-algorithms-java/modules/bubble-sort-java/cheatsheet) has quadratic time complexity. | -| _O(2^n)_ | Exponential time (in orange) | The time needed doubles for every new element added to the input. | The Fibonacci Series. | -| _O(n!)_ | Factorial time (in cyan) | The time needed is equivalent to the factorial of the input size. | The Traveling Salesman problem. | - -## Simplifying Big-O Expressions - -When determining an expression that characterizes the time or space complexity of an algorithm, an expression may contain multiple terms ( e.g., _O(n) + O(ln(n))_ ). In the context of Big-O, the focus is on the relative change as the input gets large. And as the input gets larger (approaches infinity), the higher-order terms take precedence over the lower-order terms, which is why the Big-O notation would simplify to just _O(n)_. - -## Python Big-O Practice - -The following Python example analyzes the time/space complexity of the `foo()` function: - -```py -def foo(list1, list2): - for item in list1: - print(f"Outer loop: {item}") - for item2 in list2: - print(f"Inner loop: {item2}") - -foo(["Hello", "World"], ["Spam", "Eggs"]) -``` - -The inner loop is equivalent to _O(n)_, and the outer loop will execute the inner loop _n_ times. Therefore, the Big-O notation for the `foo()` function would be _n \* O(n) = O(n^2)_. diff --git a/content/general/concepts/binary-search-tree/binary-search-tree.md b/content/general/concepts/binary-search-tree/binary-search-tree.md deleted file mode 100644 index c5b96dbe18d..00000000000 --- a/content/general/concepts/binary-search-tree/binary-search-tree.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -Title: 'Binary Search Tree' -Description: 'A binary search tree is a data structure that is comprised of nodes in a branching relationship, each node having a key signifying its value.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Conceptual' - - 'Binary Tree' - - 'Data Structures' -CatalogContent: - - 'complex-data-structures' - - 'paths/computer-science' ---- - -A **binary search tree** is a data structure that is comprised of nodes in a branching relationship, each node having a key signifying its value. Each node can have zero, one, or two child nodes branching off from it. The tree has one root node that has no parent. - -All nodes in the left branch of a parent node have values that are less than the parent node's value, and all nodes in the right branch of a parent node have values that are greater than the parent node's value. - -Below is a diagram of a binary search tree. - -![Binary Search Tree Diagram](https://raw.githubusercontent.com/Codecademy/docs/main/media/binary-tree-labeled.png) - -The part of the tree with nodes `1`, `2`, and `3` is referred to as the left subtree, and the part with nodes `5`, `6`, and `7` is referred to as the right subtree. Both subtrees are themselves binary search trees. The nodes `1`, `3`, `5`, and `7` are called leaf nodes because they have no children. - -## Binary Search Tree vs. Hash Table - -Like a [hash table](https://www.codecademy.com/resources/docs/general/data-structures/hash-table), a binary search tree is a method of storing keys for later retrieval and manipulation. Both have their own strengths, and the best storage type to use is dependent on what tasks are going to be undertaken with the data being stored. - -If the primary tasks needed are search, insert, or delete, a hash table performs them in O(1) time (in [big-O notation](https://www.codecademy.com/resources/docs/general/big-o-notation)). A binary search tree performs them in O(log(n)) time. So if just these operations are all that are needed, a hash table is more performant. - -A binary search tree is preferable to a hash table in the following circumstances: - -- There's a need for retrieving keys in sorted order. -- There's a need for operations like order statistics, finding the next smallest or largest element, or range queries. -- Memory is a consideration. Binary search trees are more memory efficient than hash tables. -- With binary search trees, operations take O(log(n)) time. While hashing averages O(1) time, some operations may be more costly, taking O(n2) time, especially when table resizing happens. diff --git a/content/general/concepts/binary-search-tree/terms/inorder-traversal/inorder-traversal.md b/content/general/concepts/binary-search-tree/terms/inorder-traversal/inorder-traversal.md deleted file mode 100644 index bd3bf4cb3c7..00000000000 --- a/content/general/concepts/binary-search-tree/terms/inorder-traversal/inorder-traversal.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -Title: 'Inorder Traversal' -Description: 'First traverses the left subtree, then the root, and then the right subtree.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Algorithms' - - 'Conceptual' - - 'Binary Tree' - - 'Data Structures' - - 'Search' - - 'Trees' -CatalogContent: - - 'complex-data-structures' - - 'paths/computer-science' ---- - -**Inorder traversal** is a depth-first search [algorithm](https://www.codecademy.com/resources/docs/general/algorithm) for a binary search tree that first traverses the left subtree, then the root, then traverses the right subtree. This provides the nodes of the binary search tree in increasing order. To get nodes in decreasing order, inorder traversal can be done in reverse. - -## Algorithm - -The inorder algorithm can be described as follows: - -```pseudo -Function Inorder(tree) - return Inorder(left-subtree) + root + Inorder(right-subtree) -``` - -## Example - -For the following binary search tree: - -![Binary Search Tree Diagram](https://raw.githubusercontent.com/Codecademy/docs/main/media/binary-tree-labeled.png) - -Inorder traversal provides the nodes in the following order: `1`, `2`, `3`, `4`, `5`, `6`, `7`. diff --git a/content/general/concepts/binary-search-tree/terms/postorder-traversal/postorder-traversal.md b/content/general/concepts/binary-search-tree/terms/postorder-traversal/postorder-traversal.md deleted file mode 100644 index b3a07e38852..00000000000 --- a/content/general/concepts/binary-search-tree/terms/postorder-traversal/postorder-traversal.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -Title: 'Postorder Traversal' -Description: 'First traverses the left subtree, then the right subtree, and then the root.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Algorithms' - - 'Conceptual' - - 'Binary Tree' - - 'Data Structures' - - 'Search' - - 'Trees' -CatalogContent: - - 'complex-data-structures' - - 'paths/computer-science' ---- - -**Postorder traversal** is a depth-first search [algorithm](https://www.codecademy.com/resources/docs/general/algorithm) for a binary search tree that first traverses the left subtree, then the right subtree, and then the root. Its primary use is deleting the tree. - -## Algorithm - -The postorder algorithm can be described as follows: - -```pseudo -Function Postorder(tree) - return Postorder(left-subtree) + Postorder(right-subtree) + root -``` - -## Example - -For the following binary search tree: - -![Binary Search Tree Diagram](https://raw.githubusercontent.com/Codecademy/docs/main/media/binary-tree-labeled.png) - -Postorder traversal provides the nodes in the following order: `1`, `3`, `2`, `5`, `7`, `6`, `4`. diff --git a/content/general/concepts/binary-search-tree/terms/preorder-traversal/preorder-traversal.md b/content/general/concepts/binary-search-tree/terms/preorder-traversal/preorder-traversal.md deleted file mode 100644 index 5d5554dd328..00000000000 --- a/content/general/concepts/binary-search-tree/terms/preorder-traversal/preorder-traversal.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -Title: 'Preorder Traversal' -Description: 'First traverses the root, then the left subtree, and then the right subtree.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Algorithms' - - 'Conceptual' - - 'Binary Tree' - - 'Data Structures' - - 'Search' - - 'Trees' -CatalogContent: - - 'complex-data-structures' - - 'paths/computer-science' ---- - -**Preorder traversal** is a depth-first search [algorithm](https://www.codecademy.com/resources/docs/general/algorithm) for a binary search tree that first traverses the root, then the left subtree, and then the right subtree. Its primary use is to create a copy of the tree. - -## Algorithm - -The preorder algorithm can be described as follows: - -```pseudo -Function Preorder(tree) - return root + Preorder(left-subtree) + Preorder(right-subtree) -``` - -## Example - -For the following binary search tree: - -![Binary Search Tree Diagram](https://raw.githubusercontent.com/Codecademy/docs/main/media/binary-tree-labeled.png) - -Preorder traversal provides the nodes in the following order: `4`, `2`, `1`, `3`, `6`, `5`, `7`. diff --git a/content/general/concepts/binary/binary.md b/content/general/concepts/binary/binary.md deleted file mode 100644 index 0d2d1e0ebfc..00000000000 --- a/content/general/concepts/binary/binary.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -Title: 'Binary' -Description: 'Binary is a number system of 1s and 0s which serves as a textual representation method for giving instructions to a computers CPU. In computing and telecommunications, binary codes are used for various methods of encoding data such as turning the character strings of source code, into bit strings or instruction sets for the CPU to execute.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Binary** is a number system of 1's and 0's which serves as a textual representation method for giving instructions to a computers CPU. - -In computing and telecommunications, binary codes are used for various methods of encoding data such as turning the character strings of source code, into bit strings or instruction sets for the CPU to execute. - -A device called a clock sends out regular pulses, and components such as transistors switch on (1) or off (0) to pass or block the pulses. In a transistor: - -- "0" represents no flow of electricity or "off". -- "1" represents electricity being allowed to flow or "on". - -Binary digits can be grouped together into bytes. Binary codes activate the CPU, and the processor executes the binary. Bit is short for binary digit. - -The Binary system was created by Gottfried Leibniz in 1689. diff --git a/content/general/concepts/bitwise-operator/bitwise-operator.md b/content/general/concepts/bitwise-operator/bitwise-operator.md deleted file mode 100644 index 85cb95cdb89..00000000000 --- a/content/general/concepts/bitwise-operator/bitwise-operator.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -Title: 'Bitwise Operator' -Description: 'Bitwise operators are typographic characters used to represent objects that describe operations which can be performed on the most granular level of computing instructions: binary digits. Bitwise operators are used to manipulate these bits in order to facilitate the performance of applications.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -**Bitwise operators** are typographic characters used to represent objects that describe operations which can be performed on the most granular level of computing instructions: binary digits. Bitwise operators are used to manipulate these bits in order to facilitate the performance of applications. - -Bitwise operators give programs greater control over applications by providing detailed implementation of algorithms (e.g., encryption, compression, etc.) and the ability to control physical state to a greater degree via manipulation of individual bits. - -They are widely used in the embedded systems where we need to set/clear/toggle single bits of a specific register without modifying the other contents and also extensively used in areas of graphics, especially XOR (exclusive OR) operations. - -## Bitwise Operator Table - -| Operator | Example | Meaning | -| -------- | -------- | -------------------------- | -| `&` | `a & b` | Bitwise AND | -| `\|` | `a \| b` | Bitwise OR | -| `^` | `a ^ b` | Bitwise XOR (exclusive OR) | -| `~` | `~a` | Bitwise NOT | -| `<<` | `a << n` | Bitwise left shift | -| `>>` | `a >> n` | Bitwise right shift | - -## Example in Python - -```py -x = 7 -y = 9 - -# Bitwise OR operation -print("x | y =", x | y) - -# Bitwise AND operation -print("x & y =", x & y) - -# Bitwise XOR operation -print("x ^ y =", x ^ y) - -# Bitwise NOT operation -print("~x =", ~x) -``` diff --git a/content/general/concepts/bot/bot.md b/content/general/concepts/bot/bot.md deleted file mode 100644 index 0dc46a04be7..00000000000 --- a/content/general/concepts/bot/bot.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -Title: 'Bot' -Description: 'Bots are software applications which perform automated services. Bots perform tedious and repetitive tasks quicker and more efficiently than it would take humans. On the internet, servers use robots.txt files to state the rules for bot behavior on the server. It is estimated that up to half of all internet traffic is made up of computer bots performing tasks on the web.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -**Bots** are software applications which perform automated services. Bots perform tedious and repetitive tasks quicker and more efficiently than it would take humans. - -On the internet, servers use **robots.txt** files to state the rules for bot behavior on the server. It is estimated that up to half of all internet traffic is made up of computer bots performing tasks on the web. Networks of zombie computers are called botnets... scary. - -## Use Cases for Bots - -- To index web content (e.g. Google's web crawlers) -- To moderate or monitor forums for undesirable content (e.g. Twitch's moderator bots) -- To provide round the clock customer service support (e.g. Shopify's customer support bot) -- To simulate human speech patterns or entertain Chat bots (e.g. Apple's Siri) - -Malicious bots can be used to perform actions on servers which do not fulfill the intended desire of the users who maintain the server or attacked application. These bots are often used for denial of service attacks, spam and other nefarious activities.In order to combat malicious bots a number of strategies have been devised. The following are some steps an organization can take to limit the damage malicious bots can do: - -- Static Approach: Analyzes header information to determine a bot’s identity, and blocking it if necessary. -- Challenge-based Approach: Use CAPTCHA or other Turing tests to filter bots from humans. -- Behavioral: Compares behavioral signatures to previous, known signatures of bad bots. diff --git a/content/general/concepts/cache/cache.md b/content/general/concepts/cache/cache.md deleted file mode 100644 index b90e35b72d9..00000000000 --- a/content/general/concepts/cache/cache.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -Title: 'Cache' -Description: 'A cache is data stored locally in an application for faster retrieval.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' - - 'Algorithms' - - 'Queries' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -A **cache** is data stored locally in an application for faster retrieval. Caches work by acting as initial locations for data access when client interfaces make a request for data. - -If the data requested is found we call this a "cache hit" and return the requested data, if the data is not found it is deemed a "cache miss". Cache misses trigger a process for getting the correct data called a "replacement policy". - -Data is transferred between memory and cache in blocks of fixed size called "cache lines" or "cache blocks" after the stale data has been removed. Larger caches have better hit rates but longer latency. To address this trade-off, many computers use multiple layers of caching, with small fast caches backed up by larger, slower caches. If the smaller cache misses, the next fastest cache (level 2, L2) is checked, and so on, before accessing external memory. - -The size of the cache can be calculated as the number of bytes stored in each data block times the number of blocks stored. "Higher-level" caches (i.e. Level 2 and above) have progressively larger numbers of blocks, larger block size and relatively longer access times, but faster than main memory. Effective caching implementations are a major way for applications to improve their performance. - -## Caching with Hardware vs Software - -- Hardware caching strategies are strategies that utilize part of the hardware in a computing device to store the necessary data. Often these computing devices offer caching on multiple layers of the hardware parts responsible for caching. - - - CPU Cache: The Central Processing Unit of a computer contains multiple levels of caching, with L1 being the fastest. Each subsequent cache layer is slower and larger. On multicore chips, the L3 cache is generally shared among all the processing cores. - - - GPU Cache: A computer's Graphics Processing Unit (GPU) has a device memory that is independent of the RAM in the host system and can be used as a cache location. - - - Disk Cache: Disk Cache aka (Disk Buffer) is the embedded memory in a hard disk drive (HDD) acting as a buffer between the rest of the computer and the physical hard disk platter that is used for storage. - -- Software caching strategies are strategies that utilize software to store the necessary data locally and retrieve it in an efficient and optimized manner. - - - CDN: Caching in the browser via Content Delivery Network (CDN) retains copies of web content at various points throughout a network and serves them to clients from the closest network location. - - - Memoization: Memoization is an optimization technique used to speed up applications by storing the results of function calls and returning the cached result when the same inputs occur again. - -That's all for now. Cache me outside, how about that! diff --git a/content/general/concepts/cdn/cdn.md b/content/general/concepts/cdn/cdn.md deleted file mode 100644 index a50065407bc..00000000000 --- a/content/general/concepts/cdn/cdn.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -Title: 'CDN' -Description: 'Content Delivery Network (CDN) is a method of implementing a cache in the browser which retains copies of web content at various points throughout a network and serves them to clients from the closest network location. This is done by geographically distributed group of servers which work together to provide fast delivery of Internet content. CDNs are among recent innovations in technology which have improved the availability and speed with which we are able to access information on the internet because content that would normally have to travel long distances in order to be consumed by the client are now stored in local hubs geographically close in order to serve it to the user much faster.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' - - 'Algorithms' - - 'Queries' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Content Delivery Network (CDN)** is a method of implementing a cache in the browser which retains copies of web content at various points throughout a network and serves them to clients from the closest network location. This is done by geographically distributed group of servers which work together to provide fast delivery of Internet content. - -CDN's are among recent innovations in technology which have improved the availability and speed with which we are able to access information on the internet because content that would normally have to travel long distances in order to be consumed by the client are now stored in local hubs geographically close in order to serve it to the user much faster. - -## CDN Benefits - -- Improving website load times: Pages load much quicker because the resources do not have to retrieve data from long distances. Data is cached locally and served therefore much quicker. -- Reducing bandwidth costs: Due to proximity to the server, data transfer is done with less bandwidth requirements. -- Increasing content availability and redundancy: Having cached details in servers across the globe allows users to consume the data locally and therefore quicker. -- Improving website security: Properly configured CDN's can prevent Denial of Service attacks by distributing the load to servers that can serve the desired resources without being overwhelmed. diff --git a/content/general/concepts/cicd-pipeline/cicd-pipeline.md b/content/general/concepts/cicd-pipeline/cicd-pipeline.md deleted file mode 100644 index d575e98baa5..00000000000 --- a/content/general/concepts/cicd-pipeline/cicd-pipeline.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -Title: 'CICD Pipeline' -Description: 'The CICD pipeline automates the software/application delivery process.' -Subjects: - - 'Developer Tools' - - 'Mobile Development' - - 'Web Design' - - 'Web Development' -Tags: - - 'Developer Tools' - - 'Development' -CatalogContent: - - 'introduction-to-javascript' - - 'paths/back-end-engineer-career-path' ---- - -The **CICD Pipeline** is the combination of continuous integration, delivery, and deployment of software development and application deployment. - -CI (Continuous Integration) is the automation process for developers. CD (Continuous Delivery and Continuous Deployment) is the automated delivery of code to the testing and development steps of the pipeline. These environments are usually in a repository like Github. Continuous deployment refers to code passing automated tests and then placed in production, which in turn is used for automatic deployment. - -## The Four Phases of a CICD Pipeline - -1. Source: The creation of code by developers, which is continuously integrated within a shared repository. Version control systems, like Git are used for tracking and managing changes to the software. When changes are committed to the repository, automated builds and tests are triggered. - -2. Build: The process of using code from the repository to link necessary dependencies and libraries to "build" an executable file. Scripts can be utilized to convert the file to a [virtual machine](https://www.codecademy.com/resources/docs/general/virtual-machines) or container. Logs generated during this time are used to find errors and send notifications to developers when the build is complete. - -3. Test: Automated testing tools confirm the build is working and any new additions are not causing disruptions to a previous working version. If there are any errors, the test results are sent back to the developers to fix. - -4. Deploy: After a build successfully passes rigorous testing, it is automatically deployed to the production environment. Since no deployment is perfect, there are still ways to report the unexpected errors and alert developers, which starts the process all over again. diff --git a/content/general/concepts/cloud-computing/cloud-computing.md b/content/general/concepts/cloud-computing/cloud-computing.md deleted file mode 100644 index 2857545fcb9..00000000000 --- a/content/general/concepts/cloud-computing/cloud-computing.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -Title: 'Cloud Computing' -Description: 'Enables on-demand access to computing services over the internet without requiring direct management of physical infrastructure.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Control Flow' - - 'Conditionals' - - 'Loops' - - 'Switch' -CatalogContent: - - 'learn-how-to-code' - - 'paths/code-foundations' ---- - -**Cloud computing** is a method that helps deliver computing services - including servers, storage, databases, networking, software, and analytics - over the internet (_the cloud_). It allows users to access resources on-demand without investing in and maintaining physical hardware. - -## How Cloud Computing Works - -Cloud computing depends on a pay-as-you-go model, where users can scale resources up or down according to their needs. Cloud providers maintain vast data centers worldwide, ensuring high availability, security, and performance. Users can interact with cloud services through a web interface, API, or command-line tools. - -## Architecture of Cloud Computing - -The cloud computing architecture consists of three main layers: - -- **Frontend:** The client-side interface, including browsers, applications, and devices accessing the cloud. -- **Middleware:** The cloud infrastructure that connects front-end devices with backend services. -- **Backend:** The cloud provider's servers, databases, and storage that handle processing and data management. - -![Architecture of cloud computing](https://raw.githubusercontent.com/Codecademy/docs/main/media/cloud-computing.png) - -## Types of Cloud Computing Services - -Cloud computing services are classified into three major types: - -- **Infrastructure as a Service (IaaS):** Gives access to virtualized computing resources like virtual machines, networking, and storage. Examples include AWS EC2, Google Compute Engine. -- **Platform as a Service (PaaS):** Offers a development environment with tools and infrastructure, allowing developers to build and deploy applications. Examples include Heroku, Google App Engine. -- **Software as a Service (SaaS):** Helps access software applications over the internet, avoiding the need for local installation. Examples include Google Drive, Dropbox, Microsoft Office 365. - -## Use Cases of Cloud Computing - -Cloud computing is used across various industries for different applications, such as: - -- **Web Hosting & Content Delivery:** Websites and applications are hosted on cloud platforms for scalability and availability. -- **Big Data Analytics:** Cloud services handle massive datasets for insights and decision-making. -- **AI & Machine Learning:** Cloud-based ML models and computing power enable AI-driven applications. -- **Remote Work & Collaboration:** Cloud applications like Google Workspace and Microsoft Teams support team collaboration. -- **Disaster Recovery & Backup:** Cloud storage ensures data protection and fast recovery from failures. - -Cloud computing continues to transform businesses and IT infrastructure, offering flexibility, efficiency, and cost-effectiveness. diff --git a/content/general/concepts/cloud-computing/terms/iac/iac.md b/content/general/concepts/cloud-computing/terms/iac/iac.md deleted file mode 100644 index e3b8c5aca39..00000000000 --- a/content/general/concepts/cloud-computing/terms/iac/iac.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -Title: 'Infrastructure as Code (IaC) Frameworks' -Description: 'IaC frameworks enable the management and provisioning of infrastructure through code, promoting automation, consistency, and repeatability.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'IaC' - - 'Automation' - - 'DevOps' -CatalogContent: - - 'learn-how-to-code' - - 'paths/code-foundations' ---- - -Infrastructure as Code (IaC) frameworks allow organizations to define and manage its computing infrastructure using code rather than manual processes. These frameworks turn configuration files into automated instructions for provisioning, configuring, and managing infrastructure resources such as servers, networks, and storage. This approach helps to eliminate inconsistencies that often arise from manual setup and simplifies the process of scaling environments. - -IaC frameworks support version control, meaning that changes to the infrastructure can be tracked over time just like code changes in a software project. This results in improved collaboration among team members and easier rollbacks to previous configurations if issues occur. By automating the provisioning process, IaC decreases the risk of human error, accelerates deployment, and enables CI/CD practices. - -Overall, IaC frameworks streamline infrastructure management, ensuring that environments are reproducible, scalable, and aligned with the needs of modern, agile development practices. diff --git a/content/general/concepts/cms/cms.md b/content/general/concepts/cms/cms.md deleted file mode 100644 index 51b71e3867c..00000000000 --- a/content/general/concepts/cms/cms.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -Title: 'CMS' -Description: '​Content Management System (CMS) is a software application that allows users to create, edit, and manage digital content such as text, images, videos, and other multimedia files.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Wordpress' - - 'CMS' -CatalogContent: - - 'learn-html' - - 'learn-css' - - 'paths/front-end-engineer-career-path' ---- - -A **Content Management System (CMS)** is a software application that allows users to create, edit, and manage digital content such as text, images, videos, and other multimedia files. A CMS typically provides a user-friendly interface that allows users to easily add, delete, and modify content without the need for technical knowledge or coding skills. The primary purpose of a CMS is to make it easier for organizations to manage and maintain their online presence by providing a central platform for organizing and publishing content. - -## CMS Features - -A content management system provides a user-friendly interface that allows non-technical users to easily create, edit, and publish content to a website without having to write any code. The CMS manages all of the underlying technical aspects of the website, such as creating and storing the content in a database, generating the necessary HTML code to display the content on the website, and handling user permissions and other security issues. - -A CMS typically has two main components: a content management application (CMA) and a content delivery application (CDA). The CMA is the user interface that allows users to create and manage content, while the CDA is the backend that handles the delivery of the content to the website or other digital platforms. Some common features of a CMS include managing and organizing digital assets, creating and editing content, and controlling access to different users. - -## Common Examples of CMS - -- **WordPress**: is a free and open-source CMS based on PHP and MySQL and It is the most popular CMS in the world. WordPress offers a wide range of features, including customizable themes, plugins, and widgets, as well as the ability to manage multiple users and content types. -- **Joomla**: Joomla is a free and open-source CMS known for its user-friendly interface and extensibility, making it a popular choice for building websites, blogs, forums, and online communities. Joomla offers a wide range of features, including customizable templates, built-in support for multiple languages, and the ability to manage multiple users and content types. -- **Drupal**: Drupal is a free and open-source CMS known for its scalability and flexibility, making it a popular choice for large, complex websites and applications. Drupal offers a wide range of features, including customizable templates, support for multiple languages, and the ability to manage multiple users and content types. -- **Wix**: Wix is a cloud-based website builder and CMS that allows users to create and manage their own websites without having to write any code. It provides a drag-and-drop interface and a wide range of pre-designed templates, making it easy for users to create professional-looking websites quickly and easily. diff --git a/content/general/concepts/comment/comment.md b/content/general/concepts/comment/comment.md deleted file mode 100644 index d6fa6da343b..00000000000 --- a/content/general/concepts/comment/comment.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -Title: 'Comment' -Description: 'A comment is a note or explanation in the source code of a computer program. They are added with the purpose of making the code easier for ourselves or other developers to understand in the future, and they are generally ignored by compilers and interpreters.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Comments' - - 'Documentation' - - 'Best Practices' -CatalogContent: - - 'learn-python-3' - - 'paths/code-foundations' ---- - -A **comment** is a note or explanation in the source code of a computer program. They are added with the purpose of making the code easier for ourselves or other developers to understand in the future, and they are generally ignored by compilers and interpreters. - -Comments are typically formatted as either: - -- Single-line comments, which start with a comment delimiter and continue until the end of the line. -- Multi-line comments, which start with a start delimiter and end with an end delimiter and can span multiple lines. - -Some programming languages support only one type of comment. For example, Python comments are single-line comments: They start with `#` and continue to the end of the line. - -Other languages employ both single-line and multi-line comments. For example, C and C++ have single-line comments that start with `//` and multi-line comments between `/*` and `*/` that can span multiple lines. - -## Uses - -How best to make use of comments is subject to dispute. Here are some common ways comments are used: - -### Code Description - -Comments can be used to summarize code or to explain the programmer's intent. They can provide additional information to aid in understanding the code. - -### Debugging - -When an error is encountered in the program, a common debugging practice is to comment out some code, meaning to add comment syntax causing that block of code to become a comment, so that it will not be executed in the program. This may be done to exclude certain pieces of code from the program. - -By strategically commenting out and running only parts of the program, the source of the error can be determined through process of elimination. - -### Metadata - -Comments in a computer program often store metadata about a program file. - -In particular, many software maintainers put submission guidelines in comments to help people who read the source code of that program to send any improvements they make back to the maintainer. - -Other metadata includes: - -- The name of the creator of the original version of the program file -- The date when the first version was created -- The names of other people who have edited the program file so far -- The URL of documentation about how to use the program -- The name of the software license for the program file diff --git a/content/general/concepts/computer-hardware/computer-hardware.md b/content/general/concepts/computer-hardware/computer-hardware.md deleted file mode 100644 index a7a07cfee43..00000000000 --- a/content/general/concepts/computer-hardware/computer-hardware.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -Title: 'Computer Hardware' -Description: 'The physical components that comprise computer systems.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Infrastructure' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -**Computer hardware** represents the physical technologies, the infrastructure that enables the processing, and other functionalities that modern devices provide. Advances in computer hardware are part-and-parcel to the growth and proliferation of computing overall. - -Below are common elements integral to the operation of computer systems: diff --git a/content/general/concepts/computer-hardware/terms/cpu/cpu.md b/content/general/concepts/computer-hardware/terms/cpu/cpu.md deleted file mode 100644 index 9e92e8e98c1..00000000000 --- a/content/general/concepts/computer-hardware/terms/cpu/cpu.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -Title: 'CPU' -Description: 'Central Processing Unit (CPU) is used to describe the electrical circuitry in a computer responsible for executing instruction sets derived from programs that have been converted into machine code. CPUs sit at the heart of the system of a computer and are connected to the motherboard. They also have caches which act as memory units capable of temporary storage and quick retrieval of files by the computer.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Central Processing Unit (CPU)** is used to describe the electrical circuitry in a computer responsible for executing instruction sets derived from programs that have been converted into machine code. - -CPU's sit at the heart of the system of a computer and are connected to the motherboard. They also have caches which act as memory units capable of temporary storage and quick retrieval of files by the computer. - -The performance or speed of a processor depends on, among many other factors, the clock rate (usually measured in hertz) and the instructions per clock (IPC), which together are the factors that make up the instructions per second (IPS) which measures CPU performance. CPU's can have multiple cores which allow them to perform operations in parallel to one another which greatly increases the speed and efficiency of the computer. - -## Major Components - -Two major components of the CPU are: - -- Control Unit (CU): The control unit is a component of the CPU that directs the operation of the processor. It controls the response to the instructions that have been sent to the processor via machine code by directing the flow of data between the CPU and the other devices. - -- Arithmetic Logic Unit (ALU): The arithmetic logic unit is a digital circuit within the processor that performs integer arithmetic and bitwise logic operations. diff --git a/content/general/concepts/computer-hardware/terms/processor/processor.md b/content/general/concepts/computer-hardware/terms/processor/processor.md deleted file mode 100644 index 3898c2c521f..00000000000 --- a/content/general/concepts/computer-hardware/terms/processor/processor.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -Title: 'Processor' -Description: 'A processor is the electric circuitry found in computer hardware which is responsible for executing instruction sets derived from programs that have been converted into machine code.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -A **processor** is the electric circuitry found in computer hardware which is responsible for executing instruction sets derived from programs that have been converted into machine code. - -Processors are comprised of components called transistors and capacitors. Transistors and capacitors are made of semiconductor material (silicon, germanium, etc.) which amplify electric currents or turn them off based on the application instructions in the form of binary 0's and 1's being fed to the processor as machine code. - -Moore's law which outlines the exponential improvements achieved by the addition of more computing power and smaller processors over time, has led processors to take the form of "microprocessors", which are implemented on metal-oxide semiconductor integrated circuit chips. Today's processors contain billions of transistors on silicon as small as a fingernail. - -Often the generic reference to a processor refers to the Central Processing Unit (CPU), which in addition to computing is a powerful source for caching data. - -## Different Types of Processors - -- Microprocessor -- Microcontroller -- Embedded Processor -- Digital Signal Processor diff --git a/content/general/concepts/computer-hardware/terms/ram/ram.md b/content/general/concepts/computer-hardware/terms/ram/ram.md deleted file mode 100644 index 2e8557b47ba..00000000000 --- a/content/general/concepts/computer-hardware/terms/ram/ram.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -Title: 'RAM' -Description: 'RAM is an acronym for Random Access Memory, which is a mechanism for storing and retrieving information in random memory units as opposed to other formats that store data in specific memory locations.' -Subjects: - - 'Computer Science' - - 'Web Development' - - 'Data Science' -Tags: - - 'Memory' -CatalogContent: - - 'paths/front-end-engineer-career-path' - - 'paths/computer-science' ---- - -**RAM** is an acronym for **Random Access Memory**, which is a mechanism for storing and retrieving information in random memory units as opposed to other formats that store data in specific memory locations. RAM is considered a volatile place for storage of information due to the fact that data can be lost if power is suddenly unavailable. - -## The Two Types of RAM - -- Static RAM (SRAM): A form of random access memory which does not need to periodically refresh its memory. Static RAM is more expensive and more complex to manufacture than DRAM due to the fact that SRAM can contain multiple transistors in layered architectures within a memory unit. As a result of this more dense architecture it has more processing power and is faster. SRAM is more prevalent in systems requiring substantial computing power. SRAM is primarily used for CPU Caches in processors. - -- Dynamic RAM (DRAM): A form of random access memory which requires the periodic refreshing of data. DRAM is more common than SRAM due to its comparatively simpler mechanical structure. Due to this more simplified structure it is cheaper and easier to manufacture. DRAM is considered main memory in processors. diff --git a/content/general/concepts/conditionals/conditionals.md b/content/general/concepts/conditionals/conditionals.md deleted file mode 100644 index b6a1721c156..00000000000 --- a/content/general/concepts/conditionals/conditionals.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -Title: 'Conditionals' -Description: 'Conditionals in programming are statements that allow the execution of different blocks of code based on certain conditions. They enable programs to make decisions and perform different actions depending on whether a condition is true or false.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Conditionals' - - 'Control Flow' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -**Conditionals** in programming are statements that allow the execution of different blocks of code based on certain criteria. They enable programs to make decisions and perform different actions depending on whether a condition is true or false and help with flow control. - -For example, in the United States a citizen must be 18 years old by election day to be eligible to vote. In this case, the condition would be if a given person is 18 or older that determines if they are eligible to vote (assuming they meet all other requirements). Such decision-making can be accomplished programmatically with conditionals. - -All programming languages support conditionals in various ways, but there are two main conditionals: `if`-`else` and `switch`. - -> **Note:** The following pseudo code blocks are not written in any particular language. - -## If-else Statements - -The `if` statement is the most basic form of a conditional. It checks a condition and executes a block of code if the condition is true. -If the condition is false, the program continues with the next instruction. The basic syntax for an `if` statement is as follows: - -```pseudo -if (condition) { - // Code to be executed if the condition is true -} -``` - -`else` can proceed an `if` statement, and provides an alternative block of code to execute when the specified condition is false. - -```pseudo -if (condition) { - // Code to be executed if the condition is true -} else { - // Code to be executed if the condition is false -} -``` - -For example, regarding the eligibility to vote, an `if`-`else` statement can be written out like so: - -```pseudo -if (int age >= 18) { - print("You can vote"); -} else { - print("You can't vote"); -} -``` - -## Switch Statements - -The `switch` statement provides a way to perform different actions based on various values of a variable or expression. - -It simplifies complex `if`-`else` chains. The basic syntax for a `switch` statement is as follows: - -```pseudo -switch (variable/expression) { - case value1: - // Code to be executed if the variable/expression matches value1. - break; - case value2: - // Code to be executed if the variable/expression matches value2. - break; - // More cases... - default: - // Required code to be executed if none of the cases match the variable/expression. - break; -} -``` - -## Conditionals in Different Languages - -- [C++](https://www.codecademy.com/resources/docs/cpp/conditionals) -- [C#](https://www.codecademy.com/resources/docs/c-sharp/conditionals) -- [Emojicode](https://www.codecademy.com/resources/docs/emojicode/conditionals) -- [Go](https://www.codecademy.com/resources/docs/go/conditionals) -- [Java](https://www.codecademy.com/resources/docs/java/conditionals) -- [JavaScript](https://www.codecademy.com/resources/docs/javascript/conditionals) -- [Kotlin](https://www.codecademy.com/resources/docs/kotlin/conditionals) -- [Powershell](https://www.codecademy.com/resources/docs/powershell/conditionals) -- [Python](https://www.codecademy.com/resources/docs/python/conditionals) -- [PHP](https://www.codecademy.com/resources/docs/php/conditionals) -- [R](https://www.codecademy.com/resources/docs/r/conditionals) -- [Ruby](https://www.codecademy.com/resources/docs/ruby/conditionals) -- [Swift](https://www.codecademy.com/resources/docs/swift/conditionals) diff --git a/content/general/concepts/control-flow/control-flow.md b/content/general/concepts/control-flow/control-flow.md deleted file mode 100644 index 1e1053c8d15..00000000000 --- a/content/general/concepts/control-flow/control-flow.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -Title: 'Control Flow' -Description: 'Control flow refers to the order in which statements and instructions are executed in a program.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Control Flow' - - 'Conditionals' - - 'Loops' - - 'Switch' -CatalogContent: - - 'learn-how-to-code' - - 'paths/code-foundations' ---- - -**Control flow** refers to the order in which statements and instructions are executed in a program. It determines how the program progresses from one instruction to another based on certain conditions and logic. Control flow mechanisms allow developers to create dynamic and flexible programs that can make decisions, repeat tasks, and respond to various inputs. - -## Ways To Control Flow in a Program - -### 1. Conditional Statements - -Conditional statements provide the ability to make decisions within a program based on certain conditions. They typically use [boolean expressions](https://www.codecademy.com/resources/docs/general/data-types/boolean) to determine whether a particular block of code should be executed or skipped. The most common conditional statements are: - -- **If Statements:** An `if` statement evaluates a condition and executes a block of code if the condition is true. It can be followed by optional `else-if` and `else` clauses to handle alternative conditions. - -- **Switch Statements:** A `switch` statement allows the program to choose between multiple alternatives based on the value of an expression. It compares the expression with various cases and executes the code block associated with the first matching case. - -### 2. Loops - -Loops are used to repeat a block of code multiple times until a certain condition is met. They are handy for iterating over collections, performing repetitive tasks, and implementing algorithms that require repeated execution. The following types of loops are commonly used: - -- **For Loops:** A `for` loop executes a block of code a fixed number of times, typically iterating over a range of values. It typically consists of an initialization statement, a condition for termination, and an increment or decrement statement. - -- **While Loops:** A `while` loop repeatedly executes a block of code as long as a specified condition remains true. It evaluates the condition before each iteration, and if the condition becomes false, the loop is terminated. - -- **Do-While Loops:** A `do-while` loop is similar to a `while` loop but guarantees that the code block is executed at least once. It evaluates the condition after executing the block, and if the condition is true, the loop continues. - -### 3. Control Flow Keywords - -Many programming languages provide control flow keywords or constructs that alter the normal flow of program execution. These keywords enable developers to perform specific actions such as early termination, branching, or jumping to a different part of the program. Some commonly used control flow keywords include: - -- **Break:** The `break` keyword is used to exit a loop or switch statement prematurely. It terminates the innermost loop or immediately exits the switch statement. - -- **Continue:** The `continue` keyword is used within a loop to skip the remaining statements in the current iteration and move to the next iteration. - -- **Return:** The `return` keyword is used to exit a function or method and return a value to the caller. It can also be used to terminate the execution of a program in some cases. - -By using these control flow mechanisms, developers can create programs that respond intelligently to different scenarios, making them more flexible and powerful. Understanding control flow is crucial for designing efficient algorithms and writing clean, readable code. diff --git a/content/general/concepts/cors/cors.md b/content/general/concepts/cors/cors.md deleted file mode 100644 index 9cf43cd054e..00000000000 --- a/content/general/concepts/cors/cors.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -Title: 'CORS' -Description: 'CORS is a tool that uses HTTP headers to help servers determine which requests from other resources can access the current, cross-origin resource.' -Subjects: - - 'Code Foundations' - - 'Web Development' -Tags: - - 'Browsers' - - 'Requests' - - 'World Wide Web' -CatalogContent: - - 'introduction-to-javascript' - - 'paths/full-stack-engineer-career-path' ---- - -**Cross-Origin Resource Sharing (CORS)** is a tool that uses [HTTP](https://www.codecademy.com/resources/docs/general/http) headers to help [servers](https://www.codecademy.com/resources/docs/general/server) determine which requests from other resources can access the current, cross-origin resource. - -In most cases, browsers will make a "preflight" request to the host server to ensure the actual request will work. This is another function of CORS. diff --git a/content/general/concepts/cors/terms/access-control-allow-origin/access-control-allow-origin.md b/content/general/concepts/cors/terms/access-control-allow-origin/access-control-allow-origin.md deleted file mode 100644 index acf6a24ff85..00000000000 --- a/content/general/concepts/cors/terms/access-control-allow-origin/access-control-allow-origin.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -Title: 'Access-Control-Allow-Origin' -Description: 'Determines which requests from other pieces of web content have access to the current resource.' -Subjects: - - 'Code Foundations' - - 'Web Development' -Tags: - - 'Browsers' - - 'Requests' - - 'World Wide Web' -CatalogContent: - - 'introduction-to-javascript' - - 'paths/full-stack-engineer-career-path' ---- - -**`Access-Control-Allow-Origin`** in a CORS response header that tells which requests from other pieces of web content (and their `origin`s) have access to the current resource and, thus, can be loaded by the browser. - -## Syntax - -```pseudo -Access-Control-Allow-Origin: directive -``` - -The `directive` is set to either of the following: - -| Directive | Description | -| :-------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `*` | This is a wildcard that tells browsers to allow requests from any content `origin` to access the resource. | -| `origin` | A single, specific `origin` of content made of a scheme/protocol, hostname, and port (e.g., a [URL](https://www.codecademy.com/resources/docs/general/url)). | -| `null` | Sets the `origin` to `null` (however, this should be [avoided](https://w3c.github.io/webappsec-cors-for-developers/#avoid-returning-access-control-allow-origin-null) in most cases). | - -## Example - -The following is an example of a response header that is set to accept requests from the `origin`, "https://www.codecademy.com/learn": - -```shell -Access-Control-Allow-Origin: https://www.codecademy.com/learn -``` diff --git a/content/general/concepts/creational-design-patterns/creational-design-patterns.md b/content/general/concepts/creational-design-patterns/creational-design-patterns.md deleted file mode 100644 index c667af6cd52..00000000000 --- a/content/general/concepts/creational-design-patterns/creational-design-patterns.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -Title: 'Creational Design Patterns' -Description: 'Creational design patterns concern themselves with the instantiation, or creation, of objects.' -Subjects: - - 'Computer Science' - - 'Interview Prep' -Tags: - - 'Classes' - - 'Conceptual' - - 'Constructors' - - 'Objects' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -**Creational design patterns** concern themselves with the instantiation of objects. At the time of creation, additional logic may be needed to decide what or how object types need to be created. - -## Structure - -Most creational design patterns generally abide by the following structure: - -![Creational Design Pattern Structure](https://raw.githubusercontent.com/Codecademy/docs/main/media/creational-design-pattern-structure.png) - -- The "Creator" declares the interface for the new object and returns it. -- The "Implementer" applies the object's interface. - -## Use Cases - -Creational design patterns promote independence and flexibility for object creation. Instead of complex, hard-coded behaviors, objects are defined by a set of smaller behaviors that are more maintainable. They can develop more complex behaviors later on. Some common scenarios for applying creational design patterns include the following: - -- How objects are created should be separate from the system they inhabit. -- Sets of related objects are made to be used together. -- Only the object interface is visible while its implementation is hidden. -- Independent, complex objects need different representations. -- A subclass is created to implement an object created by a superclass. -- Class instances are specified at run-time. -- The client can access a single instance at all times. -- The instance can be extended without being modified. - -The five main creational design patterns are outlined in the entries below: diff --git a/content/general/concepts/creational-design-patterns/terms/abstract-factory-pattern/abstract-factory-pattern.md b/content/general/concepts/creational-design-patterns/terms/abstract-factory-pattern/abstract-factory-pattern.md deleted file mode 100644 index f4a7b4fdb1f..00000000000 --- a/content/general/concepts/creational-design-patterns/terms/abstract-factory-pattern/abstract-factory-pattern.md +++ /dev/null @@ -1,392 +0,0 @@ ---- -Title: 'Abstract Factory Pattern' -Description: 'Relies on a common interface for multiple factories and defers instantiation logic to their concrete model classes.' -Subjects: - - 'Computer Science' - - 'Interview Prep' -Tags: - - 'Classes' - - 'Conceptual' - - 'Constructors' - - 'Objects' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -The **abstract factory pattern** utilizes a common interface for multiple factories without defining their concrete model classes. It is often thought of as a factory of factory patterns where object composition is used to separate instantiation logic from application logic. - -## UML Design - -![UML diagram of an abstract factory](https://raw.githubusercontent.com/Codecademy/docs/main/media/abstract-factory-uml.png) - -## Java Example - -To illustrate the abstract factory pattern, below is a real-world example written in Java, that explores potential considerations for a banking account system. A new customer will request either a current or savings account. The customer may also be entitled to different privileges depending on their credit score. Below is a table of accounts and their privileges: - -| Customer Type | Current | Saving | -| ------------- | --------------------------- | --------------------- | -| Gold | Max overdraft limit of 3500 | Interest rate of 5% | -| Silver | Max overdraft limit of 1200 | Interest rate of 3% | -| Bronze | Max overdraft limit of 500 | Interest rate of 1.5% | -| Builder | No overdraft | Interest rate of 1.5% | - -To simulate requesting and receiving a customer's credit score, a gateway has been mocked below. When given a customer's name, the`CreditAgencyGateway` class should return an appropriate `Customer` object. This class can be used later to see the different paths through our abstract factory. - -```java -public class CreditAgencyGateway { - // Depending on which name is searched for, a different customer object is returned - public Customer getCustomer(String name) { - return switch (name) { - case "Harry" -> new Customer("Harry", - "Potter", - LocalDate.of(1980, 7, 31), - "4 Privet Drive, Little Whinging", - 795); - case "Ron" -> new Customer("Ron", - "Weasley", - LocalDate.of(1980, 3, 1), - "The Burrow, Devon", - 379); - case "Hermione" -> new Customer("Hermione", - "Granger", - LocalDate.of(1979, 9, 19), - "Hampstead Garden Suburb, London", - 843); - default -> throw new IllegalArgumentException("Could not return the credit history for " + name); - }; - } -} -``` - -The `CreditAgencyGateway` class uses a [`switch` statement](https://www.codecademy.com/resources/docs/java/switch) to query a provided `name`. If the name is recognized, a new customer is returned. Otherwise, an exception is thrown. - -One of the main advantages of factory patterns is they allow for a large number of model classes and enforce a common interface between them. In the code below, an abstract model `CurrentAccount` class works as an extension for its concrete sub-classes to be based on: - -```java -public abstract class CurrentAccount { - private final String accountUID = UUID.randomUUID().toString(); - private final Customer accountHolder; - private int balance; - private int agreedOverdraftLimit; - - public CurrentAccount(Customer accountHolder, int initBalance, int agreedOverdraftLimit) { - this.accountHolder = accountHolder; - this.balance = initBalance; - this.agreedOverdraftLimit = agreedOverdraftLimit; - } - - public void addFunds(final int amount) { - balance += amount; - } - - public void withdrawFunds(final int amount) { - if (amount < balance + agreedOverdraftLimit) { - balance -= amount; - } else { - System.out.println("Insufficient funds. Unable to withdraw " + amount); - } - } - - // Enforces concrete classes to override this method - public abstract void increaseOverdraft(int requestedLimit); - - // Getters below -} -``` - -The parent `CurrentAccount` class above, as well as providing the common fields and constructor, requires its children to implement the `.increaseOverdraft()` method. This is the differentiating feature described between each current account. - -The code snippets below are the concrete implementations of `CurrentAccount`. The first is the Gold level: - -```java -public class GoldPersonal extends CurrentAccount { - // The Gold Personal has a high-max overdraft limit - public static final int MAX_OVERDRAFT = 3500; - - public GoldPersonal(Customer accountHolder, int initBalance, int agreedOverdraftLimit) { - super(accountHolder, initBalance, agreedOverdraftLimit); - } - - // Concrete overridden method - @Override - public void increaseOverdraft(int requestedLimit) { - if (requestedLimit < MAX_OVERDRAFT) { - this.setAgreedOverdraftLimit(requestedLimit); - } - } -} -``` - -Next is the Silver-level implementation of the `CurrentAccount`: - -```java -public class SilverPersonal extends CurrentAccount { - // The Silver Personal has a mid-max overdraft limit - public static final int MAX_OVERDRAFT = 1200; - - public SilverPersonal(Customer accountHolder, int initBalance, int agreedOverdraftLimit) { - super(accountHolder, initBalance, agreedOverdraftLimit); - } - - // Concrete overridden method - @Override - public void increaseOverdraft(int requestedLimit) { - if (requestedLimit < MAX_OVERDRAFT) { - this.setAgreedOverdraftLimit(requestedLimit); - } - } -} -``` - -Here is the Bronze-level implementation: - -```java -public class BronzePersonal extends CurrentAccount { - // The Bronze Personal has a low-max overdraft limit - public static final int MAX_OVERDRAFT = 500; - - public BronzePersonal(Customer accountHolder, int initBalance, int agreedOverdraftLimit) { - super(accountHolder, initBalance, agreedOverdraftLimit); - } - - // Concrete overridden method - @Override - public void increaseOverdraft(int requestedLimit) { - if (requestedLimit < MAX_OVERDRAFT) { - this.setAgreedOverdraftLimit(requestedLimit); - } - } -} -``` - -And finally, the Credit Builder: - -```java -public class CreditBuilder extends CurrentAccount { - // The Credit Builder does not allow for an overdraft - public static final int MAX_OVERDRAFT = 0; - - public CreditBuilder(Customer accountHolder, int initBalance, int agreedOverdraftLimit) { - super(accountHolder, initBalance, agreedOverdraftLimit); - } - - // Concrete overridden method - @Override - public void increaseOverdraft(int requestedLimit) { - if (requestedLimit < MAX_OVERDRAFT) { - this.setAgreedOverdraftLimit(requestedLimit); - } - } -} -``` - -In each concrete current account, a `static` variable (`MAX_OVERDRAFT`) has been provided and constructed with the correct value. This is then used in the `.increaseOverdraft()` method to ensure this limit is not exceeded. - -Below provides an abstract model `SavingAccount` class for its concrete sub-classes to be based on: - -```java -public abstract class SavingAccount { - private final String accountUID = UUID.randomUUID().toString(); - private final Customer accountHolder; - private final LocalDate dateOpened; - private double balance; - - public SavingAccount(Customer accountHolder, LocalDate dateOpened, double initBalance) { - this.accountHolder = accountHolder; - this.dateOpened = dateOpened; - this.balance = initBalance; - } - - public void addFunds(final int amount) { - balance += amount; - } - - public void withdrawFunds(final int amount) { - balance -= amount; - } - - // Enforces concrete classes to override this method - public abstract void addInterest(); - - // Getters below -} -``` - -Much like `CurrentAccount`, `SavingAccount` provides the common fields and constructor and requires its children to implement the `.addInterest()` method. This is the differentiating feature described between each savings account. - -Below provides the concrete implementations of `SavingAccount` for this example. The first is the Gold level: - -```java -public class GoldSaver extends SavingAccount { - // The Gold Saver has a high-interest rate - public static final double INTEREST_RATE_MULTIPLIER = 1.05; - - public GoldSaver(Customer accountHolder, LocalDate dateOpened, double initBalance) { - super(accountHolder, dateOpened, initBalance); - } - - // Concrete overridden method - @Override - public void addInterest() { - if (LocalDate.now().getMonth() == this.getDateOpened().getMonth() - && LocalDate.now().getDayOfMonth() == this.getDateOpened().getDayOfMonth()) { - this.setBalance(this.getBalance() * INTEREST_RATE_MULTIPLIER); - } - } -} -``` - -Then the Silver level: - -```java -public class SilverSaver extends SavingAccount { - // The Silver Saver has a mid-interest rate - public static final double INTEREST_RATE_MULTIPLIER = 1.03; - - public SilverSaver(Customer accountHolder, LocalDate dateOpened, double initBalance) { - super(accountHolder, dateOpened, initBalance); - } - - // Concrete overridden method - @Override - public void addInterest() { - if (LocalDate.now().getMonth() == this.getDateOpened().getMonth() - && LocalDate.now().getDayOfMonth() == this.getDateOpened().getDayOfMonth()) { - this.setBalance(this.getBalance() * INTEREST_RATE_MULTIPLIER); - } - } -} -``` - -And finally the Bronze level implementation: - -```java -public class BronzeSaver extends SavingAccount { - // The Bronze Saver has a low-interest rate - public static final double INTEREST_RATE_MULTIPLIER = 1.015; - - public BronzeSaver(Customer accountHolder, LocalDate dateOpened, int initBalance) { - super(accountHolder, dateOpened, initBalance); - } - - // Concrete overridden method - @Override - public void addInterest() { - if (LocalDate.now().getMonth() == this.getDateOpened().getMonth() - && LocalDate.now().getDayOfMonth() == this.getDateOpened().getDayOfMonth()) { - this.setBalance(this.getBalance() * INTEREST_RATE_MULTIPLIER); - } - } -} -``` - -In each concrete savings account, a `static` variable, the `INTEREST_RATE_MULTIPLIER`, has been provided and constructed with the correct value. It is then used to calculate interest in the `.addInterest()` method. - -The purpose of the `AccountFactory` is to return one of its concrete factories. Below provides the example of the abstract factory `AccountFactory`. - -```java -public abstract class AccountFactory { - // Returns different concrete factory depending on AccountType - public static AccountFactory getAccountFactory(AccountType accountType) { - return switch (accountType) { - case SAVINGS -> new SavingAccountFactory(); - case CURRENT -> new CurrentAccountFactory(); - default -> throw new IllegalArgumentException("Unknown account type: " + accountType); - }; - } - - // Enforces concrete factories to override this method - public abstract T getAccount(Customer customer); - - // Returns CustomerType depending on creditScore property. Put in the abstract to reduce duplicate code - protected CustomerType getCustomerType(Customer customer) { - if (customer.getCreditScore() > 700) { - return CustomerType.GOLD; - } else if (customer.getCreditScore() > 400) { - return CustomerType.SILVER; - } else if (customer.getCreditScore() > 200) { - return CustomerType.BRONZE; - } else { - return CustomerType.BUILDER; - } - } -} -``` - -The `AccountFactory` enforces its concrete sub-classes to implement its abstract `.getAccount()` method. A `.getCustomerType()` is included to reduce duplication. The same logic for returning a `CustomerType` is used in `CurrentAccountFactory` and `SavingAccountFactory`. We might expect this logic to be in the concrete classes below as they use this logic, but in this example, it doesn't matter. - -Finally, the `.getAccountFactory()` method uses a `switch` statement to return a concrete factory depending on an `AccountType`, with the `enum` provided below: - -```java -public enum AccountType { - SAVINGS, - CURRENT -} -``` - -The following factories, `CurrentAccountFactory` and `SavingAccountFactory`, are responsible for returning the correct concrete model class when called: - -```java -public class CurrentAccountFactory extends AccountFactory { - // Concrete overridden method - @Override - public CurrentAccount getAccount(Customer customer) { - final CustomerType customerType = getCustomerType(customer); - - return switch (customerType) { - case GOLD -> new GoldPersonal(customer, 0, 0); - case SILVER -> new SilverPersonal(customer, 0, 0); - case BRONZE -> new BronzePersonal(customer, 0, 0); - case BUILDER -> new CreditBuilder(customer, 0, 0); - default -> throw new IllegalArgumentException("Unable to create account."); - }; - } -} -``` - -```java -public class SavingAccountFactory extends AccountFactory { - // Concrete overridden method - @Override - public SavingAccount getAccount(Customer customer) { - final CustomerType customerType = getCustomerType(customer); - - return switch (customerType) { - case GOLD -> new GoldSaver(customer, LocalDate.now(), 0); - case SILVER -> new SilverSaver(customer, LocalDate.now(), 0); - case BRONZE, BUILDER -> new BronzeSaver(customer, LocalDate.now(), 0); - default -> throw new IllegalArgumentException("Unable to create account."); - }; - } -} -``` - -An implementation has been provided for the `.getAccount()` method. The `CustomerType` is worked out using its parent's `getCustomerType` method and captured before being used in a `switch` statement that returns the appropriate objects. - -The `Main` class below starts the program and acts as the client in this example. It begins by getting a customer from the `CreditAgencyGateway` and gets an appropriate factory by using the `.getAccountFactory()` method. Changing the name in the `.getCustomer()` method or changing the `AccountType` in the `.getAccountFactory()` method will yield different results. A specific `CurrentAccount` or `SavingAccount` can then be returned by the `getAccount` method. - -```java -public class Main { - public static void main(String[] args) { - final CreditAgencyGateway creditAgencyGateway = new CreditAgencyGateway(); - - // Get customer. Change name to change outputted account types. - final Customer customer = creditAgencyGateway.getCustomer("Hermione"); - - // Capture correct concrete factory - AccountFactory accountFactory = AccountFactory.getAccountFactory(AccountType.CURRENT); - - // Get correct account - final CurrentAccount currentAccount = (CurrentAccount) accountFactory.getAccount(customer); - System.out.println(currentAccount.getClass()); - - // Capture correct concrete factory - accountFactory = AccountFactory.getAccountFactory(AccountType.SAVINGS); - - // Get correct account - final SavingAccount savingAccount = (SavingAccount) accountFactory.getAccount(customer); - System.out.println(savingAccount.getClass()); - } -} -``` diff --git a/content/general/concepts/creational-design-patterns/terms/builder-pattern/builder-pattern.md b/content/general/concepts/creational-design-patterns/terms/builder-pattern/builder-pattern.md deleted file mode 100644 index 090cc7c86de..00000000000 --- a/content/general/concepts/creational-design-patterns/terms/builder-pattern/builder-pattern.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -Title: 'Builder Pattern' -Description: 'Decouples the responsibility of object creation from the desired objects class.' -Subjects: - - 'Computer Science' - - 'Interview Prep' -Tags: - - 'Classes' - - 'Conceptual' - - 'Constructors' - - 'Objects' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -The **builder pattern** decouples the responsibility of object creation from the desired object's class. It is normally implemented when a class requires many properties to be set during its construction and may be used to ensure immutability. - -## UML Design - -![UML diagram of a builder](https://raw.githubusercontent.com/Codecademy/docs/main/media/builder-uml.png) - -## Java Example - -To illustrate the builder pattern, below provides a real-world example in Java, depicting potential considerations for a pizza order. The -`PizzaOrder` class has 5 properties: - -- `toppings` -- `cheese` -- `sauce` -- `pizzaBase` -- `stuffCrust` - -During construction, both `pizzaBase` and `stuffCrust` are required to be set explicitly, and should cheese and/or sauce not be set before `.build()`, default values will be assigned. Construction of a `PizzaOrder` object is enforced through the `PizzaOrder`'s `Builder` inner class. After creation, a `PizzaOrder` object's properties are immutable. - -```java -public class PizzaOrder { - public static class Builder { - // Same properties as the outer PizzaOrder class - private final List toppings; - private final Cheese cheese; - private final Sauce sauce; - private final Base pizzaBase; - private final boolean stuffCrust; - - public Builder(Base pizzaBase, boolean stuffCrust) { - // Enforce required choices - this.pizzaBase = pizzaBase; - this.stuffCrust = stuffCrust; - // Default values - this.cheese = Cheese.MOZZARELLA; - this.sauce = Sauce.TOMATO; - } - - // Sets property and returns itself (either for next property to be set, or .build() to be invoked) - public Builder toppings(List toppings) { - this.toppings = toppings; - return this; - } - - public Builder cheese(Cheese cheese) { - this.cheese = cheese; - return this; - } - - public Builder sauce(Sauce sauce) { - this.sauce = sauce; - return this; - } - - public Builder base(Base pizzaBase) { - this.pizzaBase = pizzaBase; - return this; - } - - public Builder stuffCrust(boolean stuffCrust) { - this.stuffCrust = stuffCrust; - return this; - } - - // When .build() is called, a new concrete object is returned with the desired properties set - public PizzaOrder build() { - return new PizzaOrder(this); - } - } - - private final List toppings; - private final Cheese cheese; - private final Sauce sauce; - private final Base pizzaBase; - private final boolean stuffCrust; - - // Removes default constructor and forces object creation through Builder inner class - private PizzaOrder(Builder builder) { - // Constructs concrete object with builder's property values - this.toppings = builder.toppings; - this.cheese = builder.cheese; - this.sauce = builder.sauce; - this.stuffCrust = builder.stuffCrust; - } - - // Getters below -} -``` - -> **Note:** Setters are negated for immutability. Some Enums have been provided to safely model the choices an order may have. - -```java -public enum Topping { - HAM, - PINEAPPLE, - SWEETCORN -} -``` - -```java -public enum Sauce { - TOMATO, - BBQ -} -``` - -```java -public enum Base { - THIN_BASE, - DEEP_PAN -} -``` - -```java -public enum Cheese { - NONE, - MOZZARELLA -} -``` - -The `Main` class below shows how to instantiate a `PizzaOrder` object through its inner `Builder` class. - -```java -public class Main { - public static void main(String[] args) { - // Create concrete object - PizzaOrder pizzaOrder = new PizzaOrder.Builder(Base.DEEP_PAN, true).sauce(Sauce.BBQ).build(); - } -} -``` diff --git a/content/general/concepts/creational-design-patterns/terms/factory-pattern/factory-pattern.md b/content/general/concepts/creational-design-patterns/terms/factory-pattern/factory-pattern.md deleted file mode 100644 index b9f8dd2665c..00000000000 --- a/content/general/concepts/creational-design-patterns/terms/factory-pattern/factory-pattern.md +++ /dev/null @@ -1,269 +0,0 @@ ---- -Title: 'Factory Pattern' -Description: 'Defers instantiation logic of a parent abstract class to its concrete sub-classes.' -Subjects: - - 'Computer Science' - - 'Interview Prep' -Tags: - - 'Classes' - - 'Conceptual' - - 'Constructors' - - 'Objects' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -The **factory pattern** defers instantiation logic of a parent abstract class to its concrete sub-classes. At the time of object creation, the specific class type may not be known, in which a creator class' factory method is used to decouple this identifying logic. This is typically done through the methods, parameters, and a `switch` statement. - -## UML Design - -![UML diagram of a factory](https://raw.githubusercontent.com/Codecademy/docs/main/media/factory-uml.png) - -## Java Example - -To illustrate the factory pattern, below provides a real-world example, in Java, depicting potential considerations for a taxi and food delivery booking application. - -A user of the app will need to send a request for either a standard taxi, a large taxi, a mini bus, or wish to have food delivered from a restaurant. However, before the program understands their needs, the needed request needed remains unknown. When a request object is created, an estimated price is calculated and returned. - -Below provides a parent abstract class of a taxi request: - -```java -public abstract class TaxiRequest { - protected T pickUpLocation; - protected String destination; - protected double distance; - protected double estimatedPrice; - - public TaxiRequest(final T pickUpLocation, final String destination, final int distance) { - this.createTaxiRequest(pickUpLocation, destination, distance); - } - - public abstract void createTaxiRequest(final T pickUpLocation, final String destination, final int distance); - - // Getters and setters -} -``` - -> **Note:** As the `.pickUpLocation` property may be an address or a restaurant, generics are used when modeling the `TaxiRequest`. The other properties' object types are known. - -The constructor of `TaxiRequest` calls an abstract method `.createTaxiRequest()`. This enforces `TaxiRequest`'s subclasses to override the method with instantiation logic. Although the constructors of the base class may make use of the abstract super's constructor, instantiation logic remains in the concrete subclass. - -Below provides the concrete subclasses of `StandardTaxiRequest`, `SevenSeaterTaxiRequest`, and `MiniBusTaxiRequest` that all extend the abstract `TaxiRequest` class above. - -`StandardTaxiRequest`: - -```java -public class StandardTaxiRequest extends TaxiRequest { - private static final double FARE_MULTIPLIER = 1.5; - - public StandardTaxiRequest(final String pickUpLocation, final String destination, final int distance) { - super(pickUpLocation, destination, distance); - } - - @Override - public void createTaxiRequest(final String pickUpLocation, final String destination, final int distance) { - this.pickUpLocation = pickUpLocation; - this.destination = destination; - this.distance = distance; - this.estimatedPrice = distance * FARE_MULTIPLIER; - System.out.println("A taxi is on its way. The estimated fare is £" + estimatedPrice + "."); - } -} -``` - -`SevenSeaterTaxiRequest`: - -```java -public class SevenSeaterTaxiRequest extends TaxiRequest { - private static final double FARE_MULTIPLIER = 2; - - public SevenSeaterTaxiRequest(String pickUpLocation, String destination, int distance) { - super(pickUpLocation, destination, distance); - } - - @Override - public void createTaxiRequest(String pickUpLocation, String destination, int distance) { - this.pickUpLocation = pickUpLocation; - this.destination = destination; - this.distance = distance; - this.estimatedPrice = distance * FARE_MULTIPLIER; - System.out.println("A large taxi is on its way. The estimated fare is £" + estimatedPrice + "."); - } -} -``` - -`MiniBusTaxiRequest`: - -```java -public class MiniBusTaxiRequest extends TaxiRequest { - private static final double FARE_MULTIPLIER = 3.4; - - public MiniBusTaxiRequest(final String pickUpLocation, final String destination, final int distance) { - super(pickUpLocation, destination, distance); - } - - @Override - public void createTaxiRequest(final String pickUpLocation, final String destination, final int distance) { - this.pickUpLocation = pickUpLocation; - this.destination = destination; - this.distance = distance; - this.estimatedPrice = distance * FARE_MULTIPLIER; - System.out.println("A minibus is on its way. The estimated fare is £" + estimatedPrice + "."); - } -} -``` - -As these model classes inherit their properties from the base class, they each automatically have `pickUpLocation`, `destination`, and `distance` as fields. -The `pickUpLocation` in these cases is an address, and therefore, `pickUpLocation` is of type `String`. - -The constructors for these concrete models, call `super()` which in turn calls the overridden method `.createTaxiRequest()`. - -The overridden method `createTaxiRequest()` handles the instantiation logic of the class. The properties `.pickUpLocation`, `.destination`, and `.distance` are set, with the `.estimatedPrice` programmatically calculated using the static property `FARE_MULTIPLIER`. A print statement has been added to help illustrate the pattern. - -Below provides the concrete subclass `FoodDeliveryRequest` that extends the abstract class, `TaxiRequest`: - -```java -public class FoodDeliveryRequest extends TaxiRequest { - - private static final double FARE_MULTIPLIER = 0.7; - - private double foodBill; - - public FoodDeliveryRequest(Restaurant pickUpLocation, String destination, int distance) { - super(pickUpLocation, destination, distance); - } - - @Override - public void createTaxiRequest(Restaurant pickUpLocation, String destination, int distance) { - this.pickUpLocation = pickUpLocation; - this.destination = destination; - this.distance = distance; - this.foodBill = pickUpLocation.getPrice(); - this.estimatedPrice = distance * FARE_MULTIPLIER + this.foodBill; - - System.out.println("Your food from " - + this.pickUpLocation.toString().toLowerCase() - + " is on its way! The total bill (including delivery) is £" - + this.estimatedPrice - + "."); - } -} -``` - -The `FoodDeliveryRequest` differs from the other concrete model classes in two important ways. Firstly, the `estimatedPrice` is calculated to include the cost of food from the restaurant, and secondly, the `pickUpLocation` is a restaurant, not an address. - -Below provides an enum modeling the restaurant choice and its associated price: - -```java -public enum Restaurant { - MCDONALD(5.30), - KFC(4.99), - BURGER_KING(8.20), - DOMINOS(10.99); - - private final double price; - - Restaurant(double price) { - this.price = price; - } - - // Getter -} -``` - -> **Note:** When the restaurant type is chosen, the constructor provides the property `price` with the correct value. - -The factory class gives an opportunity to think about how the client may need to instantiate different objects and what information may be required. In this example, if little information is provided, a `StandardTaxiRequest` is returned. If the `pickUpLocation` is a restaurant then a `FoodDeliveryRequest` is returned. A taxi can be ordered based on the amount of passengers. And finally a specific `TaxiType` can be explicitly requested. - -Below provides the creator class to determine and instantiate request objects: - -```java -public class TaxiCreator { - - // Creates a default taxi request should little information be provided - public static TaxiRequest getTaxiRequest(final String pickUpLocation, final String destination, final int distance) { - return new StandardTaxiRequest(pickUpLocation, destination, distance); - } - - // Creates a food pick up request should a Restaurant order be the pick up location - public static TaxiRequest getTaxiRequest(final Restaurant pickUpLocation, final String destination, final int distance) { - return new FoodDeliveryRequest(pickUpLocation, destination, distance); - } - - // Creates taxi request based on the number of passengers - public static TaxiRequest getTaxiRequest(final int numOfPassengers, final String pickUpLocation, final String destination, final int distance) { - if (numOfPassengers <= 0 || numOfPassengers >= 30) { - throw new IllegalArgumentException("Unable to create TaxiRequest for " + numOfPassengers + " passengers"); - } - - switch (numOfPassengers) { - case 1: case 2: case 3: case 4 : - return new StandardTaxiRequest(pickUpLocation, destination, distance); - case 5: case 6: - return new SevenSeaterTaxiRequest(pickUpLocation, destination, distance); - default: - return new MiniBusTaxiRequest(pickUpLocation, destination, distance); - } - } - - // Creates taxi request based on TaxiType - public static TaxiRequest getTaxiRequest(final TaxiType taxiType, final String pickUpLocation, final String destination, final int distance) throws Exception { - switch (taxiType) { - case STANDARD_TAXI: - return new StandardTaxiRequest(pickUpLocation, destination, distance); - case SEVEN_SEATER: - return new SevenSeaterTaxiRequest(pickUpLocation, destination, distance); - case MINI_BUS: - return new MiniBusTaxiRequest(pickUpLocation, destination, distance); - default: - throw new IllegalArgumentException("TaxiType " + taxiType + " not recognised"); - } - } -} -``` - -The factory method `.getTaxiRequest()` has been overloaded using four different signatures. - -1. The first `.getTaxiRequest(String, String int)` that returns a `StandardTaxiRequest` object as the `pickUpLocation` is of type `String` and both - `numberOfPassingers` and `TaxiType` have been negated from the method call. - -2. The second `.getTaxiRequest(Restaurant, String, int)` that returns a `FoodDeliveryRequest` object as the `pickUpLocation` is of type `Restaurant`. - -3. The third `.getTaxiRequest(int, String, String, int)` that returns a taxi request is based on the number of passengers provided and is determined by a switch statement. Should the number of passengers exceed or fall below the required amount, an exception is thrown. - -4. Finally, the fourth `.getTaxiRequest(TaxiType, String, String, int)` that returns a taxi request based on the `TaxiType` is specified and determined by a switch statement. Should the `TaxiType` not be recognized, an exception is thrown. - -Below provides the enum `TaxiType` for requesting a specific taxi: - -```java -public enum TaxiType { - STANDARD_TAXI, - SEVEN_SEATER, - MINI_BUS -} -``` - -The `Main` class below, starts the program and acts as the client in this example. It asks the creator to instantiate different taxi request objects by calling the overloaded methods. The print statement in each of the model classes should be outputted to the console respectively. - -```java -public class Main { - - public static void main(String[] args) throws Exception { - System.out.print("Standard taxi (default) - "); - TaxiCreator.getTaxiRequest("1 Charming Av", "49 GoodFeeling Ln", 5); - - System.out.print("Food Delivery (Restaurant) - "); - TaxiCreator.getTaxiRequest(Restaurant.MCDONALD,"49 GoodFeeling Ln", 5); - - System.out.print("Seven seater (passengers) - "); - TaxiCreator.getTaxiRequest(6, "1 Charming Av", "49 GoodFeeling Ln", 5); - - System.out.print("Mini bus (TaxiType) - "); - TaxiCreator.getTaxiRequest(TaxiType.MINI_BUS, "1 Charming Av", "49 GoodFeeling Ln", 5); - - System.out.print("Error - "); - TaxiCreator.getTaxiRequest(345, "1 Charming Av", "49 GoodFeeling Ln", 5); - } -} -``` diff --git a/content/general/concepts/creational-design-patterns/terms/prototype-pattern/prototype-pattern.md b/content/general/concepts/creational-design-patterns/terms/prototype-pattern/prototype-pattern.md deleted file mode 100644 index 9af1765cfec..00000000000 --- a/content/general/concepts/creational-design-patterns/terms/prototype-pattern/prototype-pattern.md +++ /dev/null @@ -1,301 +0,0 @@ ---- -Title: 'Prototype Pattern' -Description: 'Adds cloning functionality to an objects class.' -Subjects: - - 'Computer Science' - - 'Interview Prep' -Tags: - - 'Classes' - - 'Conceptual' - - 'Constructors' - - 'Objects' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -The **prototype pattern** adds cloning functionality to an object's class. After the instantiation of an initial object, the prototype removes the need for the `new` keyword in creating subsequent objects at run time. New objects are created using the property values of a pre-existing object. - -Two types of copying are associated with the prototype pattern: - -- Shallow copy: Copies the immediate property values. -- Deep copy: Copies the immediate values, plus any referenced object. - -## Example: Shallow Copy vs Deep Copy - -Shown below is a model consisting of two classes: `TvSeries` and `Episode`. Cloning functionality has been added to `TvSeries` by implementing the `Cloneable` interface. - -```java -public class TvSeries implements Cloneable { - private final String name; - private final int seriesNo; - // Notice one or more properties are a complex type and mutable - private final List episodes; - - public TvSeries(String name, int seriesNo, List episodes) { - this.name = name; - this.seriesNo = seriesNo; - this.episodes = episodes; - } - - // Shallow copy method - @Override - public TvSeries clone() throws CloneNotSupportedException { - // Cast to TvSeries as super returns Object - return (TvSeries) super.clone(); - } - - // Deep copy - public TvSeries deepCopy() { - // New Episode objects are created during the copy - final List episodes = new ArrayList<>(); - - for (Episode episode : this.episodes) { - episodes.add(new Episode(episode.getName, episode.getEpNo)); - } - - return new TvSeries(this.name, this.seriesNo, episodes); - } - - // Getters and toString -} -``` - -`TvSeries` class has a list of complex objects (`Episode`) as one of its properties. Shallow copying through `clone()` will only copy the outermost `TvSeries` object and negate creating new objects to reference for the list of episodes. - -The `deepCopy()` method, by comparison, iterates through the list of `Episode` to create a list of new `TvSeries` objects. This list is then used by the `TvSeries` constructor when creating a copy. The new `TvSeries` object references a new or independent list of episodes. - -Below provides a model class for the complex object type `Episode` described above: - -```java -public class Episode { - private String name; - private int epNo; - - public Episode(String name, int epNo) { - this.name = name; - this.epNo = epNo; - } - - // Getters, setters, and toString -} -``` - -> **Note:** The properties of the `Episode` class are mutable. - -The following code demonstrates a limitation of the shallow copy: - -```java -public class Main { - public static void main(String[] args) throws CloneNotSupportedException { - // A 'new' TvSeries object is created as seriesOne - Episode episodeOne = new Episode("Hello Friend", 13); - final Series seriesOne = new Series("Mr Robot", 1, Collections.singletonList(episodeOne)); - - // A second TvSeries object is created by shallow copying seriesOne - final Series seriesTwo = seriesOne.clone(); - // Change the name of S2ep1 - seriesTwo.getEpisodes().get(0).setName("Unmask"); - // S2ep1 name has changed - System.out.println(seriesTwo.getEpisodes().get(0).getName()); // Unmask - // But, so has S1ep1 :( - System.out.println(seriesOne.getEpisodes().get(0).getName()); // Unmask - } -} -``` - -Our main method starts by creating two new objects: `episodeOne` of type `Episode` and `seriesOne` of type `Series`. `seriesOne` is then cloned using a shallow copy to instantiate `seriesTwo`, and as a result, our program now has two `Series` objects (`seriesOne` and `seriesTwo`) referencing a single list of episodes in memory. Finally, when the name of the episode is changed through its setter method, the name change appears in both Series 1 Episode 1 and Series 2 Episode 1. - -Below is the same example but using the `deepCopy()` in place of `clone()`: - -```java -public class Main { - public static void main(String[] args) throws CloneNotSupportedException { - // A 'new' TvSeries object is created as seriesOne - Episode episodeOne = new Episode("Hello Friend", 13); - final Series seriesOne = new Series("Mr Robot", 1, Collections.singletonList(episodeOne)); - - // A second TvSeries object is created using a deep copy of seriesOne - final Series seriesTwo = seriesOne.deepCopy(); - // Change the name of S2ep1 - seriesTwo.getEpisodes().get(0).setName("Unmask"); - // S2ep1 name has changed - System.out.println(seriesTwo.getEpisodes().get(0).getName()); // Unmask - // And s1ep1 name remains correct :) - System.out.println(seriesOne.getEpisodes().get(0).getName()); // Hello Friend - } -} -``` - -Rather than instantiating two `TvSeries` objects that reference a single list of episodes in memory, the `deepCopy()` creates a list of new episodes in memory by iterating over the old. There are now two `TvSeries` objects referencing two `Episode` objects in memory, and the name of each `Episode` object can be changed independently. - -## UML Design - -![UML diagram of a prototype](https://raw.githubusercontent.com/Codecademy/docs/main/media/prototype-uml.png) - -## Example: Prototype - -To illustrate the prototype pattern, below provides a real-world example, in Java, depicting potential considerations for a video streaming service. For some reason, returning `Film` or `TvSeries` objects is considered to be expensive. When providing the user with their watch history, the `UserRepository` can be used to set the needed properties from cloned objects provided by a registry. - -A `UserRepository` has been created with two methods: `getUserFilmHistory()` and `getUserTvSeriesHistory()`. Both simply return a list of `Strings` representing a user's watch history. - -```java -public class UserRepository { - // Returns a list of film titles - public List getUserFilmsHistory() { - return Arrays.asList( - "Army of the Dead", - "King Arthur: Legend of the Sword", - "Total Recall", - "Friday the 13th", - "The General's Daughter", - "American Gangster", - "Replicas", - "Army of Thieves", - "21 Jump Street", - "The Harder They Fall" - ); - } - - // Returns a list of Tv show titles - public List getUserTvSeriesHistory() { - return Arrays.asList("Maya and the Three", - "The Thundermans", - "Riverdale", - "Locke and Key", - "Catching Killers", - "Cocomelon", - "Maid", - "Colin in Black and White", - "Squid Game", - "You" - ); - } -} -``` - -To model the object types to be returned, `Film` and `TvSeries` have been outlined. They both extend an abstract parent class of `Show`. This allows us to use generics in `clone()`, making the returned object automatically cast to the correct type. - -```java -public abstract class Show implements Cloneable { - // Implements clone in abstract class to make use of generics - @Override - public T clone() throws CloneNotSupportedException { - return (T) super.clone(); - } -} -``` - -```java -// Film extends Show, so its clone method will return a Film instance -public class Film extends Show { - private String title; - private String format; - private String thumbnailLocation; - - // Getters, setters, and toString -} -``` - -```java -// TvSeries extends Show, so its clone method will return TvSeries instance -public class TvSeries extends Show { - private String title; - private String format; - private String thumbnailLocation; - - // Getters, setters, and toString -} -``` - -Finally, `ShowCache` has been made to add an object registry to the program. When `.loadCache()` is called, two template objects are created using the `new` keyword and placed in a static map. When `getShow()` is called by a client, the correct clone (taken from `showMap`) is returned, ready for its properties to be set. If the requested `showId` is not recognized, an exception is thrown. - -```java -public class ShowCache { - // A HashTable that contains the initial model object from which we clone from - public static Hashtable> showMap = new Hashtable<>(); - - // Instantiates the initial objects from which we clone from - public static void loadCache() { - final TvSeries tvSeries = new TvSeries(); - final Film film = new Film(); - showMap.put("Tv Series", tvSeries); - showMap.put("Film", film); - } - - // Returns clone of object stored in showMap to client - public static Show getShow(String showId) throws CloneNotSupportedException, ShowIdNotRecognisedException { - // Switch statement to find out which clone is needed - switch (showId) { - case "Film": - Film cashedFilm = (Film) showMap.get(showId); - return cashedFilm.clone(); - case "Tv Series": - TvSeries cashedTvSeries = (TvSeries) showMap.get(showId); - return cashedTvSeries.clone(); - default: - throw new ShowIdNotRecognisedException("Unable to get show: " + showId); - } - } -} -``` - -```java -public class ShowIdNotRecognisedException extends Throwable { - private static final long serialVersionUID = 1; - - public ShowIdNotRecognisedException(final String message) { - super(message); - } -} f -``` - -The `Main` class below, starts the program and acts as the client in this example. It asks the registry to instantiate the initial objects to clone from before using the `UserRepository`'s data and the `getShow` method to return a list of `Film` and `TvSeries` objects representing a user's previously watched shows. - -> **Note:** After the instantiation of initial objects in the registry's `.loadCache()`, all other `Film` and `TvSeries` objects are created through cloning functionality. The `new` keyword is absent. - -```java -public class Main { - - public static void main(String[] args) { - // Create initial objects - ShowCache.loadCache(); - final UserRepository userRepository = new UserRepository(); - // For each film title, clone Film object and set appropriate properties. Return list - final List filmHistory = userRepository.getUserFilmsHistory().stream().map(entry -> { - Film film = null; - - try { - film = (Film) getShow("Film").clone(); - film.setTitle(entry); - film.setFormat(".mp4"); - film.setThumbnailLocation("films/assets/" + entry.toLowerCase().replace(" ", "_") + film.getFormat()); - } catch (CloneNotSupportedException | ShowIdNotRecognisedException e) { - e.printStackTrace(); - } - - return film; - }).collect(Collectors.toList()); - - // For each tv show title, clone TvSeries object and set appropriate properties. Return list - final List tvSeriesHistory = userRepository.getUserTvSeriesHistory().stream().map(entry -> { - TvSeries tvSeries = null; - - try { - tvSeries = (TvSeries) getShow("Tv Series").clone(); - tvSeries.setTitle(entry); - tvSeries.setFormat(".mp4"); - tvSeries.setThumbnailLocation("tv-shows/assets/" + entry.toLowerCase().replace(" ", "_") + tvSeries.getFormat()); - } catch (CloneNotSupportedException | ShowIdNotRecognisedException e) { - e.printStackTrace(); - } - - return tvSeries; - }).collect(Collectors.toList()); - - // Print filmHistory and tvSeriesHistory to the console - System.out.println(filmHistory); - System.out.println(tvSeriesHistory); - } -} -``` diff --git a/content/general/concepts/creational-design-patterns/terms/singleton-pattern/singleton-pattern.md b/content/general/concepts/creational-design-patterns/terms/singleton-pattern/singleton-pattern.md deleted file mode 100644 index 164ecaa9fcf..00000000000 --- a/content/general/concepts/creational-design-patterns/terms/singleton-pattern/singleton-pattern.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -Title: 'Singleton Pattern' -Description: 'Ensures a class has only one object instantiated during the programs lifecycle.' -Subjects: - - 'Computer Science' - - 'Interview Prep' -Tags: - - 'Classes' - - 'Conceptual' - - 'Constructors' - - 'Objects' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -The **singleton pattern** ensures a class has only one object instantiated during the program's lifecycle. It is used to guarantee the control of a resource through its implementation. - -## UML Design - -![UML diagram of a singleton](https://raw.githubusercontent.com/Codecademy/docs/main/media/singleton-uml.png) - -## Java Example - -Generally, singletons are lazily loaded and ensure thread safety. Below is a Java example outlining the most basic form of a singleton. The `.getInstance()` method creates a new instance (if one does not exist), and the `synchronized` keyword ensures two threads can not use this method at the same time. - -```java -public class Singleton { - // The singleton instance to be returned by getInstance() - private static Singleton instance = null; - - // Constructor is made private to stop creation through 'new' keyword outside of getInstance() - private Singleton() {} - - // Returns instance when called - public static synchronized Singleton getInstance() { - // Creates new instance if none exists - if (instance == null) { - instance = new Singleton(); - } - return instance; - } -} -``` diff --git a/content/general/concepts/cryptocurrency/cryptocurrency.md b/content/general/concepts/cryptocurrency/cryptocurrency.md deleted file mode 100644 index 4cc9f9e0c70..00000000000 --- a/content/general/concepts/cryptocurrency/cryptocurrency.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -Title: 'Cryptocurrency' -Description: 'Cryptocurrencies are digital assets or tokens secured by cryptography and transferred on decentralized networks based on blockchain technology.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Blockchain' - - 'Cryptocurrency' -CatalogContent: - - 'introduction-to-blockchain' - - 'paths/computer-science' ---- - -A **cryptocurrency** is a digital asset or token secured by cryptography. Such assets are transferred on decentralized networks based on blockchain technology. - -Cryptocurrencies are not issued or controlled by any central authority, such as the federal bank of a sovereign nation as is the case with fiat money such as the US dollar. Cryptocurrencies are therefore protected from government interference, although this does not mean they cannot be manipulated by other parties. - -### Blockchain - -A blockchain is essentially a set of interconnected "blocks" that form an online ledger that is distributed across computers around the world. These linked blocks contain recorded transactions that are verified by nodes in the network. Nodes are the network computers running the software client that locally stores the blockchain data. - -The data is updated as transactions are stored in each block and every copy of the blockchain is updated simultaneously, keeping all the records identical and accurate. As the network relies on consensus mechanisms to verify transactions, it is almost impossible to forge a fraudulent transaction. - -### Mining - -Units of cryptocurrencies are created through a process known as mining, which involves using computing power to solve complex mathematical problems. The computer in the network that solves the problem the fastest generates the next block in the chain and is rewarded with units of that network, such as bitcoin. In the early days of Bitcoin, individual users were able to participate in mining. Nowadays, the computing power necessary is only achieved through a powerful network of computers known as a "mining pool". - -### Types - -Bitcoin is the most popular and widely known cryptocurrency, as well as the most valuable as measured by total market capitalization. It was created by an individual (or perhaps a group) called Satoshi Nakamoto and introduced via a white paper in 2008. With the success of Bitcoin, thousands of other cryptocurrencies have since been created with different attributes for various functions. - -Ethereum, the second most valuable cryptocurrency, features a smart contract platform that allows for numerous protocols including borrowing and lending services. There are also "stable coin" cryptocurrencies, which attempt to offer price stability and are backed by a reserve asset such as US dollars. - -There are also **altcoins**, some of which are forks of Bitcoin and others are new currencies, tokens, or assets that have been built from scratch. These altcoins include meme coins inspired by memes and internet jokes. Dogecoin, for example, was inspired by the Doge meme created from a viral photo of a Shiba Inu. - -### Purchasing Cryptocurrencies - -The primary method to convert fiat currency into a cryptocurrency like Bitcoin is using an exchange. Cryptocurrency exchanges enable users to purchase crypto assets by funding their account using government-issued currencies such as the US dollar or the Euro and then trading on their platform. The exchange generates an online wallet where the assets are stored, although these assets can generally be withdrawn to a private wallet. Exchanges are almost universally required to comply with various Know Your Customer (KYC) regulations, which is an identity verification process that must be completed before a user purchases or sells cryptocurrencies. - -## Advantages and Disadvantages - -Cryptocurrencies were originally designed with the intent of revolutionizing existing financial infrastructure through greater efficiency and transparency combined with lower costs. There exists, however, a notable divide between the theoretical ideal of a transparent and decentralized system and its practical implementation in the real world. - -Outlined below are the primary advantages and disadvantages of cryptocurrencies: - -### Advantages - -#### Decentralization - -Unlike traditional financial infrastructures, such as banks and monetary institutions, centralized intermediaries are unnecessary to enforce trust and facilitate transactions between two parties. Decentralized cryptocurrencies theoretically remove the ability of a central party to censor transactions or adjust the money supply. They also allow parties in any part of the world to transact without requiring permission from governing authorities. - -#### Efficiency - -Cryptocurrency transfers are often much faster than transactions using third-party intermediaries, and on many platforms, can be very low cost. It is possible, for example, to send millions of dollars for under $5 on the Ethereum network. At times, however, the transaction costs for the most popular cryptocurrencies can rise to up to $50 per transaction. - -#### Transparency - -All cryptocurrency transactions are visible on the publicly distributed blockchain ledger and there are tools that allow anyone to look up the data for any transactions that have occurred on the network. It is also possible to audit the money supply to ensure that additional coins have not been illegitimately generated. - -#### Security - -The only way to sign transactions or access the funds in your wallet is by gaining access to the private key of your crypto wallet. Furthermore, transactions are secured by the cryptographic nature of the blockchain and cannot be reversed like credit cards. However, there are drawbacks to the nature of crypto assets discussed below. - -### Disadvantages - -#### Pseudo-anonymity - -While cryptocurrencies are not generally connected to an individual’s name, transactions on the blockchain can be tracked and traced. Furthermore, exchanges around the world almost universally require know-your-customer (KYC) regulation, which forces these institutions to collect identifying personal details before a customer is able to trade on their platform. - -#### Criminal Activity - -Like with physical cash, cryptocurrencies have the potential to be used by criminals. In the early days of Bitcoin, there was an online marketplace on the dark web called Silk Road which allowed users to purchase illegal drugs and conduct other nefarious activities. - -#### Decentralization - -While cryptocurrencies are meant to be decentralized in theory, their ownership is often highly concentrated and the most value is generally accrued by the early investors. The statistic of highly skewed ownership is easily verifiable using blockchain data. In a study conducted by Makarov and Schoar (2021), conducted by the National Bureau of Economic Research, it was found around 10,000 individuals held about one-third of Bitcoin at that time. - -#### Security - -Cryptocurrency blockchains are very secure through cryptography, though the wallets and exchanges where cryptocurrency assets are held can be hacked. One of the most famous exchange hacks occurred in 2014 when hackers accessed and stole over 700,000 Bitcoin. - -#### Price Volatility - -The frequency and volatility of cryptocurrency price changes are remarkable when compared with traditional financial markets. For example, on December 22, 2017, the price of Bitcoin dropped more than 30% in a single day from over $16,000 USD to nearly $11,000 USD. - -#### Energy Usage - -The mining of popular cryptocurrencies requires substantial energy costs, in some cases as much as what powers entire countries. While that may be true, cryptocurrency supporters argue that the existing financial structure uses far more energy than the power required for mining. diff --git a/content/general/concepts/csv/csv.md b/content/general/concepts/csv/csv.md deleted file mode 100644 index eb100d9f0e2..00000000000 --- a/content/general/concepts/csv/csv.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -Title: 'CSV' -Description: 'Comma-Separated Values (CSV) is a text file format where individual values are separated by commas.' -Subjects: - - 'Computer Science' - - 'Data Science' -Tags: - - 'Files' - - 'Data' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -**Comma-Separated Values (CSV)** is a text file format where individual values are separated by commas. It is normally used to store tabular data and is favored for its simple structure allowing for straightforward parsing and data exchange. - -To store tabular data, CSV files usually represent each line as a new row within the table and the values delimited by commas as the cells within each row. However, this practice is not formalized so the interpretation of the cell's contents is normally application-specific. - -For example, some applications use quotation marks (`"`) or a backslash (`\`) to denote literal characters that allow the cells themselves to also contain the comma character. - -## Example CSV with Corresponding Tabular Representation - -An example CSV file containing data about large animals and a common rendering of its tabular form can be found below: - -```pseudo -Animal,Average Length (Feet),Average Weight (Tons) -African Bush Elephant,19.7,5.4 -Indian Rhinoceros,13.8,2.1 -Hippopotamus,16.5,2.0 -Giraffe,16.9,1.1 -Gaur,12.5,1.0 -``` - -| Animal | Average Length (Feet) | Average Weight (Tons) | -| --------------------- | --------------------- | --------------------- | -| African Bush Elephant | 19.7 | 5.4 | -| Indian Rhinoceros | 13.8 | 2.1 | -| Hippopotamus | 16.5 | 2.0 | -| Giraffe | 16.9 | 1.1 | -| Gaur | 12.5 | 1.0 | diff --git a/content/general/concepts/data-structures/data-structures.md b/content/general/concepts/data-structures/data-structures.md deleted file mode 100644 index 5b905eac038..00000000000 --- a/content/general/concepts/data-structures/data-structures.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -Title: 'Data Structures' -Description: 'Systems for organizing data that dictate how items relate to one another, are accessed, and modified.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Data Structures' - - 'Objects' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -**Data structures** are systems for organizing data that dictate how items relate to one another, are accessed, and modified. Many of these systems are found across most programming languages (e.g. dictionaries, arrays, sets). The respective details of how these structures perform in terms of access/search, updating elements, etc., impact how they are used in practice. - -Below are some common data structures found in computer programming: diff --git a/content/general/concepts/data-structures/terms/array/array.md b/content/general/concepts/data-structures/terms/array/array.md deleted file mode 100644 index 1d9fa46e463..00000000000 --- a/content/general/concepts/data-structures/terms/array/array.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -Title: 'Array' -Description: 'Stores elements of various data types in an ordered collection.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Arrays' - - 'Data Structures' - - 'Data Types' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -An **array** is an ordered collection of elements, and the elements can be of mixed data types. Arrays themselves are considered to be a composite [data type](https://www.codecademy.com/resources/docs/general/data-types). Python uses [lists](https://www.codecademy.com/resources/docs/python/lists) as an equivalent type. One key difference between lists and arrays is how memory is allocated. Elements of an array must be saved in adjacent or contiguous memory locations. This constraint allows for quick access of an element, but slow insertion or modification. Elements of a list, in contrast, can be saved anywhere and each element is saved with a reference to the previous element's location. This arrangement results in fast insertion or updating of a list, but relatively poor access speed. - -## Syntax - -Arrays are often created by using square brackets `[]` with a comma-separated list of individual elements inside: - -```pseudo -array = [element0, element1, element2, element3] -``` - -Nested arrays (arrays within arrays) are also possible: - -```pseudo -nested = [elementB, elementC] -outer = [elementA, nested, element4] -``` - -The length of the `outer` array is 3 elements-long because the inner `nested` array counts as an individual element. By itself, the `nested` array is 2 elements-long. - -## Index Number - -Array elements are usually referenced by an index number, which represents their position in the sequence. - -The indices of most arrays start with 0: - -```pseudo -groceryList = ["milk", "cookies", "berries", "carrots"] -// index: 0 1 2 3 -``` - -- The first element `"milk"` is at index 0. -- The second element `"cookies"` is at index 1. -- ...and so on. - -## Arrays in Different Languages - -- [C++](https://www.codecademy.com/resources/docs/cpp/arrays?utm_source=docs&utm_medium=docs&utm_campaign=docs_link_test&utm_content=docs_array) -- [JavaScript](https://www.codecademy.com/resources/docs/javascript/arrays?utm_source=docs&utm_medium=docs&utm_campaign=docs_link_test&utm_content=docs_array) -- [Java](https://www.codecademy.com/resources/docs/java/arrays?utm_source=docs&utm_medium=docs&utm_campaign=docs_link_test&utm_content=docs_array) -- [PHP](https://www.codecademy.com/resources/docs/php/arrays?utm_source=docs&utm_medium=docs&utm_campaign=docs_link_test&utm_content=docs_array) -- [Python](https://www.codecademy.com/resources/docs/python/lists?utm_source=docs&utm_medium=docs&utm_campaign=docs_link_test&utm_content=docs_list) -- [TypeScript](https://www.codecademy.com/resources/docs/typescript/arrays?utm_source=docs&utm_medium=docs&utm_campaign=docs_link_test&utm_content=docs_array) -- [Swift](https://www.codecademy.com/resources/docs/swift/arrays?utm_source=docs&utm_medium=docs&utm_campaign=docs_link_test&utm_content=docs_array) -- [Ruby](https://www.codecademy.com/resources/docs/ruby/arrays?utm_source=docs&utm_medium=docs&utm_campaign=docs_link_test&utm_content=docs_array) diff --git a/content/general/concepts/data-structures/terms/class/class.md b/content/general/concepts/data-structures/terms/class/class.md deleted file mode 100644 index 2515230cc9d..00000000000 --- a/content/general/concepts/data-structures/terms/class/class.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -Title: 'Class' -Description: 'A class is a piece of code within a program that functions as a template or blueprint for creating multiple instances of a particular object.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Classes' - - 'Objects' - - 'OOP' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -A **class** is a piece of code within a program that functions as a template or blueprint for creating multiple instances of a particular object. - -The template provides initial values and behavior for each of these instances. Each instance is an object itself. - -## Example - -Suppose we want to create a `Cat` class with three instance variables: - -- `@cat_name` -- `@cat_color` -- `@cat_age` - -```rb -class Cat - def initialize(name, color, age) - @cat_name = name - @cat_color = color - @cat_age = age - end -end -``` - -Now we can create a bunch of objects based off of the `Cat` class: - -```rb -mochi = Cat.new("Mochi", "Gray", 2) - -bean = Cat.new("Bean", "Black/Gray", 6) - -femi = Cat.new("Femme en Noir", "Black/White", 9) -``` diff --git a/content/general/concepts/data-structures/terms/dictionary/dictionary.md b/content/general/concepts/data-structures/terms/dictionary/dictionary.md deleted file mode 100644 index f36f7ed133d..00000000000 --- a/content/general/concepts/data-structures/terms/dictionary/dictionary.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -Title: 'Dictionary' -Description: 'A dictionary is an unordered set of (key, value) pairs. It provides a way to map pieces of data to each other, and allows for quick access to values associated to keys. The syntax of a dictionary is as follows: pseudo dictionary = { key1: value1, key2: value2, key3: value3' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Dictionaries' - - 'Data Types' - - 'Data Structures' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -A **dictionary** is an unordered set of (key, value) pairs. It provides a way to map pieces of data to each other, and allows for quick access to values associated to keys. - -## Syntax - -The syntax of a dictionary is as follows: - -```pseudo -dictionary = { - key1: value1, - key2: value2, - key3: value3 -} -``` - -For example: - -```py -coffee_shop = { - "cold brew": 3.50, - "latte": 4.25, - "cappucino": 3.99 -} -``` diff --git a/content/general/concepts/data-structures/terms/hash-table/hash-table.md b/content/general/concepts/data-structures/terms/hash-table/hash-table.md deleted file mode 100644 index 60924f98b02..00000000000 --- a/content/general/concepts/data-structures/terms/hash-table/hash-table.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -Title: 'Hash Table' -Description: 'A hash table is a data structure that stores an arbitrary number of items, mapping keys to values, and uses a hash function to compute an index.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Hashes' - - 'Conceptual' - - 'Data Structures' -CatalogContent: - - 'complex-data-structures' - - 'paths/computer-science' ---- - -A **hash table** is a data structure that stores an arbitrary number of items, mapping keys to values, and uses a hash function to compute an index. The hash table relates the hashed keys to an [array](https://www.codecademy.com/resources/docs/general/data-structures/array) of buckets where the associated value can be found. When looking up a value, the provided key is hashed and the resulting hash is used to retrieve the corresponding value. - -## Implementation - -Hash tables are implemented in many different programming languages such as [Java](https://www.codecademy.com/resources/docs/java) (as a [`HashMap`](https://www.codecademy.com/resources/docs/java/hashmap)) or JavaScript as a [`HashTable`](https://www.codecademy.com/resources/docs/javascript/hashtables) or [Python](https://www.codecademy.com/resources/docs/python) (as a [dictionary](https://www.codecademy.com/resources/docs/python/dictionaries)). Hash table implementations typically allow the modification, insertion, and deletion of the contained key-value pairs. - -## Efficiency - -On average, hash tables prove to be more efficient than other table lookup structures. Because of this, they are widely used for things such as [dictionaries](https://www.codecademy.com/resources/docs/general/data-structures/dictionary), [database indexing](https://www.codecademy.com/resources/docs/general/database/index), and [caching](https://www.codecademy.com/resources/docs/general/cache). diff --git a/content/general/concepts/data-structures/terms/object/object.md b/content/general/concepts/data-structures/terms/object/object.md deleted file mode 100644 index d25b7b9b947..00000000000 --- a/content/general/concepts/data-structures/terms/object/object.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -Title: 'Object' -Description: 'An object is associative data that commonly takes the form of a data structure, function, method, variable, or class.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Objects' - - 'Inheritance' - - 'Methods' - - 'Structure' - - 'Encapsulation' - - 'Classes' -CatalogContent: - - 'learn-c-plus-plus' - - 'paths/computer-science' ---- - -An **object** is associative data that commonly takes the form of a data structure, [function](https://www.codecademy.com/resources/docs/general/function), [method](https://www.codecademy.com/resources/docs/general/method), variable, or [class](https://www.codecademy.com/resources/docs/general/data-structures/class). - -Objects provide a structured programming approach and are the core units of [object-oriented-programming (OOP)](https://www.codecademy.com/resources/docs/general/programming-paradigms/object-oriented-programming). Developers can easily create various identical objects and modify existing ones within the program. - -Objects also provide [encapsulation](https://www.codecademy.com/resources/docs/general/programming-paradigms/encapsulation), meaning that the data within that object is protected from being altered or destroyed by other functions unless explicitly allowed. - -## Memory allocation - -Declaring an object doesn’t necessarily mean that memory is allocated for it. If an object is initialized with another object, it may just get a reference to the previously created object. - -To allocate memory to an object at [runtime](https://www.codecademy.com/resources/docs/general/runtime), the use of the `new` keyword is needed and, depending on the programming language, the memory can be allocated to a heap or stack. - -## Java Example - -In Java, [classes](https://www.codecademy.com/resources/docs/java/classes) are the blueprints for creating objects, which is required in object-orientation/unified modeling language (OO/UML). - -The following snippet is an example of a defined class being used to instantiate new objects (instances of that class): - -```java -// Employee.java -class Employee { - // State or field - int id; - String firstName; - String lastName; - char middleInitial; - float years; - - // Behavior or method - void cookingBread() { - System.out.println("Cooking some delicious bread."); - } -} - -// Creating five different objects from the Employee class -Employee tina = new Employee(); -Employee louise = new Employee(); -Employee linda = new Employee(); -Employee bob = new Employee(); -Employee gene = new Employee(); -``` - -In the example above, the `new` keyword was used to create five object instances of the `Employee` class according to the class constructor. - -## Accessing Fields and Methods - -Since objects are class instances in Java, they can use the `.` operator to access fields and methods in a class. - -```java -// Car.java -public class Car { - // state or field - int numberOfDoors; - String color; - String brand; - boolean isOn; - - // Constructor declaration of class - public Car(int numberOfDoors, String color, String brand, boolean isOn) { - this.numberOfDoors = numberOfDoors; - this.color = color; - this.brand = brand; - this.isOn = isOn; - } - - // Behavior or method - void turnOn() { - isOn = true; - System.out.println("The car has started? " + isOn); - } -} - -// Create object or class instance -Car mercedes = new Car(5, "black", "mercedes", true); - -// Access state -System.out.println(mercedes.numberOfDoors) - -// Access behavior -System.out.println(mercedes.turnOn()); -``` - -In the snippet above, a new `Car` object called `mercedes` is created with its `isOn` field set to `true`. When the `.turnOn()` is invoked with the `mercedes` object and its `numberOfDoors` field is accessed, the following is printed: - -```shell -5 -The car has started? True -``` - -## Types of Objects - -Objects can be categorized based on what they do or how they work based on [design patterns](https://www.codecademy.com/resources/docs/general/creational-design-patterns), which represent repeatable solutions to common tasks or problems in programming. - -> **Note:** Patterns themselves are not objects but are used to develop objects that solve general problems during software development. - -## Objects in Different Languages - -- [Objects in C++](https://www.codecademy.com/resources/docs/cpp/objects) -- [Objects in JavaScript](https://www.codecademy.com/resources/docs/javascript/objects) diff --git a/content/general/concepts/data-structures/terms/tuple/tuple.md b/content/general/concepts/data-structures/terms/tuple/tuple.md deleted file mode 100644 index 612ecba5e4d..00000000000 --- a/content/general/concepts/data-structures/terms/tuple/tuple.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -Title: 'Tuple' -Description: 'A tuple is a data structure consisting of an ordered collection with an arbitrary number of elements.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Tuples' - - 'Data Structures' - - 'Data Types' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -In computer science, a **tuple** is a data structure consisting of an ordered collection with an arbitrary number of elements. A tuple of "N" elements, where "N" is a positive integer, is generally referred to as an N-tuple. Many computer languages implement a tuple as its own structure or object type. - -Typically, a tuple implementation in any programming language has the following characteristics: - -- It can contain an [object](https://www.codecademy.com/resources/docs/general/data-structures/object) or any other [data type](https://www.codecademy.com/resources/docs/general/data-types) in any combination. -- It allows duplicate entries. -- It has a specified order, determined by the order of elements during creation. -- It is immutable and cannot have its elements changed once it is defined. -- Its elements are iterable. -- Instances are not equal unless they consist of the same members in the same order. (i.e. (1,2,3) <> (3,2,1)) - -Some languages, such as [Python](https://www.codecademy.com/resources/docs/python), have built-in support for tuples, while other languages, such as [Java](https://www.codecademy.com/resources/docs/java), don't have built-in support for tuples and need to define a class, or import a special library to implement them. - -Languages with built-in support for tuples include: - -- [Python](https://www.codecademy.com/resources/docs/python/tuples) -- [Swift](https://www.codecademy.com/resources/docs/swift/tuples) -- [TypeScript](https://www.codecademy.com/resources/docs/typescript/tuples) - -## Example - -The following defines three different tuples in Python: - -```py -a = (1, 2, 3) -b = ('x', 23, [0,6,15]) -c = (a, b) -``` diff --git a/content/general/concepts/data-types/data-types.md b/content/general/concepts/data-types/data-types.md deleted file mode 100644 index 589d3e384e5..00000000000 --- a/content/general/concepts/data-types/data-types.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -Title: 'Data Types' -Description: 'Data is classified into data types that tell the compiler how the data is intended to be used.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Data Structures' - - 'Data Types' - - 'Types' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -Data is foundational in programming and is classified into different types to indicate how it can be interpreted, compiled, and used in software. For the most part, **data types** are categorized into two groups: primitive or composite values. - -## Primitive Data Types - -Primitive data types are the building blocks for any variable or data structure in a program. They usually contain a single value such as a character, byte, or digit. A few examples of primitive types are listed below: - - -| Data Type | Description | -| --- | --- | -| [Number](https://www.codecademy.com/resources/docs/general/data-types/number) | Includes `-1`, `0`, `1`, and `3.14`(numbers with decimals treated as a separate type in some languages). | -| [String](https://www.codecademy.com/resources/docs/general/data-types/string) | Sequences of characters surrounded by single quotes (`''`), double quotes (`""`), and/or backticks (` `` `), depending on the language (e.g. `"Codecademy is awesome! 🖥️⌨️"` ). | -| [Boolean](https://www.codecademy.com/resources/docs/general/data-types/boolean) | Holds a logical value of `true` or `false`. | - -## Composite Data Types - -Composite data types can be composed of multiple of the same or different primitive data types, sometimes referred to as members, elements, or items. The following are examples of well known composite types: - - -| Data Type | Description | -| --- | --- | -| [Array](https://www.codecademy.com/resources/docs/general/data-structures/array) | Collections of values that are usually defined with `[]` brackets and referenced by index starting at 0. | -| [Object](https://www.codecademy.com/resources/docs/general/data-structures/object) | Groups of related data that are usually organized as property-value pairs. | -| [Class](https://www.codecademy.com/resources/docs/general/data-structures/class) | Templates for objects that may contain properties or methods. | - -## Other Common Data Types - -Data types have gone beyond just composites and primitives and include ones with unique qualities such as the following: - - -| Data Type | Description | -| --- | --- | -| Null | `null` or `nil` represents the absence of a value. | -| Undefined | Represents a value that has not yet been defined. | -| [Function](https://www.codecademy.com/resources/docs/general/function) | Depending on the language, functions can be utilized as variables and arguments for other functions. | -| [Void](https://www.codecademy.com/resources/docs/general/data-types/void) | Sets a function to have side effects but return no specific result. Common in C-based languages. | -| Complex Number | Type representation for complex numbers, sometimes with `i` or `complex`. | - -## Data Types in Different Languages - -The way that data types look and work may vary from one programming language to another: - -- [C++ data types](https://www.codecademy.com/resources/docs/cpp/data-types) -- [Go data types](https://www.codecademy.com/resources/docs/go/data-types) -- [JavaScript data types](https://www.codecademy.com/resources/docs/javascript/data-types) -- [Java data types](https://www.codecademy.com/resources/docs/java/data-types) -- [Python data types](https://www.codecademy.com/resources/docs/python/data-types) -- [R data types](https://www.codecademy.com/resources/docs/r/data-types) -- [Ruby data types](https://www.codecademy.com/resources/docs/ruby/data-types) -- [Swift data types](https://www.codecademy.com/resources/docs/swift/data-types) diff --git a/content/general/concepts/data-types/terms/boolean/boolean.md b/content/general/concepts/data-types/terms/boolean/boolean.md deleted file mode 100644 index a38f6417f29..00000000000 --- a/content/general/concepts/data-types/terms/boolean/boolean.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -Title: 'Boolean' -Description: 'Represents the logical values of true and false.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Booleans' - - 'Data Types' - - 'Types' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -A **boolean** holds a true or false value and are mostly used in conditional statements to control a program's flow of execution. This data type is named after George Boole, a 19th century English logician. - -Some languages use comparison operators such as: - -- `>=` and `<=`, for "greater than" and "less than", respectively. -- `==` and `is` or `!=` and `not` to test for equality and inequality, respectively. - -Other languages may use a combination of "falsy" values (e.g. `""`, `null`, or `0`) and "truthy" values such as `1`. - -## JavaScript Example - -The following example uses a comparison [operator](https://www.codecademy.com/resources/docs/javascript/operators) to return `true` or `false` based on the evaluation of the given statement. Then, a JavaScript [conditional](https://www.codecademy.com/resources/docs/javascript/conditionals) is used to determines whether the `if` or `else` code block will run: - -```codebyte/javascript -if (42 != 5) { - // If the statement above always evaluates to true... - console.log('This will always print.'); -} else { - console.log('This will never print.'); -}; -``` diff --git a/content/general/concepts/data-types/terms/number/number.md b/content/general/concepts/data-types/terms/number/number.md deleted file mode 100644 index dfd0278b7db..00000000000 --- a/content/general/concepts/data-types/terms/number/number.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -Title: 'Number' -Description: 'Represents many numeric values.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Data Types' - - 'Numbers' - - 'Types' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -**Numbers** include `-1`, `0`, `1`, and so on. Depending on the language, numbers with decimals are of a different type. In floating-point arithmetic, there is a trade-off in precision for range. The amount of bits allocated for floating-point representation affects the range in values that can be used. - -## Arithmetic Accuracy - -Languages such as JavaScript and Python yield interesting results when arithmetic operations are performed on numeric values. For example, `.1 + .2` would evaluate to `0.30000000000000004`, whereas adding whole numbers wouldn't do this. But you need to keep in mind the integer limit. It is the number where the compiler won't understand the numbers anymore. diff --git a/content/general/concepts/data-types/terms/string/string.md b/content/general/concepts/data-types/terms/string/string.md deleted file mode 100644 index 839436765e3..00000000000 --- a/content/general/concepts/data-types/terms/string/string.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -Title: 'String' -Description: 'Stores a sequence of indexed characters that can be of any length and is contained within a pair of single or double quotes.' -Subjects: - - 'Code Foundations' - - 'Computer Science' - - 'Web Development' -Tags: - - 'Strings' - - 'Data Types' - - 'Characters' -CatalogContent: - - 'learn-python-3' - - 'paths/code-foundations' ---- - -In computer science, sequences of characters are referred to as **strings**. Strings can be any length and can include any character such as: - -- Letters -- Numbers -- Symbols -- Whitespace (spaces, tabs, new lines) - -They are usually contained within a pair of `'single quotes'` or `"double quotes"`. - -Here are some examples of strings: - -```py -message = "Hello, world!" -username = "@sonnynomnom" -old_password = "Tr0ub4dor&3" -new_password = "correcthorsebatterystaple" -``` - -## Index - -Like any other list, each character in a string has an index that denotes a character's position. - -```pseudo -message = 'Howdy!' - 012345 -``` - -**Note:** In programming, the index starts from 0, so the index of the first character would be 0. - -## Finding the Character in a String Given its Index (Python) - -In Python, to provide the index of the string `message`, add square brackets `[` `]` to find out the character at that position. - -```py -message = 'Hello, world' - -print(message[0]) -# Output: H - -print(message[5]) -# Output: , -``` - -## Example of Concatenation (Python) - -It is also possible to concatenate strings together using `+` in some languages, such as Python and C++. To add a space between strings, an empty space can be put between quotation marks. - -```codebyte/py -block_number = "575" -street_name = "Broadway" - -address = block_number + ' ' + street_name - -print(address) -``` - -## Strings in Different Languages - -- [Strings in C++](https://www.codecademy.com/resources/docs/cpp/strings) -- [Strings in Java](https://www.codecademy.com/resources/docs/java/strings) -- [Strings in JavaScript](https://www.codecademy.com/resources/docs/javascript/strings) -- [Strings in Python](https://www.codecademy.com/resources/docs/python/strings) -- [Strings in Ruby](https://www.codecademy.com/resources/docs/ruby/strings) diff --git a/content/general/concepts/data-types/terms/void/void.md b/content/general/concepts/data-types/terms/void/void.md deleted file mode 100644 index 7b4ed522499..00000000000 --- a/content/general/concepts/data-types/terms/void/void.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -Title: 'Void' -Description: 'Denotes functions that have side effects but do not return an actual result.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Functions' - - 'Methods' -CatalogContent: - - 'learn-c' - - 'paths/computer-science' ---- - -Several programming languages derived from [C](https://www.codecademy.com/resources/docs/c) use a **void** type to denote functions that do not return a result and are mostly used for side effects. diff --git a/content/general/concepts/database/database.md b/content/general/concepts/database/database.md deleted file mode 100644 index 87213f6c2b8..00000000000 --- a/content/general/concepts/database/database.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -Title: 'Database' -Description: 'A database is a collection of structured information stored so it can be easily accessed and updated. In a computer system, databases are commonly accessed through a database management system, or DBMS.' -Subjects: - - 'Computer Science' - - 'Data Science' -Tags: - - 'Database' - - 'Tables' -CatalogContent: - - 'learn-sql' - - 'paths/data-science' ---- - -A **database** is a collection of structured information stored so it can be easily accessed and updated. In a computer system, databases are commonly accessed through a database management system, referred to as a DBMS. - -## Types of Databases - -There are many different ways for database systems to structure and organize data. The type of database used is dependent on the type of data being stored, and the intended use for it. - -### Relational Databases - -[Relational databases](https://www.codecademy.com/resources/docs/general/database/relational-database) structure their data in tables made up of rows and columns. Multiple tables can have relationships to each other based on the values in key columns. They provide an efficient and flexible way to access structured information. Data is typically queried and manipulated through some form of [Structured Query Language (SQL)](https://www.codecademy.com/resources/docs/sql) implemented by the DBMS. - -### Object Databases - -Object databases structure their data in the form of objects (as used in [object-oriented programming](https://www.codecademy.com/resources/docs/general/programming-paradigms/object-oriented-programming)) rather than tables. This is useful in software development where the application using the data, and the DBMS manipulating the data, can both use the same model of the data. - -#### Object-Relational Databases - -A hybrid of the above two models. Unlike pure object databases where the database is primarily a persistent store for objects created by a program written in an object-oriented programming language, object-relational databases are manipulated via a query language as in relational databases. Yet they still support objects, classes and inheritance like a pure object database. - -### NoSQL Databases - -NoSQL databases are also known as nonrelational databases. They are a wide variety of databases that use different structures for data rather than the tables used in relational databases. They are implemented using various different structures for different purposes. For example: - -- Key–Value Store: Stores data in an associative array where data is stored as a collection of key-value pairs where any possible key only appears once in the collection. -- Document Store: Stores data as documents in some standard format such as [XML](https://www.codecademy.com/resources/docs/general/xml), TAML or [JSON](https://www.codecademy.com/resources/docs/general/json). Documents are stored in the database with a unique key representing that document. -- Graph Database: Stores data as elements connected by a finite number of relations, such as a subway map or a network of friends on Facebook. diff --git a/content/general/concepts/database/terms/acid-properties/acid-properties.md b/content/general/concepts/database/terms/acid-properties/acid-properties.md deleted file mode 100644 index 5088201a2bd..00000000000 --- a/content/general/concepts/database/terms/acid-properties/acid-properties.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -Title: 'ACID Properties' -Description: 'Refers to properties a database transaction must follow in order to maintain consistency in a database.' -Subjects: - - 'Computer Science' - - 'Data Science' -Tags: - - 'Database' -CatalogContent: - - 'paths/analyze-data-with-sql' - - 'paths/data-science' ---- - -**ACID properties** refer to properties a database [transaction](https://www.codecademy.com/resources/docs/general/database/transaction) must follow in order to maintain consistency in a database. Those properties are as follows: - -- Atomicity: The entire transaction must occur, or none of it does. There are no partial transactions. -- Consistency: The database must remain consistent before and after the transaction. -- Isolation: Transactions are independent of one another, and do not interfere with each other. -- Durability: A transaction, once completed, is permanent and persists even if a system failure occurs. diff --git a/content/general/concepts/database/terms/index/index.md b/content/general/concepts/database/terms/index/index.md deleted file mode 100644 index 17151de3afd..00000000000 --- a/content/general/concepts/database/terms/index/index.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -Title: 'Index' -Description: 'Improves the speed of data retrieval in the database.' -Subjects: - - 'Computer Science' - - 'Data Science' -Tags: - - 'Database' - - 'Queries' - - 'Primary Key' - - 'Foreign Key' - - 'Index' - - 'Tables' -CatalogContent: - - 'paths/analyze-data-with-sql' - - 'paths/data-science' ---- - -A database **index** is a data structure that improves the speed of data retrieval in the database. Indexes on a table consist of one or more columns of ordered data with links to specific rows in a table. - -By matching the values in the index, the database management system can quickly retrieve the corresponding row without having to search every row in the table. - -Tables are indexed on their primary key columns, and many database systems require an index on a foreign key column as well. It is also common practice to place indexes on columns that are likely to be queried often. - -## SQL Example - -Index creation can vary from database to database, but in standard [SQL](https://www.codecademy.com/resources/docs/sql) it consists of: - -1. Using the `CREATE INDEX` statement, followed by a name for the index. -2. Applying the `ON` clause to the table name, followed by a list of the columns to be indexed. - -In the example below, adding an index on the `region` field of a `sales` table looks like this: - -```sql -CREATE INDEX sales_by_region -ON sales (region); -``` diff --git a/content/general/concepts/database/terms/relational-database/relational-database.md b/content/general/concepts/database/terms/relational-database/relational-database.md deleted file mode 100644 index 7f2a3c051fc..00000000000 --- a/content/general/concepts/database/terms/relational-database/relational-database.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -Title: 'Relational Database' -Description: 'A relational database is a store of data organized in tables made of columns and rows, and the relationships between those tables.' -Subjects: - - 'Computer Science' - - 'Data Science' -Tags: - - 'Database' - - 'Queries' - - 'Primary Key' - - 'Foreign Key' - - 'MySQL' - - 'PostgreSQL' - - 'SQLite' -CatalogContent: - - 'paths/design-databases-with-postgresql' - - 'paths/analyze-data-with-sql' - - 'paths/data-science' ---- - -[relational database example]: https://raw.githubusercontent.com/Codecademy/docs/main/media/general-relational-database.png 'Example of a Relational Database' - -A **relational database** is a store of data organized in tables made of columns and rows, and the relationships between those tables. -The software that controls a relational database is called a relational database management system (RDBMS) and typically allows management and updates to the database through an implementation of the structured query language (SQL). - -## Structure of a Relational Database - -Most tables are defined with a key column that holds a unique value for every row. That column is called a primary key. Columns in a table that reference primary keys in other tables are called foreign keys. Data in different tables are related to each other via matching values in the key columns in those tables. - -Rows in each table are also called records. Columns can also be called fields or attributes. - -Generally each table represents a particular entity type, such as a user, product, or transaction. Each row or record represents a particular instance of that entity type, and each column/field in that record represents particular values ascribed to that instance, such as name, price, or transaction date. - -For instance, a company may have a sales database with tables called `products` and `sales`. - -- The `product` table would have columns for things like name, model, unit cost, and retail price. -- The `sales` table would have columns for things like sale date, payment method, and shipping address. - -Each entry in the `sales` table would have a foreign key referring to the primary key of the `product` table (the product that was bought). - -The relation between the `product` table to the `sales` table is referred to as a one-to-many relationship (for each product there can be multiple sales). - -![Relational database example] - -## Examples of Relational Database Management Systems - -- MySQL is a free open-source RDBMS that is used for many database-driven web applications such as Drupal, Joomla and WordPress. -- SQLite is a C library used to embed relational database functionality into software packages. -- PostgreSQL is a free open-source RDBMS that emphasizes extensibility and compliance to the ANSI SQL standards. -- Microsoft SQL Server is a server-based RDBMS from Microsoft typically used as a back-end for applications running on a network. -- Microsoft Access is part of the Microsoft 365 suite of applications. It combines an RDBMS with a graphical user interface and programming tools, allowing application development inside the software. -- Microsoft Azure SQL Database is a managed cloud-based RDBMS provided as part of Microsoft Azure. diff --git a/content/general/concepts/database/terms/transaction/transaction.md b/content/general/concepts/database/terms/transaction/transaction.md deleted file mode 100644 index fd95e10266b..00000000000 --- a/content/general/concepts/database/terms/transaction/transaction.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -Title: 'Transaction' -Description: 'Refers to an encapsulated set of instructions sent to a database that must happen as a unit.' -Subjects: - - 'Computer Science' - - 'Data Science' -Tags: - - 'Database' -CatalogContent: - - 'paths/analyze-data-with-sql' - - 'paths/data-science' ---- - -A **transaction** is an encapsulated set of instructions sent to a database that must happen as a unit. If something interrupts the transaction, such as an error, none of the instructions in the transaction occur. This ensures that there are never any partially executed transactions. - -Transactions are used to preserve the consistency of a database, so that execution of a complex process, such as debiting one account and crediting another, is never partially completed. In the prior example, without transactions, an error or a resource lock could leave the first account debited without making the corresponding credit. Transactions adhere to [ACID properties](https://www.codecademy.com/resources/docs/general/database/acid-properties) in order to ensure this doesn’t happen. diff --git a/content/general/concepts/developer-tools/developer-tools.md b/content/general/concepts/developer-tools/developer-tools.md deleted file mode 100644 index 2e7f3e26711..00000000000 --- a/content/general/concepts/developer-tools/developer-tools.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -Title: 'Developer Tools' -Description: 'The technologies used in the development of software.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Infrastructure' -CatalogContent: - - 'introduction-to-javascript' - - 'paths/code-foundations' ---- - -**Developer tools** are the technologies used in the development of software. Although the suite of applications used by a team or individual developer can vary significantly, there are several classes of tools that are broadly adopted in the service of creating software applications. Below are some common tools leveraged by software developers: diff --git a/content/general/concepts/developer-tools/terms/abstract-syntax-tree/abstract-syntax-tree.md b/content/general/concepts/developer-tools/terms/abstract-syntax-tree/abstract-syntax-tree.md deleted file mode 100644 index 5df038d9afa..00000000000 --- a/content/general/concepts/developer-tools/terms/abstract-syntax-tree/abstract-syntax-tree.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -Title: 'Abstract Syntax Tree' -Description: 'An abstract syntax tree is a language-agnostic, hierarchical representation of the elements comprising the source code of a computer program.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Code Editors' - - 'Conceptual' - - 'Developer Tools' - - 'Documentation' -CatalogContent: - - 'complex-data-structures' - - 'paths/computer-science' ---- - -An **abstract syntax tree (AST)** is a language-agnostic, hierarchical representation of the elements comprising the source code of a computer program. With a given AST, it is possible to reproduce code that is functionally identical to the source code that originally generated it. In other words, the code can be reproduced in any language. This is why the generation of ASTs is a critical internal step in compiling, as it allows the compiler to interpret the source code in a way that allows it to translate the original language into equivalent machine code. - -## Tokens - -Tokenization is the process of breaking source code into an array of fundamental elements, or tokens. The AST is a graph of these tokens, specifically arranged to preserve the context of each element. - -For example, the `=` symbol is both a comparison operator and an assignment operator in some languages. Therefore, tokenization will represent the symbol `=` but not communicate its function in the program. In an AST, the token's position in the tree, along with its relation to other tokens, is also represented. So, examining the tree indicates the difference between assigning `a` to `b` with `a = b` on a line by itself and comparing `a` and `b` using an `if` conditional, `if a = b then ...`, even when `=` is represented by the same token in both cases. - -If we look at the following pseudocode: - -```pseudo -if a = b - then - return "equal" - else - return a + " not equal to " + b -``` - -A graphical representation of the AST would look like this: - -![Abstract Syntax Tree Graph](https://raw.githubusercontent.com/Codecademy/docs/main/media/abstract-syntax-tree.png 'Abstract Syntax Tree Graph') - -Like pseudocode, there are many ways to represent an AST. The output for an AST will vary based on the language and tool used to create it. However, all ASTs should have the property of completely representing the source code in a reproducible manner. - -## Uses of an AST - -ASTs have many uses in different situations, including: - -- By compilers to translate source code into equivalent binary forms. -- In code reviews for identifying redundant elements in a codebase or detecting possible vulnerabilities. -- Efficient refactors such as changing variable names with respect to their scope in the program. -- Isolating a particular method and identifying all sections of the code that refer to that particular method. diff --git a/content/general/concepts/developer-tools/terms/code-editor/code-editor.md b/content/general/concepts/developer-tools/terms/code-editor/code-editor.md deleted file mode 100644 index 9cdad2f6678..00000000000 --- a/content/general/concepts/developer-tools/terms/code-editor/code-editor.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -Title: 'Code Editor' -Description: 'A code editor is a program designed for writing software and utilizing human-readable text to make code easier to parse and understand.' -Subjects: - - 'Developer Tools' - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Code Editors' - - 'IDE' -CatalogContent: - - 'learn-python-3' - - 'paths/front-end-engineer-career-path' ---- - -A **code editor** is a program designed for writing software in which developers utilize human-readable text to make code easier to parse and understand. They have built-in knowledge of programming languages, allowing different elements of the code (i.e., variables, keywords, functions, etc.) to appear in different colors and improve readability and analysis by developers. - -Code editors can compile and run code. In addition to being able to print a code's output, these programs can also identify where and why a particular line of code [fails to execute](https://www.codecademy.com/resources/docs/general/error). - -## Notable Examples - -There are numerous code editors available, such as: - -- [Visual Studio Code](https://code.visualstudio.com/) -- [Sublime Text](https://www.sublimetext.com/) -- [Notepad++](https://notepad-plus-plus.org/) - -Which code editor program to use is really up to the individual developer's preferences. diff --git a/content/general/concepts/developer-tools/terms/ide/ide.md b/content/general/concepts/developer-tools/terms/ide/ide.md deleted file mode 100644 index c24cdfd5f24..00000000000 --- a/content/general/concepts/developer-tools/terms/ide/ide.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -Title: 'IDE' -Description: 'An IDE, or Integrated Development Environment, enables programmers to consolidate the different aspects of writing a computer program.' -Subjects: - - 'Developer Tools' - - 'Computer Science' - - 'Web Development' -Tags: - - 'IDE' - - 'Xcode' - - 'Android' - - 'Code Editors' -CatalogContent: - - 'learn-python-3' - - 'paths/front-end-engineer-career-path' ---- - -An **Integrated Development Environment (IDE)**, enables programmers to consolidate the different aspects of writing a computer program. - -IDEs increase programmer productivity by featuring common activities of writing software into a single application.. - -## Common Features - -Writing code is an important part of programming. We start with a blank file, write a few lines of code, and a program is born! IDEs facilitate this process with features like syntax highlighting and autocomplete. - -### Syntax Highlighting - -An IDE that knows the syntax of your language can provide visual cues. Keywords, words that have special meaning like `class` in Java, are highlighted with different colors. - -Compare these two code samples: - -```pseudo -// Without syntax highlighting - -public class NiceDay { - public static void main(String[] args) { - System.out.println("It's a nice day out!"); - } -} -``` - -```java -// With syntax highlighting - -public class NiceDay { - public static void main(String[] args) { - System.out.println("It's a nice day out!"); - } -} -``` - -Syntax highlighting makes code easier to read by visually clarifying different elements of language syntax. - -### Autocompletion - -When the IDE knows your programming language, it can anticipate what you’re going to type next! - -We’ve seen statements with `System.out.println()` quite a bit so far. In an IDE, we might see `System` as an autocomplete option after only typing "Sy". This saves keystrokes so the programmer can focus on logic in their code. - -![GIF](https://content.codecademy.com/courses/learn-java/revised-2019/autocomplete_v2.gif) - -### Building Executables - -Languages like Java and C++ are compiled languages. Before programs run, the source code of a **.java** or **.cpp** file must be transformed into an executable like **.class** or **.exe** by the compiler. Once compiled, the program can be run from the terminal. - -This compilation process is necessary for every program, so why not have the IDE do it for us? IDEs provide automated build processes for languages, so the act of compiling and executing code is abstracted away, like in Codecademy lessons. - -### Debugging - -No programmer avoids writing bugs and programs with errors. - -When a program does not run correctly, IDEs provide debugging tools that allow programmers to examine different variables and inspect their code in a deliberate way. - -IDEs also provide hints while coding to prevent errors before compilation. - -![Debugging GIF](https://content.codecademy.com/courses/learn-java/revised-2019/debugging_v2.png) - -## Notable Examples - -There are numerous IDEs available, such as: - -- [IntelliJ IDEA](https://www.jetbrains.com/idea/) -- [Xcode](https://developer.apple.com/xcode/) -- [Android Studio](https://developer.android.com/studio) -- [Microsoft Visual Studio](https://visualstudio.microsoft.com) - -The IDE you decide to use depends on what area of computer programming you wish to pursue. Some IDEs, like Android Studio and Xcode, are dedicated solely for building mobile applications. - -### Online IDEs - -There are many online IDEs that allow users to practice with snippets of code without installing any software on their local machine. Most provide support for several different languages. - -One example is Codecademy's own [Codebyte Editor](https://www.codecademy.com/codebyte-editor). It allows experimenting with [C++](https://www.codecademy.com/resources/docs/cpp), C#, [Go](https://www.codecademy.com/resources/docs/go), [JavaScript](https://www.codecademy.com/resources/docs/javascript), [PHP](https://www.codecademy.com/resources/docs/php), [Python 3](https://www.codecademy.com/resources/docs/python), [Ruby](https://www.codecademy.com/resources/docs/ruby), and Scheme. - -Another example is [JDoodle](https://www.jdoodle.com/) which offers support for over 75 languages including [Java](https://www.codecademy.com/resources/docs/java), [Python 2](https://www.codecademy.com/resources/docs/python), [R](https://www.codecademy.com/resources/docs/r), and [Swift](https://www.codecademy.com/resources/docs/swift). diff --git a/content/general/concepts/developer-tools/terms/version-control/version-control.md b/content/general/concepts/developer-tools/terms/version-control/version-control.md deleted file mode 100644 index caf5e128fdf..00000000000 --- a/content/general/concepts/developer-tools/terms/version-control/version-control.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -Title: 'Version Control' -Description: 'Version control is a system that helps manage changes to code or documents over time.' -Subjects: - - 'Code Foundations' - - 'Developer Tools' -Tags: - - 'Developer Tools' - - 'Version Control' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' - - 'paths/computer-science' ---- - -**Version control** is a system that helps manage changes to code or documents over time. It allows the developer to keep track of revisions, revert to earlier versions, and collaborate with others on the same project. - -There are two main types of Version Control Systems (VCS): - -1. Centralized Version Control Systems (CVCS): A single repository serves as the central point of collaboration for all users. Examples of CVCS include SVN (Subversion) and CVS (Concurrent Versions System). -2. Distributed Version Control Systems (DVCS): Each user has a complete copy of the repository on their local machine, allowing them to work offline and merge changes with others later. Examples of DVCS include [Git](https://www.codecademy.com/resources/docs/git), Mercurial, and Bazaar. - -## Purpose of VCS's - -The primary purpose of a VCS is to enable software developers to manage changes to their codebase. By using a VCS, developers can track changes, revert to previous versions, and collaborate with others. VCS's also help developers maintain a complete history of their codebase, ensuring that all changes are tracked and easily accessible. - -## Process of VCS's - -The process of using a VCS can be broken down into the following broad steps: - -- Create a Repository: Developers start by creating a repository, which is a centralized location where all code changes will be stored. -- Make Changes: Developers make changes to the codebase, either by adding new code or modifying existing code. -- Commit Changes: Once changes have been made, developers "commit" those changes to the repository. A commit is a record of the changes that have been made to the codebase. -- Review Changes: Before committing changes, developers can review the changes they have made to ensure they are correct and follow coding standards. -- Merge Changes: If multiple developers are working on the same codebase, they can merge their changes together into a single codebase. -- Revert Changes: If changes are found to be incorrect or buggy, developers can revert to an earlier version of the codebase. - -## Common Applications of VCS's - -VCS has a wide range of applications, including: - -- Collaboration: Developers can collaborate on a single codebase, making it easier to share ideas and develop better code. -- History Tracking: A VCS allows developers to keep a complete history of their codebase, enabling them to track changes over time and revert to earlier versions if necessary. -- Code Backup: By storing code in a VCS, developers can ensure that their code is backed up and accessible in case of data loss. -- Version Management: A VCS enables developers to maintain multiple versions of their codebase, which can be useful when working on different features or products. -- Error Detection: A VCS allows developers to track bugs and issues in their codebase, making it easier to identify and fix errors. - -## Benefits of Version Control - -Using a Version Control System provides several benefits, including: - -- Collaboration: A VCS allows multiple developers to work on the same project without conflicts or overwriting each other's work. -- History: A VCS tracks all changes made to the code or documents, allowing the history to be reviewed and revert to an earlier version if necessary. -- Branching and Merging: A VCS allows the creation of separate branches for different features or versions, and merge them back together when ready. -- Backing Up: It's important to regularly back up a repository to prevent data loss or corruption. -- Code Reviews: A VCS facilitates code reviews and helps enforce coding standards, improving the quality of the codebase. - -## Best Practices - -Here are some best practices to follow when using a VCS: - -- Commit Frequently: Commit small, logical changes frequently to provide a clear history of the codebase. -- Write Good Commit Messages: Write descriptive commit messages that explain what was changed and why. -- Use Branches: Use branches to develop new features or versions separately from the main codebase, and merge them back when ready. -- Review Code: Review code changes before merging them into the main codebase to catch errors and enforce coding standards. -- Redundancy: The use of a VCS provides redundancy and minimizes the risk of data loss or corruption. - -## Common Mistakes to Avoid - -Here are some common mistakes to avoid when using a VCS: - -- Forgetting to Commit: If changes are not committed frequently, it can be difficult to track progress and make it harder to revert changes later. -- Not Writing Good Commit Messages: Writing unclear or uninformative commit messages can make it harder to track changes and understand the history of the codebase. -- Not Using Branches: Failing to use branches can make it harder to develop new features or versions separately from the main codebase, and increase the risk of conflicts. -- Not Reviewing Code: Failing to review code changes can result in errors or violations of coding standards being merged into the main codebase. -- Not Backing Up the Forked Repository: Failing to back up a forked repository can result in data loss or corruption if the local machine or the central repository become unavailable. - -By avoiding these common mistakes, developers and teams can leverage VCS's to support their development goals and avoid unnecessary headaches and conflicts. - -## Conclusion - -Version Control is an essential tool for any developer or team working on code or documents. It provides benefits such as collaboration, history tracking, branching and merging, and redundancy among many others. By following best practices and using a VCS, a developer can improve the quality and efficiency of their work. diff --git a/content/general/concepts/dns/dns.md b/content/general/concepts/dns/dns.md deleted file mode 100644 index 61fdda64ad6..00000000000 --- a/content/general/concepts/dns/dns.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -Title: 'DNS' -Description: 'The Domain Name System (DNS) protocol converts domain names to IP addresses. Think of it as a phonebook for the Internet.' -Subjects: - - 'Web Development' - - 'Computer Science' -Tags: - - 'HTTP' - - 'Developer Tools' -CatalogContent: - - 'paths/front-end-engineer-career-path' - - 'paths/computer-science' ---- - -The **Domain Name System (DNS)** protocol converts domain names to IP addresses. Think of it as a phonebook for the Internet. It’s hard to remember an exact IP address when we want to access a website. - -When we request the URL `codecademy.com`, our computer sends a DNS request to a DNS server. The server then returns the correct IP addresses like `104.20.25.250` to route data to and from Codecademy. - -## Domain Name - -Each domain name is made up of three parts: - -`third-level-domain . second-level-domain . top-level-domain` - -- Top level domain: There are a limited set of top level domains, and many websites use the most common ones like ".com", ".org", and ".edu". -- Second level domain: The second level domain is unique to the company or organization that registers it, like "codecademy" or "wikipedia". -- Third level domain (subdomain): It's owned by the same group and that URL often directs you to a subset of the website. - -For example: [shop.codecademy.com](www.shop.codecademy.com) (Codecademy's merch shop): - -- Top level domain: ".com" -- Second level domain: "codecademy" -- Third level domain: "shop" diff --git a/content/general/concepts/endianness/endianness.md b/content/general/concepts/endianness/endianness.md deleted file mode 100644 index f9c9c0f0fc0..00000000000 --- a/content/general/concepts/endianness/endianness.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -Title: 'Endianness' -Description: 'Endianness describes the order in which bytes are stored in memory for multi-byte values.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Numbers' - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -**Endianness** describes the order in which bytes are stored in memory for multi-byte values. The options are generally described as big-endian or little-endian. A big-endian system stores the most significant byte at the smallest memory address and the least significant byte at the largest. A little-endian system stores the least significant byte at the smallest memory address and the most significant byte at the largest. - -## Example - -To store the 32-bit integer `0x0A0B0C0D`, it is broken down into four bytes: - -- `0x0A` -- `0x0B` -- `0x0C` -- `0x0D` - -The endianness of the computer system defines in what order these bytes are stored in memory. The following examples show it stored at memory address `0xFFF0` for both big- and little-endian systems: - -### Big-endian - -| Address | Value | -| -------- | ------ | -| `0xFFF0` | `0x0A` | -| `0xFFF1` | `0x0B` | -| `0xFFF2` | `0x0C` | -| `0xFFF3` | `0x0D` | - -### Little-endian - -| Address | Value | -| -------- | ------ | -| `0xFFF0` | `0x0D` | -| `0xFFF1` | `0x0C` | -| `0xFFF2` | `0x0B` | -| `0xFFF3` | `0x0A` | diff --git a/content/general/concepts/error/error.md b/content/general/concepts/error/error.md deleted file mode 100644 index 62f68ce1786..00000000000 --- a/content/general/concepts/error/error.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -Title: 'Error' -Description: 'An error is a mistake that causes a program to perform in unexpected ways or to fail outright.' -Subjects: - - 'Computer Science' - - 'Web Development' - - 'Data Science' -Tags: - - 'Errors' - - 'Debugging' - - 'Best Practices' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' - - 'paths/data-science' ---- - -An **error** is a mistake that causes a program to perform in unexpected ways or to fail outright. The mistakes could be from the slip of a keyboard stroke - like misspelling a variable or from forgetting a closing bracket; or a misunderstanding of requirements - like using imperial units of measurement instead of metric. - -Understanding different types of errors and how to debug them are crucial towards becoming a productive programmer. - -## History - -> “First actual case of bug being found.” - -The story goes that on September 9th, 1947, computer scientist [Grace Hopper](https://en.wikipedia.org/wiki/Grace_Hopper) found a moth in the Harvard Mark II computer’s logbook and reported the world’s first literal computer bug. However, the term “bug,” in the sense of technical error, dates back at least to 1878 and with Thomas Edison. - -## Syntax Errors - -Every language has rules regarding the structure of words and phrases in a sentence. The rules that define this structure are known as syntax. If you texted your friend "The at will meet. pub I you in 10", your friend would be confused, and you would need to re-type the text. - -Similarly to the English language, programming languages expect keywords, symbols, and values to be arranged in a certain, logical order according to syntax, otherwise the compiler will throw a syntax error. - -## Logic Errors - -Nearly every piece of code you write is an expression of some meaningful logic. This logic is the core of what you are intending to accomplish with your code. Sometimes you might write code in such a way that is syntactically correct but isn’t what you intended to express. This can be seen in any language, including English. - -## Example - -Suppose we have a JavaScript program: - -```js -function sayHello(name) { - alert("Hello ${name}); -} - -sayHello("Joe"); -``` - -Because of a missing closing quotation mark, there's an error message: - -```error -/home/script.js:2 - - alert("Hello ${name}); - ^^^^^^^^^^^^^^^^ - -SyntaxError: Invalid or unexpected token -``` - -This error says that in the file **script.js**, on line `2`, there's a `SyntaxError`. diff --git a/content/general/concepts/file-formats/file-formats.md b/content/general/concepts/file-formats/file-formats.md deleted file mode 100644 index bec98c05b36..00000000000 --- a/content/general/concepts/file-formats/file-formats.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -Title: 'File Formats' -Description: 'File formats determine how information or data, such as text and images, are created, stored, and read.' -Subjects: - - 'Computer Science' - - 'Data Science' -Tags: - - 'Files' - - 'Types' -CatalogContent: - - 'learn-the-command-line' - - 'paths/code-foundations' ---- - -**File formats** determine how information or data, such as text and images, are created, stored, and read. Each file format has a unique extension. For example, a CSV (Comma Separated Values) file has the extension **.csv**. The terms "file format" and "file type" are often used interchangeably. - -Certain formats are designed to compress data for fast processing. Others may contain more features, like how XLSX (Microsoft Excel) files can contain graphs and charts along with table data, whereas a CSV file can only contain plain table data. - -Files can also be converted to other formats, however, some features for data display may be lost depending on the type of conversion. - -## Types of File Formats - -File formats exist for different types of files. Some common file formats are listed below: - -### Programming File Formats - -| File Format | Extension | Description | -| :--------------------------------------------------------------------------------: | :-------: | -------------------------------------- | -| [C](https://www.codecademy.com/resources/docs/c) | `.c` | Contains a C program. | -| [C++](https://www.codecademy.com/resources/docs/cpp) | `.cpp` | Contains a C++ program. | -| [CSS (Cascading Style Sheets)](https://www.codecademy.com/resources/docs/css) | `.css` | Contains the styling for an HTML page. | -| [Go](https://www.codecademy.com/resources/docs/go) | `.go` | Contains a Go program. | -| [HTML (HyperText Markup Language)](https://www.codecademy.com/resources/docs/html) | `.html` | Contains an HTML web page. | -| [Java](https://www.codecademy.com/resources/docs/java) | `.java` | Contains a Java program. | -| [JS (JavaScript)](https://www.codecademy.com/resources/docs/javascript) | `.js` | Contains a JavaScript program. | -| [PHP (Hypertext Preprocessor)](https://www.codecademy.com/resources/docs/php) | `.php` | Contains a PHP program. | -| [Python](https://www.codecademy.com/resources/docs/python) | `.py` | Contains a Python program. | -| [R](https://www.codecademy.com/resources/docs/r) | `.r` | Contains an R program. | -| [Ruby](https://www.codecademy.com/resources/docs/ruby) | `.rb` | Contains a Ruby program. | -| [SQL (Structured Query Language)](https://www.codecademy.com/resources/docs/sql) | `.sql` | Contains an SQL program. | -| [Swift](https://www.codecademy.com/resources/docs/swift) | `.swift` | Contains a Swift program. | -| [TS (TypeScript)](https://www.codecademy.com/resources/docs/typescript) | `.ts` | Contains a Typescript program. | - -### Image File Formats - -| File Format | Extension | Description | -| :-------------------------------------------------------------------------------------: | :-------: | ------------------------------------------------------------------------------------------------------------ | -| JPEG (Joint Photographic Experts Group) | `.jpeg` | Standard use for minimized images. | -| PNG (Portable Network Graphics) | `.png` | Common file format for high resolution images. | -| [SVG (Scalable Vector Graphics)](https://www.codecademy.com/resources/docs/general/svg) | `.svg` | Great for responsive design. Used for images that can be scaled up or down on a page without losing quality. | - -### Other File Formats - -| File Format | Extension | Description | -| :-----------------------------------------------------------------------------------: | :-------: | ------------------------------------------------------------------------------------------- | -| [CSV (Comma-separated Values)](https://www.codecademy.com/resources/docs/general/csv) | `.csv` | Contains spreadsheet/table data. | -| Executable | `.exe` | Contains an executable. | -| [MD (Markdown)](https://www.codecademy.com/resources/docs/markdown) | `.md` | Contains easily readable markup. | -| PDF (Portable Document Format) | `.pdf` | Created to be accessed on many devices and operating systems. Contains text and image data. | -| TXT (Text) | `.txt` | Contains text. | -| Zip | `.zip` | Compresses files into a folder that can be uncompressed into its original form. | diff --git a/content/general/concepts/file-paths/file-paths.md b/content/general/concepts/file-paths/file-paths.md deleted file mode 100644 index a99156ffacd..00000000000 --- a/content/general/concepts/file-paths/file-paths.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -Title: 'File Paths' -Description: 'File paths specify the location of a file in the file system structure of a computer.' -Subjects: - - 'Web Development' - - 'Computer Science' -Tags: - - 'File Paths' - - 'Files' - - 'URL' -CatalogContent: - - 'learn-html' - - 'paths/computer-science' ---- - -A **file path** specifies the location of a file in a computer's [file system structure](https://www.codecademy.com/resources/docs/general/file-system-structure). They can be used to locate files and web resources, including: - -- Media files, such as images -- Links to [CSS stylesheets](https://www.codecademy.com/resources/docs/css) for a web page -- Files that may link to programs, such as [CDNs](https://www.codecademy.com/resources/docs/general/cdn), [frameworks](https://www.codecademy.com/resources/docs/general/cdn), or [Node applications](https://www.codecademy.com/resources/docs/open-source/node-js) -- Other files, such as [JSON](https://www.codecademy.com/resources/docs/general/json) or plain text - -## Paths and Path Separators - -In general, a path is a string of characters which specifies a unique location in a directory or page hierarchy. For file systems, each level in the hierarchy is a directory. For [URLs](https://www.codecademy.com/resources/docs/general/url), each level in the hierarchy is a page. Different sections of the path are separated by a path separator, such as a forward slash (/). These different sections represent the separate directories or pages in the hierarchy, as shown below: - -`/home/user/python/test.py` - -In this file path, the `test.py` file is inside the `python` directory. The `python` directory is a subdirectory of the `user` directory, which is a subdirectory of the `home` directory. File paths are one example of a path. Paths are also an important component of URLs. - -In [Unix](https://www.codecademy.com/resources/docs/general/unix)-based operating systems, such as Linux or macOS, the path separator is a forward slash (/). In Windows, the path separator is a back slash (\\). - -> **Note:** URLs follow a standard format that always uses a forward slash (/) as the path separator regardless of the operating system. - -## URLs and File Paths - -URLs specify the location where data and websites are hosted on the web. URLs and file paths both function similarly and provide the location a computer must go to to find a particular resource. However, a major difference is that URLs locate resources which are hosted on the Internet, and file paths locate resources which are stored locally or on a local network. - -## Absolute and Relative File Paths - -Absolute file paths specify the location of a file from the root directory in the file system structure. They are also called "full file paths" or "full paths." Some examples of absolute file paths are: - -- `/home/user/website/main/about.html` -- `/home/user/projects/js/script.js` -- `/home/user/data-analysis/scripts/main.py` - -In [Linux](https://www.codecademy.com/resources/docs/open-source/linux), the tilde (~) is commonly used to represent a user's home directory in a file path. For example, the above file paths could be changed to: - -- `~/website/main/about.html` -- `~/projects/js/script.js` -- `~/data-analysis/scripts/main.py` - -Relative file paths specify the location of a file in the same folder or on the same [server](https://www.codecademy.com/resources/docs/general/server). In other words, a relative file path specifies a location of a file that is relative to the current directory. Some examples of relative file paths are: - -- `./about.html` -- `./js/script.js` -- `./scripts/main.py` - -Relative file paths use a dot notation at the start of the path, followed by a path separator and the location of the file. A single dot (.) indicates the current directory, and a double dot (..) indicates the parent directory. For example, in Linux, `./` tells the program to look for the file from the current directory, and `../` tells the program to go up to the parent directory before looking for the file. diff --git a/content/general/concepts/file-system-structure/file-system-structure.md b/content/general/concepts/file-system-structure/file-system-structure.md deleted file mode 100644 index b15223383f5..00000000000 --- a/content/general/concepts/file-system-structure/file-system-structure.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -Title: 'File System Structure' -Description: 'The file system structure is a basic method for operating systems to organize information.' -Subjects: - - 'Computer Science' - - 'Bash/Shell' -Tags: - - 'Files' - - 'Linux' - - 'Operating Systems' -CatalogContent: - - 'learn-the-command-line' - - 'paths/computer-science' ---- - -The **file system structure** defines how information in key directories and files (existing and future) are organized and how they are stored in an operating system. - -Although different operating systems may have different standards, all major operating systems have similar characteristics and use a hierarchical structure of directories branching off the root directory. The image below illustrates an example of the hierarchy in a sample file system structure. - -![File system structure](https://raw.githubusercontent.com/Codecademy/docs/main/media/file-system-structure.png) - -## Root - -The root directory, or "root", is the highest-level directory of the file system structure. In macOS, [Linux](https://www.codecademy.com/resources/docs/open-source/linux), and other [UNIX](https://www.codecademy.com/resources/docs/general/unix)-like operating systems, the root is represented with a forward slash (`/`). In Windows, the root is represented by the drive name and a backslash (`\`). - -The root contains all directories and files associated with a particular system or device. Under the root, there are some predefined subdirectories. These directory names differ across different operating systems, but they are used to organize some common information, such as temporary files or user information. - -## Directories and Files - -All other directories and files are located below the root. Directories, or folders, contain a list of the file names for each file in the directory. They also contain other information associated with these files, such as information on where they are stored in the computer’s memory. - -Directories that are located inside other directories are called subdirectories. In hierarchical filesystems, the relationship between directories and subdirectories is sometimes described using a “parent”-”child” metaphor, where the “parent” directory is one level above the “child” directory. - -Files are storage units on a computer which contain information on file contents, instructions needed to read them, and where they are stored. A file’s location in the directory system is referred to as the [file path](https://www.codecademy.com/resources/docs/general/file-paths) and the [file format](https://www.codecademy.com/resources/docs/general/file-formats), or type, determines how data in the file is created, stored, and read. - -## Filesystem Hierarchy Standard (FHS) - -The Filesystem Hierarchy Standard (FHS) is one example of a defined file system structure. The FHS is for UNIX systems and is most popularly used in Linux. It is maintained by the Linux Foundation, and most Linux distributions follow the FHS. - -The FHS defines that all directories and files exist under the root. It also includes standard files which appear directly below the root. Some examples of these files are included below: - -- `/bin` stores all binary executable files. -- `/tmp` stores all temporary files. -- `/sys` stores information on the Linux kernel and various system devices. - -The purpose of using a defined file system structure like the FHS is so users and software can predict the locations of files and directories. This makes it easier to compile, install, and run software. diff --git a/content/general/concepts/firebase/firebase.md b/content/general/concepts/firebase/firebase.md deleted file mode 100644 index e004b4f3438..00000000000 --- a/content/general/concepts/firebase/firebase.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -Title: 'Firebase' -Description: 'Firebase is a cloud computing and app development platform hosted by Google.' -Subjects: - - 'Computer Science' - - 'Mobile Development' -Tags: - - 'Firebase' - - 'APIs' - - 'Developer Tools' -CatalogContent: - - 'paths/front-end-engineer-career-path' - - 'paths/computer-science' ---- - -[**Firebase**](https://firebase.google.com/) is a [cloud computing](https://www.codecademy.com/resources/docs/cloud-computing) and app development platform hosted by Google. - -It was founded in 2011 as Envovle, a startup which developed [APIs](https://www.codecademy.com/resources/docs/general/api) for embedded chat services in websites. Google acquired Firebase in 2014 and has further developed the services offered by the platform, some of which now include: - -- Authentication -- ML Kit -- Realtime Database -- Firebase Hosting -- Performance Monitoring -- Analytics - -These services are designed to allow developers to build and maintain apps with many backend services accessed directly by Firebase SDK's. diff --git a/content/general/concepts/flutter/flutter.md b/content/general/concepts/flutter/flutter.md deleted file mode 100644 index 8ed98f571d2..00000000000 --- a/content/general/concepts/flutter/flutter.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -Title: 'Flutter' -Description: 'Flutter is an open-source framework by Google that allows developers to create an application using only a single codebase and have it run on mobile, desktop, and the web.' -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'Flutter' - - 'OOP' -CatalogContent: - - 'intro-to-flutter' ---- - -[**Flutter**](https://flutter.dev/) is an open-source framework by Google that allows developers to create an application using only a single codebase and have it run on mobile, desktop, and the web. These kinds of applications are called cross-platform applications. In contrast, applications that are specifically designed for only a single platform, such as an app that is only supposed to run on Apple phones, are called native applications. - -The supported platforms that a single Flutter project can run on are: - -- Desktop - - Linux - - macOS - - Windows -- Mobile - - Android - - iOS -- Web - - Browsers such as Microsoft Edge, Mozilla Firefox, Google Chrome, etc. - -To create a mobile app targeting iOS and Android users, developers typically need to develop two separate apps. One app is designed for iOS using one programming language, and the other is designed for Android using a different programming language. However, with the power of Flutter, developers can create a single app using only one programming language. Furthermore, ensuring parity between the two versions becomes very easy, guaranteeing that the iOS and Android versions of the app have exactly the same features and appearance at any given time. - -Flutter apps are powered by the [Dart](https://dart.dev/) programming language. It is an object-oriented language like Python and JavaScript. In Flutter, everything is created using objects called `Widgets`. At the highest level of a Flutter app is an App widget, which is composed of screen widgets, which is finally composed of widgets that represent UI elements such as buttons, text, and images. - -There are other frameworks like Flutter that are also used to develop cross-platform applications. Some of them are: - -- [Xamarin](https://dotnet.microsoft.com/en-us/apps/xamarin) -- [React Native](https://reactnative.dev/) -- [Ionic](https://ionicframework.com/) - -Native applications generally offer better performance than cross-platform applications. However, Flutter apps come close to native performance, setting it apart from some other frameworks that don't achieve native-like performance. What works against Flutter is the typically steeper learning curve. Developers need to learn the Dart language, which is less familiar to many, while other frameworks use more commonly known languages like JavaScript, C#, and so on. diff --git a/content/general/concepts/framework/framework.md b/content/general/concepts/framework/framework.md deleted file mode 100644 index aaa9be3d8c1..00000000000 --- a/content/general/concepts/framework/framework.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -Title: 'Framework' -Description: 'Frameworks are software that provide reusable boilerplate code and functionality for building applications.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Conceptual' - - 'Frameworks' -CatalogContent: - - 'learn-rails' - - 'paths/full-stack-engineer-career-path' ---- - - - -**Frameworks** are tools that provide reusable boilerplate code and functionality for building applications. They are commonly associated with a specific programming language and are suited to different types of tasks. - -Using frameworks can save time and reduces the risk of hard-to-find errors. Plus, frameworks have already been tested, so there's less to worry about. Other advantages include: - -- Boilerplate code that is clean, secure, and scalable. -- Better tests and debugging methods. -- The ability to customize the code for a specific project. - -Unlike libraries, which are pieces of reusable code, frameworks provide supporting structures that the code must follow. - -## Types of Frameworks - -Frameworks can be used for developing many types of software including the following. - -### Web Application Frameworks - -These frameworks are used for developing any software for the Web, including websites, web applications, and Web APIs. A few common examples of web frameworks include: - -- [Angular](https://www.codecademy.com/resources/docs/open-source/angular), an open-source [TypeScript](https://www.codecademy.com/resources/docs/typescript)-based framework. -- Django, a [Python](https://www.codecademy.com/resources/docs/python)-based framework that is fast, secure, and has a great admin interface. -- [Rails](https://www.codecademy.com/resources/docs/ruby/ruby-on-rails), a full-stack framework written in [Ruby](https://www.codecademy.com/resources/docs/ruby). -- Gatsby, a [React](https://www.codecademy.com/resources/docs/react)-based framework used for building static websites like landing pages, portfolios, and blogs. - -### Mobile Development Frameworks - -These frameworks are used for building applications that can be used on various mobile devices including phones, tablets, and wearables. A few common examples of mobile frameworks include: - -- [Flutter](https://flutter.dev/) is an open-source framework supported on iOS and Android and features customizable widgets. -- [React Native](https://www.codecademy.com/resources/docs/react/react-native), a framework that is cross-platform and written in [JavaScript](https://www.codecademy.com/resources/docs/javascript). -- [NativeScript](https://nativescript.org/), an JavaScript framework that features robust backend-end support. diff --git a/content/general/concepts/front-end/front-end.md b/content/general/concepts/front-end/front-end.md deleted file mode 100644 index 1f7c2848d75..00000000000 --- a/content/general/concepts/front-end/front-end.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -Title: 'Front-End' -Description: 'The front-end of a website includes elements that the end user interacts with directly.' -Subjects: - - 'Web Design' - - 'Web Development' -Tags: - - 'Browsers' - - 'Debugging' - - 'Development' - - 'Frameworks' - - 'jQuery' - - 'Responsive' -CatalogContent: - - 'learn-html' - - 'paths/front-end-engineer-career-path' ---- - - - -The **front-end** of a website includes elements that the end user interacts with directly. A lot goes into front-end development, including: - -- Styling for the overall look of the website such as buttons, layouts, inputs, text, and images. -- Accessibility features like text-to-speech, voice recognition, simple user flows, and more make websites easier to use and provide a better user experience. -- Improvements to performance and speed for a better user experience. - -## Common Tasks - -Front-end web development can involve a variety of tasks, including: - -- Creating and updating webpages. -- Building HTML emails for email campaigns. -- Making sure webpages are responsive and work well on phones or tablets. -- Improving website performance by cleaning and splitting code. -- Adding and improving accessibility features. - -## Front-End Technologies - -The following are the three core technologies used in front-end development: - -- [HTML](https://www.codecademy.com/resources/docs/html), the "skeleton" of a webpage, is used to structure the content's layout and general behavior on the browser. -- [CSS](https://www.codecademy.com/resources/docs/css), the "skin and clothes" of the webpage, gives browsers more specific information on styling content, like the size and color of text or the look and layout of a group of elements. -- [JavaScript](https://www.codecademy.com/resources/docs/javascript) is executed on both the client-side and server-side to bring interactivity to elements such as maps and animated graphics. - -Front-End Developers also use other tools, ranging from content management systems (CMSs) like WordPress and Drupal to libraries and frameworks like [React](https://www.codecademy.com/resources/docs/react), Angular, and Vue. Libraries and frameworks allow you to use a blueprint to create web elements like buttons rather than creating a new one every time. - -## Careers in Front-End - -While there are various roles and titles in the world of front-end development, the two primary roles are front-end design and front-end engineering. - -### Front-End Designers - -Sometimes to known as a Front-End Interface Developer, this role usually takes static media such as drawings or images and translates them into webpages. This is important, since all webpages for the same site should have matching designs and be responsive to various screen sizes. - -### Front-End Engineers - -This role is more focused on a webpage's functionality and scalability. Some Front-End Engineers also work on design if their workplace uses the two roles interchangeably. diff --git a/content/general/concepts/full-stack/full-stack.md b/content/general/concepts/full-stack/full-stack.md deleted file mode 100644 index 305af3d9890..00000000000 --- a/content/general/concepts/full-stack/full-stack.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -Title: 'Full-Stack' -Description: 'Full-stack development refers to having competency in both client and server-side software.' -Subjects: - - 'Web Design' - - 'Web Development' -Tags: - - 'Browsers' - - 'Debugging' - - 'Development' - - 'Frameworks' - - 'Responsive' - - 'Servers' -CatalogContent: - - 'learn-html' - - 'paths/full-stack-engineer-career-path' ---- - -**Full-stack** development refers to having competency in both client and server-side software to build entire applications from the [back-end](https://www.codecademy.com/resources/docs/general/back-end), through [APIs](https://www.codecademy.com/resources/docs/general/api), to the [front-end](https://www.codecademy.com/resources/docs/general/front-end). Full-stack developers are able to handle both front-end and back-end tasks. Typically, full-stack developers are stronger in either front or back-end and throughout their careers, gain competence in the full-stack. - -## Hiring Trends - -Larger companies have the resources to hire large development teams, which allows them to have teams where developers can specialize in either front-end or back-end. - -Startups, on the other hand, may be limited in their ability to hire a large development team, so instead will seek full-stack developers. They tend to seek full-stack developers for several reasons, one of which is funding. - -## Common Tasks - -Full-stack web development can involve a variety of front-end and back-end tasks, including: - -- Creating and updating webpages. -- Making sure webpages are responsive and work well on phones or tablets. -- Improving website performance. -- Adding and improving accessibility features. -- Using front-end [frameworks](https://www.codecademy.com/resources/docs/general/framework) to build client-side software. -- Building and consuming APIs. -- Creating, integrating, and managing [databases](https://www.codecademy.com/resources/docs/general/database). -- Using back-end frameworks to build server-side software. -- Validating data to make sure it's formatted correctly before being sent to the database. -- Integrating user-facing elements with server-side elements to make sure that information is being sent to the right place so the server can retrieve it. - -## Popular Tech Stacks - -Full-stack developers typically utilize a combination of software, called a [tech stack](https://www.codecademy.com/resources/docs/general/tech-stack), in order to build full-stack applications. - -### MEXN Stack - -This well-known tech stack comes in a few forms but all of them use [MongoDB](https://www.codecademy.com/learn/learn-mongodb) (for the database), [Express.js](https://www.codecademy.com/resources/docs/open-source/express) (for the back-end), and [Node.js](https://www.codecademy.com/resources/docs/open-source/node-js) (for the server). One of the following front-end frameworks is commonly used in this stack: - -- [React.js](https://www.codecademy.com/resources/docs/react) (ME**R**N) -- [Angular](https://www.codecademy.com/resources/docs/open-source/angular) (ME**A**N -- [Vue](https://www.codecademy.com/learn/learn-vue-js) (ME**V**N) - -### LAMP Stack - -Technologies in the LAMP stack include some popular [open-source](https://www.codecademy.com/resources/docs/open-source) projects: - -- [Linux](https://www.codecademy.com/resources/docs/open-source/linux): Open-source operating system -- Apache: Popular open-source web server software -- MySQL: Database management system -- [PHP](https://www.codecademy.com/resources/docs/php): Web development programming language - -### Django Stack - -Highlights for this stack include the use of [Django](https://www.codecademy.com/learn/paths/build-python-web-apps-with-django), a popular [Python](https://www.codecademy.com/resources/docs/python) framework that is structured around creating templates. This can be used with a front-end framework like Vue for building a web application. diff --git a/content/general/concepts/function/function.md b/content/general/concepts/function/function.md deleted file mode 100644 index c4f82c8304c..00000000000 --- a/content/general/concepts/function/function.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -Title: 'Function' -Description: 'The function data type does not immediately run upon the execution of a file. It must be called on to perform a specific task.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Data Types' - - 'Functions' - - 'Types' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -**Functions** hold a distinct place among the [data types](https://www.codecademy.com/resources/docs/general/data-types). They are blocks of code that yield results or perform a specific task. In some programming languages, they are processed as objects of data. This is because in some languages they are derived from objects and its closest classification is with composite data types. - -Many languages treat functions as first-class objects, which means: - -- They can be assigned to variables. -- They can be passed as arguments to or returned by other functions. - -## Functions in Different Languages - -- [C](https://www.codecademy.com/resources/docs/c/functions) -- [C++](https://www.codecademy.com/resources/docs/cpp/functions) -- [JavaScript](https://www.codecademy.com/resources/docs/javascript/functions) -- [PHP](https://www.codecademy.com/resources/docs/php/functions) -- [Python](https://www.codecademy.com/resources/docs/python/functions) -- [Ruby](https://www.codecademy.com/resources/docs/ruby/functions) -- [TypeScript](https://www.codecademy.com/resources/docs/typescript/functions) diff --git a/content/general/concepts/geolocation/geolocation.md b/content/general/concepts/geolocation/geolocation.md deleted file mode 100644 index d510109ac17..00000000000 --- a/content/general/concepts/geolocation/geolocation.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -Title: 'Geolocation' -Description: 'Geolocation refers to the process of determining the geographic location of an object, usually through electronic means such as GPS.' -Subjects: - - 'Computer Science' - - 'Mobile Development' -Tags: - - 'Map' - - 'Positioning' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -**Geolocation** refers to the process of determining the geographic location of an object, usually through electronic means such as GPS. A modern example of geolocation is the location function in various electronic devices such as smartphones. - -Many modern applications can be given access to a device's geolocation data, so a review app can show restaurants within a few miles/kilometers, a banking app can show nearby branches, or a game can offer [augmented reality](https://www.codecademy.com/resources/docs/general/augmented-reality) experiences based on where the device is located. - -Also, most smartphones have a mapping app that can locate the phone on a street map in order to provide directions to some other location. - -## Common Geolocation Methods - -These are the main ways a smartphone (and other consumer electronic device) can provide geolocation services: - -- The Global Positioning System (GPS): A device can have a GPS receiver that communicates with the GPS satellite system that uses the positions of the satellites it can communicate with to determine its position on the ground. A disadvantage is that things like heavy tree cover or buildings can interfere with the signal. -- Wireless: A device connects with several different cell towers in the area and using signal strength and [triangulation](https://en.wikipedia.org/wiki/Triangulation) determines its position on the ground. The disadvantage is this can be inaccurate when there are limited cell towers available, and will not work where there is no cell reception. -- The Wi-Fi Positioning System (WPS): Like Wireless positioning above, but instead of cell towers, uses the positions of nearby Wi-Fi hotspots. This is generally only useful in urban locations with dense Wi-Fi coverage. -- Wireless-assisted GPS: Combines Wireless and/or WPS with GPS to compensate for the weaknesses of the different methods. It can often get the device's location faster than GPS alone. diff --git a/content/general/concepts/github/github.md b/content/general/concepts/github/github.md deleted file mode 100644 index dfe8b6bacf1..00000000000 --- a/content/general/concepts/github/github.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -Title: 'GitHub' -Description: 'Github is a UI-based version control platform that uses Git.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'GitHub' - - 'Git' -CatalogContent: - - 'learn-git' - - 'paths/learn-how-to-build-websites' ---- - -**GitHub (GH)** is a UI-based version control platform that runs on [Git](https://www.codecademy.com/resources/docs/git). It offers many services including version control, static website hosting, [open-source software (OSS)](https://www.codecademy.com/resources/docs/open-source/open-source-software) projects, and much more. - -## GitHub Pages - -[GitHub Pages](https://pages.github.com/) is a service offered by GH for hosting static websites for free with an unlimited amount of visits. It automatically has encryption with [HTTPS](https://www.codecademy.com/resources/docs/general/http). GitHub Pages also supports custom domains. - -## Good First Issue - -["Good First Issue"](https://docs.github.com/en/issues/using-labels-and-milestones-to-track-work/managing-labels) is a label used by open-source maintainers on GitHub to categorize issues that are intended for people who have little to no experience in making open source contributions or are new to a particular project. It also signifies to maintainers that extra assistance is needed when reviewing a new contributor's pull request, whether it's introducing the contributing guidelines or providing in-line comments on lines of code that need revision. Additionally, there is a compiled list of repositories using the "Good First Issue" label in the [topics section of GitHub](https://github.com/topics/good-first-issue). diff --git a/content/general/concepts/graphql/graphql.md b/content/general/concepts/graphql/graphql.md deleted file mode 100644 index ef2f2fdf2e4..00000000000 --- a/content/general/concepts/graphql/graphql.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -Title: 'GraphQL' -Description: 'A flexible, efficient API query language that allows clients to request precisely the data they need.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'APIs' - - 'Developer Tools' - - 'Dependency' - - 'Interface' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**GraphQL** is a modern query language and runtime for [APIs](https://www.codecademy.com/resources/docs/general/api), developed by Facebook in 2012. It provides a more flexible, powerful alternative to traditional [REST](https://www.codecademy.com/resources/docs/general/rest) APIs by enabling clients to define exactly what data they want to retrieve. - -## History - -- Developed internally at Facebook in 2012 to address limitations in mobile application data fetching. -- Open-sourced in 2015, gaining rapid adoption in web and mobile development. -- Created to solve inefficiencies in data retrieval and provide more precise data manipulation. - -## Working - -GraphQL operates through a single endpoint where clients can: - -- Define precise data requirements using a strongly typed schema. -- Request multiple resources in a single query. -- Retrieve exactly the data needed, reducing over-fetching and under-fetching. -- Provide a contract between client and server about data capabilities. - -## GraphQL vs. REST - -| Feature | GraphQL | REST | -| ---------------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | -| **Data Fetching** | Clients specify the exact data they need | Server defines fixed endpoints returning predefined data | -| **Over-fetching & Under-fetching** | Avoids both by allowing precise queries | Over-fetching (getting more data than needed) and under-fetching (making multiple requests) can occur | -| **Endpoints** | Single endpoint (`/graphql`) for all queries | Multiple endpoints for different resources (`/users`, `/posts`, etc.) | -| **Performance** | Efficient as only required data is fetched | Can be inefficient due to multiple round trips | -| **Flexibility** | Highly flexible; clients control response structure | Less flexible; fixed responses based on server design | -| **Versioning** | No versioning needed; schema evolves dynamically | Often requires versioning (`/v1/users`, `/v2/users`) | -| **Batch Requests** | Can retrieve multiple resources in one request | Requires multiple requests for multiple resources | -| **Real-time Support** | Built-in support via subscriptions | Requires WebSockets or polling for real-time data | -| **Ease of Use** | Requires learning a query language (GraphQL) | Familiar, follows standard HTTP methods (GET, POST, PUT, DELETE) | -| **Error Handling** | Centralized error handling with structured responses | Error handling varies by endpoint and implementation | -| **Caching** | More complex; requires custom caching strategies | Easily cached using HTTP caching mechanisms | diff --git a/content/general/concepts/graphs/graphs.md b/content/general/concepts/graphs/graphs.md deleted file mode 100644 index f750cdb1da8..00000000000 --- a/content/general/concepts/graphs/graphs.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -Title: 'Graphs' -Description: 'Graphs are a way of modeling systems based on a node and edge structure for representing the relationships between items.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Conceptual' - - 'Graphs' - - 'Development' -CatalogContent: - - 'learn-testing-for-web-development' - - 'paths/full-stack-engineer-career-path' ---- - -**Graphs** are a way of modeling systems based on a node and edge structure for representing the relationships between items. There are many types of systems and problems that lend themselves to be represented through graphs, including social networks, street navigation or path finding, etc. - -## Graph Types - -Graphs are often classified by their structural characteristics, some common elements include the following: - -- Directed: A graph in which the relationships between elements are not equivalent. -- Undirected: All of the connections are bidirectional: A to B is the same as B to A. -- Weighted: Edges in the graph have an associated cost. -- Acyclic: A graph that does not contain any cycles among any of the nodes. A cycle is a path which starts and ends at the same node. A tree is a common example of a directed acyclic graph: all the nodes in the graph have one orientation, parent to child. - -## Data Structures - -There are a few data structures typically used for implementing a graph. Each structure offers different benefits and constraints. - -- Edge List: This is the simplest format, it consists of an unordered list of all edge pairs. -- Adjacency List: This is a simple and space-efficient format that maps all the edges of each node to a list. -- Adjacency Matrix: This format documents the adjacent or neighboring nodes in a matrix of size n x n (n equals the total number of nodes in the graph). - -## Graph Algorithms - -There are many well-known algorithms that have been developed for working with graphs, some of them include the following: - -- Breadth First Search: A path-finding and mapping algorithm that relies on a layered approach to finding the next closest nodes within a graph. -- Dijkstra: This is a shortest-path algorithm that can be used on weighted graphs, but not on graphs that include negative weights. -- Bellman-Ford: Another shortest-path algorithm that is specifically designed for addressing graphs with negative weights. diff --git a/content/general/concepts/hacktoberfest/hacktoberfest.md b/content/general/concepts/hacktoberfest/hacktoberfest.md deleted file mode 100644 index a17ae6e2350..00000000000 --- a/content/general/concepts/hacktoberfest/hacktoberfest.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -Title: 'Hacktoberfest' -Description: 'Hacktoberfest is an annual worldwide event that is held in October that incentivizes developers to contribute to open-source software development.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Development' - - 'Open Source' -CatalogContent: - - 'introduction-to-open-source' - - 'paths/code-foundations' ---- - -**Hacktoberfest** is an annual worldwide event that is held in October. It incentivizes developers to contribute to [open-source](https://www.codecademy.com/resources/docs/open-source) software development. - -## Participation and Rewards - -Developers can participate by making four pull requests and having them accepted to any public GitHub repository between October 1st and 31st. - -Participants who successfully complete the required number of pull requests receive a reward. - -While the event encourages contributions, it also emphasizes the importance of quality over quantity. Contributions should follow the guidelines of the respective open-source projects and be meaningful improvements or additions. - -## Official Site - -The official Hacktoberfest site can be found [here](https://hacktoberfest.com). diff --git a/content/general/concepts/hexadecimal/hexadecimal.md b/content/general/concepts/hexadecimal/hexadecimal.md deleted file mode 100644 index 9ff11b64dac..00000000000 --- a/content/general/concepts/hexadecimal/hexadecimal.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -Title: 'Hexadecimal' -Description: 'Hexadecimal(hex, hex numbers, or base-16) is a numeral system that uses a base of 16 as opposed to the standard decimal system, base 10.' -Subjects: - - 'Web Development' - - 'Web Design' - - 'Computer Engineering' -Tags: - - 'colors' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -**Hexadecimal** (hex, hex numbers, or base-16) is a number system that uses a base of 16 as opposed to the standard decimal system, which is base 10. When representing a number, both number systems share the first ten digits, 0-9. However, for hexadecimal, the remaining digits 10-15 are represented by the letters A-F (not case sensitive) - -| Decimal | Hex | -| ------- | --- | -| 1 | 1 | -| 2 | 2 | -| 3 | 3 | -| 4 | 4 | -| 5 | 5 | -| 6 | 6 | -| 7 | 7 | -| 8 | 8 | -| 9 | 9 | -| 10 | A | -| 11 | B | -| 12 | C | -| 13 | D | -| 14 | E | -| 15 | F | - -## Power Of 2 - -Hexadecimal, as well as binary (base 2) and octal (base 8), have bases that are powers of two, making it easy to convert between one another. - -## Syntax - -A hexadecimal number is prefixed with `0x` in many computer languages to identify it as a base 16 number. - -## Hex Colors - -Hex numbers are often used to represent colors (hex colors) and are specified in the following way: `#RRGGBB`(red, green, and blue). One example of a hex color is `#0000FF` which represents the color blue. This is because red and green are set to their lowest value, `00`, and blue is set to its highest value, `FF`. diff --git a/content/general/concepts/historical-technical-figures/historical-technical-figures.md b/content/general/concepts/historical-technical-figures/historical-technical-figures.md deleted file mode 100644 index 4d801d1e3a0..00000000000 --- a/content/general/concepts/historical-technical-figures/historical-technical-figures.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -Title: 'Historical Technical Figures' -Description: 'Historical technical figures paved the way for new technologies to eventually be bought into our every day lives.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - '' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -**Historical technical figures** paved the way for new technologies to eventually be brought into our every day lives. Their pivotal impact on technological advances affects us to this day. - -Below are some notable historical technical figures: diff --git a/content/general/concepts/historical-technical-figures/terms/aaron-swartz/aaron-swartz.md b/content/general/concepts/historical-technical-figures/terms/aaron-swartz/aaron-swartz.md deleted file mode 100644 index 853dcc33b22..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/aaron-swartz/aaron-swartz.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -Title: 'Aaron Swartz' -Description: 'Aaron Swartz was an American programmer, writer, entrepreneur, and internet activist involved in the development of the RSS web feed format, Markdown language, Creative Commons organization, and Python web framework web.py.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Markdown' - - 'RSS' -CatalogContent: - - 'learn-python-3' - - 'paths/code-foundations' ---- - -![Aaron Swartz](https://raw.githubusercontent.com/Codecademy/docs/main/media/aaron_swartz.png) - -**Aaron Swartz** (1986-2013) was an American programmer, writer, entrepreneur, and internet activist. He was involved in the development of the RSS web feed format, [Markdown](https://www.codecademy.com/resources/docs/markdown) language, [Creative Commons licenses](https://creativecommons.org/), and Python web framework [web.py](https://webpy.org/). - -He was a co-founder of a startup called Infogami, which later became the social news site Reddit. In his later years, he co-founded an activist organization, Demand Progress, and led the charge in fighting the Stop Online Piracy Act (SOPA). - -## Writing - -In 2008, Swartz published an essay called "Guerilla Open Access Manifesto", which can be found on the internet and in the "The Boy Who Could Change the World" book published posthumously in 2016: - -> Sharing isn't immoral — it's a moral imperative. Only those blinded by greed would refuse to let a friend make a copy. - -## United States v. Aaron Swartz - -In 2011, Swartz was arrested by Massachusetts Institute of Technology (MIT) police on state breaking-and-entering charges, after connecting to the campus network in an unlocked closet, to mass download academic journal articles. - -Federal prosecutors later charged him with wire fraud and violations of the Computer Fraud and Abuse Act, carrying a maximum penalty of $1 million in fines, 35 years in prison, asset forfeiture, and supervised release. - -Swartz declined a plea bargain under which he would have served six months in federal prison. Two days after the prosecution rejected a counter-offer by Swartz, he was found dead in his Brooklyn apartment, where he committed suicide. He was 26 years old. diff --git a/content/general/concepts/historical-technical-figures/terms/ada-lovelace/ada-lovelace.md b/content/general/concepts/historical-technical-figures/terms/ada-lovelace/ada-lovelace.md deleted file mode 100644 index 543af680d42..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/ada-lovelace/ada-lovelace.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -Title: 'Ada Lovelace' -Description: 'Ada Lovelace was an English writer and mathematician and is often considered to be the first computer programmer. Lovelace is known for her work on the first programmable general-purpose computer.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Arithmetic' - - 'Numbers' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -![Ada Lovelace](https://raw.githubusercontent.com/Codecademy/docs/main/media/ada_lovelace.png) - -**Ada Lovelace** (1815-1852) was an English writer and mathematician and is often considered to be the first computer programmer. - -Lovelace is known for her work on Charles Babbage's [Analytical Engine](https://en.wikipedia.org/wiki/Analytical_Engine), the first programmable general-purpose computer. This machine included many features that are still cornerstones of today's computers such as an arithmetic logic unit, control flows, and integrated memory. - -While this machine was revolutionary, the Analytical Engine's capabilities were misunderstood at the time. However, Ada Lovelace's excellent implementation for calculating Bernoulli numbers on the conceptual machine became the first published algorithm and aided in legitimizing the practicality of such a device. - -**Fun fact:** One of the main conference rooms at Codecademy's old office was named after Ada Lovelace. diff --git a/content/general/concepts/historical-technical-figures/terms/alan-turing/alan-turing.md b/content/general/concepts/historical-technical-figures/terms/alan-turing/alan-turing.md deleted file mode 100644 index 24e97674107..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/alan-turing/alan-turing.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -Title: 'Alan Turing' -Description: 'Alan Turing was an English mathematician and computer scientist best known for his work on algorithms, computation, and creating the foundations of theoretical computer science through the development of the Turing machine.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Artificial Intelligence' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -![Alan Turing](https://raw.githubusercontent.com/Codecademy/docs/main/media/alan_turing.png) - -**Alan Turing** (1912-1954) was an English mathematician and computer scientist best known for his work on algorithms, computation, and creating the foundations of theoretical computer science through the development of the Turing machine. - -Shortly after becoming a Fellow at King's College in Cambridge, Turing published a paper describing the Turing machine, an abstract machine that can simulate any algorithm's logic. Turing used this to prove that it is not possible to create an algorithm to determine if a program will ever stop running. - -During the Second World War, Alan Turing was a key component in breaking the Enigma cipher encrypting all of Nazi Germany's secret communication. Turing's work is considered fundamental to deciding the outcome of the war with the information the code-breaking provided. - -## Turing Test - -In 1950, Turing published a paper in "Mind" called "Computing Machinery and Intelligence". It is a seminal paper on the topic of artificial intelligence (AI). The paper was the first to introduce his concept of what is now known as the Turing test (originally called imitation game) to the general public. - -> I propose to consider the question, "Can machines think?" - Alan Turing, 1950 - -The paper questioned whether or not a computer is capable of thinking like a human being. Turing proposed that a computer can be said to possess artificial intelligence if it can mimic human responses under specific conditions. - -**Fun fact:** Our main conference room was named after Alan Turing at Codecademy's old office. diff --git a/content/general/concepts/historical-technical-figures/terms/bjarne-stroustrup/bjarne-stroustrup.md b/content/general/concepts/historical-technical-figures/terms/bjarne-stroustrup/bjarne-stroustrup.md deleted file mode 100644 index f0ccb0aa508..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/bjarne-stroustrup/bjarne-stroustrup.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -Title: 'Bjarne Stroustrup' -Description: 'Bjarne Stroustrup is a Danish computer scientist and principal designer of C++, an extension of the C programming language.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'OOP' - - 'Middleware' -CatalogContent: - - 'learn-c-plus-plus' - - 'paths/computer-science' ---- - -![Bjarne Stroustrup](https://raw.githubusercontent.com/Codecademy/docs/main/media/bjarne_stroustrup.png) - -[**Bjarne Stroustrup**](https://www.stroustrup.com) (1950 - ) is a Danish computer scientist and principal designer of [C++](https://www.codecademy.com/resources/docs/cpp), an extension of the [C](https://www.codecademy.com/resources/docs/c) programming language. - -Stroustrup has authored several computer programming books focused on C++, including "The C++ Programming Language", and is currently a Visiting Professor in Computer Science at Columbia University. - -As the principal designer of C++, Bjarne Stroustrup's goal was to add object-oriented programming into C, a language well-respected for its portability and low-level functionality, and to do so efficiently. Stroustrup's continued work in maintaining C++ is associated with improvements in performance and efficiency for a great number of applications including AI/ML, RDBMS, video games, financial systems, and graphics. - -Dr. Stroustrup played a key role in the development of Codecademy's [Learn C++](https://www.codecademy.com/learn/learn-c-plus-plus) course. Here's an insightful interview called [Talking C++](https://www.codecademy.com/resources/blog/bjarne-stroustrup-interview/) that took part in the last segment of the production. diff --git a/content/general/concepts/historical-technical-figures/terms/dennis-ritchie/dennis-ritchie.md b/content/general/concepts/historical-technical-figures/terms/dennis-ritchie/dennis-ritchie.md deleted file mode 100644 index a0360b0ca7a..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/dennis-ritchie/dennis-ritchie.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -Title: 'Dennis Ritchie' -Description: 'Dennis Ritchie was an American computer scientist, the creator of the computer programming language C, and co-creator of the Unix operating system.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Unix' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -![Dennis Ritchie, image: Wikimedia Commons](https://raw.githubusercontent.com/Codecademy/docs/main/media/dennis_ritchie.png) - -Image by Wikimedia Commons - -**Dennis Ritchie** (1941 - 2011) was an American computer scientist, the creator of the computer programming language [C](https://www.codecademy.com/resources/docs/c), and co-creator of the [Unix](https://www.codecademy.com/resources/docs/general/unix) operating system. - -Ritchie, along with [Ken Thompson](https://www.codecademy.com/resources/docs/general/historical-technical-figures/ken-thompson) and others at Bell Laboratories, began working on Unix in 1967 as a replacement operating system for the Digital Equipment Corporation's PDP-7 mini computer. - -Within this same time, Ken Thompson also developed the B computer programming language with Ritchie's contribution, and in 1971, Ritchie began developing C as an extension of B. - -Today, C is one of the most commonly used languages for embedded and operating system development, such as macOS and Android. There have been several languages developed as extensions of C including C#, [C++](https://www.codecademy.com/resources/docs/cpp), and [Java](https://www.codecademy.com/resources/docs/java). diff --git a/content/general/concepts/historical-technical-figures/terms/gary-kildall/gary-kildall.md b/content/general/concepts/historical-technical-figures/terms/gary-kildall/gary-kildall.md deleted file mode 100644 index 4c0db2bbdc2..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/gary-kildall/gary-kildall.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -Title: 'Gary Kildall' -Description: 'Gary Kildall was an American computer scientist, entrepreneur, and technology educator who did pioneering work on operating systems and compilers.' -Subjects: - - 'Code Foundations' -Tags: - - 'Compilation' - - 'Operating Systems' -CatalogContent: - - 'fundamentals-of-operating-systems' - - 'paths/computer-science' ---- - -![Gary Kildall, image: Nephilim Corporation](https://raw.githubusercontent.com/Codecademy/docs/main/media/gary-kildall) - -Image from Nephilim Corporation. - -**Gary Kildall** (1942 - 1994) was an American computer scientist, entrepreneur, and technology educator. Among his contributions, he is best known for the development of **PL/M**, the first high-level programming language for microprocessors, and **CP/M**, an industry-standard operating system for early personal computers. - -## Education - -Kildall earned a B.A., M.S., and Ph.D. in computer science at the University of Washington. Kildall's [Ph.D. thesis](https://dl.acm.org/doi/10.5555/906224) founded **data-flow analysis**, an approach to using compilers to optimize code. - -## Technical Innovations - -- _PL/M_: A high-level programming language for microprocessors. Kildall developed PL/M for Intel in 1973 and it was used in Intel microprocessors throughout the '70s and '80s. PL/M is widely recognized as the first high-level programming language and compiler for microprocessors. -- _CP/M_: An operating system for microprocessors. The invention of CP/M enabled microprocessors to communicate with disk drives, a necessity for the invention of personal computers. CP/M sold over 250,000 copies and anticipated much of the later functionality of MS-DOS, the precursor to Microsoft Windows. -- _BIOS_: The Basic Input/Output System, a routine used to initialize the hardware and operating system on a microprocessor. Kildall developed BIOS to enable CP/M to be installed on different hardware without being modified. -- _XLT86_: A compiler that translates source code written for the Intel 8080 microprocessor into source code for the Intel 8086 microprocessor (a **source-to-source compiler** or **transcompiler**). XLT86, released in 1982, was one of the first transcompilers to implement code optimization techniques, which were themselves pioneered by Kildall in his Ph.D. thesis. -- _KnowledgeDisc_: A CD-ROM containing the entirety of _Grolier's Academic Encyclopedia_. Kildall helped develop the file system and data structures for this product, which was released in 1985 as the first commercially-available CD-ROM product. Kildall presented the KnowledgeDisc at a keynote talk at the first annual Microsoft CD-ROM Conference. - -## Business Ventures - -- _Digital Research, Inc. (DRI)_: A company founded by Kildall to sell operating system software including CP/M and its successors. DRI was sold in 1991 for 80-million USD. -- _Activenture_: A spin-off company from DRI focusing on optical disc technology, such as the CD-ROM. Kildall released the KnowledgeDisc through Activenture. - -## Technology Education - -- After his Ph.D., Kildall taught computer science for several years at the Naval Postgraduate School in Monterey, California. -- From 1983 to 1990, Kildall was a co-host of the PBS show _Computer Connections_, which documented developments in the growing personal computer industry. - -## Personal Writings - -In his last years, Kildall worked on a memoir, titled _Computer Connections: People, Places, and Events in the Evolution of the Personal Computer Industry_. The first several chapters of this manuscript are available for [free](https://computerhistory.org/blogs/computer-history-museum-license-agreement-for-the-kildall-manuscript/). diff --git a/content/general/concepts/historical-technical-figures/terms/gordon-moore/gordon-moore.md b/content/general/concepts/historical-technical-figures/terms/gordon-moore/gordon-moore.md deleted file mode 100644 index ecddac843f8..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/gordon-moore/gordon-moore.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -Title: 'Gordon Moore' -Description: 'Gordon Moore is the co-founder of Intel Corporation, the largest manufacturer of various computer parts like microprocessors for companies like Acer, Lenovo, HP, and Dell. He was also the primary advocate for Moores Law.' -Subjects: - - 'Computer Science' -Tags: - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Gordon Moore** is the co-founder of Intel Corporation, the largest manufacturer of various computer parts like microprocessors for companies like Acer, Lenovo, HP, and Dell. He was also the primary advocate for Moore's Law. - -## Moore's Law - -In 1965, Gordon Moore, then-CEO of Intel, predicted that twice as many transistors would be able to fit onto a computer chip every two years. This idea has served as a guiding principle and goal for the semiconductor industry to make sure that progress is being made consistently toward greater computing power in devices. Today, this is known as Moore's Law. - -Being more of an economic law than one based on physics, there are limitations to Moore's Law. Computer chips can only get so small before reaching the atomic barrier. While Moore's Law has guided most of the technology industry for over 50 years, it perhaps will not hold true. Nonetheless, it proved to be a driving force in the world of computing. diff --git a/content/general/concepts/historical-technical-figures/terms/grace-hopper/grace-hopper.md b/content/general/concepts/historical-technical-figures/terms/grace-hopper/grace-hopper.md deleted file mode 100644 index d82a9cff608..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/grace-hopper/grace-hopper.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -Title: 'Grace Hopper' -Description: 'Grace Hopper was an American computer scientist who led a decorated career in the United States Navy, becoming one of the first female rear admirals in U.S. history.' -Subjects: - - 'Computer Science' - - 'Developer Tools' -Tags: - - 'Errors' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -![Grace Hopper](https://raw.githubusercontent.com/Codecademy/docs/main/media/grace_hopper.png) - -**Grace Hopper** (1906 - 1992) was an American computer scientist who led a decorated career in the United States Navy, becoming one of the first female rear admirals in U.S. history. - -## Military Service - -Grace Hopper began her career in service in the United States Navy Reserve and was assigned to work on the Bureau of Ships Computation Project at Harvard in 1944. There she served on the computer programming staff that developed the Automatic Sequence Controlled Calculator (ASCC) also known as Mark I used in the war effort during the last part of World War II. - -## Contributions - -While the actual phrase wasn't coined by her, Grace Hopper and her team notably discovered an actual bug, a moth, stuck inside the computer and impacting its performance. They later documented this to be the "[f]irst actual case of a bug being found": - -![Bug found by Grace Hopper and her team.](https://raw.githubusercontent.com/Codecademy/docs/main/media/grace_hopper_bug.png) - -Hopper went on to contribute to the development of the UNIVAC I (Universal Automatic Computer I), the first computer designed for general business application in the U.S. at Eckert-Mauchly Computer Corporation. - -Hopper is also recognized as the originator of the theory of machine-independent programming languages with her first paper on compilers, in 1952. With the notion that code should be able to be written in English, Hopper as the director of automatic programming and her team, developed FLOW-MATIC & MATH-MATIC. - -Hopper then served as the technical consultant to the Conference on Data Systems Languages (CODASYL) committee that developed Common Business-Oriented Language (COBOL) in 1959. - -The Grace Hopper Celebration of Women in Computing Conference was designed in honor of Hopper's legacy in the field of computer science to facilitate more opportunities for women in the field. - -**Fun fact:** The cafeteria room was named after Grace Hopper in Codecademy's old office. diff --git a/content/general/concepts/historical-technical-figures/terms/john-carmack/john-carmack.md b/content/general/concepts/historical-technical-figures/terms/john-carmack/john-carmack.md deleted file mode 100644 index c1b8173de43..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/john-carmack/john-carmack.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -Title: 'John Carmack' -Description: 'John Carmack is an American video game developer, and the lead programmer of Commander Keen, Wolfenstein 3D, Doom, and Quake.' -Subjects: - - 'Game Development' - - 'Computer Science' -Tags: - - 'Graphics' - - 'VR' - - 'Algorithms' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -![John Carmack, image: Wikimedia Commons](https://raw.githubusercontent.com/Codecademy/docs/main/media/john_carmack.png) - -Image by Wikimedia Commons - -**John Carmack** (1970 - ) is an American video game developer, and the lead programmer of Commander Keen, Wolfenstein 3D, Doom, and Quake. - -In 1990, John Carmack and a small team developed the first Commander Keen game, a now classic side-scrolling video game. - -After the success of Commander Keen, Carmack co-founded [id Software](https://www.idsoftware.com), with the other developers: John Romero, Tom Hall, and Adrian Carmack. Their first release would be a genre-founding Wolfenstein 3D, which introduced several advancements in graphical fidelity and the first-person shooter (FPS) genre. - -This genre was further explored by Carmack and his team in the Doom and Quake series, some of the most successful franchises in the video game industry's history. - -To develop some of the techniques present in these titles, Carmack has developed several algorithms including the Carmack's Reverse algorithm, which was used in Doom 3 to add shadows to a rendered scene. - -Following his work with id Software, in 2013 John Carmack continued his game development career with Oculus VR as Chief Technical Officer. diff --git a/content/general/concepts/historical-technical-figures/terms/ken-thompson/ken-thompson.md b/content/general/concepts/historical-technical-figures/terms/ken-thompson/ken-thompson.md deleted file mode 100644 index 4ab50ad2866..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/ken-thompson/ken-thompson.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -Title: 'Ken Thompson' -Description: 'Ken Thompson is an American computer scientist, known for creating many significant works in the field, such as the Unix and Plan 9 operating systems, the B (1969) and Go (2019) programming languages, the grep command line utility, and UTF-8 encoding.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Unix' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -![Ken Thompson, image: Wikimedia Commons](https://raw.githubusercontent.com/Codecademy/docs/main/media/ken_thompson.png) - -Image by Wikimedia Commons - -**Ken Thompson** (1943 - ) is an American computer scientist, known for creating many significant works in the field, such as the [Unix](https://www.codecademy.com/resources/docs/general/unix) and Plan 9 operating systems, the B (1969) and [Go](https://www.codecademy.com/resources/docs/go) (2019) programming languages, the `grep` command line utility, and UTF-8 encoding. - -Ken Thompson is best known for working alongside [Dennis Ritchie](https://www.codecademy.com/resources/docs/general/historical-technical-figures/dennis-ritchie) and others at Bell Laboratories, where they began working on Unix in 1967 as a replacement operating system for the Digital Equipment Corporation's PDP-7 mini computer. - -During this time, Ken Thompson developed the B programming language, which would become the precursor for the incredibly popular and influential [C](https://www.codecademy.com/resources/docs/c) programming language. diff --git a/content/general/concepts/historical-technical-figures/terms/linus-torvalds/linus-torvalds.md b/content/general/concepts/historical-technical-figures/terms/linus-torvalds/linus-torvalds.md deleted file mode 100644 index ec713e7dc4e..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/linus-torvalds/linus-torvalds.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -Title: 'Linus Torvalds' -Description: 'Linus Torvalds is a Finnish-American computer scientist, the creator of the operating system kernel Linux, and the distributed revision control system, Git.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Linux' - - 'Git' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -![Linus Torvalds, image: Wikimedia Commons](https://raw.githubusercontent.com/Codecademy/docs/main/media/linus_torvalds.png) - -Image by Wikimedia Commons - -**Linus Torvalds** (1969 - ) is a Finnish-American computer scientist, the creator of the operating system kernel [Linux](https://www.codecademy.com/resources/docs/open-source/linux), and the distributed revision control system, [Git](https://www.codecademy.com/resources/docs/git). - -The [Linux kernel](https://www.codecademy.com/resources/docs/open-source/linux-kernel) is an [open-source](https://www.codecademy.com/resources/docs/open-source), [Unix](https://www.codecademy.com/resources/docs/general/unix)-inspired operating system kernel publicly released in Version 1.0 by Linus Torvalds in 1994. Today, the Linux operating system manages the hardware and resources of a large number of applications such as Android, Chrome OS, and many others. - -Git was later created by Torvalds in 2005 out of a need for a replacement free distributed system for the continued development of the Linux kernel. To support the needs of the Linux kernel team, Torvalds needed a free distribution system that would patch in no more than three seconds, and protect users against accidental or malicious corruption. diff --git a/content/general/concepts/historical-technical-figures/terms/tim-berners-lee/tim-berners-lee.md b/content/general/concepts/historical-technical-figures/terms/tim-berners-lee/tim-berners-lee.md deleted file mode 100644 index f616497e006..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/tim-berners-lee/tim-berners-lee.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -Title: 'Tim Berners-Lee' -Description: 'Sir Tim Berners-Lee is an English computer scientist popularly known for his development of the World Wide Web in 1989.' -Subjects: - - 'Web Development' - - 'Computer Science' -Tags: - - 'World Wide Web' - - 'HTTP' - - 'HTML' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -![Tim Berners-Lee](https://raw.githubusercontent.com/Codecademy/docs/main/media/tim_berners_lee.png) - -**Sir Tim Berners-Lee** is an English computer scientist popularly known for his development of the World Wide Web in 1989. - -While working at the European Organization for Nuclear Research (CERN) in the European Particle Physics Laboratory, Berners-Lee saw the need for a system that would share information amongst researchers globally. With this motivation, Tim Berners-Lee facilitated the first transmission between an HTTP client and server. Berners-Lee then developed the first web browser in 1990. With these milestones met, Berners-Lee developed the first-ever website, [info.cern.ch](info.cern.ch). - -In 1993, Berners-Lee wrote the very first version of [HTML](https://www.codecademy.com/resources/docs/html) (HyperText Markup Language), the standard markup language for web pages. - -Tim Berners-Lee has since been a prominent figure in the further development of the World Wide Web, standing as the director of the World Wide Web Consortium (W3C), and co-founder and CTO of Inrupt. Tim's goal as he states is to continue working toward net neutrality, privacy protection, and the inclusion of the Web. - -**Fun fact:** A conference room was named after Tim Berners-Lee in Codecademy's old office. diff --git a/content/general/concepts/historical-technical-figures/terms/yukihiro-matsumoto/yukihiro-matsumoto.md b/content/general/concepts/historical-technical-figures/terms/yukihiro-matsumoto/yukihiro-matsumoto.md deleted file mode 100644 index 24c7be1488f..00000000000 --- a/content/general/concepts/historical-technical-figures/terms/yukihiro-matsumoto/yukihiro-matsumoto.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -Title: 'Yukihiro Matsumoto' -Description: 'Yukihiro Matsumoto is a Japanese software programmer and computer scientist widely known as the chief designer of the Ruby programming language.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Ruby' - - 'Ruby' - - 'Open Source' -CatalogContent: - - 'learn-ruby' - - 'paths/code-foundations' ---- - -![Yukihiro Matsumoto (Matz)](https://raw.githubusercontent.com/Codecademy/docs/main/media/Yukihiro_Matsumoto.png) - -**Yukihiro "Matz" Matsumoto** (1965-present) is a software programmer and computer scientist widely known for his work as the chief designer of the [Ruby](https://www.codecademy.com/resources/docs/ruby) programming language. Blending parts of his favorite languages (Perl, Smalltalk, Eiffel, Ada, and Lisp), Matz formed Ruby into "a language of careful balance." As one of Japan's [open source](https://www.codecademy.com/resources/docs/open-source) evangelists, he has released products like [mruby](https://github.com/mruby/mruby) (a lightweight version of Ruby). - -Matz's demeanor has inspired the Ruby community motto "Matz is nice and so we are nice," commonly abbreviated as MINASWAN. - -## Recent Activity - -As of 2011, Matz is the Chief Architect of Ruby at [Heroku](https://www.heroku.com/), an online cloud platform-as-a-service. Starting in June 2014, he was appointed to the role of Technical Advisor for VASILY Inc. - -## Writing - -In 2001, Matz published a book called "Ruby in a Nutshell." This was later expanded and revised into a new book called "The Ruby Programming Language," released in 2008 and co-authored by David Flanagan. diff --git a/content/general/concepts/http/http.md b/content/general/concepts/http/http.md deleted file mode 100644 index febb4ebda77..00000000000 --- a/content/general/concepts/http/http.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -Title: 'HTTP' -Description: 'HTTP is used for fetching HTML documents and other web-based resources.' -Subjects: - - 'Code Foundations' - - 'Web Development' -Tags: - - 'Browsers' - - 'Development' - - 'Errors' - - 'HTTP' -CatalogContent: - - 'learn-intermediate-javascript' - - 'paths/front-end-engineer-career-path' ---- - -**Hypertext Transfer Protocol (HTTP)** is used for fetching [HTML](https://www.codecademy.com/resources/docs/html) documents and other web-based resources. It follows a model where a client (most commonly a browser) requests content stored on a server. - -## HTTPS - -Instead of HTTP, a more secure version, HTTPS, should be used in order to encrypt information sent between the client and server. This encryption is done with Transport Layer Security (or TLS, formerly [SSL](https://www.codecademy.com/resources/docs/general/ssl)). Some benefits of HTTPS include: - -- Financial data, like credit card information or bank account numbers, are protected from interception. -- Domain-ownership can be better verified by users. -- A growing standard of trust around sites that use HTTPS. - -Websites can be [certified](https://https.cio.gov/certificates/#does-the-us-government-operate-a-publicly-trusted-certificate-authority) with HTTPS so that browsers "know" the official site for a person, business, etc. These certifications are approved and signed by a trusted certificate authority (CA). - -## Requests - -HTTP requests are stateless, meaning that all requests are independent and have no knowledge of one another. Requests contain the following parts: - -- The HTTP method being used (more information shortly). -- The requested URL along with any queries or parameters. -- The HTTP version, such as 1.1 or 2.0. -- Any header information such as: - - The referrer that tells the URL where the request came from. - - Any user agent information about the requesting client. - - A unique host name that is ideal for many pages on one server. - - Cookie data about the request. -- A response-like body that contains the resource to be sent (common with the POST method). - -An HTTP client requests information specific URLs using four primary methods: - -| Method | Description | -| ------ | ----------------------------------------------------------- | -| GET | Requests data, content, or other resources from the server. | -| POST | Sends data, content, or other resources to the server. | -| PUT | Sends updates for existing content on the server. | -| DELETE | Deletes specific content from the server. | - -## Responses - -If the server is able to connect with the client and fulfill its request, it will send back a response that includes the following parts: - -- The version of HTTP being used. -- Headers similar to the ones used for HTTP requests. -- A body that contains the successfully requested resource. -- A status code with a message explaining why the request succeeded or failed. - -A breakdown of response status codes is shown below. - -### Informational - -| Status Code | Name | Description | -| ----------- | ---------- | ---------------------------------------------------------------- | -| 100 | Continue | The request should continue or be ignored if finished. | -| 102 | Processing | The server is currently processing the request; no response yet. | - -### Successful - -| Status Code | Name | Description | -| ----------- | -------- | ----------------------------------------------------- | -| 200 | OK | The request is successful and a response was sent. | -| 202 | Accepted | Processing not yet finished but request was accepted. | - -### Redirection - -| Status Code | Name | Description | -| ----------- | ----------------- | ---------------------------------------------------------------------- | -| 301 | Moved Permanently | The resource URL was changed and the new one was sent in the response. | -| 304 | Not Modified | Used by caches for serving the same, unmodified content. | - -### Client Errors - -| Status Code | Name | Description | -| ----------- | --------------- | ----------------------------------------------------------------------- | -| 400 | Bad Request | Invalid request based on client-side error (invalid syntax, URL, etc.). | -| 401 | Unauthorized | Invalid client credentials, such as an API key. | -| 404 | Not Found | Server couldn't find resource (e.g. invalid URL). | -| 408 | Request Timeout | The request is taking too long to finish. | - -### Server Errors - -| Status Code | Name | Description | -| ----------- | --------------------- | ------------------------------------------------ | -| 500 | Internal Server Error | Error occurred on the server-side. | -| 502 | Bad Gateway | Invalid response from a gateway or proxy server. | - -## Caches and Proxies - -HTTP can be used for improving web performance with [caches](https://www.codecademy.com/resources/docs/general/cache) and [proxy servers](https://www.codecademy.com/resources/docs/general/proxy-server). - -Client browsers can use caches for serving content instead of making repeated requests for the same content. Examples of caches include: - -- [CDNs](https://www.codecademy.com/resources/docs/general/cdn) that retain copies of web content and serve from close network connections. -- Proxy browser caches, like ones used in [progressive web apps](https://www.codecademy.com/resources/docs/general/progressive-web-application) that allow a single user to cache and access content offline. -- Shared proxy caches that store resources for multiple users (internet service provider, company staff network, etc.). - -Proxies are used to mask a client's IP address by assigning one to a proxy server and have requests sent from there. diff --git a/content/general/concepts/information-technology/information-technology.md b/content/general/concepts/information-technology/information-technology.md deleted file mode 100644 index 5314f2312be..00000000000 --- a/content/general/concepts/information-technology/information-technology.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -Title: 'Information Technology' -Description: 'Information Technology is the use of digital tools and technologies to store, process, obtain, transmit, and manage useful information.' -Subjects: - - 'Information Technology' - - 'Networking' -Tags: - - 'Information Technology' -CatalogContent: - - 'introduction-to-information-technology' - - 'paths/fundamentals-of-cybersecurity' ---- - -**Information Technology**, also known as IT, is the use of digital tools and technologies to store, process, obtain, transmit, and manage useful information. IT encompasses a spectrum of tasks, including designing, implementing, and maintaining systems, networks, databases, and applications. Due to living in a technology-driven world, IT plays a major role in people's lives whether it's fixing a cracked screen on a phone, doing a data transfer from an old computer to another one, or repairing a PC's hardware. - -## Roles - -These are some common roles in the IT industry: - -- Hardware Technicians: Installs, repairs, and maintains [computer hardware](https://www.codecademy.com/resources/docs/general/computer-hardware). May also be required to troubleshoot hardware and software issues, as well as provide training and support to users on how to use the devices effectively. -- Network Engineers: Designs, plans, and implements network infrastructures ranging from local area networks (LANs), wide area networks (WANs), and intranets for businesses and organizations. Ensures the security and scalability of the networks. Analyzes the network traffic and discusses suggestions on optimizing it to fulfill the organization/business' needs. -- Desktop Support Personnel: Typically provides tech support (e.g. restoring and backing up data to mobile devices) to customers via computer or phone. Handles a range of technical issues, including hardware and software problems. - -## Certifications - -Some IT roles require applicants to become certified. Common types of certifications include: - -- [CompTIA A+](https://www.comptia.org/certifications/a): Deemed to be the most popular IT certification, the curriculum focuses on topics such as networking, troubleshooting, working with operating systems, implementing strategies to lessen security vulnerabilities. To obtain this certificate, candidates are required to pass two exams. -- [Cisco Certified Network Associate(CCNA)](https://www.cisco.com/c/en/us/training-events/training-certifications/certifications/associate/ccna.html#~about-ccna): This certification focuses on topics such as networking fundamentals, IP services, security fundamentals, automation and programmability. While it has no formal prerequisites, candidates are recommended to have one or more years of experience in implementing and administering Cisco solutions. -- [CompTIA Security+](https://www.comptia.org/certifications/security): Described as the most recommended certificate to start a career in cybersecurity, this curriculum focuses on topics such as cybersecurity terms, dealing with cyber threats, how to manage data safely, etc. Even though no formal requirements to take the Security+ exam, candidates are recommended to have two years of experience in IT administration with a security focus. Candidates are also required to pass one exam in order to obtain certification. -- [Microsoft Certified: Azure Fundamentals](https://learn.microsoft.com/en-us/credentials/certifications/azure-fundamentals/): Teaches the basics of cloud computing concepts, models, and services such as private, public, and hybrid cloud, as well as [infrastructure as a service (IaaS)](https://www.codecademy.com/resources/docs/cloud-computing/iaas), [platform as a service (PaaS)](https://www.codecademy.com/resources/docs/cloud-computing/paas), and [software as a service (SaaS)](https://www.codecademy.com/resources/docs/cloud-computing/saas). It’s recommended for candidates to have skills and experience working with an area of IT, such as infrastructure management, database management, or software development. diff --git a/content/general/concepts/iot/iot.md b/content/general/concepts/iot/iot.md deleted file mode 100644 index bc8a2a44364..00000000000 --- a/content/general/concepts/iot/iot.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -Title: 'IoT' -Description: 'Internet of Things (IoT) is a term used to describe hardware which can be connected to the internet in order to provide a service.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Internet of Things (IoT)** is a term used to describe hardware which can be connected to the internet in order to provide a service. - -IoT devices primarily work through the use of sensors associated with devices that communicate data to a server. These devices communicate over a network to determine and provide information on the devices current state. Due to the extensive number of sensors and chips necessary for IOT devices there is a need for efficient and ecologically sustainable practices when it comes production of IoT appliances. - -## History - -The very first IoT devices were vending machines connected to ARPANET in 1982. These connected devices reported inventory and temperature of individual drinks. Today IoT has expanded to a myriad of use cases and promises to be a lucrative sector as more and more devices become connected. - -Experts predict that in the year 2033 there will be more devices connected to the internet than human beings, but due to the limits of IPV4 (number of unique IP addresses) the adoption of IPV6 will be needed to support connectivity for the increasing number of IoT devices. - -Two of the major challenges associated with IoT are security and privacy. While there are various competing standards for securing IoT devices, these standards have yet to become adopted across the board and therefore the spectrum of security of devices range with some devices being more secure than others. As a result application security varies from provider to provider depending on their respective security and privacy practices. diff --git a/content/general/concepts/jit-compilation/jit-compilation.md b/content/general/concepts/jit-compilation/jit-compilation.md deleted file mode 100644 index 0c2efbcb26e..00000000000 --- a/content/general/concepts/jit-compilation/jit-compilation.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -Title: 'JIT Compilation' -Description: 'Just-In-Time (JIT) compilation is a system for compiling languages as they are executed, rather than compiling prior to execution.' -Subjects: - - 'Developer Tools' -Tags: - - 'Developer Tools' - - 'Compilation' -CatalogContent: - - 'learn-java' - - 'introduction-to-javascript' - - 'paths/computer-science' ---- - -**Just-In-Time (JIT) compilation** is a system for compiling languages as they are executed, rather than compiling prior to execution. In JIT compilation, the compiling happens during [runtime](https://www.codecademy.com/resources/docs/general/runtime). - -JIT compilation can be thought of as a combination of compiled and interpreted languages. Traditionally, compiled languages are languages where the computer translates the code that comprises a program prior to execution. Interpreted languages are not translated by the computer. Instead, they use an interpreter to read and execute the code directly. [C](https://www.codecademy.com/resources/docs/c) is an example of a traditionally compiled language, and [Python](https://www.codecademy.com/resources/docs/python) is an example of an interpreted language. JIT compilation is a mixture of these two methods; source code is directly compiled into [machine code](https://www.codecademy.com/resources/docs/general/machine-code) at runtime. - -## Use Cases for JIT compilation - -Some major implementations of JIT compilation include the Java Virtual Machine (JVM) and the Common Language Runtime (CLR). JVM is used for [Java](https://www.codecademy.com/resources/docs/java) and Kotlin, and CLR is used for C#. These languages incorporate a traditional compiler, such as a [Java compiler](https://www.codecademy.com/resources/docs/java/compiler), to compile to an intermediate language prior to using JIT compilation. [JavaScript](https://www.codecademy.com/resources/docs/javascript) also uses JIT compilation, but the specific implementation depends on the browser. Low-level languages, such as [C](https://www.codecademy.com/resources/docs/c) or [C++](https://www.codecademy.com/resources/docs/cpp), do not use JIT compilation, because low-level languages do not use a runtime. - -## Benefits of JIT compilation - -There are multiple benefits of JIT compilation, such as: - -### Improved Performance for Interpreted Languages - -Compiled languages are more performant than interpreted languages. JIT compilation allows interpreted languages to have the increased performance benefits of compilation, without the overhead that comes with traditional compiling. - -### Increased Efficiency for Compiled Languages - -With traditionally compiled languages, programmers must wait for their code to compile prior to starting the execution of a program. JIT compilation does not include this wait time since it compiles the code during the execution phase. Removing this extra step increases efficiency for programmers and the development process. - -### Decreased Execution Time - -JIT compilation can improve optimizations done by the compiler because it has more information than what would be available in a traditional compiling process. This allows JIT compilation to make more performant choices as it compiles, which allows it to run more efficiently in certain cases. - -### Greater Portability - -In a traditional compiling process, the programmer is responsible for managing the multiple potential machines the code might run on. For example, if a programmer wanted to execute code to macOS, Android, and Xbox, they would need to compile three times. JIT compilation is more portable than traditional compiling, and instead, the runtime on each system is responsible for managing these relationships rather than the programmer. diff --git a/content/general/concepts/json/json.md b/content/general/concepts/json/json.md deleted file mode 100644 index f05f1e055da..00000000000 --- a/content/general/concepts/json/json.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -Title: 'JSON' -Description: 'JSON is a data format that is readable, writable, and parsable for both humans and machines.' -Subjects: - - 'Web Development' - - 'Computer Science' -Tags: - - 'JSON' - - 'Objects' - - 'Properties' - - 'Values' -CatalogContent: - - 'introduction-to-javascript' - - 'paths/full-stack-engineer-career-path' ---- - - - -**JavaScript Object Notation (JSON)** is a language-independent data format that is readable, writable, and parsable for both humans and machines. JSON is based on the syntax of the third edition of a [JavaScript](https://www.codecademy.com/resources/docs/javascript) standard known as ([ECMAScript](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/)). Many programming languages, such as [Python](https://www.codecademy.com/resources/docs/python), have implemented [libraries](https://www.codecademy.com/resources/docs/python/json-module) to parse and generate JSON-formatted data. JavaScript can parse JSON directly with the [`JSON` object](https://www.codecademy.com/resources/docs/javascript/json). - -In addition to JavaScript, JSON uses some conventions from the [C](https://www.codecademy.com/resources/docs/c)-descendant languages, including C , [C++](https://www.codecademy.com/resources/docs/cpp), and [Java](https://www.codecademy.com/resources/docs/java). - -JSON is commonly used for transferring data between clients and [servers](https://www.codecademy.com/resources/docs/general/server) for tasks such as web browsing or form submission. Some companies also use JSON to allow their data to be accessed in other applications via [API](https://www.codecademy.com/resources/docs/general/api). Some examples include: - -- [Google Maps](https://developers.google.com/maps/documentation/geocoding/start) -- [Google Auth 2.0 Authentication](https://developers.google.com/identity/protocols/oauth2/service-account) -- [Meta (formerly Facebook) Send API](https://developers.facebook.com/docs/messenger-platform/reference/send-api) -- [Spotify Music Web API](https://developer.spotify.com/documentation/web-api/) -- [LinkedIn Profile API](https://docs.microsoft.com/en-us/linkedin/shared/integrations/people/profile-api) - -More can be learned about JSON by visiting [json.org](https://www.json.org/). - -## Syntax - -```pseudo -{ - "propertyOne": "valueOne", - "propertyTwo": "valueTwo", - "propertyThree": "valueThree" -} -``` - -Data is stored in an object, depicted by a pair of curly braces `{ }`, and name-value pairs are separated by a colon `:`. The pairs themselves are separated by a comma `,`. The following are [data types](https://www.codecademy.com/resources/docs/general/data-types) that can be used: - -- [Array](https://www.codecademy.com/resources/docs/general/data-structures/array): An ordered, comma delimited, list of zero or more elements of one of JSON's data types, enclosed in square brackets. -- [Boolean](https://www.codecademy.com/resources/docs/general/data-types/boolean): Either `true` or `false`. -- [Number](https://www.codecademy.com/resources/docs/general/data-types/number): A signed decimal number. JSON makes no distinction between integer and floating point. -- [Object](https://www.codecademy.com/resources/docs/general/data-structures/object): A collection of name-value pairs inside curly brackets. -- [String](https://www.codecademy.com/resources/docs/general/data-types/string): A sequence of zero or more Unicode characters enclosed in double quotes. -- `null`: An empty value represented by the word `null`. - -[Whitespace](https://www.codecademy.com/resources/docs/general/whitespace) (e.g., spaces, tabs, line feeds, and carriage returns) is ignored between names, values, and punctuation. The following four characters are all considered whitespace: space, tab, line feed, and carriage return. - -JSON objects cannot contain [comments](https://www.codecademy.com/resources/docs/general/comment). - -Multiple JSON objects can be collected in an array-like sequence: - -```pseudo -[ - { - "propertyOne": "valueOne", - "propertyTwo": "valueTwo", - "propertyThree": "valueThree" - }, - { - "propertyA": "valueA", - "propertyB": "valueB", - "propertyC": "valueC" - } -] -``` - -A few important points to note about JSON syntax: - -- While it is derived from the JavaScript language, JSON itself is not JavaScript. -- Trailing commas are forbidden. -- Although JavaScript names are not this strict, JSON property names must be in double quotes. - -## Bad Practices - -Below are two points regarding what should be avoided when using JSON format: - -- It is not useful to abide by an [XML](https://www.codecademy.com/resources/docs/general/xml)-like, "attribute vs. element" framework. JSON is only about name-value pairs. -- While the nesting of inner-JSON objects is possible, going more than two levels deep could get complicated. - -## Example - -The following JSON example uses one level of nested objects, an array, and each valid data type: - -```pseudo -{ - "make" : "Chevy", - "model" : "Silverado", - "miles" : 27500.5, - "year" : 2020, - "owner" : { - "firstName" : "John", - "lastName" : "Doe" - }, - "features" : ["4WD", "Towing Package", "Lift Kit"], - "lease" : false, - "customizations": null -} -``` diff --git a/content/general/concepts/jsp/jsp.md b/content/general/concepts/jsp/jsp.md deleted file mode 100644 index 441295e4b2a..00000000000 --- a/content/general/concepts/jsp/jsp.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -Title: 'JSP' -Description: 'JSP (Jakarta Server Pages, formerly JavaServer Pages) is a technology that allows a web developer to mix textual content with Java code that is executed on the web server to render the final web page.' -Subjects: - - 'Web Development' - - 'Web Design' -Tags: - - 'Dynamic Programming' - - 'Servers' - - 'Server-Side Rendering' -CatalogContent: - - 'learn-java' - - 'paths/back-end-engineer-career-path' ---- - -**JSP** (Jakarta Server Pages, formerly JavaServer Pages) is a technology that allows a web developer to mix textual content with [Java](https://www.codecademy.com/resources/docs/java) code that is executed on the web [server](https://www.codecademy.com/resources/docs/general/server) to [render](https://www.codecademy.com/resources/docs/general/server-side-rendering) the final web page. In this way it is similar to [PHP](https://www.codecademy.com/resources/docs/php) except that it uses the Java programming language. With JSP the developer can create dynamic pages based on [HTML](https://www.codecademy.com/resources/docs/html), [XML](https://www.codecademy.com/resources/docs/general/xml), SOAP, or other document types. - -JSP was released in 1999 by Sun Microsystems, and version 3.1 was released on April 31, 2022. - -## Advantages & Disadvantages - -JSP has the following advantages compared to other methods of creating dynamic web pages: - -- The execution of JSP pages is faster than other technologies. -- JSP pages are compiled before being processed by the server, reducing the load on the server. -- JSP has access to all the Java APIs. -- Since JSP uses the Java Virtual Machine, it is portable and platform-agnostic. - -These are some disadvantages of JSP: - -- Debugging and tracing errors can be difficult. -- It uses roughly twice the disk storage as other dynamic web pages. -- A JSP file must be compiled on the server when first accessed, which can cause a noticeable delay on the first visit to a page. diff --git a/content/general/concepts/julia/julia.md b/content/general/concepts/julia/julia.md deleted file mode 100644 index 79b0f3ef2f3..00000000000 --- a/content/general/concepts/julia/julia.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -Title: 'Julia' -Description: 'Julia distinguishes itself as an advanced programming language designed for technical computing, featuring high-level functionality and top-notch performance.' -Subjects: - - 'Computer Science' -Tags: - - 'Programming' - - 'Dynamic Programming' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -Julia is an advanced programming language tailored for technical computing, offering high-level functionality and top-notch performance. Its creation aimed to bridge the gap between the user-friendliness of dynamic languages like Python and the speed found in statically-typed languages such as C or Fortran. diff --git a/content/general/concepts/julia/terms/variables/variables.md b/content/general/concepts/julia/terms/variables/variables.md deleted file mode 100644 index a5139b611bc..00000000000 --- a/content/general/concepts/julia/terms/variables/variables.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -Title: 'Variables' -Description: 'Stores data that can be manipulated and referenced throughout the code.' -Subjects: - - 'Computer Science' - - 'Data Visualization' -Tags: - - 'Programming' - - 'Dynamic Programming' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -In Julia, **variables** are used to store data. They can hold various data types and are mutable by default, allowing their values to be changed after assignment. - -## Syntax - -```pseudo -variable_name = value -``` - -- `variable_name`: This is the chosen name for the variable, following Julia's naming rules and conventions. -- `value`: Represents the data or value assigned to the variable, which can be of various types supported by Julia. - -## Example - -```julia -integer_variable = 10 -float_variable = 3.14 -string_variable = "Julia" -boolean_variable = true - -println("Integer variable: ", integer_variable) -println("Float variable: ", float_variable) -println("String variable: ", string_variable) -println("Boolean variable: ", boolean_variable) -``` - -The output for the above code is as follows: - -```shell -Integer variable: 10 -Float variable: 3.14 -String variable: Julia -Boolean variable: true -``` - -## Variable Nomenclature - -When declaring a variable in Julia, the variable name goes first, optionally followed by a type annotation and then the value. - -If a variable does not need a value to be assigned immediately, it can be declared without a type and a value can be assigned later: - -```pseudo -name = value # Without type annotation -name::Type = value # With type annotation -``` - -> **Note:** Variables in Julia are dynamic and can hold values of different types, but you can optionally declare the type for performance optimization and type-checking. diff --git a/content/general/concepts/linux/linux.md b/content/general/concepts/linux/linux.md deleted file mode 100644 index b91314ecbf5..00000000000 --- a/content/general/concepts/linux/linux.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -Title: 'Linux' -Description: 'Free and open-source operating system kernel that forms the foundation of numerous operating systems (distributions).' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Developer Tools' - - 'Linux' - - 'Operating Systems' - - 'Unix' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -**Linux** was created by Linus Torvalds in 1991 as an alternative to proprietary Unix systems. It has since grown into a powerful, secure, and highly customizable operating system that powers everything from personal computers to servers, smartphones (Android), and supercomputers. The Linux ecosystem is supported by a vast community of developers and users who contribute to its continuous development and improvement. - -## Working - -Linux operates on a kernel-based architecture, where the kernel manages hardware resources and provides essential services to higher-level software. It supports a multi-user, multi-tasking environment, allowing processes to run concurrently while securely sharing system resources among users. The system follows a hierarchical file structure, starting from the root directory (`/`), where all devices and resources are represented as files. - -## Architecture of Linux - -![Linux Architecture](https://raw.githubusercontent.com/Codecademy/docs/main/media/general-linux.png) - -- Hardware Layer (Core) - - - Contains physical components like CPU, memory, and storage devices - - Forms the base layer, interfacing directly with hardware - -- Kernel Layer - - - Core of the Linux operating system - - Manages hardware resources, memory, and processes - - Provides essential services and hardware abstraction - - Handles system calls and device drivers - -- Shell Layer - - - A command-line interpreter that bridges the user and kernel - - Processes user commands and scripts - - Examples include Bash, Zsh, and Fish - -- Application Layer (Outermost) - - Includes user applications, GUI interfaces, and system utilities - - Supports third-party applications and system tools - -This layered architecture follows a hierarchical structure where each layer communicates with adjacent layers, with the kernel serving as the critical intermediary between hardware and software components. Each outer layer depends on the services provided by the inner layers, creating a robust and modular system design. - -## Linux Commands - -| Command | Description | Example Usage | -| --------- | ---------------------------------------- | ----------------------------- | -| `ls` | List files and directories | `ls -l` | -| `cd` | Changes the current directory | `cd /home/user` | -| `pwd` | Displays the current directory path | `pwd` | -| `mkdir` | Creates a new directory | `mkdir new_folder` | -| `rm` | Deletes files or directories | `rm file.txt` | -| `rmdir` | Removes empty directories | `rmdir empty_folder` | -| `cp` | Copies files or directories | `cp source.txt destination/` | -| `mv` | Moves or rename files and directories | `mv old.txt new.txt` | -| `cat` | Displays file contents | `cat file.txt` | -| `nano` | Edits a file using the nano editor | `nano file.txt` | -| `vim` | Edits a file using the Vim editor | `vim file.txt` | -| `touch` | Creates an empty file | `touch newfile.txt` | -| `chmod` | Modifies file permissions | `chmod 755 script.sh` | -| `chown` | Changes file ownership | `chown user:group file.txt` | -| `find` | Searches for files in a directory | `find /home -name "*.txt"` | -| `grep` | Searches for a pattern inside files | `grep "error" logfile.log` | -| `ps` | Displays running processes | `ps aux` | -| `kill` | Terminates a process by its ID | `kill 1234` | -| `top` | Shows system resource usage in real time | `top` | -| `df` | Shows disk space usage | `df -h` | -| `du` | Shows directory size | `du -sh folder/` | -| `tar` | Archives multiple files | `tar -cvf archive.tar files/` | -| `unzip` | Extracts files from a ZIP archive | `unzip archive.zip` | -| `wget` | Downloads a file from the internet | `wget https://example.com` | -| `curl` | Fetches data from a URL | `curl -O https://example.com` | -| `echo` | Prints text to the terminal | `echo "Hello, World!"` | -| `whoami` | Displays the current logged-in user | `whoami` | -| `uptime` | Shows system uptime | `uptime` | -| `history` | Displays command history | `history` | -| `clear` | Clears the terminal screen | `clear` | diff --git a/content/general/concepts/llm/llm.md b/content/general/concepts/llm/llm.md deleted file mode 100644 index dacc664291d..00000000000 --- a/content/general/concepts/llm/llm.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -Title: 'LLM' -Description: 'Large Language Models (LLMs) are advanced AI systems trained extensively on vast text datasets to understand and generate human-like text.' -Subjects: - - 'Machine Learning' - - 'Data Science' -Tags: - - 'Machine Learning' - - 'Deep Learning' - - 'NLP' -CatalogContent: - - 'learn-data-science' - - 'paths/data-science-foundations' ---- - -**Large Language Models (LLMs)** are sophisticated artificial intelligence systems designed to process, understand, and generate human-like text. These models are trained on massive datasets of text from various sources, enabling them to perform a wide range of language-related tasks with remarkable proficiency. - -## Key Characteristics - -LLMs are characterized by several important features: - -- **Massive Scale**: They typically contain billions of parameters, allowing them to capture complex patterns in language. -- **Self-Attention Mechanisms**: Many LLMs use transformer architectures, which allow them to consider context over long sequences of text. -- **Transfer Learning**: LLMs can be fine-tuned for specific tasks after initial pre-training on general language data. -- **Zero-Shot and Few-Shot Learning**: They can perform tasks with minimal or no specific training examples. - -## Common Applications - -LLMs have found applications in various domains, including: - -- **Text Generation**: Creating human-like text for various purposes, from creative writing to code generation. -- **Language Translation**: LLMs are used to translate text from one language to another with high accuracy rates. -- **Summarization**: Condensing long texts into concise summaries while retaining key information. -- **Question Answering**: Providing relevant answers to questions based on given context or general knowledge. -- **Sentiment Analysis**: Sentiment analysis is used to determine whether the user's attitude towards a particular topic, product, or service is positive, negative, or neutral. - -## Prominent Examples - -Some well-known LLMs include: - -- GPT (Generative Pre-trained Transformer) series by OpenAI -- BERT (Bidirectional Encoder Representations from Transformers) by Google -- T5 (Text-to-Text Transfer Transformer) by Google -- LaMDA (Language Model for Dialogue Applications) by Google -- Claude by Anthropic - -## Ethical Considerations - -The development and deployment of LLMs give rise to significant ethical concerns like: - -- **Bias**: LLMs have the potential to sustain or magnify biases embedded in their training data. -- **Privacy**: Concerns about the use of personal data in training and the potential for generating sensitive information. -- **Misinformation**: The ability of LLMs to generate convincing but potentially false information. -- **Environmental Impact**: The significant computational resources required for training and running large models. - -As LLMs continue to evolve, addressing these ethical concerns remains a crucial aspect of their development and deployment. diff --git a/content/general/concepts/machine-code/machine-code.md b/content/general/concepts/machine-code/machine-code.md deleted file mode 100644 index 5dd9900e613..00000000000 --- a/content/general/concepts/machine-code/machine-code.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -Title: 'Machine Code' -Description: 'Machine code (also known as machine language or native code) is a low level programming language in the form of hexadecimal or binary instructions that execute computer programs on the computers CPU.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Machine code** (also known as machine language or native code) is a low level programming language in the form of hexadecimal or binary instructions that execute computer programs on the computers' CPU. Machine code is the lowest level of code which means that it communicates the programs instructions in the form of software directly to the hardware of the computer via the Central Processing Unit (CPU). - -In the early days of programming, applications were written directly in machine code, but as that method of developing applications is tedious and inefficient, programmers developed new higher level programming languages like C, Java and Python to be processed by compilers and turned into machine code for execution in the CPU. - -Every computer processor has its own instruction set designed to process machine code. These instruction sets make up a sort of class for the interpretation of machine code. Due to the distributed market and competition, CPU creators lack a universal machine code standard to rule them all, which means special attention is required to ensure new processors are able to support (without bugs) pre-existing and current programs when they are ultimately converted into machine code. - -The ASCII value for the letter "A" in machine code is `01000001`, but this data is displayed as "A" on the screen. Everything visually represented in computers is based on output of machine code processed by the CPU. - -## What Machine Code looks like - -An easy way to visualize how machine code is stored is to look at some in a hex editor, which shows the binary data represented by hexadecimal numbers. - -For example, take the instruction: - -``` -0xEB 0xFE -``` - -This could also be written as `11101011 11111110` in binary. - -This instruction represents an infinite loop on a x86 CPU. It can be coded in assembly language like this: - -``` -j: -jmp j -``` diff --git a/content/general/concepts/machine-learning/machine-learning.md b/content/general/concepts/machine-learning/machine-learning.md deleted file mode 100644 index c6561c32bf2..00000000000 --- a/content/general/concepts/machine-learning/machine-learning.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -Title: 'Machine Learning' -Description: 'Machine learning is a branch of artificial intelligence that enables systems to learn from data and make predictions or decisions without explicit programming.' -Subjects: - - 'Computer Science' - - 'Machine Learning' - - 'Web Development' -Tags: - - 'Algorithms' - - 'Machine Learning' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Machine learning (ML)** is a branch of [Artificial Intelligence (AI)](https://www.codecademy.com/resources/docs/ai) that allows computers to analyze data, identify patterns, and make decisions without explicit programming. Instead of following hard-coded rules, ML algorithms identify patterns in data and improve their performance over time. This ability makes ML essential in applications such as recommendation systems, fraud detection, natural language processing, and self-driving cars. - -The growing availability of large datasets, computational power, and advanced algorithms has fueled the rapid evolution of ML. Businesses and researchers use ML to automate tasks, enhance decision-making, and drive innovation across industries. By leveraging different types of learning techniques, such as supervised, unsupervised, and reinforcement learning, ML models can solve complex problems and generate accurate predictions. - -## Types of Machine Learning - -Machine learning is broadly categorized into three types based on how models learn from data: - -1. **Supervised Learning**: In supervised learning, models learn from labeled datasets, where each input is paired with a known output. The algorithm maps inputs to outputs based on training examples. - - **Applications**: Spam detection, image classification, speech recognition. - - **Algorithms**: Linear regression, decision trees, support vector machines (SVMs), neural networks. -2. **Unsupervised Learning**: In unsupervised learning, models analyze unlabeled data and detect patterns without predefined categories. It is used for clustering, anomaly detection, and dimensionality reduction. - - **Applications**: Customer segmentation, anomaly detection, data compression. - - **Algorithms**: K-means clustering, hierarchical clustering, Principal Component Analysis (PCA) (for dimensionality reduction). -3. **Reinforcement Learning**: In reinforcement learning, an agent interacts with an environment and learns optimal actions by maximizing cumulative rewards. - - **Applications**: Robotics, game playing (e.g., AlphaGo), self-driving cars. - - **Algorithms**: Q-learning, Deep Q-Networks (DQN), Proximal Policy Optimization (PPO). - -## How Machine Learning works - -The machine learning pipeline consists of several key stages that transform raw data into a functional model: - -1. **Data Collection**: Gathering relevant data from various sources such as databases, APIs, or web scraping. The quality and quantity of data significantly impact model performance. -2. **Data Preprocessing**: Cleaning, transforming, and normalizing data to remove noise, handle missing values, and convert it into a format suitable for training. Techniques like feature scaling and encoding categorical variables are commonly used. -3. **Model Selection and Training**: Choosing an appropriate algorithm based on the problem type and dataset. The model is trained using historical data to learn patterns and make predictions. -4. **Model Evaluation**: Assessing model performance using metrics such as precision, accuracy, recall, and F1-score. Cross-validation and hyperparameter tuning help improve results. -5. **Deployment and Monitoring**: Deploying the trained model to a production environment where it makes real-world predictions. Continuous monitoring ensures the model remains accurate and adapts to new data. - -## Key Applications of Machine Learning - -Machine learning is transforming multiple industries with innovative applications: - -- **Healthcare**: ML models assist in disease diagnosis, personalized treatment recommendations, and medical imaging analysis. -- **Finance**: Fraud detection, risk assessment, and algorithmic trading rely on ML to process vast amounts of financial data. -- **E-commerce**: Recommendation engines use ML to suggest products based on user behavior and preferences. -- **Autonomous Vehicles**: Self-driving cars utilize ML for object detection, path planning, and navigation. -- **Natural Language Processing (NLP)**: Chatbots, sentiment analysis, and speech recognition systems leverage ML for language understanding. - -## Challenges and Ethical Considerations - -Despite its advantages, machine learning faces several challenges: - -- **Bias and Fairness**: Training data biases can lead to unfair predictions and discriminatory outcomes. Ensuring diverse datasets is crucial. -- **Data Privacy**: Handling sensitive user data responsibly and ensuring compliance with regulations like GDPR is essential. -- **Model Interpretability**: Many ML models, especially deep learning models, act as "black boxes," making it difficult to understand their decision-making process. diff --git a/content/general/concepts/memoization/memoization.md b/content/general/concepts/memoization/memoization.md deleted file mode 100644 index 01a4f980663..00000000000 --- a/content/general/concepts/memoization/memoization.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -Title: 'Memoization' -Description: 'Memoization is a technique that improves the speed of a program by storing any new inputs for future reference, if needed.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Algorithms' - - 'Conceptual' - - 'Dynamic Programming' -CatalogContent: - - 'learn-how-to-code' - - 'paths/computer-science' ---- - -**Memoization** is a technique that improves the speed of a program by storing any new inputs for future reference, if needed. This cuts down on any repeated computations in the program where the same inputs are being used to return the same result. - -This technique gets its name from the Latin word, "memorandum", which means to be remembered. Memoization can be applied to many contexts in computer programming, including: - -- Making calls to recursive or pure functions where some calculations use the same inputs and return the same outputs. -- Fetching from the server with the same base API endpoints. - -Memoization can be implemented in most programming languages, including [JavaScript](https://www.codecademy.com/resources/docs/javascript/memoization) and [Python](https://www.codecademy.com/resources/docs/python/memoization). However, while memoization saves performance time, it comes with a cost in memory space since it is caching results that were already calculated. diff --git a/content/general/concepts/method/method.md b/content/general/concepts/method/method.md deleted file mode 100644 index 5bbdab5c7b2..00000000000 --- a/content/general/concepts/method/method.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -Title: 'Method' -Description: 'A method is a small piece of code, usually defined in a class, that can be used outside the class and in other parts of the program.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Classes' - - 'Objects' - - 'Methods' - - 'OOP' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -Classes can be broken into two core parts: - -- The data that is attributed to a class's members or properties. -- The behaviors that are defined or inherited in the class. - -**Methods** are the "behavior" part of the class. When an instance variable is created from a class, it has access to the class's associated methods. Methods can accept parameters (sometimes they're called "arguments") and can return a result. - -In object-oriented programming, methods promote reusability and keep functionality encapsulated inside an object. - -## Example - -In the Python example below, a class for a character in a game, `Character`, is defined with certain behaviors. The character can: - -- Introduce themselves via `.introduceSelf()`. -- Move left given an integer amount via `.moveLeft()`. -- Move right given an integer amount via `.moveRight()`. - -```py -class Character: - def __init__(self, name, movex): - self.name = "Player" # Character's name - self.movex = 0 # Character's starting position - - def introduceSelf(self): - # Print out an introduction phrase - print(f"Hello! I'm {self.name}.") - - def moveLeft(self, x): - # Move the character left by x pixels - self.movex -= x - - def moveRight(self, x): - # Move the character right by x pixels - self.movex += x -``` - -Now, when an instance of `Character` is created, the game character can introduce themselves, move left, or move right. - -## Methods in Different Languages - -- [Methods in C++](https://www.codecademy.com/resources/docs/cpp/methods) -- [Methods in Java](https://www.codecademy.com/resources/docs/java/methods) -- [Methods in JavaScript](https://www.codecademy.com/resources/docs/javascript/methods) -- [Methods in Python](https://www.codecademy.com/resources/docs/python) diff --git a/content/general/concepts/middleware/middleware.md b/content/general/concepts/middleware/middleware.md deleted file mode 100644 index 624644ea2af..00000000000 --- a/content/general/concepts/middleware/middleware.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -Title: 'Middleware' -Description: 'Middleware is software that connects data, APIs, software tools, and other applications in order to bring a complete application to the end user.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'APIs' - - 'Database' - - 'Middleware' -CatalogContent: - - 'learn-sql' - - 'paths/back-end-engineer-career-path' ---- - -**Middleware** is software that connects applications together. The term "middleware" comes from the fact that this software sits between the front-end, or client-side, of an application and the back-end, or server-side, where the resources are being requested. - -## Types of Middleware - -Data, APIs, software tools, and other applications are connected by middleware in order to bring a complete or bundled application to the end user. There are many types of middleware software depending on the use cases. Some of the most commonly used middleware are listed below. - -### Message Oriented Middleware - -A message oriented middleware, or MOM, allows applications to exchange messages and communicate with one another. This middleware offers ease of use but can be costly at larger scales. - -#### Examples - -
- RabbitMQ - RabbitMQ is a messaging broker platform used by applications to send and receive messages. -
- -
- IBM MQ - IBM MQ is another example of message oriented middleware. Some of the core components include messages, message queues, and queue manager. -
- -
- Amazon SNS - Amazon simple notification service is a way to manage messaging between applications and users. -
- -### Database Middleware - -This type of middleware gives access to databases and provides points of interaction between a variety of databases. This middleware improves efficiency however it can be language specific which can create limitations. - -#### Examples - -
- ODBC - Open Database Connectivity is an API used for accessing database management systems. -
- -
- JDBC - Java Database Connectivity is an API that uses Java to access databases. -
- -### API Middleware - -This type of middleware provides developers with the tools to create and manage APIs used in applications. While it offers scalability, connections can be slow when dealing with different servers. - -#### Examples - -
- API management platforms - API management platforms allow developers to access, control, and analyze APIs. -
- -
- API gateways - API gateways provide services related to user authentication and rate limiting. -
diff --git a/content/general/concepts/modulo/modulo.md b/content/general/concepts/modulo/modulo.md deleted file mode 100644 index 557a15f417e..00000000000 --- a/content/general/concepts/modulo/modulo.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -Title: 'Modulo' -Description: 'A modulo operation takes two arguments and returns the remainder of the first argument divided by the second.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Arithmetic' - - 'Numbers' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -**Modulo** is a mathematical operation that returns the remainder of a division of two arguments. It is available in every programming language. - -## Syntax - -The remainder is what is left over after dividing the first argument, the dividend, by the second, the divisor or modulus: - -```pseudo -remainder = dividend % divisor -``` - -Most programming languages use the `%` symbol to represent the modulo operation, though some may use `mod` or other variations. - -## Examples - -The following is an example of the modulo operator in [Python](https://www.codecademy.com/resources/docs/python): - -```codebyte/py -modulus = 14 % 5 -print(f"14 % 5 results in a modulus of {modulus}") - -modulus = 37 % 3 -print(f"37 % 3 Results in a modulus of {modulus}") - -modulus = 21 % 7 -print(f"21 % 7 results in a modulus of {modulus}") - -modulus = 15 % -4 -print(f"15 % -4 results in a modulus of {modulus}") -``` diff --git a/content/general/concepts/nft/nft.md b/content/general/concepts/nft/nft.md deleted file mode 100644 index b7ec6a28950..00000000000 --- a/content/general/concepts/nft/nft.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -Title: 'NFT' -Description: 'A non-fungible token (NFT) acts as a digital representation to prove ownership for a digital good backed by blockchain technology.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Blockchain' - - 'Web3' - - 'Cryptocurrency' -CatalogContent: - - 'introduction-to-blockchain' - - 'paths/computer-science' ---- - -A **non-fungible token (NFT)** acts as a digital representation to prove ownership for a digital good backed by blockchain technology. - -The term "token" in the phrase "non-fungible token" refers to this digital representation. "Non-fungible" simply means "non-replaceable". It can't be replaced, is one of a kind, and is always unique. - -For example, a single U.S. Dollar note of $1 is fungible because it is able to be replaced with another $1 note. However, each NFT is always unique and cannot be simply swapped for another different NFT, even if both are a representation of the same general good. This means that non-fungible items can be far more valuable than fungible items. - -## Minting an NFT - -Creating an NFT is known as “minting”. Minting an NFT is the process of taking a piece of content and putting it on a digital registry, or the blockchain. During this process, some critical information such as owner name, date, and time is placed on the blockchain. The most common blockchain for minting NFTs is [Ethereum](https://ethereum.org/en). A person can manage any NFTs that the person mints or owns through a crypto wallet. - -A crypto wallet is a digital wallet used to store cryptocurrencies and NFTs. They are the only place where NFTs can be minted or purchased. The ownership history of an NFT is easily traceable, verifiable, and can be seen by anyone using the blockchain. - -As of now, NFTs are most often used to prove ownership over a digital good, but they have many other potential uses yet to be explored in an ever-growing market. - -## Environmental Impact - -The amount of electricity consumed for regulating and verifying blockchain transactions leads to massive carbon emissions. It’s estimated that a single NFT transaction (minting or selling) can emit an average of [40kg of CO2](https://earth.org/nfts-environmental-impact/). diff --git a/content/general/concepts/node-js/node-js.md b/content/general/concepts/node-js/node-js.md deleted file mode 100644 index 2ec7102384c..00000000000 --- a/content/general/concepts/node-js/node-js.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -Title: 'Node.js' -Description: 'Node.js is an open-source runtime that lets developers run JavaScript outside the browser, enabling server-side development.' -Subjects: - - 'Developer Tools' - - 'Web Development' -Tags: - - 'Node' - - 'NPM' - - 'Server' -CatalogContent: - - 'introduction-to-javascript' - - 'paths/full-stack-engineer-career-path' ---- - -[Node.js](https://nodejs.org/en) is an open-source runtime that allows developers to run [JavaScript](https://www.codecademy.com/resources/docs/javascript) outside the browser. Using an event-driven, non-blocking model, Node.js efficiently handles tasks like [server-side](https://www.codecademy.com/resources/docs/general/server-side-rendering) scripting, file operations, and database interactions, making JavaScript a versatile full-stack language. - -## History of Node.js - -Created in 2009 by Ryan Dahl, Node.js addressed the inefficiencies of traditional multi-threaded server models. Built on Chrome’s V8 engine, it introduced a single-threaded, event-driven architecture, enabling efficient handling of multiple connections. The launch of [npm (Node Package Manager)](https://www.codecademy.com/resources/docs/javascript/npm) further expanded its capabilities, fostering a vast ecosystem of reusable libraries. Today, Node.js powers backend development, microservices, desktop applications, and IoT solutions across various industries. - -## Node.js Architecture - -Node.js uses a single-threaded event loop to handle incoming requests asynchronously. This non-blocking approach allows it to process multiple connections simultaneously without waiting for any single task to complete. As a result, Node.js excels in real-time applications such as chat apps, online gaming, and streaming services, where rapid data updates and fast response times are crucial. - -## Pros and Cons of Node.js - -### Pros - -Node.js offers several advantages, making it a popular choice for developers building scalable, high-performance applications. - -- **Full-Stack JavaScript**: Developers can use the same language for both frontend and backend, simplifying the technology stack. -- **Non-Blocking, Event-Driven Architecture**: Efficiently handles multiple requests simultaneously, making it ideal for real-time applications. -- **High Performance**: Chrome’s V8 engine compiles JavaScript into machine code, ensuring fast execution. -- **Scalability**: Its lightweight, single-threaded model is well-suited for microservices and large-scale applications. -- **Extensive Package Ecosystem (npm)**: Access to millions of open-source packages speeds up development. -- **Cross-Platform Compatibility**: Runs on Windows, Linux, Unix, macOS, and more, allowing for flexible deployment. -- **Active Community & Industry Adoption**: A large developer base provides frequent updates, extensive documentation, and robust support. - -### Cons - -Despite its strengths, Node.js has limitations, particularly when handling CPU-intensive tasks or managing dependencies within its vast ecosystem. - -- **CPU-Intensive Limitations**: The single-threaded architecture can become a bottleneck for heavy computation without workarounds like worker threads. -- **Callback Complexity**: Managing nested callbacks in asynchronous code can make it harder to read and maintain, though Promises and `async/await` help mitigate this issue. -- **Frequent Updates**: Rapid release cycles may introduce breaking changes, requiring continuous maintenance. -- **Unreliable Packages & Dependency Issues**: The npm ecosystem lacks strict quality controls, creating potential stability and security risks. diff --git a/content/general/concepts/number/number.md b/content/general/concepts/number/number.md deleted file mode 100644 index 3aac1d6692c..00000000000 --- a/content/general/concepts/number/number.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -Title: 'Number' -Description: 'A number is a mathematical value used to represent a quantity.' -Subjects: - - 'Code Foundations' - - 'Information Technology' -Tags: - - 'Data Types' - - 'Information Technology' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -A **number** is a primitive data type used to represent mathematical values and is commonly used in arithmetic operations, data encoding, and other computations. Examples of numbers include _0_, _-1_, _0.3_, and other numeric values. - -> **Note:** In some programming languages, decimals may be treated as a separate data type, such as `float` or `double`. - -## Number Systems - -A number system defines how a number is represented. The representation depends on the number of digits (base) it uses. The main number systems are: - -- **Decimal System** (Base 10): This system uses 10 digits, 0-9. Each digit’s place value corresponds to a power of 10. -- **Binary System** (Base 2): The binary system uses only two digits, 0 and 1, to represent values. It is extensively used by computers and electronic devices to represent HIGH (_1_) and LOW (_0_) states. -- **Octal System** (Base 8): The octal system uses 8 digits, 0-7. It is used in computer systems to represent values like UTF-8 characters and file permissions in UNIX systems. -- **Hexadecimal System** (Base 16): The hexadecimal system uses 16 digits, where 0-9 are taken directly from the decimal system and 10-15 are represented by letters A-F (i.e., _10_ is A, _11_ is B, _12_ is C, _13_ is D, _14_ is E, and _15_ is F). It is commonly used in computer science, particularly for representing memory addresses. - -## Basic Arithmetic Operations on Two Numbers (JavaScript) - -This code calculates the sum, difference, division, and product of the given numbers and prints the results to the console: - -```codebyte/javascript -const sum = 3 + 4; -const difference = 4 - 3; -const division = 8/2; -const product = 4*2; - -console.log(sum, difference, division, product); -``` diff --git a/content/general/concepts/octal/octal.md b/content/general/concepts/octal/octal.md deleted file mode 100644 index dc99a381402..00000000000 --- a/content/general/concepts/octal/octal.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -Title: 'Octal' -Description: 'Octal is a number system base 8.' -Subjects: - - 'Computer Science' - - 'Data Science' - - 'Code Foundations' -Tags: - - 'Arithmetic' - - 'Encoding' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' ---- - -The **octal** number system is a base-8 number system that uses digits from 0-7 to represent any number. Octal is a number system similar to other number systems like [binary](https://www.codecademy.com/resources/docs/general/binary) and hexadecimal. - -Octal was often used because machines were based on 12, 24, or 36 bits. In contrast, binary or hexadecimal are commonly used in modern technologies, especially with 16, 32, or 64-bit machines. The octal number system has an advantage over the hexadecimal system in that characters from the alphabet are not used to express a number in octal. - -## Example - -| octal | decimal | -| ----- | ------- | -| 0 | 0 | -| 1 | 1 | -| 2 | 2 | -| 3 | 3 | -| 7 | 7 | -| 10 | 8 | -| 11 | 9 | -| 12 | 10 | -| 20 | 16 | -| 40 | 32 | -| 100 | 64 | - -Each digit corresponds to a power of 8. The last digit (decimal 0-7) is 80, equalling 1. The one in front of it is 81, and so on. So each digit represents the figure times 8 to the power of its position. An octal number is converted to decimal like so (using octal 125 as an example): - -125 = 1 \* 82 + 2 \* 81 + 5 \* 80 = 64 + 16 + 5 = 85 diff --git a/content/general/concepts/parameter/parameter.md b/content/general/concepts/parameter/parameter.md deleted file mode 100644 index caa73b5a26a..00000000000 --- a/content/general/concepts/parameter/parameter.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -Title: 'Parameter' -Description: 'A parameter is the name of a variable passed into a function. Parameters allow functions to accept inputs. An argument, on the other hand, is the actual value of the variable (also known as the parameter) passed into a function. Suppose we have a function called tripleThis(): js function tripleThis(x) { return x * 3; } tripleThis(6);' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Functions' - - 'Parameters' - - 'Arguments' -CatalogContent: - - 'introduction-to-javascript' - - 'learn-python-3' ---- - -A **parameter** is the name of a variable passed into a function. Parameters allow functions to accept inputs. An argument, on the other hand, is the actual value of the variable (also known as the parameter) passed into a function. - -## Example - -Suppose we have a function called `tripleThis()`: - -```js -function tripleThis(x) { - return x * 3; -} - -tripleThis(6); -``` - -The parameter is `x` since it is the variable. The argument is `6` since it is the actual value. diff --git a/content/general/concepts/processor/processor.md b/content/general/concepts/processor/processor.md deleted file mode 100644 index eb3f408de1c..00000000000 --- a/content/general/concepts/processor/processor.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -Title: 'Processor' -Description: 'A processor is a hardware component, typically a chip, that executes instructions and performs data processing tasks in a computer or electronic device.' -Subjects: - - 'Computer Science' - - 'Information Technology' -Tags: - - 'Memory' - - 'Components' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -A **processor** is a hardware component that interprets and executes instructions from programs or data. It performs calculations, logic operations, and manages data flow within a system. Processors are essential for a wide range of tasks in computing and electronics, and are found in devices like computers, smartphones, and more. - -## History - -The history of processors ranges from primitive vacuum tubes to multi-core processors being able to handle tons of workload. Some key milestones in their history include: - -- **1940s-1950s**: Early computers used bulky vacuum tubes for processing, which made them large and inefficient. -- **1960s**: The invention of transistors led to smaller, faster, and more reliable processors. -- **1970s**: The Intel 4004, the first microprocessor, integrated all processing functions into a single chip. -- **1980s**: The Intel 8086 introduced the x86 architecture, which powered personal computers like the IBM PC. -- **1990s**: The Intel Pentium processors revolutionized personal computer performance. -- **2000s-Present**: Multi-core processors enabled improved multitasking, while ARM chips became dominant in mobile devices. -- **2010s-Present**: Processors became smaller and more powerful with nanometer technology, and AI-specific chips began to emerge. - -## Types of Processors - -Depending upon their function, processors are divided into many types. Some of them are: - -- **Central Processing Unit (CPU)**: The primary processor in a computer, responsible for executing the majority of instructions in a program. It handles tasks such as arithmetic, logic, and data management. -- **Graphics Processing Unit (GPU)**: A specialized processor designed for graphics-related tasks, such as rendering images, video processing, and running complex simulations. GPUs are commonly found in gaming systems, workstations, and high-performance computing applications. -- **Digital Signal Processor (DSP)**: A processor optimized for signal processing tasks, including sound, image, and video processing. DSPs are used in devices like smartphones, audio equipment, and telecommunications systems. -- **Application-Specific Integrated Circuit (ASIC)**: A custom-designed processor for a specific application, often used in specialized systems such as cryptocurrency mining or network equipment. -- **Microcontrollers**: Small, embedded processors found in everyday devices like microwaves, washing machines, and cars. They are often responsible for managing tasks and controls in these devices. - -Additionally, as artificial intelligence (AI) continues to grow, specialized processors called **Neural Processing Units (NPUs)**, also known as AI accelerators, are being developed to handle AI-specific workloads more efficiently. diff --git a/content/general/concepts/programming-optimization/programming-optimization.md b/content/general/concepts/programming-optimization/programming-optimization.md deleted file mode 100644 index 882b349cff0..00000000000 --- a/content/general/concepts/programming-optimization/programming-optimization.md +++ /dev/null @@ -1,224 +0,0 @@ ---- -Title: 'Programming Optimization' -Description: 'Optimization in programming is the process of modifying a software system to execute faster and become more efficient by minimizing the use of available computing resources.' -Subjects: - - 'Web Development' -Tags: - - 'Development' - - 'Optimization' -CatalogContent: - - 'paths/computer-science' - - 'web-development' ---- - -**Programming Optimization** is the process of modifying a software system to amplify its functionality, making the application execute faster and more efficiently by minimizing the use of computing resources. In other words, a computer program may be optimized to reduce execution time, memory usage, disk space, bandwidth, and even draw less power. This usually requires a trade-off, where one aspect is implemented at the expense of the others, e.g., increasing the size of the [cache](https://www.codecademy.com/resources/docs/general/cache) improves [run-time](https://www.codecademy.com/resources/docs/general/runtime) performance but also increases memory consumption. - -It has become an important focal point since today’s users appreciate a highly performant experience and have significantly higher expectations. It has become a deciding factor in the success of modern business in today’s digital market. Optimization in programming is a key element in the improvement of such performance. - -## Programming Optimization - -Optimization in programming is an extensive topic, it relies on many different metrics, focuses, and areas within the application depending on specific situations. - -Awareness and consideration of performance issues in the design and implementation should be kept in mind during every part of the development cycle, but it doesn’t need to be the primary concern. It could potentially complicate the design and/or implementation, hence it is often left until the final iteration of the application. - -Techniques used can be broken up among various scopes which can affect anything from a single statement to the entire program. Generally speaking, locally scoped techniques are easier to implement than global ones, though they may result in smaller gains. - -These are important points to target for optimization in programming: - -- Reducing code complexity -- Avoiding unnecessary for-loops -- Using data structures similar to like sorting, string concatenation -- Avoiding unnecessary functions -- Avoiding dots -- Initializing dictionary elements -- Import statement overhead -- Data aggregation -- Re-map functions at runtime -- Profiling code - -## Levels of Optimization - -Every application, generally, is composed of 2 areas where programming optimizations can be applied within levels of development: - -**Client Side**, which is the side seen on the web browser by the user, includes: - -- [JavaScript](https://www.codecademy.com/resources/docs/javascript) that runs in the browser -- Load times for pages -- Images -- Videos -- Downloading of any resources required by the application, etc. - -A few of the techniques that can be applied to optimize the programming on the client side could be: - -- Caching and content delivery networks -- Bundle and minification -- Image usage -- Removing duplicate JavaScript and [CSS](https://www.codecademy.com/resources/docs/css) code -- Using minimalist styling frameworks, etc. - -**Server Side**, this second side relates to any computations done behind the scenes, it tends to involve: - -- Database queries and processing -- Application configuration and dependencies, etc. - -Although not restricted to the ones below, typical strategies that help with this include: - -- Using an appropriate server application instead of the default -- Enable caching(opcode, memory, http and application) -- De-fragmentation of database tables -- Database settings -- Virtualization -- [DNS](https://www.codecademy.com/resources/docs/general/dns) query response time - -> **Note:** This list can continue depending on the requirements needed. - -These programming optimizations can occur at different levels within the cycle of the application's creation. Consideration tends to be given to efficiency throughout a project, though this varies significantly, but major optimization in the programming is often considered a refinement to be done later, if ever. - -Typically the higher levels have greater impact and are harder to change later on in a project, requiring significant changes or even a complete rewrite. On longer-running projects there are typically cycles of optimization, where improving one area reveals limitations in another, and these are typically curtailed when performance is acceptable and gains become too small or costly. - -### Design - -The architecture design of a system plays a major role, its optimization can overwhelmingly affect the system's performance by making the best use of the available resources and expected load (e.g. network latency can be optimized to minimize requests, ideally making a single request rather than multiple requests to the network). - -Ultimately the choice of design depends on the goals of the project: If speed of the output is a key priority in the compilation when designing the compiler, taking into account the same level of work, a one-pass compiler is faster than a multi-pass compiler and although a multi-pass is slower, it may fulfill the overall objective just fine. The platform and programming source code language to be used will also be decided at this level. - -Changing any of these will most definitely require extensive rewrites, which is always a practice to avoid, regardless if a modular system may allow rewrites of some components (e.g. a [Python](https://www.codecademy.com/resources/docs/python) program may rewrite performance-critical sections in [C](https://www.codecademy.com/resources/docs/c)). In a distributed system, choice of design (e.g. client-server, peer-to-peer, etc.) occurs at this level and may be extremely challenging to modify later on, particularly if all components cannot be replaced in sync (e.g. old clients). - -### Algorithms and Database Structures - -After the design solution, an efficient implementation for the algorithms and data structure should be decided on, and will play a key role to the system’s performance. - -Generally, data structures are more difficult to change than algorithms since a data structure and its performance assumptions are used throughout the program. Changing a data structure after implementing it is an uphill battle, it’s crucial to think wisely before implementing an algorithmic solution for any optimization. This can be minimized by the use of abstract data types in function definitions, keeping the concrete data structure definitions restricted to a few places. - -Optimized systems tend to have algorithms that are constant O(1), logarithmic O(log n), linear O(n), or log-linear O(n log n). For example, a linear search is asymptotically slower than a binary search, but a linear search is faster for small inputs and a binary search is faster for large inputs. Quadratic complexity algorithms O(n2) fail to scale and even linear algorithms cause problems if repeatedly called and are typically replaced with constant or logarithmic whenever it is possible to do so. - -Beyond asymptotic order of growth, the constant factors matter: An asymptotically slower algorithm may be faster or smaller because it is simpler than an asymptotically faster algorithm when they are both faced with a small input, which may be the reality for most cases. - -[Memoization](https://www.codecademy.com/resources/docs/general/memoization) is also an important dynamic programming caching technique to optimize the code, preventing redundant computations. Because of the importance of caching, there are often many levels of caching in a system because of possible problems from memory use and correctness issues from stale caches. - -### Source Code - -Beyond algorithm implementation, source code level choices can make a significant impact in programming optimization performance. - -For example: - -- Control flow statements like while-loops are slower than for-loops for an unconditional loop. -- On early C compilers, for-loops had an unconditional jump, however, while-loops have a conditional jump. -- A language that is dynamically typed may be slower than a statically typed language, but it may be easier to write and maintain. - -In the most general terms, source code optimization tends to substitute generic high-level programming structures with lower-level source code, thus enhancing performance and/or reducing resource consumption (e.g. [CPU](https://www.codecademy.com/resources/docs/general/computer-hardware/cpu), memory, etc.)). - -Such aforementioned programming optimizations can now be performed by compilers. Although compilers can optimize source code at a lower level, they are often limited to general purpose optimization, thus making manual optimization still necessary, allowing talented and experienced programmers to be creative with their solutions. - -Important source code optimizing objectives to focus on would be: - -- Rewrite or remove redundant code. -- Reduce execution speed. -- Reduce available resources, whenever possible. - -Also, important key points to keep in mind before optimizing the source code: - -- Time-based optimization can execute faster output, but it can also lead to a bigger code base, which can create conflict with memory and consumption. -- Performance optimization is a never-ending process. There will always be improvement opportunities for faster source code, especially as technology keeps moving ahead. -- Certain optimization methods in programming to execute faster outputs may not follow best coding standards and practices. Avoiding such methods will render better results long term. -- Using certain optimization methods in programming to execute faster outputs could result in best coding standards and practices not being followed. Avoiding such methods will render better results in the long term. - -The following are some examples of different types of source coding optimizations: - -#### Loop Optimization - -A majority of system programs, if not all, operate in loops. It is vital to optimize these to save CPU cycles and memory, avoiding loop-invariants and performing -induction analysis will have a positive impact on optimization. - -Example: - -```javascript -do { - i = 10; - v = v + i; -} while (v < 100); -``` - -The code above repeats the assignment of the identifier `i` for every iteration. - -```javascript -i = 10; -do { - v = v + i; -} while (v < 100); -``` - -Written as above should not only save the CPU cycles but can also be used on any [processor](https://www.codecademy.com/resources/docs/general/computer-hardware/processor). - -#### Strength Reduction - -Some expressions use more CPU cycles, time, and memory than others. These expressions should be replaced with less expensive expressions without sacrificing the output (e.g. multiplication (`x \* 2`) uses more CPU cycles than (`x<<1`) but produces the same output). - -#### Partially Dead Code - -This type of source code refers to statements that include value calculations that are used only in particular and irregular conditions. - -#### Unreachable Code Elimination - -Before implementing this type of source code optimization, ideally a control flow graph should be created first. Only after determining that a particular inaccessible code block does not have an incoming edge, these branches can then be deleted after continual propagation and folding. - -#### Function Inlining - -The body of the function takes the place of a function call. This saves a lot of time by eliminating the need to copy all parameters, store the return address, and so on. - -#### Function Cloning - -For different calling arguments, specialized source code functions are implemented (e.g. overloading a function). - -#### Partial Redundancy - -In a parallel route, redundant expressions are calculated along every path without changing the operands. Partially redundant expressions, on the other hand, are calculated along at least one path (but not all) without changing the operands. A code-motion approach, loop-invariant can possibly result in a largely redundant render. - -### Builds - -This level lands in between the source code and the compiler level. Using preprocessor definitions to disable unneeded software features can be done to optimize for specific processor models, hardware capabilities, and/or predicting branching. These types of directives and build flags can facilitate improvement within the source code and compiler, also source-based software distribution systems can take advantage of this form of optimization. - -Towards the end of the development stage will be an optimal time to perform any deep programming optimizations since these tend to reduce readability and also the source codes and/or technologies to achieve this may complicate the maintenance and any debugging that may be needed. - -### Compilers - -A compiler is a specific piece of software that converts the source code of a computer language into machine code, byte code, or another programming language. - -Typically, the source code is written in a high-level, human-readable language and these structures are replaced with highly efficient low-level programming codes to the extent of the compiler's program. The compiler can improve loops and address computations after completing intermediate code and leverage memory hierarchy and CPU registers while generating the target machine code. - -We can categorize the programming optimization at this level, broadly, into 2 types: - -1. Machine Independent - This step of source code optimization compiling aims to improve intermediate code to produce a better target. No CPU registers or absolute memory addresses are involved to be translated. - -2. Machine Dependent - After the target code has been created and converted to fit the machine architecture, machine-dependent optimization is performed. It may use absolute memory references rather than relative memory accesses and also requires CPU registers. Machine-dependent optimizers make a concerted attempt to maximize the memory hierarchy's benefits. - -### Run Time - -By dynamically adjusting parameters in response to the actual input or other factors, adaptive optimization may be able to perform run-time optimization beyond the capability of static compilers. At the cost of overhead and based on runtime data, customized machine code can be done by (Just-in-Time (JIT) Compilers)[https://www.codecademy.com/resources/docs/general/jit-compilation] and can also have self modifying code which is adaptable depending on the runtime conditions. - -Optimizing based on run-time profiles is an ahead-of-time (AOT) compilation technique similar to an "average case" analogy to adaptive optimization. It's common for assembly language programs to use self-modifying code to optimize themselves, depending on runtime conditions. - -Through instruction scheduling, compilers can support programs to take advantage of CPU design features (e.g. out-of-order execution, speculative execution, instruction pipelines, and branch predictors), that perform programming optimizations at runtime. Thus, other versions of the code may be required to be utilized across different platforms and/or processors. - -### Platform Dependence and Independence - -Programming optimization techniques can also be openly categorized as platform dependent or independent. - -Independent developments are effective across most, if not all, platforms, while dependent techniques use determined properties and/or rely on parameters from the single platform in question or even a single processor. - -For compile-level optimization in programming: platform-independent techniques are generic techniques, such as: - -- Loop unrolling -- Reduction in function calls -- Memory efficient routines -- Reduction in conditions - -will impact most CPU architectures in a similar way. - -The previous example in the source code level can apply to a platform-independent optimization: the inner for-loop, where it was observed that a loop with an inner for-loop performs more computations per unit of time than a loop without it or one with an inner while-loop. - -These can typically lower the overall length of instruction paths needed to finish the program and/or the amount of memory used overall. - -Contrarily, when it comes to platform-dependent techniques, these use instruction scheduling, instruction-level parallelism, data-level parallelism, and cache optimization techniques (i.e., parameters that vary across different platforms). - -> **Note:** The best time to schedule instructions may vary even between processors with the same architecture. diff --git a/content/general/concepts/programming-paradigms/programming-paradigms.md b/content/general/concepts/programming-paradigms/programming-paradigms.md deleted file mode 100644 index 746363c4f3f..00000000000 --- a/content/general/concepts/programming-paradigms/programming-paradigms.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -Title: 'Programming Paradigms' -Description: 'An approach to programming. Depending on the language, the preferred paradigm may differ.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Dynamic Programming' - - 'Functional Programming' - - 'OOP' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -A **programming paradigm** is an approach to programming. Depending on the language, the preferred paradigm may differ. Some languages, such as [C++](https://www.codecademy.com/resources/docs/cpp) and [JavaScript](https://www.codecademy.com/resources/docs/javascript), cover multiple paradigms. - -Moving from low-level languages (e.g., [machine code](https://www.codecademy.com/resources/docs/general/machine-code)) to high-level languages (e.g., [Python](https://www.codecademy.com/resources/docs/python)), programming paradigms change. - -Below are some of the existing paradigms: diff --git a/content/general/concepts/programming-paradigms/terms/encapsulation/encapsulation.md b/content/general/concepts/programming-paradigms/terms/encapsulation/encapsulation.md deleted file mode 100644 index f185f020457..00000000000 --- a/content/general/concepts/programming-paradigms/terms/encapsulation/encapsulation.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -Title: 'Encapsulation' -Description: 'Encapsulation is one of the four principles of object-oriented programming (OOP), and it advances the benefits of modularity and hiding away of complexities in order to better maintain and reason about code.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'OOP' - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Encapsulation** advances the benefits of modularity and hiding away of complexities in order to better maintain and reason about code. It is one of the four principles of [object-oriented programming (OOP)](https://www.codecademy.com/resources/docs/general/programming-paradigms/object-oriented-programming). - -Most of the time encapsulation can be achieved by creating [classes](https://www.codecademy.com/resources/docs/general/data-structures/class) with an overarching design structure that includes private and public [methods](https://www.codecademy.com/resources/docs/general/method) (or getters and setters) for our systems to interact. - -## Python Example - -In the following [Python](https://www.codecademy.com/resources/docs/python) example, a `Robot` class is created with a `__version` property, initialized as a number. Getter and setter methods are made to allow any instance of `Robot` to be set with a `__version` and have it changed later]: - -```py -class Robot(object): - def __init__(self): - self.__version = 22 - - def getVersion(self): - print(self.__version) - - def setVersion(self, version): - self.__version = version - -obj = Robot() - -obj.getVersion() -obj.setVersion(23) -obj.getVersion() - -print(obj.__version) -``` diff --git a/content/general/concepts/programming-paradigms/terms/functional-programming/functional-programming.md b/content/general/concepts/programming-paradigms/terms/functional-programming/functional-programming.md deleted file mode 100644 index 18ec80225bd..00000000000 --- a/content/general/concepts/programming-paradigms/terms/functional-programming/functional-programming.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -Title: 'Functional Programming' -Description: 'Encourages programming with pure functions and evaluating expressions instead of statements.' -Subjects: - - 'Code Foundations' - - 'Computer Science' - - 'Web Development' -Tags: - - 'Functions' - - 'Recursion' -CatalogContent: - - 'learn-to-code' - - 'paths/code-foundations' ---- - -**Functional programming (FP)** is a declarative software development paradigm that encourages constructing programs by composing pure functions and evaluating expressions instead of statements. The functions are isolated and independent of the state of the application. - -In FP, dependencies such as variables or objects needed for a function, are always declared explicitly by passing them into the function as arguments. Any operation inside the function is therefore bound to the arguments passed, instead of depending on global objects or variables. This makes the function: - -- Suitable for testing and debugging. -- Predictable, reusable, and stable when refactoring code. - -FP helps make code more modular and understandable. - -## Core Principles of FP - -FP revolves around a few fundamental concepts that are important to discern in order to understand what makes it a popular approach to software development. - -### First-Class Entities - -In FP, functions are considered to be first-class entities. This means that functions can be: - -- Assigned to a variable. -- Passed as arguments into other functions. -- Returned from other functions, just as any other data type can. - -Higher-order functions are a type of first-class functions, as they can take functions as arguments and/or return a function. - -### Pure Functions - -Pure functions are the bread and butter of FP. They are functions that always produce the same output for the same set of inputs and do not cause any side effects. The application state is not impacted apart from the return value of the pure functions and no data is altered. This aspect is known as referential transparency: pure functions can be replaced with their returned value without changing the behavior of a program. - -### Immutability - -That latter property of pure functions can further be defined as immutability. This means that variables or objects outside of the function are unaffected. Instead, copies are created and returned from the function if needed. - -Generally speaking, FP is about avoiding a shared mutable state, which is when different parts of the program are able to access data that can be modified and that exist in a shared scope. - -### Function Composition - -The process of composing functions can be described by chaining two or more function calls; once the first function is called, its return value is passed to a second function as an argument. - -### Recursive Functions - -In FP, iteration is implemented through recursion as opposed to `for` and `while` loops. Recursive functions repeatedly call themselves until a specified base case is met. Conceptually, this technique breaks down a problem into smaller pieces, contributes to the removal of side effects, and improves readability. diff --git a/content/general/concepts/programming-paradigms/terms/inheritance/inheritance.md b/content/general/concepts/programming-paradigms/terms/inheritance/inheritance.md deleted file mode 100644 index 163d51cda94..00000000000 --- a/content/general/concepts/programming-paradigms/terms/inheritance/inheritance.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -Title: 'Inheritance' -Description: 'Inheritance is one of the most important principles of object-oriented programming (OOP). It allows for one class (child class) to inherit the fields and methods of another class (parent class). An inherited class is also called a subclass of its superclass (parent class). Inheritance is considered one of the four pillars of OOP, along with abstraction, and encapsulation, and polymorphism. java // Parent Class class Machine { // Machine class member' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Inheritance' - - 'OOP' - - 'Objects' -CatalogContent: - - 'learn-python-3' - - 'learn-c-plus-plus' - - 'learn-java' ---- - -**Inheritance** is one of the most important principles of object-oriented programming (OOP). It allows for one class (child class) to inherit the fields and methods of another class (parent class). - -An inherited class is also called a subclass of its superclass (parent class). - -Inheritance is considered one of the four pillars of OOP, along with abstraction, and encapsulation, and polymorphism. - -## Example - -```java -// Parent Class -class Machine { - // Machine class member -} - -// Child Class -class Car extends Machine { - // Car inherits traits from Machine - - // Additional Car class members, functions, etc. -} -``` diff --git a/content/general/concepts/programming-paradigms/terms/object-oriented-programming/object-oriented-programming.md b/content/general/concepts/programming-paradigms/terms/object-oriented-programming/object-oriented-programming.md deleted file mode 100644 index fd8a437e3da..00000000000 --- a/content/general/concepts/programming-paradigms/terms/object-oriented-programming/object-oriented-programming.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -Title: 'Object-Oriented Programming' -Description: 'Object-oriented programming (OOP) is a software development paradigm which encourages sculpting desired entities with properties and methods in named classes to create applications.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Objects' - - 'Inheritance' - - 'Methods' - - 'Structure' - - 'Encapsulation' - - 'Classes' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Object-oriented programming (OOP)** is a software development paradigm which encourages sculpting desired entities with properties and methods in named classes to create applications. - -OOP relies on two major concepts: the class and the object - these foundational concepts applied in code enable us to build applications. - -Classes that have been instantiated in our code become objects that can interact with one another to perform the desired functions of the application. Object oriented programming was created to guide the creation of better software, by achieving easier maintenance and reusability. - -## Principles of OOP - -There are four main principles of OOP: - -- [**Encapsulation**](https://www.codecademy.com/resources/docs/general/programming-paradigms/encapsulation): A desired outcome of organizing code in classes in order to keep things from being mixed with other unrelated bits of code. Encapsulation make it easier to reason about code because of the modularity of code written in object oriented styled classes. - -- [**Inheritance**](https://www.codecademy.com/resources/docs/general/programming-paradigms/inheritance): A principle which allows an instance of an object to borrow attributes and methods from its parent class. - -- [**Polymorphism**](https://www.codecademy.com/resources/docs/general/programming-paradigms/polymorphism): The ability of the class to be dynamic in its use of class methods so that objects with the same parent class can make use of these parent class methods. - -- **Abstraction**: A principle that highlights the benefit of hiding complex parts of code from other parts in order to make it easier to reason and make decisions about the code. diff --git a/content/general/concepts/programming-paradigms/terms/polymorphism/polymorphism.md b/content/general/concepts/programming-paradigms/terms/polymorphism/polymorphism.md deleted file mode 100644 index 734974558e0..00000000000 --- a/content/general/concepts/programming-paradigms/terms/polymorphism/polymorphism.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -Title: 'Polymorphism' -Description: 'Polymorphism is one of the four principles of object-oriented programming (OOP). It promotes dynamic inheritance of child classes from their parent class in order to make use of these features themselves in code. With polymorphism, child classes are able to inherit methods from their parent class for use. This ability to inherit functionality from parent classes not only speeds up the development process, but also helps us reason and understand our code more intuitively as we can see the correlation between objects for easier understanding and manipulation of source code. py from math import pi class Shape: def init(self, name): self.name = name' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Polymorphism** is one of the four principles of object-oriented programming (OOP). It promotes dynamic inheritance of child classes from their parent class in order to make use of these features themselves in code. - -With polymorphism, child classes are able to inherit methods from their parent class for use. This ability to inherit functionality from parent classes not only speeds up the development process, but also helps us reason and understand our code more intuitively as we can see the correlation between objects for easier understanding and manipulation of source code. - -```py -from math import pi - -class Shape: - def __init__(self, name): - self.name = name - - def area(self): - pass - - def fact(self): - return "I am a two-dimensional shape." - - def __str__(self): - return self.name - -class Square(Shape): - def __init__(self, length): - super().__init__("Square") - self.length = length - - def area(self): - return self.length**2 - - def fact(self): - return "Squares have each angle equal to 90 degrees." - -class Circle(Shape): - def __init__(self, radius): - super().__init__("Circle") - self.radius = radius - - def area(self): - return pi*self.radius**2 - -a = Square(4) -b = Circle(7) - -print(b) -print(b.fact()) -print(a.fact()) -print(b.area()) -``` diff --git a/content/general/concepts/progressive-web-application/progressive-web-application.md b/content/general/concepts/progressive-web-application/progressive-web-application.md deleted file mode 100644 index d9675bd65c1..00000000000 --- a/content/general/concepts/progressive-web-application/progressive-web-application.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -Title: 'Progressive Web Application' -Description: 'A progressive web application provides a consistent, browser-based experience across multiple platforms like mobile and desktop.' -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'Accessibility' - - 'Browsers' - - 'Browser Compatibility' - - 'Development' -CatalogContent: - - 'introduction-to-javascript' - - 'paths/front-end-engineer-career-path' ---- - - - -A **progressive web application (PWA)** is software that is built with common web technologies to provide a consistent, browser-based experience across multiple platforms like mobile and desktop. Browser compatibility for PWAs is various but is generally supported in the following: - -- Google Chrome -- Apple Safari -- Firefox (for Android, not desktop) -- Microsoft Edge - -## PWA Principles - -Rather than being a programming language or separate technology, PWAs are a collection of key principles followed in every application, including: - -- Discoverable: The app can be readily found on app stores and search engines. -- Installable: The app can be installed as a "native-like app" on a device for later use on the browser. -- Linkable: A secure and unique link can be used to visit and share the app. -- Network independence: The app provides an offline experience with service workers and other web APIs. -- Re-engagement: The app can update content when not in use and push notifications to the user. -- Responsive design: The app's user interface is consistent across all resolutions and screen sizes. -- Secure: The app uses HTTPS for secure browsing. diff --git a/content/general/concepts/protocol/protocol.md b/content/general/concepts/protocol/protocol.md deleted file mode 100644 index 6d492a4b851..00000000000 --- a/content/general/concepts/protocol/protocol.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -Title: 'Protocol' -Description: 'A protocol describes the rules, syntax, and semantics used by two or more devices in a computer network to connect and communicate with each other.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Browsers' - - 'Requests' - - 'Semantic' - - 'Syntax' - - 'World Wide Web' -CatalogContent: - - 'introduction-to-javascript' - - 'paths/full-stack-engineer-career-path' ---- - -A **protocol** describes the rules, syntax, and semantics used by two or more devices in a computer network to connect and communicate with each other. - -## The Internet - -The most prominent computer network is the internet, which uses a collection of protocols known as the Internet Protocol Suite. This collection uses multiple layers to describe how data should be packetized, addressed, [routed](https://www.codecademy.com/resources/docs/general/routing), and received between members of the network. - -## Common Protocols - -Some notable network protocols include the following: - -| Protocol | Description | -| :------------------------------------------------------------------------------------------: | ------------------------------------------------------------------------------------------------------ | -| [Hypertext Transfer Protocol (HTTP)](https://www.codecademy.com/resources/docs/general/http) | Used for fetching HTML documents and other web-based resources. | -| Internet Protocol (IP) | Routes and addresses data packets for sending between networks. | -| Transmission Control Protocol (TCP) | Facilitates client-server communication of network data. | -| User Datagram Protocol (UDP) | Disregards error checks/corrections in favor of time-sensitive tasks (gaming, video conferences, etc.) | diff --git a/content/general/concepts/proxy-server/proxy-server.md b/content/general/concepts/proxy-server/proxy-server.md deleted file mode 100644 index e9d2be58d58..00000000000 --- a/content/general/concepts/proxy-server/proxy-server.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -Title: 'Proxy Server' -Description: 'Proxy servers are intermediary computers that allows a client to connect with a web server while maintaining privacy.' -Subjects: - - 'Computer Science' - - 'Cybersecurity' -Tags: - - 'Browsers' - - 'Cybersecurity' - - 'Encoding' - - 'Requests' - - 'Servers' - - 'Validation' -CatalogContent: - - 'introduction-to-cybersecurity' - - 'paths/securing-express-applications' ---- - - - -**Proxy servers** are intermediary computers that allows a client to connect with a web server while maintaining privacy. - -Every computer needs a unique IP address to connect with the server(s) of a network. The IP address sends a request to the server for a response with data such as the web page for this entry. Proxy servers come with their own IP address that is used to direct the client's request to the server. - -Depending on the setup, use-cases for a single proxy server include the following: - -- It can serve as a common "exit point" for the client and the network to access the internet. -- It can be an "entry point" for clients outside of the network to access multiple internal servers. - -Unlike [VPNs](https://www.codecademy.com/resources/blog/what-is-a-vpn/), which offer a secure connection that is system-wide, proxy servers only offer privacy protection while web browsing. - -## Forward Proxy Servers - -Forward proxy servers are used to manage how a person or organization communicates with and accesses external web servers. If an unauthorized user tried to visit a restricted page on the network, the forward proxy server would step in and send a message back saying that the user was denied access. - -Depending on the specific needs, forward proxy servers come in the following forms and configurations: - -- Transparency proxies are commonly used by institutions (schools, libraries, etc.) to enforce acceptable use policies and cache content for improved performance. -- An anonymous server uses its own IP address for web requests while identifying itself as a proxy (ideal for avoiding ads). -- High anonymity proxies usually change their IP address after each request, maximizing privacy. - -## Reverse Proxy Servers - -Reverse proxy servers are used by people and organizations for managing incoming web traffic and housing data on multiple servers. With this server in place, all website requests are directed to a single proxy server that can then fetch the requested data and send it back to the computer. - -In this setup, the reverse proxy server acts as a traffic cop to ensure that no website server is overloaded with requests. It also serves as a security buffer that prevents people from directly communicating with company servers. diff --git a/content/general/concepts/pseudocode/pseudocode.md b/content/general/concepts/pseudocode/pseudocode.md deleted file mode 100644 index 4b48d2181e6..00000000000 --- a/content/general/concepts/pseudocode/pseudocode.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -Title: 'Pseudocode' -Description: 'Pseudocode is a method of describing the steps in an algorithm or other computed process written in plain language. It does not rely on any particular implementation of a programming language, and instead is intended for a human audience. It omits the portions required for machine implementation of the algorithm, such as variable declarations, and includes natural language description details.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Conceptual' - - 'Documentation' - - 'Development' -CatalogContent: - - 'paths/code-foundations' - - 'learn-how-to-code' ---- - -**Pseudocode** is a method of describing the steps in an algorithm or other computed process written in plain language. It does not rely on any particular implementation of a programming language, and instead is intended for a human audience. It omits the portions required for machine implementation of the algorithm, such as variable declarations, and includes natural language description details. - -Pseudocode is a compact machine-independent way of communicating an algorithm and is used in teaching, scientific papers, and in program development. -There is no particular standard for pseudocode syntax. However, guidelines may exist in certain situations, such as in an academic environment, or for publication. - -Pseudocode may borrow format and syntax for control structures from some conventional programming languages, while things like function calls and blocks of code within a loop may be replaced by natural language descriptions. Therefore, implementations of pseudocode may vary widely, from a close approximation to a finished program, to a block of formatted prose. - -## Example 1 - -The following is a pseudocode description of a basic bubble sort algorithm using C++ formatting: - -```cpp -function bubbleSort(A : list of sortable items) { - n = length(A); - do { - swapped = false - for (i = 1; i <= n-1; i = i + 1) { - // If this pair is out of order - if (A[i-1] > A[i]) { - // Swap them and remember something changed - // swap(A[i-1], A[i]); - // swapped = true; - } - } - } - while (swapped); -} -``` - -## Example 2 - -The following is a pseudocode description of the above algorithm in more prose-like formatting: - -```pseudo -variable A is a zero-indexed list of sortable items - -set n = the number of items in A - -loop - set swapped = false - for i = 1 to n-1 - if A[i] is less than prior element then swap A[i] with prior element - set swapped = true - end for - if swapped is false then exit loop -end loop -``` diff --git a/content/general/concepts/qr-code/qr-code.md b/content/general/concepts/qr-code/qr-code.md deleted file mode 100644 index 34458d41652..00000000000 --- a/content/general/concepts/qr-code/qr-code.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -Title: 'QR Codes' -Description: 'A QR Code, or quick response code, is code used to store information that can be read by a QR scanner.' -Subjects: - - 'Computer Science' -Tags: - - 'Images' -CatalogContent: - - 'learn-c-plus-plus' - - 'paths/computer-science' ---- - -## What is a QR Code? - -A **QR Code** (quick response code) is code used to store information and it can be read by a device that has QR scanning software on it. QR codes differ from barcodes seen in a retail or grocery store in that a standard barcode is one-dimensional and reads horizontally. A QR code is a square-shaped, with the data enclosed within the square. The three squares in the corners of the QR code tell the QR code scanning software how the QR code is orientated, so the scanning software can read the QR code’s data correctly. [Here](https://www.qr-code-generator.com/qr-code-marketing/qr-codes-basics/) is a good web page detailing how the data is structured in the QR code. - -QR codes are used just like their bar code counterparts: They contain data, and when scanned the data is entered into an app or is used by a device, greatly speeding up the data entry process and eliminating typing errors. Barcodes usually hold just a number, and once scanned and entered into an application. The scanned number can be used to lookup a specific item and retrieve the item’s name, price, and other information. QR codes hold all kinds of data, so they are more widely used than barcodes. - -Some QR codes are static, and some are dynamic. A static QR code has all the data encoded, and the data will not change. If a data entry error is made during QR code creation, that error is permanent. A dynamic QR code fixes the problem. A dynamic QR code will retrieve data from the internet, allowing the QR code owner to edit the data as needed. - -QR codes do need to be square in shape, but there is room for some artistic styling. The squares and data dots can have rounded corners. The QR code does not have to be black on white. The black can be changed to another color, but a higher contrast leads to more readability. A logo can be included in the center square. These changes make the QR code visually unique and more suited to its use. - -## Reading a QR Code - -To read a QR code one does not need a special laser bar code reader. Most camera apps in mobile devices contain QR code scanning software. Just open the camera app, focus on the QR code, and a clickable link appears in the camera app. - -## Creating a QR Code - -Software is used to create the QR code. The user enters the data to be encoded and how the QR code will be used. When the user is done entering the data, the software will create the QR code. There are several QR code generator websites. Some will generate basic QR codes for free. - -## Uses for QR Codes - -QR codes have many more uses than regular bar codes. QR codes hold more data, and they are easily readable by today’s mobile devices. The data can be just text, or instructions to open an app and populate fields. A QR code can hold the URL for a web page or help log into a Wi-Fi network. QR codes can show proof of purchase. They are also used to track how many times the QR code has been scanned. There are several other uses as well. - -One of the most common uses for QR codes is an URL for a web page. Instead of requiring a user to enter “codecademy.com/resources/docs/general” into a web browser, the URL is embedded into a QR code. The user scans the QR code and clicks the link. Many restaurants use QR code URLs for online menus. Sporting events use QR codes allowing spectators to get up-to-the-minute stats. Charitable organizations use QR codes to direct donors to the donation website. - -QR codes are also used as entry passes. When purchasing a movie ticket online, the user will be sent a QR code. The user retrieves the QR code on a mobile device, and at the movie theater, the user has the QR code scanned and is admitted. - -But QR codes can also be used to point a user to a malicious web site, just like a phishing email. One should be careful about scanning and clicking on a QR code. A QR code passed out at a conference, enabling the attendees to log into the local Wi-Fi is going to be safe to scan and click. On the other hand, a QR code on a flyer stuck to a lamppost might be suspect. Just like emails, use good judgement before scanning and clicking. - -QR codes are easy to create and use. They make it easy for users to use their mobile devices without the need to type in data. QR codes are used by the QR code’s creator, allowing the creator to track how the QR code is used. diff --git a/content/general/concepts/ram/ram.md b/content/general/concepts/ram/ram.md deleted file mode 100644 index f50d4b4d0dd..00000000000 --- a/content/general/concepts/ram/ram.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -Title: 'RAM' -Description: 'Random Access Memory (RAM) is a high-speed, temporary storage component that enables quick access to data and instructions for active programs and processes.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Algorithms' - - 'Memory' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Random Access Memory (RAM)** is an essential component of modern computing devices, acting as a bridge between the processor and long-term storage. Unlike a hard drive or SSD, which stores data permanently, RAM provides temporary storage that allows the CPU to quickly access the data needed for active tasks. This makes RAM crucial for multitasking, as more RAM enables a system to handle multiple applications simultaneously without slowing down. - -RAM is a volatile memory type, meaning it loses all stored data when power is turned off. It is significantly faster than traditional storage drives, allowing computers to run software efficiently. The speed and capacity of RAM play a crucial role in determining system performance, influencing how quickly applications load and how smoothly they run. - -## History - -The development of RAM has gone through several stages, evolving to meet the growing demands of computing: - -- **1940s-1950s**: Early computers used magnetic core memory, which provided random access but was slow and bulky. -- **1960s-1970s**: The introduction of semiconductor memory revolutionized computing, leading to the first Dynamic RAM (DRAM) chips. -- **1980s-1990s**: Advancements in RAM technology, such as SDRAM (Synchronous DRAM), improved speed and efficiency. -- **2000s-Present**: Modern RAM types, including DDR (Double Data Rate) RAM, have evolved across multiple generations (DDR, DDR2, DDR3, DDR4, DDR5), providing faster speeds, lower power consumption, and improved performance. - -Today's RAM modules are smaller, faster, and more efficient than ever, supporting high-performance computing, gaming, and data-intensive applications. - -## How RAM Works - -RAM functions as a high-speed workspace for the CPU, allowing it to store and quickly retrieve data needed for active tasks. The basic working process of RAM includes: - -- **Data Loading**: When an application is launched, its required files and instructions are loaded into RAM from long-term storage (HDD/SSD). -- **Active Processing**: The CPU reads and writes data in RAM while executing tasks. Since RAM is much faster than traditional storage, it enables real-time processing. -- **Data Removal**: When an application is closed or the system is powered off, RAM clears its stored data since it is volatile memory. - -This cycle repeats continuously, ensuring that computing tasks are performed efficiently and without delay. More RAM allows for a larger working space, improving performance, especially in memory-intensive applications like video editing, gaming, and virtual machines. - -## Features of RAM - -- **Volatile Memory**: RAM loses stored data when power is turned off. -- **High-Speed Access**: RAM is significantly faster than traditional storage devices like HDDs and SSDs. -- **Multitasking Support**: More RAM enables smooth operation of multiple applications at once. -- **Different Types** Includes Static RAM (SRAM) for cache memory and Dynamic RAM (DRAM) for system memory, with variants like DDR3, DDR4, and DDR5. -- **Expandable**: Many computers allow RAM upgrades to improve performance. - -With continuous advancements, RAM technology continues to evolve, offering better efficiency and higher speeds for modern computing needs. - -## Types of RAM - -RAM is broadly classified into two main types: **Static RAM (SRAM)** and **Dynamic RAM (DRAM)**: - -1. **Static RAM (SRAM)** - - - Uses flip-flop circuits to store data. - - Faster and more reliable than DRAM. - - Commonly used in CPU cache (L1, L2, L3). - - More expensive and consumes more power. - -2. **Dynamic RAM (DRAM)** - - - Stores data using capacitors that need frequent refreshing. - - Slower than SRAM but more affordable and widely used. - - Used as the main system memory in computers. - - Available in different generations, including: - - **DDR (Double Data Rate) RAM**: Successor to SDRAM with improved speed. - - **DDR2, DDR3, DDR4, DDR5**: Successive generations offering higher bandwidth, lower power consumption, and better efficiency. - - **GDDR (Graphics DDR) RAM**: Specialized for GPUs, optimized for high-speed graphics processing. diff --git a/content/general/concepts/regular-expressions/regular-expressions.md b/content/general/concepts/regular-expressions/regular-expressions.md deleted file mode 100644 index f8edf363c74..00000000000 --- a/content/general/concepts/regular-expressions/regular-expressions.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -Title: 'Regular Expressions' -Description: 'Regular expressions, often shortened to regex or regexp, is a language used for pattern-matching text content.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Regular Expressions' - - 'Strings' - - 'Data Types' - - 'Characters' -CatalogContent: - - 'learn-python-3' - - 'learn-java' ---- - -**Regular expressions**, often shortened to regex or regexp, is a language used for pattern-matching text content. It is implemented in several different programming languages, either directly or through libraries. Languages that implement regular expressions include [Python](https://www.codecademy.com/resources/docs/python), [Java](https://www.codecademy.com/resources/docs/java), [JavaScript](https://www.codecademy.com/resources/docs/javascript), [C](https://www.codecademy.com/resources/docs/c) and [C++](https://www.codecademy.com/resources/docs/cpp). Regular expressions are generally standardized, though some implementations may provide some additions and variations to the basic syntax. - -Implementation in each programming language is generally through functions and methods that accept some text and a regular expression pattern, and return a result based on what the regular expression pattern matched in the text. - -## Regular Expression Patterns - -A regular expression pattern is a string made up of normal characters mixed with metacharacters that have special meanings defining how characters should be matched. For instance, the pattern "h" by itself would match the single letter "h", whereas if we add the metacharacter ".", which matches any one character, then "h." would match sequences such as "ha", "ho", "h5" and "h!". - -Regular expressions use the following metacharacters and sequences for pattern matching: - -| Metacharacter | Description | Example | -| :-----------: | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | -| `^` | Matches the start of text, or the start of a line, depending on the settings of the regex engine. | `^a` only matches the first "a" in "a match is made" | -| `$` | Matches the end of text, or the end of a line, depending on the settings of the regex engine. | `!$` only matches the second "!" in "Hello! World!" | -| `.` | Matches any one character. | `.` matches "c", "a" and "t" in "cat" | -| `*` | Matches the preceding element zero or more times. | `co*t` matches "ct", "cot" and "coot" | -| `+` | Matches the preceding element one or more times. | `co+t` matches "cot", "coot" but not "ct" | -| `?` | Matches the preceding element zero or one time. | `co?t` matches "ct", "cot" but not "coot" | -| `{n}` | Matches the preceding element exactly `n` times. | `co{2}t` matches "coot" but not "cot" or "cooot" | -| `{,max}` | Matches the preceding element zero to `max` times. | `co{,2]t` matches "ct", "cot", "coot" but not "cooot" | -| `{min,}` | Matches the preceding element `min` or more times. | `co{2,}t` matches "coot" and "cooot" but not "cot" | -| `{m,n}` | Matches the preceding element at least `m` and not more than `n` times. | `co{2,3}t` matches "coot" and "cooot" but not "cot" | -| `[ ]` | Matches the characters inside the brackets. Can also specify ranges of characters such as `[a-z]`. | `[bcm]at` matches "cat", "bat" and "mat" | -| `[^ ]` | Matches characters not inside the brackets. Can also specify ranges of characters such as `[^a-z]`. | `b[^a]t` matches "bit", "bot", and "but" but not "bat" | -| `\|` | Matches the pattern on the right of the `\|` or the pattern on the left. | `yes\|no` matches both "yes" and "no" | -| `( )` | Groups a pattern together and marks it for future reference | `(ca\|bi)t` matches "cat" and "bit" | -| `\w` | Matches alphanumeric characters and "\_". | `\w+` matches "Hello" and "World" in "Hello World!" | -| `\W` | Matches non-word characters. | `\W` matches the space and "!" in "Hello World!" | -| `\b` | Matches word boundaries. | `o\b` matches the first "o" in "Hello World!" | -| `\B` | Matches non-word boundaries. | `o\B` matches the second "o" in "Hello World!" | -| `\d` | Matches a digit character. | `\d+` matches "123" in "abc123" | -| `\D` | Matches a non-digit character. | `\D+` matches "abc" in "abc123" | -| `\s` | Matches a whitespace character. | `\s` matches the space in "Hello World!" | -| `\S` | Matches a non-whitespace character. | `\S+` matches "Hello" and "World!" in "Hello World!" | diff --git a/content/general/concepts/rest/rest.md b/content/general/concepts/rest/rest.md deleted file mode 100644 index 0649cb9a26d..00000000000 --- a/content/general/concepts/rest/rest.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -Title: 'REST' -Description: 'REST is an architectural style for API design that is defined by 6 constraints.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'APIs' - - 'Developer Tools' - - 'Dependency' - - 'Interface' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**REST** is an architectural style for [API](https://www.codecademy.com/resources/docs/general/api) design that is defined by six constraints. These constraints, or design principles, were first documented in Roy Fielding's dissertation ["Architectural Styles and the Design of Network-based Architectures"](https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm). The acronym REST stands for REpresentational State Transfer. - -A REST [API](https://www.codecademy.com/resources/docs/general/api) is an API that follows the constraints of REST architectural style. REST APIs are the most commonly used APIs today. - -## REST Constraints - -1. Uniform Interface: The API must use standard HTTP methods to represent the operations that can be performed on a resource (endpoint). Examples of these HTTP methods are `GET`, `POST`, `PUT`, and `DELETE`. -2. Layered System: The API can be implemented with multiple layers, where each layer performs a different task. For example, the data layer (where information is stored) could be implemented on a different server than the authentication layer (where requests are verified). -3. Cacheable: Clients must be able to [cache](https://www.codecademy.com/resources/docs/general/cache) responses, and the server must be able to tell clients how long it should keep a response stored in its cache. -4. Client-Server Model: The client and server must be separate. They must communicate using HTTP requests and responses. -5. Statelessness: The server must not store information related to the client's state or session. The client is responsible for storing and handling this information. -6. Code-On-Demand (optional): In certain cases, the API can send executable code to be run on-demand by the client. JavaScript is a popular language for code-on-demand, but other languages can be used. This is an optional requirement that determines if code within the document can be executed. diff --git a/content/general/concepts/routing/routing.md b/content/general/concepts/routing/routing.md deleted file mode 100644 index 2b2afa34efd..00000000000 --- a/content/general/concepts/routing/routing.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -Title: 'Routing' -Description: 'Routing is the process of deciding what paths communication signals may take across one or more networks.' -Subjects: - - 'Computer Science' - - 'Cybersecurity' - - 'Web Development' -Tags: - - 'Cybersecurity' - - 'Networking' -CatalogContent: - - 'introduction-to-cybersecurity' - - 'paths/computer-science' ---- - -**Routing** is the process of deciding what paths communication signals may take across one or more networks. This process is used in many scenarios related to computer networking, including: - -- A PC communicating with a printer across a Local Area Network, or LAN. -- A phone's web browser communicating with a web server over the Internet. - -Through routing, these communication signals, called packets, can take multiple paths from the source to the destination. - -## Routers - -The process of routing is executed by devices known as routers. They live on the network where there are junctions (nodes) between these various paths. Routers can either be physical pieces of hardware or software based, which tend to be more limited in functionality. - -A router always has some default path to send network traffic if no specific destination is specified. For packets with a specific destination, if there is more than one path, the router can make a decision on what path to use based on several criteria, which can include: - -- Hop Count: The number of intermediate devices (routers) between the source and destination. -- Bandwidth: The maximum amount of data that can travel a route in a given period of time. -- Delay/Latency: The time between a signal sent on a route, and the response received. - -## Types of Routing - -There are several types of routing, based on the characteristics of the destination: - -- Unicast Routing: The packet is being sent to a single specified location. -- Broadcast Routing: The packet is sent to all nodes on the network, even nodes that haven't requested it. -- Multicast Routing: Similar to broadcast routing, but packets are only sent to nodes that want them. -- Anycast Routing: The destination consists of several devices with the same logical address and the packet is routed to the closest of these devices. diff --git a/content/general/concepts/runtime/runtime.md b/content/general/concepts/runtime/runtime.md deleted file mode 100644 index 41b726fb623..00000000000 --- a/content/general/concepts/runtime/runtime.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -Title: 'Runtime' -Description: 'Runtime is the period of time during which a program is running.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Developer Tools' - - 'Debugging' - - 'Compilation' -CatalogContent: - - 'paths/front-end-engineer-career-path' - - 'paths/computer-science' ---- - -**Runtime** is the period of time during which a program is running, executing the specific instructions that make up the software. - -Runtime errors are common types of errors in software development. A runtime error is any error a program has while it is running. - -## Runtime Environment - -The runtime environment is the infrastructure required to implement features in the language itself. This can include functions for optimization, memory management, debugging, and input/output. Runtimes make software development easier for engineers by making these functions more accessible. diff --git a/content/general/concepts/scope/scope.md b/content/general/concepts/scope/scope.md deleted file mode 100644 index 431625063dd..00000000000 --- a/content/general/concepts/scope/scope.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -Title: 'Scope' -Description: 'Visibility and accessibility of variables, functions, and objects within a particular part of a program.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Accessibility' - - 'Variables' - - 'Visibility' -CatalogContent: - - 'paths/computer-science' ---- - -**Scope** in programming refers to the visibility and accessibility of variables, functions, and objects within a particular part of a program. It defines where these entities can be accessed and how long their values persist during program execution. Understanding scope is crucial for writing maintainable and bug-free code, as it helps organize and manage variables, prevents naming conflicts, and ensures proper memory management. - -## Example - -To illustrate the concept of scope, consider the following pseudocode snippet, which demonstrates various types of scope using common programming structures: - -```pseudo -function main() - set globalVariable = 10 - - if true: - set blockVariable = 20 - - for i = 1 to 3: - set loopVariable = i - display loopVariable - - display blockVariable - - display globalVariable -end function -``` - -In this pseudocode, the following scopes exist: - -1. Global Scope: The `globalVariable` is declared outside any functions or blocks, making it accessible from anywhere within the program, including all functions and blocks. -2. Local Scope: The `blockVariable` is declared within the `if`-statement block. It is only accessible within that block and any nested blocks, such as the `for`-loop. Trying to access `blockVariable` outside of its block would result in an error. The `loopVariable` is declared within the `for`-loop block. It has scope limited to that block and is only accessible during each iteration of the loop. Attempting to access `loopVariable` outside of the loop would result in an error. - -The pseudocode snippet demonstrates how variables can have different scopes depending on where they are declared. Understanding scope is essential for correctly accessing variables and avoiding conflicts between different parts of a program. - -## Scope in Different Languages - -- [Javascript](https://www.codecademy.com/resources/docs/javascript/variable-scope) -- [Python](https://www.codecademy.com/resources/docs/python/scope) -- [Ruby](https://www.codecademy.com/resources/docs/ruby/scope) diff --git a/content/general/concepts/semantic-technologies/semantic-technologies.md b/content/general/concepts/semantic-technologies/semantic-technologies.md deleted file mode 100644 index 86cbb9b6768..00000000000 --- a/content/general/concepts/semantic-technologies/semantic-technologies.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -Title: 'Semantic Technologies' -Description: 'A class of technologies used for data management with a focus on the underlying meaning of the data.' -Subjects: - - 'Data Science' -Tags: - - 'Data' - - 'Database' - - 'Graphs' - - 'Metadata' - - 'Semantic' -CatalogContent: - - 'paths/data-science-foundations' - - 'paths/data-science-nlp' ---- - -**Semantic technologies** are a class of data management technologies that focus on making the underlying meaning of data more transparent to both human and machine users. - -Semantic technologies encompass a variety of standards, frameworks, data models, and applications, which are described in further detail below. - -## Semantic Data Models - -Semantic technologies organize information using the following data models. - -### Taxonomies - -A **taxonomy** consists of hierarchies of concepts. For example, the concept `poodle` is a subclass of the concept `dog`, in the sense that all poodles are dogs. In turn, the concept `dog` is a subclass of the concept `mammal`. Taxonomies are data models consisting of definitions of concepts and a specification of the hierarchies (relations of subclass and superclass) between them. - -### Ontologies - -An **ontology** is an enriched taxonomy. Ontologies include all the elements in taxonomies and add the following: - -- _Additional relations over concepts_: Ontologies can include relations other than subclass and superclass. For example, to represent the information that cars have tires as parts, one can define a relation `partOf` as holding between the concepts `tire` and `car`. Notice that this is not a hierarchy relation: it does not say that all tires are cars or that all cars are tires. -- _Properties of concepts_: Ontologies can include properties that apply to concepts. For example, to represent the information that cars have weights, one can define the property `weight` as applying to the concept `car`. -- _Additional information about properties and relations_ - - _The domain and range of properties and relations_: Ontologies can include specifications of what types of entities a property or relation applies to (domain) and what values it can take (range). For example, one could specify that the domain of a relation `authorOf` is `person`, and the range is `document`. - - _Formal structures of properties and relations_: Ontologies can include axioms specifying the formal structures of properties and relations. For example, one could include an axiom that _partOf_ is transitive, to convey the information that if `A` is `partOf` `B`, and `B` is `partOf` `C`, then `A` is `partOf` `C`. - -### Knowledge Graphs - -A **knowledge graph** models the properties of, and relations between, particular things using an ontology. For example, suppose a grocery store had an ontology modeling all of the concepts relevant to their operations, including concepts about store employees (`cashier`, `manager`, `employee`, etc.), products (`napkins`, `produce`, `apple`), and so on. They could then create a knowledge graph which models and tracks the relationships between particular employees (`Bob Johnson`, `Snoop Dog`), products as identified by barcodes (`175937462846`, `175937462840`), and so on. - -## Fundamental Semantic Technology Stack - -Most semantic technologies are based on the three following fundamental standards. - -### Resource Description Framework (RDF) - -**RDF** is a language for storing data. RDF stores data in **triples**, which represent information using a subject-predicate-object format. For example, the information that Brazil is larger than Italy could be represented as a triple as follows: - -```pseudo -subject:Brazil predicate:largerThan object:Italy -``` - -> **Note:** This example is not valid RDF, although it resembles the syntax of some RDF serializations. - -### Web Ontology Language (OWL) - -**OWL** is a language for creating taxonomies, ontologies, and knowledge graphs using RDF data. OWL provides vocabulary to implement the elements of an ontology, such as `owl:TransitiveProperty`, which specifies that a property or relation is transitive, and `owl:DatatypeProperty` which specifies that the range of values that a property or relation can take. - -### SPARQL Protocol and RDF Query Language (SPARQL) - -**SPARQL** is a language for querying RDF data. Suppose that a supply-chain manager at a grocery store wanted to identify all of the apples in the store using a knowledge graph. A SPARQL query for getting this information would look something like the following: - -```pseudo -SELECT ?x -WHERE { - ?x rdf:type groceryOntology:apple -} -``` - -This query will return everything in the knowledge graph that is an instance of the class `apple` in the ontology used to create the knowledge graph (`groceryOntology`). - -## Advantages of Semantic Technologies - -Proponents of semantic technologies claim that they have several advantages over other common data management technologies, including [relational](https://www.codecademy.com/resources/docs/general/relational-database) and [tabular](https://www.codecademy.com/resources/docs/general/csv) databases. These include: - -- Better for integrating data from heterogeneous sources -- Better for extracting data from unstructured sources -- Easier to adapt when the data model needs to be changed -- More accessible to AI systems -- Enable automated logical inferences from existing data diff --git a/content/general/concepts/semantic-technologies/terms/owl/owl.md b/content/general/concepts/semantic-technologies/terms/owl/owl.md deleted file mode 100644 index 29c80cf729a..00000000000 --- a/content/general/concepts/semantic-technologies/terms/owl/owl.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -Title: 'OWL' -Description: 'A language which provides vocabulary for creating ontologies and knowledge graphs.' -Subjects: - - 'Data Science' -Tags: - - 'Ontologies' - - 'Knowledge Graphs' - - 'Semantic' -CatalogContent: - - 'paths/data-science-foundations' - - 'paths/data-science-nlp' ---- - -**Web Ontology Language (OWL)** is a language which provides vocabulary for creating **ontologies** and **knowledge graphs**. OWL is used to describe the classes, properties, and relations that constitute these semantic data models. - -OWL ontologies and knowledge graphs are written in [Resource Description Framework (RDF)](https://www.codecademy.com/resources/docs/general/semantic-technologies/rdf) and consist of RDF statements. RDF is a language used to represent information as semantic data. - -## OWL Vocabulary - -Some important and commonly used OWL terms are described in the tables below. - -### Declarations - -The following OWL terms are used to declare new classes, individuals, and properties: - -| OWL Term | Usage Syntax | Meaning | -| :--------------------: | :---------------------------------: | :-------------------------------: | -| `owl:Class` | `:ex rdf:type owl:Class` | `:ex` is an OWL class | -| `owl:NamedIndividual` | `:ex rdf:type owl:NamedIndividual` | `:ex` is an OWL named individual | -| `owl:ObjectProperty` | `:ex rdf:type owl:ObjectProperty` | `:ex` is an OWL object property | -| `owl:DatatypeProperty` | `:ex rdf:type owl:DatatypeProperty` | `:ex` is an OWL datatype property | - -An _object property_ is a predicate which takes an instance of a class as both its subject and object. For example, an object property `hasAuthor` can be defined as holding between instances of the classes `books` and `authors`. - -A _datatype property_ is a predicate which takes an instance of a class as its subject and a literal (such as a string or number) as its object. For example, a datatype property `soldCopies` can be defined as holding between an instance of the class `books` and an integer number. - -A _named individual_ is a particular member of a class. - -### Relations Between Classes - -The following OWL terms are used to describe relationships between OWL classes: - -| OWL Term | Usage Syntax | Meaning | -| :------------------: | :---------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------: | -| `owl:intersectionOf` | `:ex1 owl:intersectionOf (:ex2 :ex3)` | `:ex1` contains all and only members of both `:ex2` and `:ex3` | -| `owl:unionOf` | `:ex1 owl:unionOf (:ex2 :ex3)` | `:ex1` contains all and only members of either `:ex2` or `:ex3` | -| `owl:complementOf` | `:ex1 owl:complementOf :ex2` | `:ex1` contains all and only non-members of `:ex2` | -| `owl:disjointWith` | `:ex1 owl:disjointWith :ex2` | `:ex1` contains no members in common with `:ex2` | -| `owl:AllValuesFrom` | `:ex1 rdf:type owl:Restriction`
`:ex1 owl:onProperty :ex2`
`:ex1 owl:AllValuesFrom :ex3` | `:ex1` contains all and only members that are related by property `:ex2` only to members of `:ex3` | -| `owl:SomeValuesFrom` | `:ex1 rdf:type owl:Restriction`
`:ex1 owl:onProperty :ex2`
`:ex1 owl:SomeValuesFrom :ex3` | `:ex1` contains all and only members that are related by property `:ex2` to at least one member of `:ex3` | - -### Object Property Vocabulary - -The following OWL terms are used to describe the behavior of OWL object properties: - -| OWL Term | Usage Syntax | Meaning | -| :------------------------: | :---------------------------------------: | :-----------------------------------------------------------------------------------------------: | -| `owl:ReflexiveProperty` | `:ex rdf:type owl:ReflexiveProperty` | Every individual is related to itself by `:ex` | -| `owl:IrreflexiveProperty` | `:ex rdf:type owl:IrreflexiveProperty` | No individual is related to itself by `:ex` | -| `owl:SymmetricProperty` | `:ex rdf:type owl:SymmetricProperty` | If A is related to B by `:ex`, then B is related to A by `:ex` | -| `owl:AsymmetricProperty` | `:ex rdf:type owl:AsymmetricProperty` | If A is related to B by `:ex`, then B is not related to A by `:ex` | -| `owl:TransitiveProperty` | `:ex rdf:type owl:TransitiveProperty` | If A is related to B by `:ex`, and B is related to C by `:ex`, then A is related to C by `:ex` | -| `owl:propertyChainAxiom` | `:ex1 owl:propertyChainAxiom (:ex2 :ex3)` | If A is related to B by `:ex2`, and B is related to C by `:ex3`, then A is related to C by `:ex1` | -| `owl:propertyDisjointWith` | `:ex1 owl:propertyDisjointWith :ex2` | If A is related to B by `:ex1`, then A is not related to B by `:ex2` | - -## OWL Profiles - -There are three _profiles_ or _fragments_ of OWL that can be used in place of the complete OWL vocabulary. These profiles avoid some OWL vocabulary in order to increase the efficiency of query and automated reasoning tools used on OWL ontologies. - -OWL profiles are briefly described below: - -- _OWL / EL (Existential Logic)_: OWL / EL is designed for building ontologies that define large numbers of classes and properties. -- _OWL / QL (Query Logic)_: OWL / QL is designed for building ontologies that can be used to query data in [relational databases](https://www.codecademy.com/resources/docs/general/relational-database) through traditional query languages (such as [SQL](https://www.codecademy.com/resources/docs/sql)). -- _OWL / RL (Rules Logic)_: OWL / RL is designed for building ontologies that work with business rules engines. - -## OWL Namespace - -OWL vocabulary is stored at the following _IRI_ (International Resource Identifier): - -> http://www.w3.org/2002/07/owl# - -The prefix `owl` is conventionally used as shorthand for this IRI in OWL ontologies and is used this way in the tables above. - -> **Note:** OWL profiles share the same IRI with full OWL. It is up to the ontology designer to avoid using non-compliant vocabulary when creating an ontology with an OWL profile. diff --git a/content/general/concepts/semantic-technologies/terms/rdf/rdf.md b/content/general/concepts/semantic-technologies/terms/rdf/rdf.md deleted file mode 100644 index 4876acadbf8..00000000000 --- a/content/general/concepts/semantic-technologies/terms/rdf/rdf.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -Title: 'RDF' -Description: 'A language for representing semantic data.' -Subjects: - - 'Data Science' -Tags: - - 'Data' - - 'Semantic' - - 'Metadata' - - 'Tuples' -CatalogContent: - - 'paths/data-science-foundations' - - 'paths/data-science-nlp' ---- - -**Resource Description Framework (RDF)** is a language for representing information. All data within the suite of semantic technologies is represented in RDF. - -## RDF Triples - -RDF represents data in the format of **triples** — ordered sets of three elements. These elements signify a subject, a predicate, and an object. - -An RDF triple can therefore be represented as follows: - -```pseudo -subject, predicate, object -``` - -- _`subject`_: The element which the triple says something about. -- _`predicate`_: A feature or property that applies to `subject`. -- _`object`_: The value of the feature or property represented by `predicate`. - -As an illustration, consider the sentence 'The novel _Pachinko_ was written by Min Jin Lee'. This sentence conveys some information about _Pachinko_, specifically: that it has the characteristic of having an author, and that this author is Min Jin Lee. This information can be represented using the following triple: - -```pseudo -Pachinko, hasAuthor, Min Jin Lee -``` - -### Triple Terms - -In contrast to the above examples, the elements in a valid RDF triple cannot just be any values at all, such as arbitrary strings (e.g., `hasAuthor`). Rather, each of these elements can only be particular values: - -- A `subject` is either an **International Resource Identifier (IRI)**, a **blank node**, or a **quoted triple**. -- A `predicate` must be an IRI. -- An `object` is either an IRI, a blank node, a quoted triple, or a **literal**. - -Each of these terms is explained below: - -- _IRI_: A generalization of [URI](https://www.codecademy.com/resources/docs/general/uri), IRIs identify and link to resources on private and public networks. -- _Quoted triple_: An RDF triple used within a different RDF triple. Quoted triples allow statements to be made within RDF about other RDF statements. -- _Literal_: A value representing a number, string, boolean, date/time, or other simple values. -- _Blank node_: Do not specify a particular entity. Blank nodes allow stating that something stands in a given relationship without identifying what that thing is. - -The following is an example of a triple using IRIs for the subject and predicate, and a literal (integer value) for the object: - -```pseudo -https://www.goodreads.com/en/book/show/130520, http://document-ontology.org/ontology#soldCopies, 2661988 -``` - -## RDF Serializations - -Valid RDF must be written in a concrete RDF syntax, also known as an **RDF serialization**. Two important RDF serializations are briefly described below. - -### Turtle - -**Turtle** is a compact RDF syntax intended to make RDF simple for humans to read and write. - -The most basic way to write RDF statements in Turtle is to enclose IRIs in angle brackets and end each statement with a period, as shown below: - -```pseudo - . -``` - -The above example represents the triple about _Pachinko_ using IRIs that correspond to the subject (_Pachinko_), predicate (hasAuthor), and object (Min Jin Lee). - -However, Turtle allows for simpler formatting of statements by using IRI prefixes and grouping predicates and objects under a common subject, as shown below: - -```pseudo -@base . -@prefix doc: . - - - doc:authoredBy ; - doc:soldCopies 1276201. - - - doc:authoredBy ; - doc:soldCopies 2661988. -``` - -The above example defines prefixes for IRIs that are used multiple times, a shorthand notation useful for improving readability and writing RDF more efficiently. Statements are also grouped under a common subject for the same reasons. - -Turtle documents are saved with the extension `.ttl`. - -### N-Triples - -**N-Triples** is a simple RDF syntax that is a subset of Turtle. This means that anything written in N-Triples is valid in Turtle, but not vice-versa. N-Triples simplifies Turtle to allow RDF to be more compressible and quickly parsable by other technologies that read RDF documents. - -Statements written in N-Triples must use the simple syntax given in the first example of Turtle. The second example, which uses prefixes and grouping predicates, is not valid N-Triples. - -N-Triples documents are saved with the extension `.nt`. diff --git a/content/general/concepts/semantic-technologies/terms/sparql/sparql.md b/content/general/concepts/semantic-technologies/terms/sparql/sparql.md deleted file mode 100644 index 1233423cbab..00000000000 --- a/content/general/concepts/semantic-technologies/terms/sparql/sparql.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -Title: 'SPARQL' -Description: 'A language for querying RDF data.' -Subjects: - - 'Computer Science' - - 'Data Science' -Tags: - - 'Data' - - 'Semantic' - - 'Metadata' -CatalogContent: - - 'paths/data-science-foundations' - - 'paths/data-science-nlp' ---- - -**SPARQL Protocol and RDF Query Language (SPARQL)** is a language used to retrieve and manipulate data stored in [RDF](https://www.codecademy.com/resources/docs/general/semantic-technologies/rdf). - -## Query Patterns - -A **query pattern** is a set of RDF triples with one or more terms in each triple replaced by a variable. SPARQL uses query patterns to identify which data to retrieve when running a query. - -A query pattern is introduced with the keyword `WHERE`. The following is an example of a query pattern with a variable as the object term: - -```pseudo -WHERE { - ?x -} -``` - -As seen above, variables in SPARQL begin with the character `?`. - -A query pattern either matches or does not match any given RDF triple. There is a match if, and only if, there is a triple within the query pattern that shares all the same terms with the other triple, with the exception of any variables. - -For instance, the following triple matches the example query pattern given above: - -```pseudo - . -``` - -Conversely, the following triple does not not match the example query pattern, since it contains a non-matching subject term: - -```pseudo - . -``` - -## Query Forms - -The following keywords are used to implement different types of queries or **query forms**. Query forms differ in what information they return based on a collection of RDF data. - -Here is an example that specifies the RDF data to be queried for the given example queries: - -```sparql -@base . -@prefix doc: . - - - doc:authoredBy ; - doc:title "Pachinko"; - doc:soldCopies 1276201. - - - doc:authoredBy ; - doc:title "The Mosquito Coast"; - doc:soldCopies 2661988. - - - doc:authoredBy ; - doc:title "A Gesture Life" - doc:soldCopies 87740. -``` - -### SELECT - -A **`SELECT`** query returns some of the values of the terms in the RDF data that match with the variables of the query pattern defined within the query. The ones that will be returned among these values are specified in the `SELECT` clause. - -For example, the following query will return the values matching `?title` in the query pattern: - -```sparql -PREFIX doc: -SELECT ?title -WHERE { - ?x doc:title ?title -} -``` - -This results in the below output: - -| ?title | -| :------------------: | -| "Pachinko" | -| "The Mosquito Coast" | -| "A Gesture Life" | - -The special character `*` can be used to return the values matching all variables in the query pattern: - -```sparql -PREFIX doc: -SELECT * -WHERE { - :gesture-life ?x ?y -} -``` - -The above query produces the following output: - -| ?x | ?y | -| :------------: | :-----------------------------------------: | -| doc:authoredBy | https://en.wikipedia.org/wiki/Chang-Rae_Lee | -| doc:title | "A Gesture Life" | -| doc:soldCopies | 87740 | - -### ASK - -An **`ASK`** query returns a value of `true` or `false`. If there are triples in the RDF data matching the query pattern, `true` will be returned. Otherwise, `false` will be returned. - -> **Note:** Query patterns within `ASK` queries do not need to be introduced with a `WHERE` clause. - -The following is an example of an `ASK` query: - -```sparql -PREFIX doc: -ASK { - ?x ?y "Pachinko" -} -``` - -Here is the output: - -```shell -true -``` - -### CONSTRUCT - -A **`CONSTRUCT`** query returns a set of triples based on the query pattern and a template provided in the `CONSTRUCT` clause. The query will take the terms that match the query pattern and insert them into the template to create a new set of triples. - -For example, the following `CONSTRUCT` query would return a set of triples asserting that each object in the RDF data is a book: - -```sparql -PREFIX doc: -CONSTRUCT { - ?x rdf:type doc:isBook -} -WHERE { - ?x ?y ?z -} -``` - -This results in the following output: - -```shell -@base . -@prefix doc: . - - rdf:type doc:isBook. - rdf:type doc:isBook. - rdf:type doc:isBook. -``` - -### DESCRIBE - -A **`DESCRIBE`** query returns a set of triples that describe either an entire set of RDF data or particular terms within that data. The exact information returned by a `DESCRIBE` query is not guaranteed, but rather depends on the implementation of specific SPARQL query processors. - -An example of a `DESCRIBE` query for an entire set of RDF data is as follows: - -```pseudo -DESCRIBE -``` - -This query would return some triples describing the data located in the IRI within the query. - -To create a query that describes a particular term within this data, a query pattern within a `WHERE` clause would be used: - -```sparql -PREFIX doc: -DESCRIBE ?x -WHERE { - ?x doc:title "A Gesture Life" -} -``` - -This query would return some triples describing the term `` within our sample data. - -## Filters - -**Filters** are clauses containing boolean expressions that can be used to restrict the space of matches for a given query pattern. Specifically, a filter eliminates triples that contain terms which, when substituted into the filter clause, result in the expression evaluating as `false` or throwing an error. - -Filters are specified in a query pattern within a `WHERE` clause by using the keyword `FILTER`: - -```pseudo -WHERE { - # A query pattern is defined here - FILTER () -} -``` - -The query will first match the data to the pattern above the `FILTER` clause and then further restrict those matches based on the content of the filter. - -### Functions and Operators Within Filters - -SPARQL includes many functions and operators that can be used within a `FILTER` clause to create boolean expressions. Some examples are given below: - -- Arithmetic functions and logical operators: For example, `=`, `!=` (inequality), `>`, `>=`, `+`, `*`, `||` (logical OR), and `&&` (logical AND). - - Example: `FILTER (?x >= ?y * ?z)` -- `IN` and `NOT IN`: Tests whether a value is contained within a list of other values. - - Example: `FILTER (?x IN (13, 14, 15)) -- `CONTAINS`: Tests whether a string is contained within another string. - - Example: `FILTER (CONTAINS("gmail.com", ?x))` -- `CONCAT`: Concatenates multiple strings together. - - Example: `FILTER (CONTAINS(CONCAT(?x , ".com"), ?y))` - -## Solution Modifiers - -A **solution modifier** is a clause that changes the final output of a SPARQL query. Solution modifiers are applied outside of the query pattern to the set of matching solutions from that query pattern, altering the final data returned to the user. - -Some important types of solution modifiers are given below: - -- `ORDER BY`: Alters the order of a solution. `DESC` can be used to place solutions in a descending order based on a given variable, otherwise the default order is ascending. - - Example: `ORDER BY DESC(?x)` -- `LIMIT`: Limits the number of values returned for a solution. - - Example: `LIMIT 15` -- `OFFSET`: Skips a certain number of values for a solution (only used together with `ORDER BY`). - - Example: `OFFSET 5` diff --git a/content/general/concepts/serialization/serialization.md b/content/general/concepts/serialization/serialization.md deleted file mode 100644 index 95c13461980..00000000000 --- a/content/general/concepts/serialization/serialization.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -Title: 'Serialization' -Description: 'Serialization is the process of translating a complex object into a format that can be deserialized back into a copy of the original object.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Classes' - - 'Data Structures' - - 'JSON' - - 'Objects' -CatalogContent: - - 'learn-java' - - 'paths/computer-science' ---- - -**Serialization** is the process of translating a complex object into a format, typically a string of characters, that can be deserialized back into a copy of the original object. This is beneficial as it allows the software to save the state of an arbitrary object to a destination that can be completely unaware of its details. Any object can be saved to a simple string variable, database field, external file system, third-party application in the [cloud](https://www.codecademy.com/resources/docs/cloud-computing), or even printed out on a sheet of paper. - -Common formats for serialization include [XML](https://www.codecademy.com/resources/docs/general/xml) and [JSON](https://www.codecademy.com/resources/docs/general/json), which have the advantage of being human-readable. However, that is not a requirement, and in some cases, serialization uses other formats such as binary which aren't human-readable. Regardless of the format, the purpose of serialization is that at a later point in time, the serialized data can be read or processed as input and be deserialized back into a copy of the original object. - -When programming languages implement serialization, they often require special declarations in defined classes to make their associated objects serializable and often require special libraries to implement this functionality. - -## Example - -Here is a simple example of serialization in Python: - -```py -import json - -def SerializeDict(input_dict): - print("Serializing input to JSON") - output_str = json.dumps(input_dict) - print(output_str) - -test_dict = { - "make": "Chevy", - "model": "Silverado", - "msrp" : 15000, - "options": ["4-wheel-drive","Towing Package","Heated Seats"], - "year": 2019 -} - -SerializeDict(test_dict) -``` - -The output looks like this: - -```shell -Serializing input to JSON -{"make": "Chevy", "model": "Silverado", "msrp": 15000, "options": ["4-wheel-drive", "Towing Package", "Heated Seats"], "year": 2019} -``` diff --git a/content/general/concepts/server-side-rendering/server-side-rendering.md b/content/general/concepts/server-side-rendering/server-side-rendering.md deleted file mode 100644 index 8652a5b78ec..00000000000 --- a/content/general/concepts/server-side-rendering/server-side-rendering.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -Title: 'Server-Side Rendering' -Description: 'Server-side rendering (SSR) is rendering the content on the server and presenting it to the client when a request is made.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Web Development' - - 'Server-Side Rendering' - - 'Computer Science' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Server-side rendering (SSR)** is rendering the content on the server and presenting it to the client when a request is made. - -When a request is made in client-side rendering (opposite of server-side rendering), the server sends separate files and content that is rendered in the browser. JavaScript works both on the server and browser, so it is possible for developers to render the content of an application where they want. - -## Why SSR is Important - -- When content is rendered on a server, the time required for downloading, parsing, and executing JavaScript code is reduced. This will ensure faster load times for web pages. - -- SSR helps in improving SEO (search engine optimization) by pre-rendering the page. Thus, search engine crawlers can easily read the generated HTML file. In client-side rendering, crawlers read an empty HTML file with links to JavaScript that reduce the search ranking of the web page. Fast loading of the server-side rendered web page also helps the site rank higher in search results. - -## Disadvantages - -When the user clicks on a link for some content, the whole website is rendered again on the server. And if the number of concurrent users increases, the load on the servers increases. At scale, this can be troubling and expensive for SSR. - -SSR applications can also be more complex to build. For example, setting up SSR with React can be a little intimidating. This has been made easier in the recent years with the [Next.js](https://www.codecademy.com/resources/docs/open-source/next-js) framework. diff --git a/content/general/concepts/server/server.md b/content/general/concepts/server/server.md deleted file mode 100644 index e8abb0cfbd1..00000000000 --- a/content/general/concepts/server/server.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -Title: 'Server' -Description: 'A server is a hardware or software device used to provide resources to clients or requesting applications. Servers run on an architecture for fulfilling requests called the "Client-Server Model", which works by the client asking the server for specific data in an agreed upon format and the server readying and providing the data.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -A **server** is a hardware or software device used to provide resources to clients or requesting applications. Servers run on an architecture for fulfilling requests called the "Client-Server Model", which works by the client asking the server for specific data in an agreed upon format and the server readying and providing the data. - -The internet largely runs based on this client-server model. The term server is broad enough to encompass the myriad of specific servers that can be found today such as web servers, game servers, email servers, and proxy servers to name a few. - -## Data Centers - -Large groups of servers can be referred to as data centers. As data center level scale, maintenance of servers requires diligent control of physical environments such as the temperature of locations housing servers, redundancy, etc. Cooling servers is very important at data center level server scale because servers emit heat (especially in close proximity to one another) and therefore need to be cooled down with fans and temperature control measures like air conditioning which at scale can be quite substantial in terms of resources. - -## Virtualization and Beyond - -In the early days of computing, a single server could be used to provide data to a client resource. Eventually, a single server could serve several clients and one client could communicate with several servers. These days server technology has advanced so that multiple servers can be placed on a single physical server using hypervisors. The ability to host multiple servers on a single device is known as virtualization, and has led to exponential leaps in computing power, and efficiency in application deployment. diff --git a/content/general/concepts/socket-io/socket-io.md b/content/general/concepts/socket-io/socket-io.md deleted file mode 100644 index 4e7402d8e20..00000000000 --- a/content/general/concepts/socket-io/socket-io.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -Title: 'Socket.IO' -Description: 'Socket.IO is a JavaScript library that enables real-time, bidirectional, and event-based communication between the browser and the server. It consists of: - Server-side library for Node.js - Client-side library for the browser (which can be also run from Node.js) In simpler terms, Socket.IO enables live communication between computers. It simplifies the process to write messaging applications like video chat, audio chat, and text chat. Some of the companies that use Socket.IO include Alibaba Travels, PLAID, Trello, and Patreon.' -Subjects: - - 'Web Development' - - 'Computer Science' -Tags: - - 'Libraries' - - 'HTTP' - - 'Developer Tools' -CatalogContent: - - 'paths/front-end-engineer-career-path' - - 'paths/computer-science' ---- - -**Socket.IO** is a JavaScript library that enables real-time, bidirectional, and event-based communication between the browser and the server. It consists of: - -- Server-side library for Node.js -- Client-side library for the browser (which can be also run from Node.js) - -In simpler terms, Socket.IO enables live communication between computers. It simplifies the process to write messaging applications like video chat, audio chat, and text chat. - -Some of the companies that use Socket.IO include Alibaba Travels, PLAID, Trello, and Patreon. diff --git a/content/general/concepts/software-development-life-cycle/software-development-life-cycle.md b/content/general/concepts/software-development-life-cycle/software-development-life-cycle.md deleted file mode 100644 index 417727d39d2..00000000000 --- a/content/general/concepts/software-development-life-cycle/software-development-life-cycle.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -Title: 'Software Development Life Cycle' -Description: 'The Software Development Life Cycle (SDLC) is a process that is used to efficiently produce cost-effective and high-quality software through a series of structured steps or phases.' -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'Development' - - 'Models' -CatalogContent: - - 'learn-how-to-code' - - 'paths/full-stack-engineer-career-path' ---- - -The **Software Development Life Cycle (SDLC)** is a structured process that is ideally used to efficiently produce cost-effective and high-quality software. It is a standard industry approach to software development that documents an entire project and timeline. Through clear documentation, internal stakeholders can collectively understand the direction of a project. - -## Phases - -The SDLC phases are as follows: - -1. Plan: The phase where requirement gathering and analysis takes place. It involves brainstorming ideas to solve some problem as a result of customer feedback or need. -2. Define: The phase where requirement defining takes place and involves creating a Software Requirement Specification (SRS). The SRS document defines the purpose, product, and technical requirements. This allows everyone working on the software to understand the product's mission. -3. Design: Based on the SRS and results in a Design Document Specification (DDS). The DDS is reviewed by all stakeholders based on a set of criteria. -4. Develop: The building phase that deals with reviewing and implementing code that will be integrated into the software. -5. Test and Integrate: The phase that [software tests](https://www.codecademy.com/resources/docs/general/software-testing) are performed to determine if the software satisfies the SRS. If it meets requirements, then the product or feature is integrated into the software. -6. Maintain: An ongoing phase that involves supporting and updating the software as needed. - -## Models - -The Waterfall Model was the first model to be created, however, there are currently many different models for implementing a SDLC: - -- Agile: Iterative development and continuous integration. The scrum methodology is a common implementation of the agile model in which teams work in sprints. Sprints are time-constrained periods where a team works to complete a certain goal. -- Big Bang: Named after the physical theory, this model involves creating a product through available resources for technical development. There is little planning or documenting. -- Iterative: Depending on the requirements of the product, the software is modified upon each iteration and changes are released as a new version of the software. -- Prototype: A prototype, that does not necessarily represent the final logic of the software, is created and tested until it meets requirements for deployment or integration. -- Rapid Application Development (RAD): Meets requirements through prototyping iteratively. -- Spiral: Based on the waterfall and iterative models. -- V: Based on the waterfall model. -- Waterfall: The goal is to create a minimum viable product (MVP). Each phase in the SDLC must be completed before moving on to the next phase. diff --git a/content/general/concepts/software-development-life-cycle/terms/agile-model/agile-model.md b/content/general/concepts/software-development-life-cycle/terms/agile-model/agile-model.md deleted file mode 100644 index 86066dbfd86..00000000000 --- a/content/general/concepts/software-development-life-cycle/terms/agile-model/agile-model.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -Title: 'Agile Model' -Description: 'Emphasizes iteration, flexibility, and cross-team collaboration.' -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'Development' - - 'Models' -CatalogContent: - - 'learn-how-to-code' - - 'paths/full-stack-engineer-career-path' ---- - -**Agile** is a software development methodology that emphasizes iteration, flexibility and cross-team collaboration. - -Agile as a defined development methodology is fairly new. In 2001, a group of 17 software developers calling themselves the Agile Alliance published the [Agile Manifesto](https://www.agilealliance.org/agile101/the-agile-manifesto/), which consists of 4 values and [12 principles](https://www.agilealliance.org/agile101/12-principles-behind-the-agile-manifesto). Taken together, these documents argue that software development should incorporate numerous opportunities for user feedback, be created by self-organized cross-functional teams, and demonstrate tangible progress every few weeks. - -## The Agile Ecosystem - -Since its inception, several distinct Agile frameworks have been developed and become popular in the tech sector. Two of the most popular of these are Scrum and Lean. An important note is that while these frameworks are often used interchangeably with Agile, they are not the same. Agile is a general set of development principles, Lean and Scrum are specific frameworks for carrying out those principles. While these and other frameworks have important differences in implementation, they all share a number of features, which are: - -- Work is completed by a self-organized, cross-functional team. -- Work is completed in 2-4 week intervals, often called sprints. -- There is an emphasis on communication, reflection, and iteration before, during, and after these sprints. - -Many organizations that practice agile development incorporate aspects of multiple frameworks. Therefore, those looking for a career in software development, operations, or devops would benefit from familiarizing themselves with a few different strategies. diff --git a/content/general/concepts/software-development-life-cycle/terms/big-bang-model/big-bang-model.md b/content/general/concepts/software-development-life-cycle/terms/big-bang-model/big-bang-model.md deleted file mode 100644 index a81582a5f08..00000000000 --- a/content/general/concepts/software-development-life-cycle/terms/big-bang-model/big-bang-model.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -Title: 'Big Bang Model' -Description: 'A software development model without specific processes.' -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'Development' - - 'Models' -CatalogContent: - - 'learn-how-to-code' - - 'paths/full-stack-engineer-career-path' ---- - -The **Big Bang model** is a [Software Development Life Cycle](https://www.codecademy.com/resources/docs/general/software-development-life-cycle) (SDLC) model without specific processes. - -The Big Bang model requires no or minimal planning. Instead, the development starts with acquiring the inputs, such as: - -- Time. -- Effort. -- Resources. - -This model focuses on software development so developers can jump straight to the implementation to create software as the outcome. - -The diagram below shows an overview of the Big Bang model: - -![SDLC Big Bang Model](https://raw.githubusercontent.com/Codecademy/docs/main/media/sdlc-bigbang.png) - -## Use-cases - -The Big Bang model is best suited in the following cases: - -- smaller or simple projects, -- small development teams, -- when requirements are not specified at the start of the project or can change during the development, -- experimental projects, -- projects for learning purposes. - -## Advantages - -The strength of the Big Bang model lies in its simplicity. This model can offer the following advantages: - -- it requires no or minimal planning, -- it is easy to understand the process and manage the project, -- it can be time and cost-effective, -- it requires few resources, -- it provides flexibility for developers and also the project. - -## Disadvantages - -The Big Bang model, mainly due to the minimal planning included in it, has the following disadvantages: - -- it is not suitable for complex, larger or ongoing projects, -- it comes with uncertainty, can have high risks and low reliability, -- unclear requirements at the beginning of the development can create higher costs or longer developmental times for the final product. diff --git a/content/general/concepts/software-development-life-cycle/terms/iterative-model/iterative-model.md b/content/general/concepts/software-development-life-cycle/terms/iterative-model/iterative-model.md deleted file mode 100644 index c7be8003545..00000000000 --- a/content/general/concepts/software-development-life-cycle/terms/iterative-model/iterative-model.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -Title: 'Iterative Model' -Description: 'An approach to software development that emphasizes the importance of incremental progress and continuous feedback in the software development lifecycle (SDLC).' -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'Documentation' - - 'Best Practices' - - 'Development' -CatalogContent: - - 'introduction-to-open-source' - - 'paths/computer-science' ---- - -The **Iterative model** to software development is a methodology that emphasizes the importance of incremental progress and continuous feedback in the software development lifecycle (SDLC). This approach involves breaking down a larger project into smaller, more manageable chunks that can be developed, tested, and deployed in shorter time frames. Each iteration builds upon the previous one, with feedback and adjustments being incorporated into subsequent iterations. - -## Origins - -The origins of the Iterative model can be traced back to the 1950s and 1960s when software development was in its infancy. However, the model only began to gain wider acceptance and use in the 1980s. At that time, software development was viewed as a linear process that involved several distinct stages, such as requirements gathering, design, coding, testing, and maintenance. However, as software projects became larger and more complex, it became clear that this linear approach was inadequate. In response, software developers began to experiment with approaches that used iteration, emphasizing incremental progress and continuous feedback. - -## Current Usage - -Today, the Iterative model is widely used in software development and is seen as an effective way to manage complex projects that involve multiple stakeholders, changing requirements, and evolving technologies. It is particularly well-suited for agile development methodologies that emphasize collaboration, flexibility, and adaptability. - -## Advantages - -Some of the benefits of the Iterative model include: - -- Improved flexibility: Allows developers to respond quickly to changing requirements and adapt to new technologies as they emerge. -- Increased collaboration: Emphasizes collaboration between developers, customers, and other stakeholders, which can lead to better communication and a more effective development process. -- Better risk management: Allows developers to identify and mitigate potential risks early in the development process, reducing the likelihood of costly errors later on. - -## Disadvantages - -- Increased complexity: This approach can make the development process more complex as it involves frequent changes and modifications to the requirements and design. This can lead to confusion and difficulties in managing the project. -- Costly: Iterative development can be more costly than traditional development methods due to the need for frequent testing and rework. Additionally, the need for continuous feedback and collaboration can increase project overheads. -- Time-consuming: This model of development can be time-consuming due to the need for frequent testing and rework. This can lead to delays in the project timeline and increased time to market. -- Can be difficult to manage: Managing iterative development can be challenging, especially when dealing with large teams and complex projects. It can be difficult to keep track of changes and ensure that everyone is working towards the same goal. -- Requires experienced team members: The success of the Iterative model depends on having experienced team members who can effectively manage the development process, provide feedback, and make decisions quickly. This can be a challenge for organizations that lack the necessary talent or resources. - -Overall, the Iterative model is an important methodology for software development today. It provides a flexible, collaborative, and adaptive framework for managing complex projects and delivering high-quality software. By emphasizing incremental progress and continuous feedback, this approach allows developers to respond quickly to changing requirements and customer feedback, ensuring that the final product meets the needs of its users. diff --git a/content/general/concepts/software-development-life-cycle/terms/prototype-model/prototype-model.md b/content/general/concepts/software-development-life-cycle/terms/prototype-model/prototype-model.md deleted file mode 100644 index 02282a972aa..00000000000 --- a/content/general/concepts/software-development-life-cycle/terms/prototype-model/prototype-model.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -Title: 'Prototype Model' -Description: 'The Prototype model involves creating a simplified model of the product to test its concept and functionality.' -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'Development' - - 'Models' -CatalogContent: - - 'learn-how-to-code' - - 'paths/full-stack-engineer-career-path' ---- - -The **Prototype model** is a software development approach that involves creating a simplified model of the future product to test its concept and functionality with minimal resource costs. The process of creating a prototype involves a few steps based on testing results and feedback: development, testing, and continuous improvement. - -The prototype may include only the essential design elements and features that are necessary for visualizing and demonstrating the fundamental capabilities of the product. Prototypes are used by the development team in collaboration with customers and stakeholders to test the product's design, architecture, and functionality. - -## Objectives of Prototype Model - -1. Idea testing: Prototyping can determine the potential of an idea before the final product is created. -2. Obtaining feedback: Prototypes provide an opportunity to receive feedback from users, colleagues, or investors, which can help improve the product. -3. Reducing time and development costs: Prototyping helps identify problems early in the development process, reducing the time and costs associated with correcting errors in the future and improving the product's quality. -4. Improving communication between teams: By creating a prototype, the product takes on a tangible form and ceases to be abstract, making it easier to discuss the idea among project participants. -5. Convincing stakeholders: Prototypes are an effective way to demonstrate a product's potential to investors, clients, or management, which can provide necessary support and financing. - -## Types of Prototypes - -Prototypes can be classified by the method of creation: - -1. Paper prototype: The simplest and fastest to create, requiring only pen and paper. It’s great for initial versions of prototypes. Paper prototypes show the structure and design of the product, as well as its basic functional elements. -2. Digital prototype: Created in specialized software and services for prototyping. Digital prototypes accurately show product functionality and may contain additional elements, such as animations and interactive components. - -Prototypes can also be classified by the level of detail: - -1. Low-fidelity prototype: Reflects the basic structure and functionality of the product, but does not include detailed design such as interface elements. -2. High-fidelity prototype: A detailed and interactive prototype that includes interface design and other elements that will be present in the final product. - -## Stages in the Prototype Model - -1. Requirements gathering: At this stage, the project team communicates with customers, conducts research, and collects all the requirements for the future product. -2. Design: At this stage, the structure and design of the product are determined. For example, for a website, this would include the number of pages, the purpose of each page, and the placement of key elements. -3. Prototyping: Creating a prototype using the design that was developed in the previous stage. -4. Prototype testing and feedback collection: The developed prototype is tested to identify errors and areas for improvement. -5. Prototype refinement: The feedback obtained from testing is used to improve the prototype and meet the requirements of the product. -6. Development: After the prototype has been refined and meets customer requirements, the team moves on to the final product development. - -The Prototype model follows an iterative development process, where testing and feedback collection are conducted for each new version of the prototype. Based on the results of testing and new requirements for improving the prototype are formed, and a new version is released. This process is repeated until the prototype satisfies the interests of all project participants. diff --git a/content/general/concepts/software-development-life-cycle/terms/rapid-application-development/rapid-application-development.md b/content/general/concepts/software-development-life-cycle/terms/rapid-application-development/rapid-application-development.md deleted file mode 100644 index 54adaf63390..00000000000 --- a/content/general/concepts/software-development-life-cycle/terms/rapid-application-development/rapid-application-development.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -Title: 'Rapid Application Development (RAD)' -Description: 'Rapid Application Development (RAD) is a software development methodology that emphasizes quick prototyping and iterative development to meet the requirements of a project.' -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'Documentation' - - 'Best Practices' - - 'Development' -CatalogContent: - - 'introduction-to-open-source' - - 'paths/computer-science' ---- - -**Rapid Application Development (RAD)** is a software development methodology that emphasizes quick prototyping and iterative development to meet the requirements of a project. The primary goal of RAD is to reduce development time and costs by quickly delivering a working prototype to the client for feedback and iteration. - -## Origins - -RAD was developed in the 1980s by James Martin as a response to the Waterfall model, which was the dominant methodology at the time. Martin wanted to create a more efficient approach to software development that could handle fast-changing requirements and enable quick delivery of applications. The RAD approach was based on iterative development, where the emphasis was on building a prototype quickly and then refining it based on feedback from stakeholders. - -## Methodology - -RAD involves a collaborative approach where developers work closely with stakeholders to identify requirements, design, prototype, develop, and test the software. The process is iterative, meaning that feedback from the client is used to refine the prototype until the final product is delivered. RAD is particularly useful for projects with fast-changing requirements and where time-to-market is critical. - -## Phases of Rapid Application Development - -RAD typically consists of four phases: - -1. **Requirements Planning:** Project team collaborates with stakeholders to identify and prioritize software requirements. User involvement ensures understanding of needs and expectations. -2. **User Design:** Prototypes and mock-ups are created through rapid iterations of design, implementation, and testing. Functional prototypes are demonstrated to gather feedback and validation from users and stakeholders. -3. **Construction:** Coding and development of the software system takes place, emphasizing speed and efficiency. Reusable components and existing frameworks are utilized. Iterative development, frequent testing, and user feedback ensure meeting desired requirements. -4. **Cutover:** Transition from development to production environment occurs, involving final testing, deployment, and user training. Thorough testing identifies and resolves remaining issues. After successful testing, the system is deployed, and users are trained for effective software usage. - -## Advantages - -- Rapid prototyping and iterative development ensure that the final product meets the client's needs. -- Reduces development time and costs. -- Collaboration between developers and stakeholders ensures that the project's requirements are met. -- Flexible and adaptable which is ideal for projects with rapidly changing requirements. -- Improved time-to-market, as prototypes can be quickly delivered to the client for feedback. - -## Disadvantages - -- Can result in a poorly architected system if the focus is on delivering quickly over robust architectural design. -- Requires significant collaboration between developers and stakeholders, which can be challenging. -- May not be suitable for complex projects where requirements are not well defined or where there are significant technical constraints. -- Quality of the final product may be compromised if fast delivery is emphasized over quality. -- Requires skilled developers with expertise in rapid prototyping and iterative development. - -While the RAD methodology's emphasis on rapid prototyping and iterative development has its advantages, it also has the potential for poorly designed software. The use of RAD should be considered on a case-by-case basis, depending on the project's specific requirements and constraints. diff --git a/content/general/concepts/software-development-life-cycle/terms/spiral-model/spiral-model.md b/content/general/concepts/software-development-life-cycle/terms/spiral-model/spiral-model.md deleted file mode 100644 index 25b8ad33734..00000000000 --- a/content/general/concepts/software-development-life-cycle/terms/spiral-model/spiral-model.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -Title: 'Spiral Model' -Description: 'Combines the Waterfall model with iterative development.' -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'Development' - - 'Models' -CatalogContent: - - 'learn-how-to-code' - - 'paths/full-stack-engineer-career-path' ---- - -The **Spiral model** is a Software Development Life Cycle (SDLC) that combines the [Waterfall model](https://www.codecademy.com/resources/docs/general/software-development-life-cycle/waterfall-model) and iterative development approaches. Each phase within this model involves risk analysis and prototyping. - -The Spiral model was first introduced by Barry Boehm in 1986 as a result of applying iterative development in constructing software. It is divided into four phases: - -1. Planning -2. Risk Analysis -3. Engineering -4. Evaluation - -Each iteration consists of all above phases but has different aims which are usually: - -- Prototype -- Release candidate -- Launch - -## Advantages - -- Products are prototyped for quick introduction. -- Errors and failures are identified and handled as they arise. -- Frequent feedback and refinement through cycles. -- Flexible and adaptive to changes. - -## Disadvantages - -- Complex workflow and requires expertise especially in risk analysis. -- Costly and time-consuming. diff --git a/content/general/concepts/software-development-life-cycle/terms/v-model/v-model.md b/content/general/concepts/software-development-life-cycle/terms/v-model/v-model.md deleted file mode 100644 index c5e3090e018..00000000000 --- a/content/general/concepts/software-development-life-cycle/terms/v-model/v-model.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -Title: 'V Model' -Description: 'Focused on the validation and verification of the product.' -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'Development' - - 'Models' -CatalogContent: - - 'learn-how-to-code' - - 'paths/full-stack-engineer-career-path' ---- - -The **V model** is a Software Development Life Cycle (SDLC) that is based on the [Waterfall model](https://www.codecademy.com/resources/docs/general/software-development-life-cycle/waterfall-model) and emphasizes the verification and validation of the product. Each phase of this model is paired with a level of testing. - -The V model was first implemented in the late twentieth century and has been widely used ever since. It can be divided in five main phases: - -1. Requirements analysis -2. System design -3. Architectural design -4. Module design -5. Coding - -Except for coding, the other four phases are each linked to a distinct testing activity. Going up from the bottom (module design), those testing activities are, respectively: - -- Unit testing -- Integration testing -- System testing -- Acceptance testing - -## Advantages - -- Testing within each stage ensures each requirement is properly checked and validated, and that the product is of high quality and fulfills the requirements. -- Errors and issues can be detected at early stages of development due to an emphasis on testing early and often. -- Easy management and project planning. - -## Disadvantages - -- Unsuitable for large and complex projects or that require constant changes. -- Uncertain and risky due to lack of risk analysis. diff --git a/content/general/concepts/software-development-life-cycle/terms/waterfall-model/waterfall-model.md b/content/general/concepts/software-development-life-cycle/terms/waterfall-model/waterfall-model.md deleted file mode 100644 index 7079bb2e428..00000000000 --- a/content/general/concepts/software-development-life-cycle/terms/waterfall-model/waterfall-model.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -Title: 'Waterfall Model' -Description: 'Creates a minimum viable product through phases that are completed in a specific order.' -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'Development' - - 'Models' -CatalogContent: - - 'learn-how-to-code' - - 'paths/full-stack-engineer-career-path' ---- - -The **Waterfall model** is a Software Development Life Cycle (SDLC) that aims to create a minimum viable product (MVP). Each phase in this SDLC must be completed before moving on to the next. It is suited to projects where features are easily defined from the start. - -The Waterfall model was the first SDLC methodology to be created and was first documented in 1970 by American computer scientist Dr. Winston W. Royce, though the term "waterfall" wasn't used until later. - -The diagram below shows how the workflow mirrors the natural flow of a waterfall, with the stages being completed in linear, sequential steps: - -![SDLC Waterfall Model](https://raw.githubusercontent.com/Codecademy/docs/main/media/sdlc-waterfall.jpg) - -## Advantages - -- Clear, defined structure. -- Easy to predict project timeline, budget, and scope. - -## Disadvantages - -- Difficult to make changes once the project is underway. -- Testing is delayed until development is completed, so errors aren't found until later. diff --git a/content/general/concepts/software-engineering/software-engineering.md b/content/general/concepts/software-engineering/software-engineering.md deleted file mode 100644 index 685dad17d2e..00000000000 --- a/content/general/concepts/software-engineering/software-engineering.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -Title: 'Software Engineering' -Description: 'Software engineering is a field of study that involves using engineering principles to design, build, test, and maintain software systems.' -Subjects: - - 'Web Development' - - 'Computer Science' -Tags: - - 'Development' - - 'Servers' - - 'Frameworks' - - 'Developer Tools' -CatalogContent: - - 'learn-how-to-code' - - 'paths/full-stack-engineer-career-path' ---- - -**Software engineering** is a field of study that involves using engineering principles to design, build, [test](https://www.codecademy.com/resources/docs/general/software-testing), and maintain software systems. Software engineers need to understand how to write quality code and use various tools and [frameworks](https://www.codecademy.com/resources/docs/general/framework) to perform these tasks. There are many programming languages used in software engineering, including [JavaScript](https://www.codecademy.com/resources/docs/javascript), [Java](https://www.codecademy.com/resources/docs/java), [C#](https://www.codecademy.com/resources/docs/c-sharp), [Python](https://www.codecademy.com/resources/docs/python), and more. - -## Software Engineering vs. Computer Science - -Software engineering and computer science are closely related, and many software engineers have degrees or certifications in computer science. Both fields include fundamental information on computer science and programming. However, a key difference is that computer science focuses more on theoretical and mathematical aspects related to computing, and software engineering focuses more on practical aspects related to building software systems. - -Software engineers apply their knowledge of computer science to address the practical problems related to software development and maintenance. Software engineering also involves implementing some of the many topics which come out of computer science. - -Additionally, software engineers must perform other tasks that relate to the [software development life cycle](https://www.codecademy.com/resources/docs/general/software-development-life-cycle). This can include quality assurance, documentation, and working with clients or stakeholders. - -## Types of Software Engineers - -Software engineers are commonly categorized into three types: front-end, back-end, and full-stack. - -### Front-End Engineers - -A [front-end](https://www.codecademy.com/resources/docs/general/front-end) engineer creates and manages the user-facing components of an application, such as a website. They typically work on web applications, although some front-end engineers work on desktop and mobile applications. Front-end engineers are familiar with programming languages such as JavaScript, [TypeScript](https://www.codecademy.com/resources/docs/typescript), [Ruby](https://www.codecademy.com/resources/docs/ruby), as well as mark-up languages [HTML](https://www.codecademy.com/resources/docs/html), and [CSS](https://www.codecademy.com/resources/docs/css). They also use web development tools and frameworks, such as [Angular](https://www.codecademy.com/resources/docs/open-source/angular), [React](https://www.codecademy.com/resources/docs/react), and [Bootstrap](https://www.codecademy.com/resources/docs/open-source/bootstrap). - -### Back-End Engineers - -A [back-end](https://www.codecademy.com/resources/docs/general/back-end) engineer creates and manages the [server](https://www.codecademy.com/resources/docs/general/server)-side components of an application. Many back-end engineers also interact with [databases](https://www.codecademy.com/resources/docs/general/database), because servers communicate with databases to manage data processing and storage. Back-end engineers are familiar with languages such as Java, C#, Python, [C](https://www.codecademy.com/resources/docs/c), [C++](https://www.codecademy.com/resources/docs/cpp), and [SQL](https://www.codecademy.com/resources/docs/sql). They also use many databases, frameworks, and environments, such as [Node.js](https://www.codecademy.com/resources/docs/open-source/node-js), [Ruby on Rails](https://www.codecademy.com/resources/docs/ruby/ruby-on-rails), Django, MySQL, and MongoDB. - -### Full-Stack Engineers - -A [full-stack](https://www.codecademy.com/resources/docs/general/full-stack) engineer performs front-end and back-end software engineering tasks. They typically work on web applications, although some full-stack engineers work on desktop and mobile applications. Full-stack engineers have the skills to work on the user interface, server, and database components of an application. They are also familiar with an assortment of front-end and back-end languages, tools, and frameworks. - -## Where Do Software Engineers Work? - -Software engineers work in a variety of industries. Although many software engineers work at tech companies, there are other industries that hire software engineers, such as financial institutions, healthcare organizations, government agencies, and education institutions. diff --git a/content/general/concepts/software-testing/software-testing.md b/content/general/concepts/software-testing/software-testing.md deleted file mode 100644 index c16afd45d24..00000000000 --- a/content/general/concepts/software-testing/software-testing.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -Title: 'Software Testing' -Description: 'Software testing refers to the process of verifying and evaluating the function of a software application or product.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Conceptual' - - 'Developer Tools' - - 'Development' -CatalogContent: - - 'learn-testing-for-web-development' - - 'paths/full-stack-engineer-career-path' ---- - - - -**Software testing** is the process of verifying and evaluating the functionality of a software application or product. It checks if the product meets requirements, reduces and eliminates bugs, and mitigates the long-term costs for a company in terms of any fixes and updates that would be needed. - -It is most common to initiate software testing during the design phase but it can even take place after the deployment phase of the [software development life cycle](https://www.codecademy.com/resources/docs/general/software-development-life-cycle). - -## Testing Types - -There are several kinds of software testing with varying degrees of specificity, including the following: - -- Usability tests can be performed on one or a combination of tasks to see how the programming functions in different user-based scenarios. -- Acceptance testing involves checking to make sure the several functions of a system work as expected. -- Regression testing assesses the impact of new features and helps engineers adjust how each feature affects with the program overall. -- Integration testing aims to figure out how well different components of the app work with each other. -- [Unit testing](https://www.codecademy.com/resources/docs/general/unit-testing) attempts to see how different units of code perform in isolation from the rest of the program. -- Through functional testing, engineers can see how software accomplishes specific, intended purposes. -- Stress tests assess the performance of programs during worst-case scenarios to understand if and how they break. -- Performance testing reveals how the program will perform in more common, real-world scenarios. - -## Testing Strategies - -Two specific techniques are used to assess the stability and performance of software: black-box and white-box testing. Each offers a different perspective into how well the source code holds up. - -- Black-box testing involves testing software without looking inside — the coding, systems, and dependencies. -- White-box testing aims to examine the structure within the application, or the inner workings of the app, as opposed to its overall functionality. - -## Languages Used in Testing - -Some programming languages that are commonly used for testing software include the following: - -- [Java](https://www.codecademy.com/resources/docs/java) -- [Python](https://www.codecademy.com/resources/docs/python) -- [Ruby](https://www.codecademy.com/resources/docs/ruby) diff --git a/content/general/concepts/ssl/ssl.md b/content/general/concepts/ssl/ssl.md deleted file mode 100644 index f33aacd6e06..00000000000 --- a/content/general/concepts/ssl/ssl.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -Title: 'SSL' -Description: 'SSL stands for Secure Socket Layer, and is a cryptographic protocol for securing computer networks.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Web Development' - - 'Computer Science' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Secure Socket Layer (SSL)** is a cryptographic protocol for securing computer networks. - -> **Note**: SSL was deprecated in 1999 and renamed Transport Layer Security (TLS) by the [Internet Engineering Task Force](https://www.ietf.org). TLS is essentially an improved version of SSL (it is SSL 3.1) and features a number of improvements that address security concerns that were discovered in the initial and prior implementations of SSL. - -SSL uses a cryptographic mechanism featuring a public and private key to encrypt data communicating over internet networks. SSL uses a protocol known as a 'handshake' to determine the authenticity of a server. The main advantage of SSL is the confidence it gives to users that a server has been authenticated by a trusted Certificate Authority (CA). Valid SSL certs can only be issued by accredited Certificate Authorities which have rigid standards for issuing them. - -SSL validation can be instantly recognized on the web by seeing a green padlock in the url portion of a browser, in addition to traffic going over HTTPS. - -These days Google ranks pages higher due to SSL cert verification and many browsers outright discourage or prevent their users from viewing sites that are lacking TLS/SSL validation. - -## Benefits of SSL include - -- E-commerce trust: Users who see a green padlock on e-commerce sites are more likely to go through with the transaction because they trust that the site is secure. -- It gives users peace of mind that the website is handling data with integrity and that data has not been tampered as its being transferred between networks. -- Encryption of data so that it is not viewable as plain text when being transferred. diff --git a/content/general/concepts/static-site-generators/static-site-generators.md b/content/general/concepts/static-site-generators/static-site-generators.md deleted file mode 100644 index 143b4184293..00000000000 --- a/content/general/concepts/static-site-generators/static-site-generators.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -Title: 'Static Site Generators' -Description: 'A static site generator (SSG) is a tool used to render webpages on a server at build time, prior to when a client makes a request.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Static Site' - - 'Server-Side Rendering' -CatalogContent: - - 'paths/computer-science' - - 'paths/full-stack-engineer-career-path' ---- - -A **static site generator (SSG)** is a tool used to render webpages on a [server](https://www.codecademy.com/resources/docs/general/server) at build time, before a client makes a request. - -## Evolution of Webpage Rendering - -In the early days of the web, websites were served as static pages in the form of multiple [HTML](https://www.codecademy.com/resources/docs/html) files. A client would make a request to a server and in return, receive a set of unchanging (i.e., static) resources. Any visible changes to the site would need to be made by manually editing the HTML hosted on the server. - -However, as the web evolved, websites were no longer limited to providing static content. [Server-side rendering (SSR)](https://www.codecademy.com/resources/docs/general/server-side-rendering) was adopted and allowed for content to be “customized” dynamically. Content management systems (CMSs), such as WordPress and Drupal, employ an SSR approach and were introduced in response to the growing amount of content that needed to be maintained. - -## How SSGs Differ from CMSs - -Static site generation is a concept that leverages the benefits of static pages and CMSs. Like CMSs, the content (data) and the structure (templates) are decoupled, but instead of the server generating the page at the time of a request, the page is pre-rendered at build time. The page can now be served as a static file in response to a client request, eliminating the time associated with generating the page on demand. - -## Examples of SSGs - -Some commonly used SSGs include: - -- [Jekyll](https://jekyllrb.com/) -- [Hugo](https://gohugo.io/) -- [Gatsby](https://www.gatsbyjs.com/) -- [Next.js](https://www.codecademy.com/resources/docs/open-source/next-js). - -A comprehensive list of SSGs available in different languages is available at [staticgen.com](http://staticgen.com). - -## Benefits of SSGs - -- **SEO-friendliness**: Since pages are built ahead of time, they are easier for search engine web crawlers to parse in contrast to websites that require client-side rendering (e.g., single-page applications). -- **CDN-friendliness**: Pre-built pages can be served from a [content delivery network (CDN)](https://www.codecademy.com/resources/docs/general/cdn) close to the end user since there’s no need to execute server logic or obtain data from a [database](https://www.codecademy.com/resources/docs/general/database), making the page quickly accessible. -- **Security**: It’s much more challenging for bad actors to inject malicious code since the served pages are static and don’t require processing at the time of a request. -- **Scalability**: Since server-side logic is performed ahead of time, an increase in the number of concurrent users has less impact on the server load compared to SSR performed at request time. This makes it easier to scale to a large number of users, especially if using a CDN. diff --git a/content/general/concepts/statistics/statistics.md b/content/general/concepts/statistics/statistics.md deleted file mode 100644 index bc7678cd56c..00000000000 --- a/content/general/concepts/statistics/statistics.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -Title: 'Statistics' -Description: 'Statistics is the science that is concerned with methods for collecting, organizing, analyzing, and interpreting data.' -Subjects: - - 'Data Science' - - 'Computer Science' -Tags: - - 'Statistics' - - 'Data' - - 'NumPy' -CatalogContent: - - 'paths/data-science-foundations' - - 'learn/statistics-mean-median-mode-course' ---- - -**Statistics** is the science that is concerned with methods for collecting, organizing, analyzing, and interpreting **data**. Data refers to any collection of facts, such as numbers, words, measurements, or descriptive details. In the realm of statistics, data can be used to find correlations, make predictions, and draw conclusions about a population based on a sample. Visual representations such as charts make data easier to analyze and understand. - -## Fields That Use Statistics - -Statistics is used extensively in fields such as computer science, economics, sociology, physics, and many more. It is also a core component of **machine learning**, a subset of artificial intelligence that uses algorithms to perform specific tasks without explicit instructions. Machine learning algorithms require statistical methods to extract significant patterns, relationships, and insights from complex datasets. - -## Working With Data as a Developer - -**Python** is the most popular programming language for data science. It is used for data analysis, data visualization, machine learning, and many more. Python is a great choice for beginners because it is easy to learn and has a wide range of applications. It has support for libraries such as: - -- [NumPy](https://www.codecademy.com/resources/docs/numpy) is used for working with arrays and matrices of numerical data. It provides a wide range of mathematical functions and is widely used in scientific computing. -- [Pandas](https://www.codecademy.com/resources/docs/pandas) is used for data manipulation and analysis. It provides data structures for efficiently storing and manipulating large datasets, as well as tools for cleaning, transforming, and analyzing data. -- [Matplotlib](https://www.codecademy.com/resources/docs/matplotlib) is used for creating static, animated, and interactive visualizations in Python. It provides a wide range of plotting functions and is widely used in scientific computing and data analysis. -- Scikit-learn is used for machine learning in Python. It provides a wide range of tools for classification, regression, clustering, and dimensionality reduction, as well as tools for model selection and evaluation. diff --git a/content/general/concepts/subroutine/subroutine.md b/content/general/concepts/subroutine/subroutine.md deleted file mode 100644 index 555a1f39826..00000000000 --- a/content/general/concepts/subroutine/subroutine.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -Title: 'Subroutine' -Description: 'A subroutine is a set of computer instructions written to perform specific tasks.' -Subjects: - - 'Computer Science' -Tags: - - 'Subroutine' - - 'Functions' -CatalogContent: - - 'paths/code-foundations' - - 'learn-how-to-code' ---- - -A **subroutine** is a set of computer instructions written to perform specific tasks. It is also known as a function or a procedure. A subroutine packages code for an operation or a set of operations, which makes code reusable and readable. - -## Syntax - -Every programming language has its own syntax for defining and calling a subroutine or function. Often, the basic format of a subroutine will follow the model below: - -Pseudo code for declaring a subroutine: - -```pseudo -declare - # subroutine code -end -``` - -Pseudo code for calling a subroutine: - -```pseudo -call -``` - -In modern programming languages, we use functions that are similar to subroutines. These functions take in argument(s) and may return some value(s) after execution. - -Let's look at subroutine in JavaScript syntax. - -A function, `func_name()`, is declared and takes in any number of arguments: - -```js -function func_name(/* var1, var2, var3,... */) { - // Function body - - // Return statement is optional - return return_value; -} -``` - -To call or invoke the function with any number of arguments: - -```js -func_name(/* var1, var2, var3,... */); -``` - -## Codebyte Example - -```codebyte/js -function sum(var1, var2) { - let return_value = var1 + var2; - return return_value; -} - -let total = sum(10, 12); - -console.log(total); -``` - -## Subroutines/Functions in Different Languages - -- [Functions in C++](https://www.codecademy.com/resources/docs/cpp/functions) -- [Functions in JavaScript](https://www.codecademy.com/resources/docs/javascript/functions) -- [Functions in PHP](https://www.codecademy.com/resources/docs/php/functions) -- [Functions in TypeScript](https://www.codecademy.com/resources/docs/typescript/functions) -- [Functions in Ruby](https://www.codecademy.com/resources/docs/ruby/functions) diff --git a/content/general/concepts/svg/svg.md b/content/general/concepts/svg/svg.md deleted file mode 100644 index 3976519e9ce..00000000000 --- a/content/general/concepts/svg/svg.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -Title: 'SVG' -Description: 'Scalable Vector Graphics (SVG) is a XML-based file format for describing two-dimensional vector images. SVGs description of vector graphics with text allows for infinitely-scalable high-fidelity images with small file sizes.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Images' - - 'Files' - - 'HTML' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Scalable Vector Graphics (SVG)** is a XML-based file format for describing two-dimensional vector images. SVG's description of vector graphics with text allows for infinitely-scalable high-fidelity images with small file sizes. - -Unlike the common bitmap image formats of JPEG and PNG, Scalable Vector Graphics files do not describe the location and colors of individual pixels. Instead, SVG files represent basic shapes and curves within a two-dimensional coordinate plane. This provides their scalability as well as straightforward scripting of transformations and animations using JavaScript as is commonly found on the web. - -## Example - -An example SVG image containing the most common shapes can be found below: - -```html - - - - - - - - - - - - - - - - - -``` diff --git a/content/general/concepts/tech-stack/tech-stack.md b/content/general/concepts/tech-stack/tech-stack.md deleted file mode 100644 index dc56756fd4d..00000000000 --- a/content/general/concepts/tech-stack/tech-stack.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -Title: 'Tech Stack' -Description: 'A tech stack refers to a set of software that work together to build digital products or solutions such as websites or mobile applications.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'ASP.NET' - - 'Frameworks' - - 'Rails' -CatalogContent: - - 'learn-rails' - - 'paths/full-stack-engineer-career-path' ---- - -A **technology (or "tech") stack** refers to a set of software that work together to build digital products or solutions such as websites and mobile applications. Essential for building maintainable and scalable software, tech stacks are also known as technology infrastructures or solution stacks. - -### Front-End Tech Stack - -The [front-end](https://www.codecademy.com/resources/docs/general/front-end) is the part of an application the user interacts with. The [UI/UX design](https://www.codecademy.com/resources/docs/uiux) of an application or website should be seamless and straightforward, which is why it is a primary goal of front-end development. - -The three major elements that make up the front-end stack are [HTML](https://www.codecademy.com/resources/docs/html), [CSS](https://www.codecademy.com/resources/docs/css), and [JavaScript](https://www.codecademy.com/resources/docs/javascript). - -### Back-End Tech Stack - -The [back-end](https://www.codecademy.com/resources/docs/general/back-end), or server-side, refers to parts of an application's code that allow it to operate and handle new and existing data.It is inaccessible to the user. The back-end of an application is where the data and operating syntax are stored and accessed. - -The back-end tech stack is comprised of programming languages, [frameworks](https://www.codecademy.com/resources/docs/general/framework), [databases](https://www.codecademy.com/resources/docs/general/database), and [servers](https://www.codecademy.com/resources/docs/general/server). - -## Common Stacks - -### LAMP Stack - -The LAMP stack is a popular back-end tech stack used to create web apps. It is one of the oldest tech stacks and provides a collection of software for delivering high-performance web applications. This stack contains the following technologies: - -- Linux: An open-source operating system based on the Linux kernel. -- Apache: A free and open-source cross-platform web server. -- MySQL: A relational database management system for storing and manipulating data on the back-end. -- PHP: A server-side scripting programming language used for creating dynamic web applications. - -### MERN And Alternative Stacks - -MERN is a set of JavaScript-based technologies used in the web application development process. Alternative stacks are the MEVN and MEAN stack. The only difference being Vue.js or Angular.js is used in place of React.js as the front-end technology: - -- MongoDB: A document database used to build highly available and scalable internet applications. -- Express(.js): A back-end framework built on Node.js and it provides features for developing mobile and web applications. -- [React(.js)](https://www.codecademy.com/resources/docs/react)/Vue.js/Angular.js: These are front-end technologies for building user interfaces and single-page applications. -- Node(.js): A runtime environment that runs JavaScript on the server-side. diff --git a/content/general/concepts/terminal/terminal.md b/content/general/concepts/terminal/terminal.md deleted file mode 100644 index c08fb51f029..00000000000 --- a/content/general/concepts/terminal/terminal.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -Title: 'Terminal' -Description: 'A terminal is a command-line interface (CLI) that allows users to interact with a computer’s operating system by executing text-based commands.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Algorithms' - - 'Command Line' - - 'Bash/Shell' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -The **terminal**, also known as the command line or shell, is a powerful tool that enables users to communicate directly with the operating system. Unlike graphical user interfaces (GUIs), which rely on icons and menus, the terminal uses text-based commands to perform tasks such as file management, software installation, and system administration. - -The terminal provides greater control and efficiency, making it a preferred tool for developers, system administrators, and power users. It supports various command-line interpreters, such as Bash (Linux/macOS), Command Prompt (Windows), and PowerShell (Windows). By learning terminal commands, users can automate repetitive tasks, troubleshoot system issues, and navigate files more quickly than through GUI-based interactions. - -## Common Useful Terminal Commands - -### File and Directory Management - -| Command | Description | -| ------------------- | ------------------------------------ | -| `ls` | List files and directories. | -| `cd [directory]` | Change the current directory. | -| `pwd` | Print the current directory path. | -| `mkdir [directory]` | Create a new directory. | -| `rm [file]` | Remove a file. | -| `rm -r [directory]` | Remove a directory and its contents. | - -### File Operations - -| Command | Description | -| --------------------------- | -------------------------- | -| `cp [source] [destination]` | Copy files or directories. | -| `mv [source] [destination]` | Move or rename files. | -| `touch [filename]` | Create an empty file. | -| `cat [file]` | Display file contents. | - -### System Monitoring and Management - -| Command | Description | -| ------------ | --------------------------------------------------- | -| `top` | Show real-time system processes and resource usage. | -| `ps` | Display running processes. | -| `kill [PID]` | Terminate a process by its process ID (PID). | -| `clear` | Clear the terminal screen. | - -### Networking and Package Management - -| Command | Description | -| -------------------------------- | ------------------------------------------ | -| `ping [hostname]` | Check network connectivity. | -| `wget [URL]` | Download a file from the internet. | -| `curl [URL]` | Fetch data from a URL. | -| `apt install [package]` (Linux) | Install a package on Debian-based systems. | -| `brew install [package]` (macOS) | Install a package using Homebrew. | - -## Benefits of Using a Terminal - -- **Efficiency**: Commands execute tasks faster than GUI-based methods. -- **Automation**: Scripts can be created to automate repetitive tasks. -- **Remote Access**: Allows users to manage systems remotely via SSH. -- **Advanced Control**: Provides deeper access to system configurations. -- **Lightweight Usage**: Uses fewer system resources than GUI applications. - -By mastering the terminal, users can streamline their workflow, troubleshoot system issues effectively, and gain greater control over their computing environment. diff --git a/content/general/concepts/tokenization/tokenization.md b/content/general/concepts/tokenization/tokenization.md deleted file mode 100644 index 72c46fec36e..00000000000 --- a/content/general/concepts/tokenization/tokenization.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -Title: 'Tokenization' -Description: 'Tokenization is the process of breaking down text into smaller units called tokens, which are used in natural language processing and text analysis.' -Subjects: - - 'AI' - - 'Computer Science' - - 'Data Science' - - 'Machine Learning' -Tags: - - 'Machine Learning' - - 'NLP' - - 'Text Processing' -CatalogContent: - - 'learn-data-science' - - 'paths/data-science-foundations' ---- - -**Tokenization** is a fundamental process in natural language processing (NLP) involving breaking down text into smaller units called tokens. These tokens can be words, characters, or even punctuation marks, depending on the specific tokenization approach used. This process is crucial for preparing text data for various NLP tasks and machine learning models. - -## Types of Tokenization - -There are several approaches to tokenization, including: - -- **Word Tokenization**: Splits text into individual words, typically using whitespace or punctuation as delimiters. -- **Subword Tokenization**: Breaks text into smaller units than words, such as prefixes, suffixes, or other subword segments, useful for handling rare or unknown words. -- **Character Tokenization**: Splits text into individual characters, which can be useful for certain tasks or languages. -- **Sentence Tokenization**: Divides text into sentences, which is often a preliminary step before word tokenization. - -## Importance in NLP - -Tokenization is critical in NLP for several reasons: - -- **Input Preparation**: Most NLP models require tokenized input. -- **Vocabulary Creation**: Tokens form the basis of the vocabulary used by language models. -- **Feature Extraction**: Tokens can be used as features for various NLP tasks. -- **Standardization**: Tokenization helps standardize text for consistent processing. - -## Common Challenges - -Tokenization of the input text can face several challenges, including: - -- **Ambiguity**: Words can have multiple meanings or be part of phrases, making correct tokenization difficult. -- **Language Specificity**: Different languages may require different tokenization approaches. -- **Handling Special Cases**: Managing contractions, hyphenated words, URLs, and other unique text elements. -- **Preserving Meaning**: Ensuring that the tokenization process doesn't alter the original meaning of the text. - -## Popular Tokenization Algorithms - -Several algorithms and tools are commonly used for tokenization: - -- **NLTK Tokenizers**: Provided by the Natural Language Toolkit, offering word and sentence tokenization functionalities. -- **WordPiece**: Used by models like BERT, it employs a subword tokenization method that constructs the vocabulary from common subwords. -- **SentencePiece**: An unsupervised text tokenizer capable of handling multiple languages without language-specific preprocessing. - -Understanding tokenization is crucial for anyone working with text data in machine learning and artificial intelligence applications. The choice of tokenization method can significantly impact the performance of NLP models and AI systems. diff --git a/content/general/concepts/unicode/unicode.md b/content/general/concepts/unicode/unicode.md deleted file mode 100644 index 26c7c81bbcb..00000000000 --- a/content/general/concepts/unicode/unicode.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -Title: 'Unicode' -Description: 'Unicode is a text-processing standard that assigns a unique number to each character across most human languages and writing systems.' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Characters' - - 'Symbol' -CatalogContent: - - 'introduction-to-javascript' - - 'paths/full-stack-engineer-career-path' ---- - -**Unicode** is a text-processing standard that assigns a unique number, known as a code point, to each character across most human languages and writing systems. It is device- and platform-agnostic and is maintained by the [Unicode Consortium](https://home.unicode.org/). The adoption of the Unicode standard has grown so much that it is now implemented in many modern operating systems, programming languages, and it is the default encoding used in [XML](https://www.codecademy.com/resources/docs/general/xml) and [HTML](https://www.codecademy.com/resources/docs/html). - -## Common Character Sets - -Below are some tables of common Unicode character sets. - -> **Note:** These tables only showcase a few characters from each set. More information can be found in [the official Unicode character code charts](https://www.unicode.org/charts). - -### Arrows - -| Code | Character | Description | -| :----: | :-------: | ---------------- | -| U+2190 | ← | Leftwards arrow | -| U+2191 | ↑ | Upwards arrow | -| U+2192 | → | Rightwards arrow | -| U+2193 | ↓ | Downwards arrow | - -### Dingbats - -| Code | Character | Description | -| :----: | :-------: | ----------------------------------- | -| U+2731 | ✓ | Checkmark | -| U+2729 | ✫ | Star (trace) | -| U+274C | ❌ | Cross mark (red) | -| U+274E | ❎ | Negative squared cross mark (green) | - -### Math Symbols - -| Code | Character | Description | -| :-----------: | :-------: | ------------------------- | -| U+00B1 | ± | Plus-minus sign | -| U+03F4/U+03B8 | ϴ/θ | Theta (capital/lowercase) | -| U+2211 | ∑ | Sigma | -| U+221A | √ | Plus-minus sign | diff --git a/content/general/concepts/unit-testing/unit-testing.md b/content/general/concepts/unit-testing/unit-testing.md deleted file mode 100644 index 199abb0c8e6..00000000000 --- a/content/general/concepts/unit-testing/unit-testing.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -Title: 'Unit Testing' -Description: 'Unit testing involves testing parts of code to verify its behavior.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Debugging' - - 'Development' -CatalogContent: - - 'learn-javascript-unit-testing' - - 'paths/front-end-engineer-career-path' ---- - -**Unit testing** is an important part of coding and software development because it verifies whether individual parts of the source code behave and work as expected. - -These parts, or units, of code can be anything from a class function to a snippet of code that performs a specific task. Testing these units individually allows for finding errors earlier on in the development process. - -## Types of Unit Testing - -Unit testing is usually categorized into two types: - -- Manual testing -- Automated testing - -### Manual Testing - -Manual testing is when tests are done directly by testers. This can involve actions such as clicking on objects, providing input, or scrolling through items. - -Depending on the length of the software, this type of testing can be time-consuming. An alternative to this would be automated testing. - -### Automated Testing - -Automated testing is when programs are written specifically to test code. This is optimal when manual testing becomes tedious, frequent testing is needed, or when multiple individuals are adding or making changes to the code. - -Writing scripts to test parts of the source code is a way to automate testing. Combined with a testing automation tool, these scripts can run automatically and immediately inform developers if any errors have occurred. - -## Pros and Cons - -Unit testing is an important part of the development phase when writing code because it can potentially highlight errors earlier in development. It's best practice to test parts or units of code to verify its correctness during development or after making changes. - -Every project can benefit from unit testing because: - -- It can reduce the chances of having compound errors. - -- Makes debugging easier. - -- Helps creators write better code by encouraging them to write in smaller chunks. - -- Makes it easier to make changes to the source code. - -However, it is important to note that there are some disadvantages to unit testing including: - -- One line of code may need multiple lines of test code to test it. - -- Can’t test everything; not every execution path can be covered with unit testing. - -- It can not catch integration errors or broad system errors. - -Unit-testing may seem like a time-consuming process that could take a while to get a handle on. Nevertheless, having a process in place that contributes to the robustness and correctness of the source code can save time in the long-run. diff --git a/content/general/concepts/unix/unix.md b/content/general/concepts/unix/unix.md deleted file mode 100644 index d1bc34a0dfc..00000000000 --- a/content/general/concepts/unix/unix.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -Title: 'Unix' -Description: 'Unix is a family of operating systems that are all derived from the original AT&T Unix developed at Bell Labs in 1969.' -Subjects: - - 'Computer Science' - - 'Code Foundations' -Tags: - - 'Developer Tools' - - 'Linux' - - 'Operating Systems' - - 'Unix' -CatalogContent: - - 'paths/computer-science' - - 'paths/code-foundations' ---- - -**Unix** is a family of operating systems that are all derived from the original AT&T Unix developed at Bell Labs in 1969. Unix is a multitasking, multiuser operating system that is characterized by the implementation of many small modular software tools that can be combined using a scripting language known as the [Unix shell](https://en.wikipedia.org/wiki/Unix_shell). Unix and Unix-like operating systems are currently used widely on servers, workstations, and mobile devices. - -Originally developed for internal use at Bell Labs in the late 1970s, AT&T licensed Unix to a variety of outside parties, leading to a number of academic and commercial Unix variants. These include: - -- [Berkeley Software Distribution](https://en.wikipedia.org/wiki/Berkeley_Software_Distribution#External_links) from the University of California, Berkeley (now discontinued). -- [SunOS/Solaris](https://www.oracle.com/solaris/solaris11/) from Sun Microsystems (now Oracle). -- [Advanced Interactive eXecutive (AIX)](https://www.ibm.com/it-infrastructure/power/os/aix) from IBM. - -## Timeline - -1991 - [Linus Torvalds](https://www.codecademy.com/resources/docs/general/historical-technical-figures/linus-torvalds) released the [open-source](https://www.codecademy.com/resources/docs/open-source) [Linux](https://www.codecademy.com/resources/docs/open-source/linux) kernel as a Unix-like free alternative to proprietary Unix systems. It had since exploded into dozens, if not hundreds of different variant distributions. - -1992 - A free derivative of BSD Unix was released, leading to the [NetBSD](https://www.netbsd.org/) and [FreeBSD](https://www.freebsd.org/) projects. Since 1994 BSD Unix has developed several different branches, including [OpenBSD](https://www.openbsd.org/). - -2000 - Apple released a BSD Unix System named [Darwin](https://en.wikipedia.org/wiki/Darwin_%28operating_system%29#External_links) that eventually became the core of the macOS operating system. diff --git a/content/general/concepts/uri/uri.md b/content/general/concepts/uri/uri.md deleted file mode 100644 index 2e9d3544f2f..00000000000 --- a/content/general/concepts/uri/uri.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -Title: 'URI' -Description: 'A URI is a string that returns data used by web technologies such as APIs.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Link' - - 'URL' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -A **Uniform Resource Identifier (URI)** is a string that refers to a resource used by a web technology like a browser or an [API](https://www.codecademy.com/resources/docs/general/api). - -## Syntax - -```pseudo -|----------------------------URL-------------------| -| |--------------------------URN------------|------| -scheme://domain:port/path/to/resource?query=params#fragment -|----------------------------URI--------------------------| -``` - -URIs encompass the syntax of both [URLs](https://www.codecademy.com/resources/docs/general/url) and [URNs](https://www.codecademy.com/resources/docs/general/urn). It uses a `scheme` such as the [HTTP](https://www.codecademy.com/resources/docs/general/http) protocol to describe how the resource is retrieved. This is followed by a `domain` that ends in something like ".com" or ".gov" and may also include a `port` number. Then, a file path is described along with any possible `query` params and page `fragment`s. - -## Example - -Codecademy has a page on Wikipedia, which contains a section about "Features". The complete URI for this specific resource looks like this: - -```shell -https://en.wikipedia.org/wiki/Codecademy#Features -``` - -The following is used in the example URI: - -- A protocol scheme (`https`). -- A subdomain (`en`) that specifies the language for the site. -- The domain (`wikipedia.org`) containing the ".org" top-level domain. -- A directory to Codecademy's wiki page (`/wiki/Codecademy`). -- A fragment (`#Features`) linking to a specific section in the page. diff --git a/content/general/concepts/url/url.md b/content/general/concepts/url/url.md deleted file mode 100644 index ef4b2c02acb..00000000000 --- a/content/general/concepts/url/url.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -Title: 'URL' -Description: 'Uniform Resource Locators (URLs) refer to where a resource can be found.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Link' - - 'URL' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -A **Uniform Resource Locator (URL)** refers to where a resource can be found. This includes locations for web pages and media such as [images](https://www.codecademy.com/resources/docs/html/images) and [videos](https://www.codecademy.com/resources/docs/html/videos). URLs use protocols to perform different tasks with these resources including: - -- Web browsing with [HTTP/HTTPS](https://www.codecademy.com/resources/docs/general/http) -- Transferring files with FTP/SFTP -- Sending emails with SMTP - -## Syntax - -```pseudo -|----------------------------URL-------------------| -| |--------------------------URN------------|------| -scheme://domain:port/path/to/resource?query=params#fragment -|----------------------------URI--------------------------| -``` - -Since URLs and [URNs](https://www.codecademy.com/resources/docs/general/urn) are a subset of [URIs](https://www.codecademy.com/resources/docs/general/uri), the syntax can be similar. However, URLs use a `scheme` that describes the protocol used to find the resource. Next, a `domain` and possible `port` number are used to describe the authority behind the resource. - -## Example - -```shell -https://www.codecademy.com/resources/blog/what-is-web-development/ -``` - -The example above uses the following: - -- A protocol scheme (`http`) to connect to the Internet -- A subdomain (`www`) for the world-wide web -- A domain (`codecademy.com`) to a website -- A path (`/resources/blog/what-is-web-development/`), which locates the specific resource - -> **Note:** URLs follow a standard format that always uses a forward slash (/) as the path separator regardless of the operating system. diff --git a/content/general/concepts/urn/urn.md b/content/general/concepts/urn/urn.md deleted file mode 100644 index 6e0a46bd76c..00000000000 --- a/content/general/concepts/urn/urn.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -Title: 'URN' -Description: 'Refers to resources without disclosing any location or proof of existence.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Link' - - 'URL' -CatalogContent: - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -A **Uniform Resource Name (URN)** are general [URIs](https://www.codecademy.com/resources/docs/general/uri) that refer to resources without disclosing any location or proof of existence. - -## Syntax - -```pseudo -urn:nid:data -``` - -URNs use namespace identifiers (`nid`) that are unique and registered with the [Internet Assigned Numbers Authority](https://www.iana.org/). The `data` is commonly unique information such as serial numbers. - -## Example - -Libraries and booksellers may use the International Standard Book Number (ISBN) system to catalog and uniquely identify materials in their collection, like so: - -```shell -urn:isbn:9781098110338 -``` diff --git a/content/general/concepts/user-interface-design/user-interface-design.md b/content/general/concepts/user-interface-design/user-interface-design.md deleted file mode 100644 index 6016656842f..00000000000 --- a/content/general/concepts/user-interface-design/user-interface-design.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -Title: 'User Interface Design' -Description: 'User interface design is the art and science of maximizing the usability of a digital product or service.' -Subjects: - - 'Web Design' - - 'Web Development' -Tags: - - 'Interface' - - 'Responsive' -CatalogContent: - - 'learn-color-design' - - 'paths/front-end-engineer-career-path' ---- - - - -**User interface (UI)** design is the art and science of maximizing the usability of a digital product or service. With the advent of web applications, responsive design, and mobile development, UI design has grown into a field of its own. - -Overall, users have less and less tolerance for a text-heavy UI, especially on smaller devices. Poor UI leads to a poor user experience (UX), and many people flee at the sight of a poorly designed screen. As a result, many sites and apps invest a lot of time and effort into making their UI responsive with visually appealing and easy-to-use functions. - -## Design Rules - -While a cutting-edge discipline, UI design still adheres to rules and principles. Designers strive to increase software usability and reduce the learning-curve. They also ensure all the interfaces within a system or technology are consistent. - -Borrowing from [Adobe's Four Golden Rules of Design](https://xd.adobe.com/ideas/process/ui-design/4-golden-rules-ui-design/), users must have the following capabilities when interacting with the UI: - -- The user controls the navigation and can undo their actions. -- A minimal amount of steps are needed to perform a task. -- There is sensible feedback for certain user actions such as gestures, taps, and button clicks. -- Indicators of page loads (progress bars, percentages, etc.) should be present. -- There should be visible help guides and other functions for users of all skill levels. diff --git a/content/general/concepts/uuid/uuid.md b/content/general/concepts/uuid/uuid.md deleted file mode 100644 index ef164b337ec..00000000000 --- a/content/general/concepts/uuid/uuid.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -Title: 'UUID' -Description: 'UUID is a universally unique identifier. It can be generated on any computer without the use of a centralized authority.' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Id' - - 'NPM' -CatalogContent: - - 'introduction-to-javascript' - - 'paths/computer-science' ---- - -A **universally unique identifier (UUID)** is a string of 128 bits that is supposed to be unique with little to no chance of clashing with any other UUIDs produced by anybody else in the world. It can be generated on any computer without the use of a centralized authority. - -UUIDs are usually used in database tables as unique keys. They are useful any time we need an ID that needs to be unique in an application or system. - -## Format - -A UUID is usually represented as 32 hexadecimals, separated in five groups by 4 hyphens. For example: - -```pseudo -123e4567-e89b-12d3-a456-42661417400 -``` - -So a total of 36 characters in the form `8-4-4-4-12`. - -## UUID Example in JavaScript - -UUIDs can be used in JavaScript with the [uuid](https://www.npmjs.com/package/uuid) package. The package can be installed via [npm](https://www.codecademy.com/resources/docs/javascript/npm): - -```shell -npm install uuid -``` - -This example shows how to generate a UUID with the `uuidv4()` function: - -```js -const { v4: uuidv4 } = require('uuid'); - -console.log(uuidv4()); -// Output: 7637c099-79c8-4685-ad47-b1b985f7ac2b -``` diff --git a/content/general/concepts/virtual-machines/virtual-machines.md b/content/general/concepts/virtual-machines/virtual-machines.md deleted file mode 100644 index ea3c5fd9a71..00000000000 --- a/content/general/concepts/virtual-machines/virtual-machines.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -Title: 'Virtual Machines' -Description: 'Virtual machines are software resources that can perform the same tasks as physical computers.' -Subjects: - - 'Computer Science' -Tags: - - 'Servers' - - 'Cloud Computing' - - 'Operating Systems' - - 'Cybersecurity' -CatalogContent: - - 'foundations-of-cloud-computing' - - 'paths/computer-science' ---- - -A **virtual machine (VM)** is a software resource that can perform the same computing functions as a physical computer system, such as running applications or storing data. However, VMs do not use physical hardware to perform these tasks. Instead, VMs exist as code and use software-defined versions of hardware that are installed on a host [server](https://www.codecademy.com/resources/docs/general/server). - -A single server or physical computer can run multiple VMs at the same time. Each VM has its own operating system and functions as an independent compute resource, even though they may share the same host server. For example, a computer running macOS could use a VM to run a separate instance of the Windows operating system from the same computer. - -## How Do VMs Work? - -VMs run on top of the operating system of the host machine, similar to other applications on a physical computer. All VMs on a single host share the same physical resources, such as memory and storage. - -Multiple VMs can be managed with a software known as a “hypervisor”. A hypervisor is used to create, manage, and run the VMs on a host machine. The hypervisor is used to manage hardware resources from the host machine, which enables these resources to be shared amongst multiple VMs. - -## Benefits of VMs - -VMs provide many benefits, such as the following: - -### Improved Hardware Utilization - -Multiple VMs can be run on a single physical server or computer. This allows physical hardware to be used more efficiently because a single VM frequently does not use enough resources to need its own dedicated hardware. Assigning multiple VMs to a single physical host also lowers costs by reducing the number of physical computers needed. - -### Organized Development and Test Environments - -VMs can provide separate environments with separate operating systems, which can be used for development and testing purposes. VMs make it easy to separate testing resources and conduct tests which won’t have any impact on production or other surrounding environments. - -### Increased Security - -Using separate VMs is considered a secure way to explore potentially malicious applications or viruses. Because they are separate environments, VMs can be used for these tasks without the risk of compromising the host machine. - -This isolation improves security. If an attacker gained access to a single VM, they wouldn't have access to the host machine or other VMs that share the same host. - -### Increased Flexibility - -VMs are flexible and can easily be migrated to different hypervisors or hosts. Resources on a VM can also be added and removed easily, and different VMs can be used to operate different displays and operating systems from the same host machine. - -## Who Uses VMs? - -Nearly all software companies use VMs and other virtualization technology. They are a fundamental component of [cloud computing](https://www.codecademy.com/resources/docs/cloud-computing), [cybersecurity](https://www.codecademy.com/resources/docs/cybersecurity), and more. diff --git a/content/general/concepts/virtual-reality/virtual-reality.md b/content/general/concepts/virtual-reality/virtual-reality.md deleted file mode 100644 index 5e5a3b9758d..00000000000 --- a/content/general/concepts/virtual-reality/virtual-reality.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -Title: 'Virtual Reality' -Description: 'Virtual Reality (VR) is the computer-generated simulation of a three-dimensional image or environment that can be interacted with in a seemingly real or physical way by a person using special electronic equipment, such as a helmet with a screen inside or gloves fitted with sensors' -Subjects: - - 'Computer Science' - - 'Web Development' -Tags: - - 'Best Practices' - - 'Memory' -CatalogContent: - - 'paths/code-foundations' - - 'paths/computer-science' - - 'paths/front-end-engineer-career-path' ---- - -**Virtual reality (VR)** is a technology that uses head-mounted headsets with displays to generate realistic images, sounds, and other sensations to put users into an immersive virtual environment. VR can create unbounded worlds that people can walk around and interact with using their hands, and to feel as if they were transported to another place. - -It’s still considered an evolving trend of the tech industry — fun, exciting, and bustling with opportunities. - -## Augmented Reality vs. Virtual Reality - -[Augmented reality (AR)](https://www.codecademy.com/resources/docs/general/augmented-reality) utilizes the current physical setting of the user while introducing a layer of synthetic digital, sonic, or somatic presentation to enhance the user experience. Conversely, VR involves use of a headset to facilitate an experience rooted in the graphic and sonic presentation within the VR setup as opposed to using the individual's more broad physical surroundings for interaction. - -Virtual reality is poised to grow substantially in use during the 21st century as it has many potential uses in many industries including entertainment, health, education, tourism, military, art, and design. - -## VR Examples - -- Web development: [A-Frame](https://www.codecademy.com/learn/learn-a-frame) is a popular [open-source](https://www.codecademy.com/resources/docs/open-source) web framework for building virtual reality experiences in the web browser. -- Automotive industry: Companies like [Jaguar](https://techwireasia.com/2020/02/how-jaguar-land-rover-uses-vr-to-design-and-engineer-new-vehicles/) are incorporating VR into their vehicle design before commissioning expensive prototypes. -- Healthcare: - - Software like [Osso VR](https://www.ossovr.com/) allow for practicing surgical techniques on virtual bodies. - - [BehaVR](https://www.behavr.com/) is used as pain relief for burn injuries. -- Real estate: [Klapty](https://www.klapty.com/explore) features virtual tours of apartments and houses that are on the market. -- Education: Products like [Engagevr](https://engagevr.io) provides learning experiences in a risk-free space mostly for soft skills such as public speaking and active listening. -- Tourism: [Globetrotter](https://globetrotter-vr.com/) features interactive virtual tours of places around the world for users to consider which activities and destinations to try out. diff --git a/content/general/concepts/webrtc/webrtc.md b/content/general/concepts/webrtc/webrtc.md deleted file mode 100644 index 3c3e6e1858a..00000000000 --- a/content/general/concepts/webrtc/webrtc.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -Title: 'WebRTC' -Description: 'Web real-time communication (WebRTC) is a free and open-source collection of APIs that allow peer-to-peer connections between two or more browser clients.' - -Subjects: - - 'Mobile Development' - - 'Web Development' -Tags: - - 'APIs' - - 'WebRTC' - - 'Video' -CatalogContent: - - 'learn-websockets' - - 'paths/front-end-engineer-career-path' ---- - -[**WebRTC**](https://webrtc.org/) (Web Real-Time Communication) is a free and open-source collection of APIs that allow peer-to-peer connections between two or more browser clients. - -Originally developed in 2011 and currently maintained by Google, WebRTC has been published as a specification by the W3C and is supported by all major browsers. - -## WebRTC vs WebSockets - -WebRTC is commonly used for video chatting apps because it allows two or more computers to connect and send audiovisual data without needing a server. - -Conversely, WebSockets allow for a two-way connection between a server and client using the `ws://` protocol. diff --git a/content/general/concepts/whitespace/whitespace.md b/content/general/concepts/whitespace/whitespace.md deleted file mode 100644 index ad64c3ac458..00000000000 --- a/content/general/concepts/whitespace/whitespace.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -Title: 'Whitespace' -Description: 'Whitespace uses horizontal and vertical space characters or blank lines to format code and improve readability.' -Subjects: - - 'Computer Science' - - 'Data Science' - - 'Web Development' -Tags: - - 'Formatting' - - 'Typography' -CatalogContent: - - 'learn-python-3' - - 'paths/computer-science' ---- - -In programming, **whitespace** uses horizontal and vertical space characters or blank lines to format code and improve readability. - -## Example - -The code example below is hard to read since there is little to no whitespace. It also does not have indentation with spaces so people can not easily see what is nested within what. - - - -```js -function createRangeIterator(min = 0, max = Infinity, step = 1) { -let nextNum = min; -let numCount = 0; -const rangeIterator = { -next: function () { -let result; -if (nextNum < max) { -result = { value: nextNum, done: false }; -nextNum += step; -numCount++; -return result; -} -return { value: numCount, done: true }; -}, -}; -return rangeIterator; -} -``` - - - -When whitespace is used, the code is much more readable: - -```js -function createRangeIterator(min = 0, max = Infinity, step = 1) { - let nextNum = min; - let numCount = 0; - - const rangeIterator = { - next: function () { - let result; - if (nextNum < max) { - result = { value: nextNum, done: false }; - nextNum += step; - numCount++; - return result; - } - return { value: numCount, done: true }; - }, - }; - - return rangeIterator; -} -``` diff --git a/content/general/concepts/wsdl/wsdl.md b/content/general/concepts/wsdl/wsdl.md deleted file mode 100644 index a97f061083b..00000000000 --- a/content/general/concepts/wsdl/wsdl.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -Title: 'WSDL' -Description: 'WSDL (Web Services Description Language) is a specification for an XML document that describes a web service.' -Subjects: - - 'Web Development' - - 'Web Design' -Tags: - - 'Data Structures' - - 'Development' -CatalogContent: - - 'learn-html' - - 'paths/front-end-engineer-career-path' ---- - -**WSDL (Web Services Description Language)** is a specification for an [XML](https://www.codecademy.com/resources/docs/general/xml) document that describes a web service. A WSDL document is a machine-readable description of how a service can be called, what parameters it expects, and what type of data structures are returned by it. [WSDL Version 2.0](https://www.w3.org/TR/wsdl/) was released by the [World Wide Web Consortium](https://www.w3.org/standards/) (W3C) in 2007, but support for this version of the specification is still poorly implemented, with much web development software only supporting [WSDL Version 1.1](https://www.w3.org/TR/2001/NOTE-wsdl-20010315). - -WSDL documents are usually constructed and read by web development software, and developers don't often need to interact with these files directly. - -## Elements - -A WSDL document is made up of the following elements: - -- ``: The root element defining the name of the service, declares namespaces used in the document, and contains all the other elements. -- ``: The data types used in the form of XML schemas. -- ``: Description of the data exchanged between the web service and its consumers. -- ``: Combines multiple messages to form a complete transaction. -- ``: A single request/response operation defined within a ``. -- ``: Defines the specific details on how a `` operation is actually transmitted. -- ``: An individual endpoint address for a binding. -- ``: Defines the collection of ports supported by the web service. -- ``: Human-readable comments that can be included within any other WSDL element. - -## Structure - -The structure of a WSDL document looks like this: - -```pseudo - - - description of types... - - - - description of a message... - - - - - description of an operation... - - - - - description of a binding... - - - - description of a service... - - -``` diff --git a/content/general/concepts/xml/terms/xpath/xpath.md b/content/general/concepts/xml/terms/xpath/xpath.md deleted file mode 100644 index 3e43b884f0d..00000000000 --- a/content/general/concepts/xml/terms/xpath/xpath.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -Title: 'XPath' -Description: 'XPath is a language used to query different parts of an XML document.' -Subjects: - - 'Code Foundations' - - 'Data Science' -Tags: - - 'Data Structures' - - 'Development' -CatalogContent: - - 'learn-python-3' - - 'paths/data-analyst' ---- - -**XPath** is a language used to query different parts of an [XML](https://www.codecademy.com/resources/docs/general/xml) document. There are several versions of the specification from the [World Wide Web Consortium](https://www.w3.org/) (W3C): - -- [XPath 1.0](https://www.w3.org/TR/1999/REC-xpath-19991116/) was introduced in 1999 and is still the most widely implemented version. -- [XPath 2.0](https://www.w3.org/TR/xpath20/) was introduced in 2007, with the second edition in 2010. It offered considerable revisions primarily around a richer type system and is a subset of version 1.0 of the more expansive XQuery language. -- [XPath 3.0](https://www.w3.org/TR/xpath-30/) was introduced in 2014 and is a subset of XQuery 3.0. -- [XPath 3.1](https://www.w3.org/TR/xpath-31/) was introduced in 2017 with additional data types to support JSON. - -XPath is implemented via libraries for many different programming languages, such as [Python](https://www.codecademy.com/resources/docs/python), [Java](https://www.codecademy.com/resources/docs/java) and [JavaScript](https://www.codecademy.com/resources/docs/javascript). If a language offers tools for any sort of XML processing, it will probably offer support for using some version of XPath to query XML documents. - -## Syntax - -XPath treats an XML document as a tree structure, much like folders stored on a disk drive. In fact, in its simplest form, XPath expressions can resemble file paths. These file-path-like expressions are referred to as location paths. Each location path consists of a sequence of location steps separated by slashes (`/`), and each location step has three components: - -- An axis specifying what "direction" we're looking for a node. -- A node test specifying what node we want to match. -- Zero or more predicates that add restrictions onto what node the expression will ultimately match. (i.e. conditions the node has to satisfy in order to match.) - -A location step's full syntax is: - -```pseudo -axis-specifier::node-test[predicate] -``` - -The most common axes have abbreviated syntax so the whole axis name doesn't need to be used. An example of this is the fact the child axis is the default so doesn't require an axis specifier at all. - -### Axis Specifiers - -XPath uses the following axis specifiers: - -- `ancestor` -- `ancestor-or-self` -- `attribute`: `@a` is an abbreviation for `attribute::a`. -- `child`: The default axis. `a` is an abbreviation for `child::a`. -- `descendant` -- `descendant-or-self`: `//` is an abbreviation for `/descendant-or-self::node()/`. -- `following` -- `following-sibling` -- `namespace` -- `parent`: `..` is an abbreviation for `parent::node()`. -- `preceding` -- `preceding-sibling` -- `self`: `.` is an abbreviation for `self::node()`. - -### Node Tests - -Node tests consist of specific node names, or more general expressions. The more general expressions include: - -- `node()` or `*` matches any node at all. -- `comment()` matches an XML comment node. -- `text()` matches a text node excluding any children. -- `processing-instruction()` matches XML processing instructions. - -### Predicates - -Predicates define an expression that must evaluate true for the node test to succeed. There can be any number of predicates, and they are evaluated in order from left to right. For example, `A[1][./@C = "1"]` matches only if the first `A` element has an attribute `C` equal to "1" whereas `A[./@C="1"][1]` matches the first `A` element that has an attribute `C` equal to "1". A predicate must have a numeric or boolean value. A numeric value is equivalent to specifying the position of the node to match (i.e. `A[5]` is the same as `A[position()=5]`). - -Location paths can be used inside predicates, and are evaluated relative to the node being tested. so the `./@C` in `A[./@C="1"]` is looking to match the `C` attribute of the `A` element. - -The following operators can be used inside of predicates in XPath 1.0: - -- The union operator `|` creates the union of two node-sets. -- The boolean operators `and` & `or`. -- The boolean function `not()`. -- Mathematical operators: `+`, `-`, `*`, `div` (divide), and `mod`. -- The comparison operators `=`, `!=`, `<`, `>`, `<=` & `>=`. - -Predicates also have several functions available in XPath 1.0, the following are some of the more commonly used ones: - -- `contains(string1, string2)`: Checks if `string2` is contained within `string1` and returns true or false. -- `count(node-set)`: Returns the number of nodes in `node-set`. -- `false()`: Returns false. -- `last()`: Returns the position of the last match of the current node test. -- `local-name(node-set)`: Returns the local name of the first node in `node-set`, or if `node-set` is omitted, the local name of the current node. -- `normalize-space(string)`: Returns `string` with leading and trailing whitespace removed, and all sequences of whitespace characters replaced by a single space. If omitted, operates on the context node converted to a string. -- `position()`: Returns the numeric position of the current node. -- `starts-with(string1, string2)`: Checks if `string1` starts with `string2` and returns true or false. -- `sum(node-set)`: Converts the string values of the nodes in `node-set` into numbers and returns the sum of those numbers. -- `true()`: Returns true. - -## Examples - -Consider the following XML document: - -```pseudo - - - - - - - - -``` - -Example XPath expressions include: - -- `A/B/D`: The most basic type of XPath expression. Each location step is separated by a slash. The default axis is the child axis and `A`, `B` & `C` represent the element nodes we're matching. This expression matches all `D` elements that are children of `B` elements that are children of `A` elements. It would match both `D` elements in the example. The expression can be written in expanded form as `child::A/child::B/child::D`. -- `A//D`: Also matches both `D` elements in the example, because the double slash (`//`) represents the descendant-or-self axis. This expression matches all `D` elements that are descendants of the `A` element. The expanded form of the expression is `child::A/descendant-or-self::node()/child::D`. -- `A//D[1]`: Adds a predicate (in the square brackets `[...]`) to the `D` node test. Using a number alone in the square brackets is a shorthand way of specifying the position of the element. This predicate specifies that we're only matching the first `D` descendant of `A`. The expanded form of the expression is `child::A/descendant-or-self::node()/child::D[position()=1]`. -- `A//@C`: The `@` indicates we're searching along the attribute axis. In this case, we're looking for all `C` attributes belonging to `A` or `A`'s descendants. This matches the two `C` attributes in the `B` elements in the example. The expanded form of the expression is `child::A/descendant-or-self::node()/attribute::C`. -- `//*[../@C="3"]`: The `*` is a wildcard that matches any node. `..` means the parent axis, in this case the parent of the node referenced by the predicate. This expression matches any node in the document whose parent has a `C` attribute with a value of `3`. In the above case that is the second `D` element. The expanded form of the expression is `/descendant-or-self::node()/child::node()[parent::node()/attribute::C="3"]`. -- `//*[./@C="3"]`: Same as the prior example, except that `.` means the self axis. In this case that refers to the node referenced by the predicate. This expression matches any node in the document that has a `C` attribute with a value of `3`. In the above case that is the second `B` element. The expanded form of the expression is `/descendant-or-self::node()/child::node()[self::node()/attribute::C="3"]`. diff --git a/content/general/concepts/xml/xml.md b/content/general/concepts/xml/xml.md deleted file mode 100644 index 030fd245b08..00000000000 --- a/content/general/concepts/xml/xml.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -Title: 'XML' -Description: 'XML (Extensible Markup Language) is used to define the content and structure of data in a document.' -Subjects: - - 'Code Foundations' - - 'Data Science' -Tags: - - 'Data Structures' - - 'Development' - - 'Tags' -CatalogContent: - - 'learn-python-3' - - 'paths/data-analyst' ---- - -**XML (Extensible Markup Language)** is used to define the content and structure of arbitrary data in a document. It is a human-readable text-based markup language used to store and transmit many different types of data, from individual records in a database, to things as complex as a Microsoft Word document. XML is primarily defined in the [XML 1.0 Specification](http://www.w3.org/TR/REC-xml) from the [World Wide Web Consortium](https://www.w3.org/standards/) (W3C). XML was designed for simplicity, general application, and usability across the Internet. While document-based, it is widely used to store all types of arbitrary data structures. - -Many computer languages, such as [Python](https://www.codecademy.com/resources/docs/python) or [Java](https://www.codecademy.com/resources/docs/java), provide their own libraries or modules for processing XML documents. XML has proved to be a popular format for [serializing](https://www.codecademy.com/resources/docs/general/serialization) objects. - -An XML document can consist of the following pieces: - -## Elements - -An element is defined with an opening tag with an arbitrary name enclosed with angle brackets `<...>` and a closing tag defined by the same name enclosed in angle brackets and a leading slash ``. Between these two tags can be an arbitrary number of other elements or a text value. An element can combine opening and closing tags by enclosing the tag name with angle brackets and a trailing slash `<.../>`. A well-formed XML document has only one outermost element that contains the rest of the document's content. - -The following are all valid elements: - -```pseudo -text - - -``` - -Element names are case sensitive and cannot contain spaces or special characters and cannot begin with a digit. - -## Attributes - -Attributes consist of name-value pairs that can be included in an opening tag of an element, after the element's name. Any attribute name can appear only once and can only have one value. The following are examples of attributes: - -```pseudo - - -``` - -Attribute names have the same restrictions as element names. - -## Comments - -XML permits comments anywhere except inside element tags. They are enclosed between the tags `` and do not affect the parsing of the XML document. They behave exactly like [HTML comments](https://www.codecademy.com/resources/docs/html/comments). - -## Entities - -For rendering special characters, XML uses [entities like HTML](https://www.codecademy.com/resources/docs/html/entities). Entities can be used inside attribute and text values, but not in element and attribute names. They are required for some special characters. Unlike HTML, XML only has five predefined entities: - -| Name | Entity | Character | -| ----------------- | :------: | :-------: | -| Quotation mark | `"` | `"` | -| Ampersand | `&` | `&` | -| Apostrophe | `'` | `'` | -| Less-than sign | `<` | `<` | -| Greater-than sign | `>` | `>` | - -`&` and `<` are required when rendering those characters in any content. `"` and `'` are required when rendering those characters in attribute values. - -Like HTML, XML allows numeric entity references, allowing most Unicode characters to be used in the content. These are used in the following way: - -- `&#number;`: where `number` is the character's decimal Unicode number. -- `&#xnumber;`: where `number` is the character’s hexadecimal Unicode number. - -So the `©` copyright character can be represented as `©` or `©`. diff --git a/content/general/general.md b/content/general/general.md deleted file mode 100644 index 0d81ea0e472..00000000000 --- a/content/general/general.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -Title: 'General' -Description: 'The General section is home to all programming and computer-related concepts that are language-agnostic and do not belong in one of the focused topic areas.' -CatalogContent: - - 'learn-html' - - 'paths/code-foundations' ---- - -The General section is home to all programming and computer-related concepts that are language-agnostic and do not belong in one of the focused topic areas such as [AI](https://www.codecademy.com/resources/docs/ai), [cybersecurity](https://www.codecademy.com/resources/docs/cybersecurity), or [open-source](https://www.codecademy.com/resources/docs/open-source). These include universal foundational programming terminologies that are often shared among languages and frameworks. - -Here are entries from ["Computer Hardware"](https://www.codecademy.com/resources/docs/general/computer-hardware), to ["Developer Tools"](https://www.codecademy.com/resources/docs/general/developer-tools), to ["Historical Technical Figures"](https://www.codecademy.com/resources/docs/general/historical-technical-figures). diff --git a/content/git/concepts/add/add.md b/content/git/concepts/add/add.md deleted file mode 100644 index fb3c73525c0..00000000000 --- a/content/git/concepts/add/add.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -Title: 'Add' -Description: 'The git add command is used to add changes from the working tree to the staging area. This is where changes are saved for the next commit.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'Version Control' -CatalogContent: - - 'learn-the-command-line' - - 'learn-git' ---- - -In Git, adding is used to add changes from the working tree to the staging area. This is where changes are saved for the next commit. When the file name appears in green, it indicates that the file is tracked and will be staged for the next commit. - -## Example - -Below is a short example of how the `git add` command works. Assuming a change was saved in a **message.txt** text file, running `git status` will show this: - -```shell -$ git status - -On branch main - -No commits yet - -Untracked files: - (use "git add ..." to include in what will be committed) - message.txt - -nothing added to commit but untracked files present (use "git add" to track) -``` - -Since the file is untracked, `git add` can be used to stage it for the next commit. Afterwards, running `git status` again should yield the following: - -```shell -$ git add message.txt -$ git status - -On branch main - -No commits yet - -Changes to be committed: - (use "git rm --cached ..." to unstage) - new file: message.txt -``` - -The file now appears in green when running `git status`, indicating that it is staged and will be saved with the next commit. - -There are many extensions to the `git add` command such as: - -- `-n`: Where the file will not be added to the staging area but will show whether or not the file exists and/or if it will be ignored. -- `-f`: Which stages all files including those which are ignored. -- `.` : Which stages all the files in the current directory. On the command line, it references the current directory. -- `-A`: Which stages all the files in the current directory as well as subdirectories. diff --git a/content/git/concepts/amend/amend.md b/content/git/concepts/amend/amend.md deleted file mode 100644 index 95b45f397b0..00000000000 --- a/content/git/concepts/amend/amend.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -Title: 'Amend' -Description: 'Modifies the most recent Git commit without creating a new one.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Command Line' - - 'Documentation' - - 'Error Handling' - - 'Git' -CatalogContent: - - 'learn-git' - - 'paths/computer-science' ---- - -**Amend** is a Git feature that allows developers to modify the most recent commit. It is commonly used to correct mistakes such as adding a missing file, fixing an incorrect commit message, or making minor adjustments without creating an entirely new commit. - -This feature is particularly helpful for maintaining a clean and concise commit history, ensuring that changes are logically grouped and easy to understand. - -## Syntax - -The syntax for using the amend feature in Git is: - -```pseudo -git commit --amend -``` - -To amend both the content of the commit and the commit message, the following would be used: - -```pseudo -git commit --amend -m "Your new commit message" -``` - -## Example 1 - -Suppose, the developer created and committed a feature, but forgot to include a file: - -```shell -# Original commit -echo "Initial code" > feature.txt -echo "Forgotten content" > forgotten-file.txt -git add feature.txt # Dev forgot to add forgotten-file.txt -git commit -m "Add initial code for the feature" -``` - -Here's the original commit history: - -```shell -git log --oneline -abc1234 Add initial code for the feature -``` - -The developer realized that he hasn't included a file in the original commit. So, he performs the amend operation to both include the file in that commit and change the commit message: - -```shell -# Amending the original commit -git add forgotten-file.txt -git commit --amend -m "Add initial code for the feature and forgotten file" -``` - -Here's the amended commit history: - -```shell -git log --oneline -def5678 Add initial code for the feature and forgotten file # Commit abc1234 has been replaced by def5678 -``` - -## Example 2 - -Suppose, the developer is going through another commit history: - -```shell -git log --oneline -abc1234 Original commit message -``` - -While going through it, the developer didn't like the above commit message. So, he decides to use the amend operation to only change the commit message without touching the contents of the commit: - -```shell -git commit --amend -m "Corrected commit message" -``` - -Here's the amended commit history: - -```shell -git log --oneline -abc1234 Corrected commit message -``` - -> **Note:** Use `git commit --amend` carefully if the commit has already been shared with others, as it rewrites history. diff --git a/content/git/concepts/branch/branch.md b/content/git/concepts/branch/branch.md deleted file mode 100644 index 2597e1df811..00000000000 --- a/content/git/concepts/branch/branch.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -Title: 'Branch' -Description: 'A branch is an independent version of the main codebase.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-the-command-line' - - 'learn-git' ---- - -In Git, a branch is an independent version of the main codebase. They're used for modifying or adding new code to a project without affecting the main codebase, usually named the `main` branch. - -Branches are a core component of software development with Git. When a new branch is created, a copy of the source branch is made. All code changes (additions or deletions) in the new branch are isolated from the source branch or main codebase. When the changes in the new branch are ready, they can be merged back into the main codebase. Branches also make it easier to test code or undo changes because they can be deleted without affecting the main codebase or any other branches. - - - -## Creating a Branch - -The syntax for creating a branch in Git is this: - -```pseudo -git branch -``` - -Using this command from `` will create a new branch called `` based off of the code that is currently in ``. - -## Renaming a branch - -To rename a local branch in Git, use the following syntax: - -```pseudo -git branch -m -``` - -The `-m` flag here is short for `--move`. A good way to remember this is to think of renaming as "moving" the branch from one name to another. - -## Deleting a Branch - -The syntax for removing a branch in Git is this: - -```pseudo -git branch -d -``` - -As long as the branch has no uncommitted code, this command will remove the branch entirely. It will no longer be available to check out, and the changed code will be unrecoverable. - -Sometimes, Git will refuse to delete a branch because it has unmerged changes in an existing upstream or remote version of that branch. In such cases, it can be forcefully deleted with either the `-d --force` or capitalized `-D` flag, like so in the `my-branch` examples below. - -Option 1: - -```shell -git branch -d --force my-branch -``` - -Option 2: - -```shell -git branch -D my-branch -``` - -Performing a force delete tells Git the user understands that all changes on that branch will be lost forever, and they want to delete the branch anyway. - -## Moving Between Branches - -The syntax for moving between branches in Git is this: - -```pseudo -git checkout -``` - -This will change the active branch to the one named `branch-name`. Any editing done at this point will be to the copy of the code within `branch-name` rather than the previous branch. - -The `checkout` command is often used immediately after creating a new branch. This is so common that there is a shorthand command to create a new branch and switch to it automatically: - -```shell -git checkout -b branch-name -``` - -This is the same as performing the following commands in direct succession: - -```shell -git branch branch-name -git checkout branch-name -``` - -## Merging Branches - -The syntax for moving code from one branch into another in Git is this: - -```pseudo -git merge -``` - -This will merge the code from `` to the currently checked out branch. - -## Example - -When working with code, a programmer will often want to work on a specific feature. They will create a branch off of the main one, and code within it. Once they are happy with the feature and are certain that it is ready to be added back to the main branch they will merge it from the feature branch into the main one. Finally, they will clean up their repository by deleting the feature branch. - -First, we branch off of the `main` branch and check out the new one: - -```shell -git checkout main # Make sure we are in the main branch - -git branch my-awesome-feature # Create the new branch - -git checkout my-awesome-feature # Switch to the new branch -``` - -When our code is ready, and fully committed to the new branch: - -```shell -git checkout main # Go back to the main branch - -git merge my-awesome-feature # Combine the code from my-awesome-feature into the main branch - -git branch -d my-awesome-feature # Remove the branch now that the code has been combined -``` diff --git a/content/git/concepts/checkout/checkout.md b/content/git/concepts/checkout/checkout.md deleted file mode 100644 index b023674d34d..00000000000 --- a/content/git/concepts/checkout/checkout.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -Title: 'Checkout' -Description: 'The git checkout command switches, creates and restores branches in the working directory to a specific state.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' - - 'paths/computer-science' ---- - -The **`git checkout`** command switches, creates and restores branches in the working directory to a specific state. The `git checkout` command also allows switching to a specific commit without changing branches. - -## Syntax - -Checkout with branches: - -```pseudo -git checkout [options] -``` - -- `` specifies the name of the branch to switch to or create. -- `[options]` optional flags that can be used with the checkout command. Here are some of the most commonly used options: - - `-b` creates a new branch with the specified name and switches to it immediately. - - `-` returns to the previously checked-out branch. This flag does not need the ``. - - `-f` (--force) forces the checkout, discarding any local changes in the working directory. - -Checkout to a specific commit: - -```pseudo -git checkout -``` - -## Switch to an existing branch - -The following command will switch to an already existing branch, created previously with the [git branch](https://www.codecademy.com/resources/docs/git/branch) command: - -```pseudo -git checkout existing-branch -``` - -> **Note**: From Git 2.23, the new specific `git switch` command has been introduced to switch branches, making it clearer and safer than `git checkout` because it avoids the ambiguity of the latter's multi-purpose nature. - -## Create and switch to a new branch - -It is possible to create and switch to a new branch with a single command using the `-b` option: - -```pseudo -git checkout -b new-branch -``` - -## Restore a file from a specific commit - -`git checkout` also allows to restore a file from a specific commit using its hash: - -```pseudo -git checkout -- example.txt -``` - -## Examine a Previous Commit - -`git checkout` also allows temporarily moving to a specific commit without changing branches. This state is called **detached `HEAD` state**: - -```pseudo -git checkout -``` - -The detached `HEAD` state allows to: - -- Examine the state of the repository at that specified commit. -- Create new branches if the developer needs to start from that point. -- Any code changes made in this state will not be associated with any existing branch unless a new branch is created. diff --git a/content/git/concepts/cherry-pick/cherry-pick.md b/content/git/concepts/cherry-pick/cherry-pick.md deleted file mode 100644 index f23d088fdf1..00000000000 --- a/content/git/concepts/cherry-pick/cherry-pick.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -Title: 'Cherry Pick' -Description: 'The cherry-pick command is used to select and put individual commits from one branch to another.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-the-command-line' - - 'learn-git' ---- - -The **cherry-pick** command entails picking individual [commits](https://www.codecademy.com/resources/docs/git/commit) from one [branch](https://www.codecademy.com/resources/docs/git/branch) to another. - -## Syntax - -```pseudo -git cherry-pick -``` - -`` is the commit hash and can be found using [git log](https://www.codecademy.com/resources/docs/git/log). -Below are a couple of optional flags that can be used with the `cherry-pick` command: - -- `edit`: allows edits to the commit message prior to committing. -- `signoff`: add a 'signoff' signature line to the end of the `cherry-pick` commit message. - -## Example - -Below is a short example of how to use `git cherry-pick`. The developer copied and pasted the commit sha `2f410g1` on GitHub from a branch called `pets:main`to the branch `adding-content-about-dogs` after typing `cherry-pick`. - -```pseudo -# Switch to the `adding-content-about-dogs` branch. -git checkout adding-content-about-dogs -# Cherry-pick the commit with the SHA `2f410g1`. -git cherry-pick 2f410g1 -``` - -To complete this command, the developer then pushes the changes to the `adding-content-about-dogs` with the following commit message: - -```pseudo -commit -m "feat: cherry-pick content about poodles" -``` - -## Disadvantage - -A common disadvantage of using the `cherry-pick` command is that it creates duplicate commits to the desired branch. In the example below, there are now two commits with the same message. This can make it difficult for other developers to track the codebase's commit history and understand why certain changes were made. - -```pseudo -commit 3456789 -Author: Dang Smith -Date: Fri Aug 8 16:27:04 2023 -0700 - - Cherry-picked commit with SHA 2f410g1 - -commit 2f410g1 -Author: Ooh Doe -Date: Fri Aug 8 16:29:04 2023 -0700 - - Added content about poodles -``` - -## Prevention Strategies - -A common way to prevent the creation of duplicate commits is using `--no-commit` in the `cherry-pick` command. In the example below, The `--no-commit option` will apply the changes from the cherry-pick to the working directory, but it will not create a new commit. This allows developers to inspect the changes and make any necessary edits before committing the final changes to the main branch. - -```pseudo -# Switch to the `adding-content-about-dogs` branch. -git checkout adding-content-about-dogs -# Cherry-pick the commit with the SHA `2f410g1`, but do not commit the changes. -git cherry-pick --no-commit 2f410g1 - -# Inspect the changes made by the cherry-pick. -git diff HEAD - -# Commit the changes with your own message. -git commit -m "Added content about poodles" -``` - -The following is the commit history after the `cherry-pick`: - -```pseudo -commit 23289 -Author: Ooh Doe -Date: Fri Oct 8 16:29:04 2023 -0700 - -Added content about poodles -``` - -As shown above, there is only one commit in spite of cherry-picking it from SHA `2f410g1` due to the use of `--no-commit`. diff --git a/content/git/concepts/clone/clone.md b/content/git/concepts/clone/clone.md deleted file mode 100644 index a9b2d422d01..00000000000 --- a/content/git/concepts/clone/clone.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -Title: 'Clone' -Description: 'Cloning means copying an existing remote repository to the current local directory.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -In Git, cloning means copying an existing remote repository to the current directory. - -Many common Git commands are performed only on a local repository, that is, a repository that exists on a local machine. Here's a command that will interact with a remote repository — a repository on a server that can be accessed through the internet. - -## Syntax - -The syntax for cloning in Git via HTTPS is this: - -```pseudo -git clone https://github.com/repository/URL.git -``` - -## Example - -In the example below, `git clone` is used to clone the [Codecademy Docs](https://github.com/codecademy/docs) repository: - -```shell -$ git clone https://github.com/Codecademy/docs.git - - Cloning into 'docs'... - remote: Enumerating objects: 21512, done. - remote: Counting objects: 100% (3517/3517), done. - remote: Compressing objects: 100% (1795/1795), done. - remote: Total 21512 (delta 2233), reused 1727 (delta 1466), pack-reused 17995 - Receiving objects: 100% (21512/21512), 3.48 MiB | 9.56 MiB/s, done. - Resolving deltas: 100% (10600/10600), done. -``` diff --git a/content/git/concepts/commit/commit.md b/content/git/concepts/commit/commit.md deleted file mode 100644 index 53148e00070..00000000000 --- a/content/git/concepts/commit/commit.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -Title: 'Commit' -Description: 'Commits are used as snapshots of a given branch in a repository. They serve as the growth history of all the branches in a Git repository.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -In Git, **commits** are used as snapshots of a given branch in a repository. Collectively, they serve as the growth history of all the branches in a Git repository. The most recent commit is considered directly related to the pointer of the current branch. - -## Syntax - -```shell -git commit -``` - -## How Do I Commit? - -### Step 1: Files Ready - -Before using `git commit`, make sure to have all the necessary files staged for the commit. - -```shell -git add filename -``` - -The `git add .` command can be used to add all files in the current directory. - -### Step 2: Commit - -After the files are staged for commit, use the following syntax: - -```shell -git commit -``` - -> **Note:** Using the `git commit` command by itself will open up an editor (usually set to [Vim](https://www.codecademy.com/resources/docs/command-line/vim) by default), where users will be asked to add a commit message. After writing a message, saving and closing the file (`:wq` in Vim) will add that message to the current commit. - -Here is an example of what the commit message prompt might look like when using `git commit`: - -```shell -Add git_practice.js and install dependencies - -# Please enter the commit message for your changes. Lines starting -# with '#' will be ignored, and an empty message aborts the commit. -# -# On branch main -# Changes to be committed: -# new file: git_practice.js -# new file: package-lock.json -# new file: package.json -``` - -Here is what the command line would look like afterwards: - -```shell -$ git commit -[main (root-commit) b77d68b] Add git_practice.js and install dependencies - 3 files changed, 26 insertions(+) - create mode 100644 git_practice.js - create mode 100644 package-lock.json - create mode 100644 package.json -``` - -Using the `-m` flag like so, `git commit -m `, adds a commit message without opening up an editor: - -```shell -$ git commit -m "this is a commit message" -[main (root-commit) b77d68b] this is a commit message - 3 files changed, 26 insertions(+) - create mode 100644 git_practice.js - create mode 100644 package-lock.json - create mode 100644 package.json -``` diff --git a/content/git/concepts/config/config.md b/content/git/concepts/config/config.md deleted file mode 100644 index 3f625157dfb..00000000000 --- a/content/git/concepts/config/config.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -Title: 'Config' -Description: 'Git configuration is a fundamental aspect of using Git, allowing users to customize various settings and preferences on both a global and repository-specific level.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'Version Control' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -**Git configuration** is a fundamental aspect of using Git, allowing users to customize various settings and preferences on both a global and repository-specific level. Configuration settings manage various aspects of the profile and operation of Git, including identity details, preferred text editors, merge strategies, and more. Git stores these settings in configuration files, making it essential for efficient and smooth collaboration with Git. - -## Viewing Git Configurations - -To view Git a configuration, utilize the `git config` command. To see global configuration settings, use: - -```shell -git config --global --list -``` - -## Setting Git Configurations - -Git configurations can be set using the `git config` command. For instance, to set name and email address, which are crucial for authorship identification: - -```shell -git config --global user.name "Your Name" -git config --global user.email "your.email@example.com" -``` - -Repository-specific configurations can also be set without the `--global` flag. - -## Removing Git Configurations - -To remove a specific configuration setting, use the `--unset` flag with the `git config` command. For example, to remove the user email from the global configuration: - -```shell -git config --global --unset user.email -``` - -## Git Configuration Files - -Git stores all of these configuration settings in simple files which can be found in different places: - -- Global settings are saved in a file called `.gitconfig` in the user's home directory. -- Project-specific settings are saved in `.git/config` within the repository. - -> **Note:** Settings in the repository's local configuration file will override settings in the global file. - -These files are just plain text files and can be edited directly rather than using the `git config` commands. A basic configuration file that sets user info and adds some aliases may look like: - -```plaintext -[user] - name = Jane Doe - email = JaneDoe@example.com -[alias] - ci = commit - co = checkout - st = status -``` diff --git a/content/git/concepts/diff/diff.md b/content/git/concepts/diff/diff.md deleted file mode 100644 index 279a44c0a07..00000000000 --- a/content/git/concepts/diff/diff.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -Title: 'Diff' -Description: 'The diff command displays changes in different elements of a working environment: files, directories, commits, branches, etc.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-the-command-line' - - 'learn-git' ---- - -The **`diff`** command displays changes in different elements of the working environment: files, directories, commits, and even branches. In other words, `diff` shows what changed for one or several elements in a repository. - -## Syntax - -The syntax for comparing data changes in a repository using `diff` is: - -```pseudo - git diff -``` - -## Examples - -There are various ways in which `git diff` can be used. - -### 1. git diff - -Used as it is, the command shows the difference between the working directory and the staging area. - -Suppose the initial version of the file `scene.txt` below has already been [committed](https://www.codecademy.com/resources/docs/git/commit). - -```plaintext -COBBYTO -In a dream, brain activity will be roughly thirty times higher than usual. The effect is increased by entering a dream within that dream. - -ARIANEA -How long should each level take? -``` - -The file `scene.txt` is modified as follows and the changes are saved in the working directory. - -```plaintext -COBBYTO -In a dream, brain activity will be roughly thirty times higher than usual. The effect is increased by entering a dream within that dream. - -ARIANEA -How long? - -COBBYTO -According to my calculations, the time span is approximately three days at the top layer, three months one layer down, and six years a level after. - -ARIANEA -Who would want to live in an illusory world for six years? -``` - -Using `git diff` in the terminal will produce the following output: - -```shell -$ git diff -diff --git a/scene.txt b/scene.txt -index c16c37f..c680bb4 100644 ---- a/scene.txt -+++ b/scene.txt -@@ -2,4 +2,10 @@ COBBYTO - In a dream, brain activity will be roughly thirty times higher than usual. The effect is increased by entering a dream within that dream. - - ARIANEA --How long? -\ No newline at end of file -+How long? -+ -+COBBYTO -+According to my calculations, the time span is approximately three days at the top layer, three months one layer down, and six years a level after. -+ -+ARIANEA -+Who would want to live in an illusory world for six years? -\ No newline at end of file -``` - -With only one file tracked, using `git diff` is the same as using `git diff scene.txt` - -### 2. git diff --cached - -`git diff --cached` displays the changes between the staging area and the last commit (i.e., changes between what is [staged](https://www.codecademy.com/resources/docs/git/add) but not yet committed). - -If `git diff --cached` is run in the terminal, no output is produced. This is expected because nothing has been added to the staging area yet. Therefore, there's no status change between the latter and the last commit. This can be verified by running [`git status`](https://www.codecademy.com/resources/docs/git/status). - -```shell -$ git status -On branch master -Changes not staged for commit: - (use "git add ..." to update what will be committed) - (use "git checkout -- ..." to discard changes in working directory) - - modified: scene.txt - -no changes added to commit (use "git add" and/or "git commit -a") -``` - -Adding `scene.txt` to the staging area and running `git diff --cached` in the terminal yield the following: - -```shell -$ git diff --cached -diff --git a/scene.txt b/scene.txt -index c16c37f..c680bb4 100644 ---- a/scene.txt -+++ b/scene.txt -@@ -2,4 +2,10 @@ COBBYTO - In a dream, brain activity will be roughly thirty times higher than usual. The effect is increased by entering a dream within that dream. - - ARIANEA --How long? -\ No newline at end of file -+How long? -+ -+COBBYTO -+According to my calculations, the time span is approximately three days at the top layer, three months one layer down, and six years a level after. -+ -+ARIANEA -+Who would want to live in an illusory world for six years? -\ No newline at end of file -``` - -The output is the same as the output for `git diff` in the previous section because the changes saved have been added to the staging area. Additionally, if `git diff` is run in the terminal, no output is produced. diff --git a/content/git/concepts/fetch/fetch.md b/content/git/concepts/fetch/fetch.md deleted file mode 100644 index 46062668e73..00000000000 --- a/content/git/concepts/fetch/fetch.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -Title: 'Fetch' -Description: 'Retrieves changes (commits, files, etc.) from another repository or local branch, but does not integrate them.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' - - 'Version Control' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -The **`fetch`** command retrieves changes (commits, files, etc.) from another repository or local [branch](https://www.codecademy.com/resources/docs/git/branch), but does not integrate them. This command allows programmers to bring in and review changes made in a central repository into their local machine. - -## Syntax - -```pseudo -git fetch -``` - -This will bring in changes made in the `` that exist in the Git ``. However, the changes will not be merged; that must be done with the [`merge`](https://www.codecademy.com/resources/docs/git/merge) command. - -**Note**: Using the [`pull`](https://www.codecademy.com/resources/docs/git/pull) command performs a `fetch`, followed by a `merge`, within the same line. - -## Fetching From a Remote - -A common use case for the `fetch` command is bringing in and reviewing changes made in a remote branch. The remote must exist in order for `fetch` to be able to access and retrieve the changes made there. - -```shell -$ git remote -v - -origin https://github.com/CodeNinja/docs.git (fetch) -origin https://github.com/CodeNinja/docs.git (push) -``` - -Next, running `git fetch` on the `main` branch of the `origin` remote will bring any changes, including any new commits or files, into the current branch: - -```shell -$ git fetch origin main -From https://github.com/CodeNinja/docs - * branch main -> FETCH_HEAD -``` - -After this point, a `merge` command can be used to actually integrate the changes. diff --git a/content/git/concepts/fork/fork.md b/content/git/concepts/fork/fork.md deleted file mode 100644 index f8c92eaa710..00000000000 --- a/content/git/concepts/fork/fork.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -Title: 'Fork' -Description: 'A duplicate of a repository that resides within the independent directories of a contributor.' -Subjects: - - 'Code Foundations' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' - - 'Version Control' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -A **fork** is a duplicate of an existing repository. This "fork" is an independent entity that allows a contributor to interact with the original repository. Collaboration, experimentation, and contributions to open-source code are made possible by forking. It enables developers worldwide to collaborate, make changes, and contribute to projects while retaining the integrity of the source code. It is a secure approach to modify and test code without making changes directly to the original. - -> **Note:** The fork command is provided by a separate command-line tool than Git. - -## Steps to Fork a Repository - -- Step 1 - -First the user login to his/her GitHub account using the command: - -```shell -gh auth login -``` - -- Step 2 - -After successful login, the user can fork the repository using the command: - -```shell -gh repo fork -``` - -This will create a new copy of the original repository. - -> **Note:** Users can get `repository_url` by going to the Github repository that they want to fork and copying the URL. diff --git a/content/git/concepts/gitignore/gitignore.md b/content/git/concepts/gitignore/gitignore.md deleted file mode 100644 index 3677ec14df3..00000000000 --- a/content/git/concepts/gitignore/gitignore.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -Title: '.gitignore' -Description: 'A configuration file that instructs Git to ignore specific files and directories when tracking changes in a repository.' -Subjects: - - 'Code Foundations' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' - - 'Version Control' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -A **.gitignore** file specifies the files and directories that Git should ignore when tracking changes in a repository. This is particularly useful for excluding build artifacts, temporary files, dependencies, and sensitive information from version control. The .gitignore file should be located in the root directory of a repository. - -## Common .gitignore patterns - -Below are common patterns typically included in .gitignore files: - -```plaintext -# Ignore node modules directory -node_modules/ - -# Ignore build output directories -dist/ -build/ - -# Ignore environment files -.env -.env.local - -# Ignore log files -*.log - -# Ignore system files -.DS_Store -Thumbs.db - -# Ignore IDE specific files -.idea/ -.vscode/ -*.sublime-project -*.sublime-workspace -``` - -## Creating a .gitignore file - -Step 1: Create a new .gitignore file in the repository's root directory: - -```shell -touch .gitignore -``` - -Step 2: Open the file in the preferred text editor and specify the files and directories to ignore: - -```shell -# Open with VS Code -code .gitignore - -# Open with Vim -vim .gitignore -``` - -> **Note:** Wildcards like '\*' can be used for pattern matching and '#' for comments in the .gitignore file. - -## Common .gitignore rules - -1. Specific file: `filename.txt` -2. File pattern: `*.log` -3. Directory: `node_modules/` -4. Nested directory: `**/logs/` -5. Negation (don't ignore): `!important.log` - -> **Note:** If ignored files have already been committed, remove them from Git's tracking using `git rm --cached ` before .gitignore takes effect. diff --git a/content/git/concepts/head/head.md b/content/git/concepts/head/head.md deleted file mode 100644 index 70bd8a446fe..00000000000 --- a/content/git/concepts/head/head.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -Title: 'HEAD' -Description: 'In Git, HEAD refers to the current commit or the latest snapshot of the working directory.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'Version Control' -CatalogContent: - - 'learn-the-command-line' - - 'learn-git' ---- - -In Git, **`HEAD`** is a reference to the current branch or commit that the user is working on. It typically points to the most recent commit in the current branch, but can also point to other commits when working with detached `HEAD` states. - -## Purpose of `HEAD` - -- **Current Commit Reference**: `HEAD` helps Git know where the current working directory is in relation to the commit history. -- **Working Directory**: `HEAD` allows Git to track changes relative to the last commit made on the active branch. -- **Branch Switching**: `HEAD` changes when you switch branches, as it always points to the tip of the branch you're working on. - -## Viewing `HEAD` - -To check the current commit or branch where `HEAD` is pointing, the following command can be used: - -```shell -git log --oneline -``` - -This shows a simplified log of the commit history, where the commit at the top is the one pointed to by `HEAD`. - -## Detached `HEAD` State - -A **detached `HEAD`** occurs when `HEAD` is not pointing to the tip of a branch, but rather to a specific commit. In this state, changes are not linked to any branch. - -For example, this command checks out a specific commit, causing `HEAD` to be detached from any branch: - -```pseudo -git checkout -``` - -Changes made in detached `HEAD` state won't be associated with any branch unless explicitly created as a new branch. It can be useful for exploring past commits or making temporary changes. - -## Updating `HEAD` - -`HEAD` is updated when switching branches, as it points to the latest commit of the newly checked-out branch: - -```shell -git checkout develop -``` - -This command switches the current branch to `develop` and `HEAD` points to the most recent commit on the `develop` branch. - -## Resetting `HEAD` - -We can use `git reset` to move `HEAD` to a previous commit, changing the state of the working directory: - -```pseudo -git reset --hard -``` - -For example, this command resets `HEAD` to the commit with hash `abc1234`, and the working directory will match the state of that commit: - -```shell -git reset --hard abc1234 -``` diff --git a/content/git/concepts/init/init.md b/content/git/concepts/init/init.md deleted file mode 100644 index 681391f0443..00000000000 --- a/content/git/concepts/init/init.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -Title: 'Init' -Description: 'Initializing a Git repository when beginning a new project is the first step to take in order to track changes.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -In Git, `init` is used to initiate the process of creating a repository. When beginning a new project, this is the first step to take in order to track changes to the code throughout all files and folders. - -## Syntax - -```shell -git init -``` - -## Initializing a Git Repository - -### Step 1: Navigate to the Desired Directory - -The `init` command initializes a Git repository in the current directory. Prior to using this command, users must take care to navigate to the appropriate directory — this will become the root directory of the repository. The `cd` command can be used to navigate the filesystem from the command line: - -```pseudo -cd go/to/desired/project/directory -``` - -### Step 2: Init - -In the appropriate directory, initialize a repository to begin tracking changes made to all the files with the following git command: - -```shell -git init -``` - -After the initialization is complete, the following should appear in the command line. - -```shell -Initialized empty Git repository in /go/to/desired/project/directory/.git/ -``` - -A new, hidden **.git** directory is then added alongside the new repository's root directory. In this case, the root directory is `directory`. diff --git a/content/git/concepts/log/log.md b/content/git/concepts/log/log.md deleted file mode 100644 index 9b173e63f3b..00000000000 --- a/content/git/concepts/log/log.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -Title: 'Log' -Description: 'The git log command is used to track the commit history of a project repository.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'Version Control' -CatalogContent: - - 'learn-the-command-line' - - 'learn-git' ---- - -In Git, the **`log`** command is used to track a [branch's](https://www.codecademy.com/resources/docs/git/branch) commit history. After running, it will display project-related information, such as a detailed commit history, which can be used as a reference to go back in time to a previous version of the project. - -## Example - -Below is a short example of how the `git log` command works. Running `git log` will show a list of all previous commits on the current branch: - -```shell -$ git log - -On current branch - -commit f5b5bd8f9eaa443d4020cbe918x742e7ddd22000 -Author : John Doe -Date: Mon May 22 14:21:03 2023 -0400. -``` - -The example log above shows the different elements that make up a commit, but the most useful is the git hash (f5b5bd8f9eaa443d4020cbe918x742e7ddd22000), which can be used to revert our commit changes using the git revert command. diff --git a/content/git/concepts/merge/merge.md b/content/git/concepts/merge/merge.md deleted file mode 100644 index b42fd390c55..00000000000 --- a/content/git/concepts/merge/merge.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -Title: 'Merge' -Description: 'Merging allows a user to apply all changes from one branch to another when the work is completed.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -In Git, completed changes made to a [branch](https://www.codecademy.com/resources/docs/git/branch) can be merged to the `main` branch. When collaborating on a remote repository, a [pull request](https://www.codecademy.com/resources/docs/git/pull-requests) will need to be opened in order to do this. Anyone with push access to the repository can complete the merge. - -## Git Command - -To merge a branch into the local `main` branch: - -```shell -git checkout main # Switch to the main branch -git merge branch_name -``` - -For example, the following merges a branch called `feature_test` branch to the `main` branch: - -```shell -git checkout main -git merge feature_test -``` - -## Merging a Pull Request on GitHub - -> _For information on how to open a pull request, see the [Pull Requests](https://www.codecademy.com/resources/docs/git/pull-requests) section._ - -1. On the GitHub repository page, click the "Pull requests" tab at the top. - -2. In the "Pull Requests" list, choose the pull request that you'd like to merge. - -3. Depending on the merge options enabled for your repository, you can: - - - Merge all the commits into the base branch by clicking **Merge pull request**. If the **Merge pull request** option is not shown, then click the merge drop down menu and select **Create a merge commit**. - - - Squash the commits into one commit by clicking the merge drop down menu, selecting **Squash and merge** and then clicking the **Squash and merge** button. - - - Rebase the commits individually onto the base branch by clicking the merge drop down menu, selecting **Rebase and merge** and then clicking the **Rebase and merge** button. - -4. If prompted, type a commit message, or accept the default commit message. - -5. If you have more than one email address associated with your GitHub account, click the email address drop-down menu and select the email address to use as the Git author email address. Only verified email addresses appear in this drop-down menu. If you enabled email address privacy, then `@users.noreply.github.com` is the default commit author email address. - -6. Click **Confirm merge**, **Confirm squash and merge**, or **Confirm rebase and merge**. - -7. (Optional) Last but not the least, delete the feature branch. This keeps the list of branches in your repository nice and tidy. diff --git a/content/git/concepts/mergetool/mergetool.md b/content/git/concepts/mergetool/mergetool.md deleted file mode 100644 index e1949c9ba52..00000000000 --- a/content/git/concepts/mergetool/mergetool.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -Title: 'mergetool' -Description: 'The mergetool command is used to activate a tool used to solve merge conflicts that occur in a branch.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-the-command-line' - - 'learn-git' ---- - -In [Git](https://www.codecademy.com/resources/docs/git), a merge conflict is a situation that commonly occurs when merging a [branch](https://www.codecademy.com/resources/docs/git/branch) into a codebase. The **mergetool** command is often used to resolve this these conflicts. - -## Syntax - -```pseudo -git mergetool -``` - -## Example - -Below is an example on how to use `git mergetool`. The developer runs the command and the merge conflict appears: - -```git -git mergetool -# Conflicting section: -<<<<<<< HEAD -## Creating a Tutorial -We highly recommend using Markdown to create your tutorial for our audio editor. -======= -If you need help, check out our templates. ->>>>>>> UPDATING-THE-DOCS -``` - -- `<<<<<<< HEAD`: where the developer's changes appear. -- `====`: Divides the developer's changes from the changes in the other branch, followed by `>>>>>>> UPDATING-THE-STYLE-GUIDE` - -To complete this command, the developer removes the conflict markers `<<<<<<<`, `=======`, `>>>>>>>`, and pushes the changes to the `updating-the-style-guide` branch with the following commit message: - -```git -git commit -m "docs: update information about tutorials" -``` - -## Other tools - -Here are a list of other tools that are used to solve merge conflicts: - -- [**Kaleidoscope**](https://kaleidoscope.app/): Developers often use this to resolve merge conflicts due to its use of different highlighted colors and powerful features ranging from a Convert to Merge command, text filters that remove unimportant data, and a debugger. -- [**Visual Studio Code**](https://code.visualstudio.com/docs/sourcecontrol/overview#_3way-merge-editor): This Integrated Development Environment (IDE) has a built-in 3-way merge editor, which displays the incoming changes to the file and provides a button that enables the changes to be accepted into the file. This allows developers to edit files and resolve conflicts easily. -- [**Sublime Merge**](https://www.sublimemerge.com/): Tool comes in a paid and free version. It is deemed to have a great user interface and is intuitively easy to use. diff --git a/content/git/concepts/mv/mv.md b/content/git/concepts/mv/mv.md deleted file mode 100644 index ac566f160a1..00000000000 --- a/content/git/concepts/mv/mv.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -Title: 'Move' -Description: 'A command for moving or renaming files within a Git repository.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -The **`git mv`** command is used to move or rename files _within_ a Git repository. It's a more convenient way to move or rename files compared to manually deleting and adding files. This command also helps in tracking the history of file movements and naming alterations. - -## Syntax - -```pseudo -git mv -``` - -## Use Cases - -### 1. Moving a File - -To move a file from one location to another, use the `git mv` command like this: - -```pseudo -git mv source_filepath destination_filepath -``` - -This will move the `file.txt` from the `source` directory to the `destination` directory. - -### 2. Renaming a File - -To rename a file, simply use the `git mv` command with the old and new file names: - -```pseudo -git mv old-name.txt new-name.txt -``` - -This renames `old-name.txt` to `new-name.txt`. - -1. It is essential to commit the changes after using `git mv` to ensure that the file moves and renames are properly tracked in the Git history. - -2. Renaming or moving files with `git mv` preserves the file's history and is especially useful in collaborative development to maintain a clear and organized project structure. - -3. The `git mv` command can also be used with wildcards or regular expressions to move or rename multiple files simultaneously. diff --git a/content/git/concepts/pull-requests/pull-requests.md b/content/git/concepts/pull-requests/pull-requests.md deleted file mode 100644 index ebf5cb0ebaa..00000000000 --- a/content/git/concepts/pull-requests/pull-requests.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -Title: 'Pull Request' -Description: 'Pull requests are used to recommend merging code from one branch into a different branch. PRs are a core tool in open-source software development.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -Pull requests (PRs) are used to recommend the merging of code from one [branch](https://www.codecademy.com/resources/docs/git/branch) into a different branch. PRs are a core tool in open-source software development as it allows developers to propose changes to large, open-source codebases. - -After reviewing, if the changes are approved by the author(s)/collaborators of the repository, they are merged into the base branch (this is usually named the `main` branch). If the changes are not approved, the maintainer(s) may either ask the requester for additional changes or decline the PR altogether. - -The review process by the contributors, usually involves: - -- Examining the code submitted in the PR for errors and/or optimizations. -- Running tests to ensure the code works as intended. -- Discussing potential modifications. - -PRs are featured on popular version control platforms such as [GitHub](https://github.com/) and [GitLab](https://about.gitlab.com/). - -## Create a Pull Request - -### Method 1: Fork (Ideal for Open Source Projects, Conditionally Required) - -1. Fork the project. -2. Clone the forked repository to your local machine. -3. Create a new branch, then switch to it. -4. `add`, `commit`, and `push` the changes to your forked repository. -5. From the web page of your forked repository, click on the "Pull requests" tab. - -> **Note**: Forking a repository is only needed when the user lacks write access to the original repository or wants to make changes without affecting the original repository. - -### Method 2: Collaborators (Ideal for Small Teams) - -If you are a collaborator of a repository (meaning the repository owner has added you as a collaborator), you can: - -1. Clone the repository to your machine. -2. Create a new branch, then switch to it. -3. Make your changes, `commit`, and then `push` the branch to the repository. -4. From the web page of the repository, click on the "Pull Requests" tab. - -### Method 3: Within an Organization/Company - -If you are part of an organization/company, depending on your permissions, you may have the privilege to push branches directly and create PRs (Pull Requests). You can follow the same steps as Method 2 to create a PR. - -> **Note:** Regardless of the method you choose, be sure to follow the contribution guidelines and standards specific to the project you are working on. - -No matter which method you use, you need to visit the relevant repository to access the PRs (Pull Requests). - -Navigate to the repository of the relevant project and go to 'Pull requests'. -![navbar Git Hub](https://raw.githubusercontent.com/Codecademy/docs/main/media/dongle-pullrequest-repositorie.png) - -Once on the page, you'll see a blue button labeled 'New pull request'; click on it. -![New pull request interface](https://raw.githubusercontent.com/Codecademy/docs/main/media/new-pullrequest-button.png) - -Finally, you just need to configure your Pull Request (PR), specifying the destination repository and branch, as well as the source branch and repository. -![New pull request setting](https://raw.githubusercontent.com/Codecademy/docs/main/media/pullrequest-settings.png) diff --git a/content/git/concepts/pull/pull.md b/content/git/concepts/pull/pull.md deleted file mode 100644 index 6e72b66b2d9..00000000000 --- a/content/git/concepts/pull/pull.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -Title: 'Pull' -Description: 'Retrieves and integrates changes from another repository or local branch (often from either a machine or hosting service like GitHub).' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' - - 'Version Control' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -The **`pull`** command retrieves and integrates changes from another repository or local [branch](https://www.codecademy.com/resources/docs/git/branch). This command is like a combination of the [`fetch`](https://www.codecademy.com/resources/docs/git/fetch) and [`merge`](https://www.codecademy.com/resources/docs/git/merge) commands and is often used for the following: - -- Move code from a remote machine or repository to a local one. -- Retrieve code from a repository hosting service like [GitHub](https://www.codecademy.com/resources/docs/general/github). - -Functionally, the `pull` command is a [`fetch`](https://www.codecademy.com/resources/docs/git/merge) command followed by a [`merge`](https://www.codecademy.com/resources/docs/git/merge) command. - -Pulling a repository allows programmers to access code from a remote backup and make it available on their local machine. It is also used when collaborating with others in order to keep the local code up to date with the team's current version. - -## Syntax - -```pseudo -git pull -``` - -This will move the code from `` currently in branch ``, and move it to the branch checked out locally on the user's computer. - -## How to Pull - -Prerequisites to pulling from a remote repository include: - -- Being inside of the local repository (if not, the next step will return an error) -- Being inside of the correct branch and having a clean [`git status`](https://www.codecademy.com/resources/docs/git/status) in that branch: - - ```shell - $ git checkout new-feature-branch - $ git status - - On branch new-feature-branch - nothing to commit, working tree clean - ``` - -- Having a valid remote repository set. In this case, the remote repository is named `origin` and can be found at the URL `https://github.com/CodeNinja/product-dev`: - - ```shell - $ git remote -v - - origin https://github.com/CodeNinja/product-dev.git (fetch) - origin https://github.com/CodeNinja/product-dev.git (push) - ``` - -At this stage, pulling can be accomplished with a valid remote and branch name: - -```shell -git pull origin new-feature-branch -``` - -When the pull completes, it will display a message like this: - -```shell -remote: Counting objects: 5, done. -remote: Compressing objects: 100% (3/3), done. -remote: Total 5 (delta 2), reused 0 (delta 0), pack-reused 0 -Unpacking objects: 100% (5/5), done. -From https://github.com/CodeNinja/product-dev.git - * branch new-feature-branch -> FETCH_HEAD -``` diff --git a/content/git/concepts/push/push.md b/content/git/concepts/push/push.md deleted file mode 100644 index 85b540775c6..00000000000 --- a/content/git/concepts/push/push.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -Title: 'Push' -Description: 'Pushing is the process of moving code from one Git repository to another. Often this is used to move code from a local machine to GitHub.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -In Git, pushing is the process of moving code from one repository to another one. Often this is used to move code from a local machine to a remote one, or to a repository hosting service like GitHub. - -Pushing a repository allows a programmer to maintain an easily accessible backup in a second location. It is also used when collaborating with people that would not have access to the computer that the code is written on. - -## Syntax - -The syntax for pushing changes in Git is this: - -```shell -git push -``` - -## How to Push - -Prerequisites to pushing from within a repository include: - -- Being inside of a repository (if not, the next step will return an error) -- Having a clean `git status` (no uncommitted, but tracked, files): - - ```shell - $ git status - - On branch main - nothing to commit, working tree clean - ``` - -- Having a valid remote repository set. In this case the remote repository is named `origin` and can be found at the url `https://github.com/CompanyName/product-dev`: - - ```shell - $ git remote -v - - origin https://github.com/CompanyName/product-dev.git (fetch) - origin https://github.com/CompanyName/product-dev.git (push) - ``` - -At this stage, pushing can be accomplished with a valid remote and branch name: - -```shell -git push origin main -``` - -When the push completes, it will display a message like this: - -```shell -Enumerating objects: 5, done. -Counting objects: 100% (5/5), done. -Writing objects: 100% (3/3), 304 bytes | 304.00 KiB/s, done. -Total 3 (delta 0), reused 0 (delta 0), pack-reused 0 -To https://github.com/CompanyName/product-dev.git - 0e21f7b..2a668cb main -> main -``` diff --git a/content/git/concepts/rebase/rebase.md b/content/git/concepts/rebase/rebase.md deleted file mode 100644 index 9abbac6ac17..00000000000 --- a/content/git/concepts/rebase/rebase.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -Title: 'Rebase' -Description: 'Rebasing integrates or shifts a series of commits onto a fresh base commit.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'Github' - - 'Version Control' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -**Rebase** is one of two Git utilities intended for [merging](https://www.codecademy.com/resources/docs/git/merge) changes from one branch into another. Essentially, it involves taking one branch and appending it to the end of another branch, with the "end" being represented by the latest commit in the branch. - -A more straightforward analogy is akin to reordering the chapters in a book to enhance its coherence. Instead of adding new chapters at the end, as in a merge, it repositions the changes onto a new base, hence the term "rebase." This process rewrites the history, resulting in a more seamless, linear timeline. It can be valuable for maintaining a clean and organized Git history. - -## Syntax - -To rebase the current branch onto another branch, run: - -```shell -git rebase -``` - -In this command, `` refers to the branch or commit to rebase the current branch onto. This command takes the changes from the current branch and applies them on top of the specified base branch or commit. - -The following command initiates an editor where rebase instructions for individual commits can be input. - -```shell -git rebase --interactive -``` - -## Rebasing a branch - -1. Make sure the working directory is clean: Commit or stash any changes in the current branch to ensure there are no uncommitted modifications. -2. Checkout the branch to rebase: Use `git checkout ` to switch to the branch to rebase. -3. Fetch the latest changes: Run `git fetch` to capture the latest changes from the remote repository. -4. Start the rebase: Start a rebase in either the regular or interactive modes. -5. Resolve conflicts (if any): Git will pause the rebase if there are conflicts. Use git status to identify the files with conflicts and resolve them manually. After resolving conflicts, use `git add ` and `git rebase --continue` to continue the rebase. -6. Complete the rebase: After resolving conflicts (if any), the rebase will continue automatically or when `git rebase --continue` is used. -7. Push the rebased branch: When working on a shared branch, it's essential to push the rebased branch with `git push` to update the remote branch. -8. Clean up (optional): Once the rebase is successful, the old branch can be deleted if needed with `git branch -d `. - -## Merge vs Squash vs Rebase - -### Merge Commit - -**Merge commits** integrate a feature branch into the main branch, keeping the full commit history and adding a merge commit to record the integration. - -**Scenario:** - -- Your main branch has two commits. -- You create a feature branch and make two commits, and your team adds a commit to the main branch. -- When you merge the feature branch into the main branch, a merge commit is added, preserving the history of all feature branch commits. - -```shell -# Create and switch to a feature branch -git checkout -b feature-branch - -# Make two commits on the feature branch -git commit -m "Feature commit 1" -git commit -m "Feature commit 2" - -# Switch back to main branch and simulate team commits -git checkout main -git commit -m "Main branch commit" - -# Merge the feature branch into main -git merge feature-branch -``` - -**Terminal Output:** - -```shell -* b4d1f6c Merge branch 'feature' -|\ -| * 9f8e7a2 Feature Commit 2 -| * 8c7d6b1 Feature Commit 1 -* | 6a5f4c3 Main Commit 3 -|/ -* 4e3d2f1 Main Commit 2 -* 1a2b3c4 Main Commit 1 -``` - -**Pros:** - -- Retains the complete commit history. -- Useful for debugging and tracing changes. - -**Cons:** - -- Creates a cluttered history, especially in large teams with frequent commits. -- `git log` can become confusing. - -## Squash Commit - -**Squash commits** condense multiple commits from a feature branch into a single commit while merging into the main branch. - -**Scenario:** - -- Your main branch has two commits. -- You create a feature branch, make two commits, and your team adds a commit to the main branch. -- When you squash merge, the two feature branch commits are combined into one and added as a single commit on top of the main branch. - -```shell -# Create and switch to a feature branch -git checkout -b feature-branch - -# Make two commits on the feature branch -git commit -m "Feature Commit 1" -git commit -m "Feature Commit 2" - -# Switch back to main branch and simulate a team commit -git checkout main -git commit -m "Main Commit 3" - -# Squash merge the feature branch into main -git merge --squash feature-branch -git commit -m "Squashed Feature Commit" -``` - -**Terminal Output:** - -```shell -* 3f4e5d6 Squashed Feature Commit -* 6a5f4c3 Main Commit 3 -* 4e3d2f1 Main Commit 2 -* 1a2b3c4 Main Commit 1 -``` - -**Pros:** - -- Produces a clean, linear history. -- Only a single commit represents the entire feature. - -**Cons:** - -- Loses granular commit history, making debugging harder. - -## Rebase Merge - -**Rebase merges** integrate commits from a feature branch by _replaying_ them onto the main branch without adding a merge commit. This results in a linear history. - -**Scenario:** - -- Your main branch has two commits. -- You create a feature branch, make two commits, and your team adds a commit to the main branch. -- When rebasing, the two feature branch commits are applied on top of the latest main branch commit, creating a straight-line history. - -```shell -# Create and switch to a feature branch -git checkout -b feature-branch - -# Make two commits on the feature branch -git commit -m "Feature commit 1" -git commit -m "Feature commit 2" - -# Switch back to main branch and simulate team commits -git checkout main -git commit -m "Main branch commit" - -# Rebase the feature branch onto main -git checkout feature-branch -git rebase main -``` - -**Terminal Output:** - -```shell -* 9f8e7a2 Feature Commit 2 -* 8c7d6b1 Feature Commit 1 -* 6a5f4c3 Main Commit 3 -* 4e3d2f1 Main Commit 2 -* 1a2b3c4 Main Commit 1 -``` - -**Pros:** - -- Creates a clean, linear commit history. -- Avoids unnecessary merge commits. - -**Cons:** - -- Resolving merge conflicts during a rebase can be more challenging. -- If the feature branch has multiple commits that modify the same code, conflicts may need to be resolved repeatedly. - -## Considerations for Using Git Rebase - -- Avoid rebasing on the main branch. -- Use rebase only on local branches. -- Never rebase a branch after it has been pushed to a shared repository. diff --git a/content/git/concepts/reflog/reflog.md b/content/git/concepts/reflog/reflog.md deleted file mode 100644 index df88f8c0918..00000000000 --- a/content/git/concepts/reflog/reflog.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -Title: 'Reflog' -Description: 'Tracks updates to references like HEAD, helping recover lost commits and debug repository changes.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'Github' - - 'Version Control' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -**Git Reflog** (short for reference log) is a mechanism that records updates to the tips of branches, commits, and other references. It provides a detailed history of actions performed in the repository, even for changes that are not part of the main commit history. - -Reflog is particularly useful for recovering lost commits or tracking the changes to references like `HEAD`. - -## Viewing the Reflog - -To view the reflog, the following command can be used: - -```shell -git reflog -``` - -In addition to the basic `git reflog` command, `git reflog show` can be used to view the reflog of a specific reference, such as a branch or tag: - -```pseudo -git reflog show -``` - -> **Note:** If no reference is provided, `git reflog show` defaults to the current `HEAD` reference. - -This will output a list of recent reference updates, including actions like `git commit`, `git merge`, `git rebase`, or even resets. Each entry is prefixed with an index, allowing users to reference past states. - -Here is an example output: - -```shell -1a2b3c4 (HEAD -> main) HEAD@{0}: commit: Add feature X -5d6e7f8 HEAD@{1}: reset: moving to HEAD~2 -8g9h0i1 HEAD@{2}: checkout: moving from feature to main -``` - -Each entry in the reflog follows this structure: - -- **Commit Hash**: The hash of the reference at that point. -- **Reference**: Describes the state of the repository (e.g., `HEAD`, `branch-name`). -- **Timestamp**: The time of the action. -- **Action Description**: Explains what changed (e.g., `git commit`, `git merge`, `git reset`). - -## Recovering Lost Commits - -The reflog is an invaluable tool for recovering commits that seem "lost". For example, if a branch is accidentally deleted or reset, the commits can still be recovered using the commit hash shown in the reflog. - -To recover a commit, the following command can simply be run: - -```pseudo -git checkout -``` - -Alternatively, a new branch from the commit can be created: - -```pseudo -git branch recovered-branch -``` - -## Using Reflog for Undoing Changes - -The reflog can be used to undo changes, such as resets or rebases: - -- Identify the desired state from the reflog using the command: - -```shell -git reflog -``` - -- Reset the repository to that state: - -```pseudo -git reset --hard HEAD@{n} -``` - -`{n}` needs to be replaced with the appropriate index from the reflog. - -## Clearing the Reflog - -Over time, the reflog can grow large. To clear or expire old entries, the following command can be used: - -```shell -git reflog expire --expire=30.days.ago --all -``` - -This removes reflog entries older than 30 days for all references. - -> **Note:** Reflog data is stored locally, so it’s unavailable in cloned repositories. The default expiration for reflog entries is 90 days, but this can be configured. diff --git a/content/git/concepts/remotes/remotes.md b/content/git/concepts/remotes/remotes.md deleted file mode 100644 index 1d6f9bcce05..00000000000 --- a/content/git/concepts/remotes/remotes.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -Title: 'Remotes' -Description: 'Repositories that are not local.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'GitHub' -CatalogContent: - - 'learn-git' - - 'learn-the-command-line' ---- - -Git **remotes** are copies of repositories that are not stored locally. Working with a remote often involves two copies or references: - -1. The forked repository (repo): By convention, these are named the `origin` remote which refers to the default repo. -2. The base or home repo: The `upstream` remote refers to the remote repo that is being tracked for changes and contributions. - -## Syntax - -Remotes can be set with the `git remote add` command: - -```shell -git remote add remotename remoteURL -``` - -## Adding Remotes Using Docs - -To manually set up the remotes, the forked repository would be named the `origin` remote: - -```pseudo -git remote add origin https://github.com/yourusername/docs.git -``` - -The base `Codecademy/docs` repo would be named the `upstream` remote: - -```shell -git remote add upstream https://github.com/Codecademy/docs.git -``` - -> **Note:** If the repository is cloned onto the computer, the remote defaults to `origin`. Additional set up would only be needed for the `upstream` remote. - -Run the `git remote -v` (`v` flag is for verbose) command to check the list of remotes: - -```shell -git remote -v -upstream https://github.com/Codecademy/docs.git (fetch) -upstream https://github.com/Codecademy/docs.git (pull) -``` diff --git a/content/git/concepts/reset/reset.md b/content/git/concepts/reset/reset.md deleted file mode 100644 index 6f4f8681c34..00000000000 --- a/content/git/concepts/reset/reset.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -Title: 'Reset' -Description: 'The git reset command is used to set the HEAD pointer back to a previous commit and optionally undo staged changes and the working tree.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'Version Control' -CatalogContent: - - 'learn-the-command-line' - - 'learn-git' ---- - -The **`reset`** command is used to change the state of the Git repository or undo commits. - -> **Note:** This command is ideal for undoing uncommitted changes made in a private, local repository. For undoing changes in a public, remote repository, the `revert` command is recommended. - -## Syntax - -```pseudo -git reset -``` - -This is run in the [terminal](https://www.codecademy.com/resources/docs/command-line/terminal). The `` and `` are discussed in more detail below. - -### Mode Options - -The `` refer to how far `reset` will go when rolling back changes to a previous commit, including: - -- Where the `HEAD` is pointing towards (usually done with just `git reset`). -- Whether the staging area or index, reflects the commit the `HEAD` is now pointing towards. -- Whether the working tree is rolled back to reflect the changes reset in the `HEAD` and staging area. - -More specifically, these modes include: - -- `--soft`: This rolls back to an earlier commit by moving the `HEAD` pointer towards it but leaving the staging area and working tree untouched, allowing for new commits to be made. -- `--mixed`: In addition to moving the `HEAD` pointer to an earlier commit, the staging area is cleared to reflect the changes made in that commit (this runs by default). -- `--hard`: This goes one step further and resets the working tree to reflect the previous commit reflected in the staging area and the `HEAD` pointer. - -If, for example, an error was made in a text file,`example.txt`, and the changes were accidentally [added](https://www.codecademy.com/resources/docs/git/add) and [committed](codecademy.com/resources/docs/git/commit), `git reset` can be used to go back to the state before that commit was made. - -### Referencing Commits - -The `commit-reference` refers to a commit's unique hash, or save point, that was generated after creation. This hash is a long string that is a mix of characters and numbers that is usually represented by a shorter version: `05df67f9066c8ddd95c8d7bb2137acfb8b18e167` -> `05df67f` - -`git reset` can be used with either the commit hash or with the `HEAD` keyword, which refers to the commit being viewed on the currently checked-out branch. - -Alternatively, a filename can be used in place of the `commit-reference` to undo a `git add` for a file that wasn't meant to be staged for commit. - -## Example - -This is what the terminal would look like after creating a commit by accident on the `main` branch and running [a `git status` check](https://www.codecademy.com/resources/docs/git/status): - -```shell -On branch main -nothing to commit, working tree clean -``` - -The text above indicates the following: - -- The `main` branch is up to date, with the `HEAD` pointing towards the most recent commit. -- There is nothing to commit in the staging area. -- New changes haven't been made yet in the working tree, hence why it is "clean". - -To set the `HEAD` back by one commit as well as clear the staging area, one of the following commands can be run: - -```shell -git reset HEAD~1 -git reset --mixed HEAD~1 -``` - -Since the `--mixed` mode runs by default, both of the commands are identical in function. This will do the following: - -- It will move the `HEAD` pointer back by one (`~1`) commit. -- The staging area will be cleared of changes. -- The overall state of the `main` branch is set to before changes in `example.txt` were added to the staging area for the previous commit. - -If `git status` is run once more, this should appear on the terminal: - -```shell -On branch main -Changes not staged for commit: - (use "git add ..." to update what will be committed) - (use "git restore ..." to discard changes in working directory) - modified: example.txt - -no changes added to commit (use "git add" and/or "git commit -a") -``` diff --git a/content/git/concepts/restore/restore.md b/content/git/concepts/restore/restore.md deleted file mode 100644 index cb9f299c2f1..00000000000 --- a/content/git/concepts/restore/restore.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -Title: 'Restore' -Description: 'The git restore command undoes changes in the working tree by restoring content from a source.' -Subjects: - - 'Bash/Shell' - - 'Developer Tools' -Tags: - - 'Git' - - 'Version Control' -CatalogContent: - - 'learn-the-command-line' - - 'learn-git' ---- - -The **`restore`** command enables developers to restore files to a specific state. This functionality restoring to undo any changes made to files in both the working directory and staging area. This command is particularly valuable when reverting alterations, whether staged for a commit or not. - -## Syntax - -The syntax of the `git restore` command is as follows: - -```pseudo -git restore -- -``` - -Nine additional options are available for `git restore`: - -- `-s --source=`: Allows restoring the working tree files with the content from the specified tree. -- `-p --patch`: Enables interactive selection of hunks in the difference between the restore source and the restore location. -- `-W --worktree -S --staged`: Specifies the restore location. If neither option is specified, by default the working tree is restored by default. -- `-q --quiet`: Suppresses feedback messages and implies `--no-progress`. -- `--progress --no-progress`: Control progress status reporting. -- `--ours --theirs`: Used when restoring files in the working tree from the index, to use stage #2 (ours) or #3 (theirs) for unmerged paths. -- `-m --merge`: Recreates the conflicted merge in the unmerged paths when restoring files to the working tree from the index. -- `--conflict= - Classes - - - -
-

PIZZA MAN

-
- -

- Pizza Man is a family-owned business since 1964. Our goal is to make the - best pizza and have it delivered to your place. -

-

We have 3 locations so far and growing.

- - -``` - -The code above will result in an output in a browser similar to: - -![Browser window with different text blocks formatted according to their class attribute](https://raw.githubusercontent.com/Codecademy/docs/main/media/html-classes-example-1.jpg) - -## For JavaScript - -The `class` attribute is used to perform [JavaScript](https://www.codecademy.com/resources/docs/javascript) operations on HTML elements. Through the Document Object Model ("DOM") there are various JavaScript methods built for selecting elements via their class. - -Assuming the markup from the last example is linked to a JavaScript file: - -```js -const innerDiv = document.getElementsByClassName('header-1')[0]; -console.log(innerDiv.textContent); -``` - -The code above selects the first element of a given class, and prints its content to the console. - -```shell -'PIZZA MAN' -``` diff --git a/content/html/concepts/attributes/terms/dir/dir.md b/content/html/concepts/attributes/terms/dir/dir.md deleted file mode 100644 index bff4a7f2f12..00000000000 --- a/content/html/concepts/attributes/terms/dir/dir.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -Title: 'dir' -Description: 'Sets the direction of the text of an HTML element.' -Subjects: - - 'Web Development' - - 'Web Design' -Tags: - - 'Attributes' - - 'Elements' - - 'Style' -CatalogContent: - - 'learn-html' - - 'paths/front-end-engineer-career-path' ---- - -The HTML global **`dir`** attribute sets the direction of an [HTML element](https://www.codecademy.com/resources/docs/html/elements)'s text. This is useful for languages that use right-to-left scripts like Adlam, Arabic, Dhivehi, Hebrew, Mandinka, N'Ko, Pashto, Persian, Pular, Sindhi, Syriac, Thaana, Urdu, Yiddish, etc. - -## Syntax - -```pseudo - -``` - -`dir` can be set to the following values: - -| Direction | Description | -| --------- | -------------------------------------------------------------------------------------------------------------------- | -| `ltr` | Default left-to-right text direction, i.e., English. | -| `rtl` | Right-to-left text direction, i.e., Arabic. | -| `auto` | The browser figures out the text direction based on the content (only recommended if the text direction is unknown). | - -> **Note:** Always declare the language using the `lang` attribute in conjunction with setting the text direction with the `dir` attribute. Language declarations do not imply directionality or vice versa. The two must be set separately. - -## Example 1 - -The following example sets the `dir` attribute on a [`

` element](https://www.codecademy.com/resources/docs/html/elements/p) to `rtl`: - -```html -

- This paragraph is in English but incorrectly goes right to left. -

-``` - -This results in the following output: - -![Incorrect use of dir attribute](https://raw.githubusercontent.com/Codecademy/docs/main/media/html-dir-incorrect.png) - -> **Note:** The punctuation mark, `.`, is placed at the front of the sentence when using `rtl` direction. The LRM control character `‎` can be placed at the end of the sentence to display the punctuation as if the text is left-to-right. - -## Example 2 - -The following example sets the `dir` attribute on a `

` element to `ltr`: - -```html -

This paragraph is in English and correctly goes left to right.

-``` - -This results in the following output: - -![Correct use of dir attribute](https://raw.githubusercontent.com/Codecademy/docs/main/media/html-dir-correct.png) diff --git a/content/html/concepts/attributes/terms/id/id.md b/content/html/concepts/attributes/terms/id/id.md deleted file mode 100644 index 869d90dbbcd..00000000000 --- a/content/html/concepts/attributes/terms/id/id.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -Title: 'id' -Description: 'Used to specify a unique id for an HTML element, which cannot be shared across multiple elements within the same HTML document.' -Subjects: - - 'Web Development' - - 'Web Design' -Tags: - - 'Attributes' - - 'Elements' - - 'Tags' -CatalogContent: - - 'learn-html' - - 'paths/front-end-engineer-career-path' ---- - -The HTML global **`id`** attribute is used to specify a unique identifier for an [HTML element](https://www.codecademy.com/resources/docs/html/elements). It cannot be shared across multiple elements within the same HTML document. The `id` attribute can be used as a bookmark to navigate to a specific point in a document. It can also serve as a selector in [CSS](https://www.codecademy.com/resources/docs/css) to style the element or to manipulate the element in [JavaScript](https://www.codecademy.com/resources/docs/javascript). Contrary to the [`class`](https://www.codecademy.com/resources/docs/html/classes) attribute, elements can only have one id value. - -## Syntax - -```pseudo -
My Element
-``` - -The syntax consists of `id` followed by the assignment operator (`=`) and an `id` name in quotation marks (`" "`). The `id` name is case-sensitive and must contain at least one character. It cannot start with a number or contain whitespaces. - -## Unique ID Attributes - -Specific and unique `id` attributes can be assigned to elements to differentiate them, and `id` values can be referenced in CSS and JavaScript to manipulate, format, and perform specific instructions on a single element alone, without affecting others of the same type. - -Valid `id` attribute values begin with a letter and must comprise only letters (`a`-`Z`), digits (`0`-`9`), hyphens (`-`), underscores (`_`), and periods (`.`). - -```html -

Hello World

-``` - -> **Note:** While `th1s_is.v4lid` is indeed a valid `id` value, it's best to use a consistent naming scheme such as camel case (`thisIsValid`), dash case (`this-is-valid`), or snake case (`this_is_valid`). - -## Example - -In the example below, the `

` (paragraph) element is given a unique identifier in its `id` attribute, and the text color is set using the `style` attribute: - -```html -

- Here's some text that is being altered by the HTML attributes -

-``` - -![Use of unique id attribute with inline CSS](https://raw.githubusercontent.com/Codecademy/docs/main/media/html-attribute-id-example-img1.png) - -## Navigation Using Bookmarks - -Bookmarks allow users to navigate on a webpage using links leading to another location on a page (i.e., to another element) with a specific `id`. - -### Example - -Element with a defined `id` attribute that serves as a bookmark: - -```html -

About my city

-``` - -Link to the bookmark: - -```html -Navigate to the section about my city -``` - -A link can also target a location on another page: - -```html -Jump to the section about my city -``` - -Clicking on the link in the examples above will direct the browser screen to the location where `id` is `"my-city"` (either on the same page or on another page). - -![Use of a unique id attribute for navigation on the same and other pages in the website](https://raw.githubusercontent.com/Codecademy/docs/main/media/html-attribute-id-example2-gif.gif) - -## Styling With `id` - -Similarly to the `class` attribute, `id` is typically used to assign styles to the element it identifies. However, only one specific element can be targeted with `id` (compared to the `class` attribute which can be used to target multiple elements at once). - -### Example - -Styling via `id` in a stylesheet: - -```css -#my-city { - color: #ff0000; -} -``` - -The HTML element with `id` is selected in CSS for styling using `#` followed by the `id` value. This applies to internal or external ruleset styling methods. The example above applies a color to the designated element, for an overview of all styling methods, please see [CSS Anatomy](https://www.codecademy.com/resources/docs/css/anatomy). - -![CSS styling using id selector](https://raw.githubusercontent.com/Codecademy/docs/main/media/html-attribute-id-exampl3.png) - -## Using `id` With JavaScript - -The `id` attribute is also used to manipulate the element through DOM (Document Object Model) with [JavaScript](https://www.codecademy.com/resources/docs/javascript). - -### Example - -```js -function changeColor(newColor) { - let element = document.getElementById('idOfElement'); - - element.style.color = newColor; -} -``` - -In the example above, the element is selected using the `getElementById()` method. The color of that element is then changed by assigning a new value, that is passed in as an argument of the function, to the `style.color` property. - -![Use of id attributes to style HTML elements in JavaScript](https://raw.githubusercontent.com/Codecademy/docs/main/media/html-attribute-id-example4.png) diff --git a/content/html/concepts/attributes/terms/lang/lang.md b/content/html/concepts/attributes/terms/lang/lang.md deleted file mode 100644 index f31d4fdff53..00000000000 --- a/content/html/concepts/attributes/terms/lang/lang.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -Title: 'lang' -Description: 'Specifies the language of the element’s content.' -Subjects: - - 'Web Development' - - 'Web Design' -Tags: - - 'HTML' - - 'Attributes' - - 'Accessibility' -CatalogContent: - - 'learn-html' - - 'paths/full-stack-engineer-career-path' ---- - -The `lang` attribute is a global HTML attribute used to set the language of the element’s content. It helps browsers, screen readers, and translation tools understand how to process and present the text. - -## Syntax - -```pseudo - -``` - -- `language-code`: Sets the language code for the element's content. - -## Example - -The following example demonstrates the usage of the `lang` attribute: - -```html - - - My Website - - -

Welcome to my website!

- - -``` - -The above code sets the language of the `` element's content to English (`en`). diff --git a/content/html/concepts/attributes/terms/src/src.md b/content/html/concepts/attributes/terms/src/src.md deleted file mode 100644 index 129ff838637..00000000000 --- a/content/html/concepts/attributes/terms/src/src.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -Title: 'src' -Description: 'Specifies the location of a digital source.' -Subjects: - - 'Web Development' - - 'Web Design' -Tags: - - 'Attributes' - - 'Elements' - - 'Style' -CatalogContent: - - 'learn-html' - - 'paths/front-end-engineer-career-path' ---- - -The **`src`** attribute specifies the location of a digital source, which is typically a URL or a [file path](https://www.codecademy.com/resources/docs/html/file-paths). It is required for HTML elements like [``](https://www.codecademy.com/resources/docs/html/elements/img) so that they can appear on a website or application. - -## Syntax - -```pseudo - -``` - -`src` can also be used in the following elements: - -| HTML Tag | Description | -| ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | -| [`