Merge branch 'master' into feat/xyflow

pull/7803/head
Arik Chakma 3 weeks ago
commit ad8ae9e576
  1. 2
      .astro/settings.json
  2. 8
      .env.example
  3. 15
      astro.config.mjs
  4. 4
      package.json
  5. BIN
      public/og-images/ai-tutor.png
  6. BIN
      public/pdfs/roadmaps/cpp.pdf
  7. 84
      public/roadmap-content/ai-engineer.json
  8. 28
      public/roadmap-content/angular.json
  9. 4
      public/roadmap-content/api-design.json
  10. 86
      public/roadmap-content/aspnet-core.json
  11. 5
      public/roadmap-content/backend.json
  12. 59
      public/roadmap-content/computer-science.json
  13. 742
      public/roadmap-content/cpp.json
  14. 52
      public/roadmap-content/cyber-security.json
  15. 5
      public/roadmap-content/data-analyst.json
  16. 10
      public/roadmap-content/devops.json
  17. 15
      public/roadmap-content/engineering-manager.json
  18. 6
      public/roadmap-content/full-stack.json
  19. 30
      public/roadmap-content/game-developer.json
  20. 5
      public/roadmap-content/git-github.json
  21. 70
      public/roadmap-content/java.json
  22. 7
      public/roadmap-content/javascript.json
  23. 163
      public/roadmap-content/mlops.json
  24. 264
      public/roadmap-content/nodejs.json
  25. 4
      public/roadmap-content/php.json
  26. 9
      public/roadmap-content/postgresql-dba.json
  27. 12
      public/roadmap-content/python.json
  28. 40
      public/roadmap-content/qa.json
  29. 10
      public/roadmap-content/redis.json
  30. 220
      public/roadmap-content/server-side-game-developer.json
  31. 35
      public/roadmap-content/software-architect.json
  32. 12
      public/roadmap-content/sql.json
  33. 7
      public/roadmap-content/system-design.json
  34. 15
      public/roadmap-content/typescript.json
  35. 5
      public/roadmap-content/vue.json
  36. BIN
      public/roadmaps/cpp.png
  37. 13
      src/api/ai-roadmap.ts
  38. 16
      src/components/AccountSidebar.astro
  39. 1
      src/components/Activity/ProjectProgress.tsx
  40. 2
      src/components/Activity/ResourceProgress.tsx
  41. 109
      src/components/Analytics/GoogleAd.astro
  42. 59
      src/components/Analytics/GoogleAdSlot.astro
  43. 19
      src/components/Analytics/RedditPixel.astro
  44. 2
      src/components/AstroIcon.astro
  45. 2
      src/components/AuthenticationFlow/CourseLoginPopup.tsx
  46. 8
      src/components/AuthenticationFlow/EmailSignupForm.tsx
  47. 16
      src/components/AuthenticationFlow/GitHubButton.tsx
  48. 19
      src/components/AuthenticationFlow/GoogleButton.tsx
  49. 11
      src/components/AuthenticationFlow/LinkedInButton.tsx
  50. 2
      src/components/AuthenticationFlow/LoginPopup.astro
  51. 226
      src/components/Billing/BillingPage.tsx
  52. 39
      src/components/Billing/BillingWarning.tsx
  53. 22
      src/components/Billing/CheckSubscriptionVerification.tsx
  54. 68
      src/components/Billing/EmptyBillingScreen.tsx
  55. 96
      src/components/Billing/UpdatePlanConfirmation.tsx
  56. 306
      src/components/Billing/UpgradeAccountModal.tsx
  57. 76
      src/components/Billing/VerifyUpgrade.tsx
  58. 1
      src/components/CustomRoadmap/RoadmapHeader.tsx
  59. 33
      src/components/CustomRoadmap/RoadmapHint.tsx
  60. 19
      src/components/Dashboard/DashboardAiRoadmaps.tsx
  61. 2
      src/components/Dashboard/DashboardCustomProgressCard.tsx
  62. 3
      src/components/Dashboard/DashboardProgressCard.tsx
  63. 11
      src/components/Dashboard/ListDashboardCustomProgress.tsx
  64. 2
      src/components/ExploreAIRoadmap/AIRoadmapsList.tsx
  65. 2
      src/components/ExploreAIRoadmap/EmptyRoadmaps.tsx
  66. 172
      src/components/GenerateCourse/AICourse.tsx
  67. 116
      src/components/GenerateCourse/AICourseActions.tsx
  68. 82
      src/components/GenerateCourse/AICourseCard.tsx
  69. 484
      src/components/GenerateCourse/AICourseContent.tsx
  70. 19
      src/components/GenerateCourse/AICourseFooter.tsx
  71. 503
      src/components/GenerateCourse/AICourseLesson.tsx
  72. 131
      src/components/GenerateCourse/AICourseLessonChat.css
  73. 484
      src/components/GenerateCourse/AICourseLessonChat.tsx
  74. 79
      src/components/GenerateCourse/AICourseLimit.tsx
  75. 80
      src/components/GenerateCourse/AICourseOutlineHeader.tsx
  76. 117
      src/components/GenerateCourse/AICourseOutlineView.tsx
  77. 252
      src/components/GenerateCourse/AICourseRoadmapView.tsx
  78. 46
      src/components/GenerateCourse/AICourseSearch.tsx
  79. 205
      src/components/GenerateCourse/AICourseSidebarModuleList.tsx
  80. 103
      src/components/GenerateCourse/AILimitsPopup.tsx
  81. 81
      src/components/GenerateCourse/AIRoadmapViewSwitch.tsx
  82. 57
      src/components/GenerateCourse/CircularProgress.tsx
  83. 103
      src/components/GenerateCourse/FineTuneCourse.tsx
  84. 166
      src/components/GenerateCourse/GenerateAICourse.tsx
  85. 107
      src/components/GenerateCourse/GetAICourse.tsx
  86. 69
      src/components/GenerateCourse/ModifyCoursePrompt.tsx
  87. 88
      src/components/GenerateCourse/RegenerateLesson.tsx
  88. 89
      src/components/GenerateCourse/RegenerateOutline.tsx
  89. 42
      src/components/GenerateCourse/Resizeable.tsx
  90. 473
      src/components/GenerateCourse/TestMyKnowledgeAction.tsx
  91. 195
      src/components/GenerateCourse/UserCoursesList.tsx
  92. 48
      src/components/GenerateRoadmap/AITermSuggestionInput.tsx
  93. 121
      src/components/GenerateRoadmap/GenerateRoadmap.tsx
  94. 114
      src/components/GenerateRoadmap/IncreaseRoadmapLimit.tsx
  95. 171
      src/components/GenerateRoadmap/OpenAISettings.tsx
  96. 50
      src/components/GenerateRoadmap/PickLimitOption.tsx
  97. 10
      src/components/GenerateRoadmap/ReferYourFriend.tsx
  98. 96
      src/components/GenerateRoadmap/RoadmapSearch.tsx
  99. 48
      src/components/GenerateRoadmap/RoadmapTopicDetail.tsx
  100. 4
      src/components/Guide/RelatedGuides.tsx
  101. Some files were not shown because too many files have changed in this diff Show More

@ -3,6 +3,6 @@
"enabled": false
},
"_variables": {
"lastUpdateCheck": 1739229597159
"lastUpdateCheck": 1742812122664
}
}

@ -1,4 +1,10 @@
PUBLIC_API_URL=https://api.roadmap.sh
PUBLIC_AVATAR_BASE_URL=https://dodrc8eu8m09s.cloudfront.net/avatars
PUBLIC_EDITOR_APP_URL=https://draw.roadmap.sh
PUBLIC_COURSE_APP_URL=http://localhost:5173
PUBLIC_COURSE_APP_URL=http://localhost:5173
PUBLIC_STRIPE_INDIVIDUAL_MONTHLY_PRICE_ID=
PUBLIC_STRIPE_INDIVIDUAL_YEARLY_PRICE_ID=
PUBLIC_STRIPE_INDIVIDUAL_MONTHLY_PRICE_AMOUNT=10
PUBLIC_STRIPE_INDIVIDUAL_YEARLY_PRICE_AMOUNT=100

@ -11,6 +11,21 @@ import react from '@astrojs/react';
// https://astro.build/config
export default defineConfig({
site: 'https://roadmap.sh/',
redirects: {
'/devops/devops-engineer': {
status: 301,
destination: '/devops',
},
'/ai-tutor': {
status: 301,
destination: '/ai',
},
},
vite: {
server: {
allowedHosts: ['roadmap.sh', 'port3k.kamranahmed.info'],
},
},
markdown: {
shikiConfig: {
theme: 'dracula',

@ -55,6 +55,7 @@
"js-cookie": "^3.0.5",
"lucide-react": "^0.452.0",
"luxon": "^3.5.0",
"markdown-it-async": "^2.0.0",
"nanoid": "^5.0.7",
"nanostores": "^0.11.3",
"node-html-parser": "^6.1.13",
@ -65,6 +66,8 @@
"react-calendar-heatmap": "^1.9.0",
"react-confetti": "^6.1.0",
"react-dom": "^18.3.1",
"react-resizable-panels": "^2.1.7",
"react-textarea-autosize": "^8.5.7",
"react-tooltip": "^5.28.0",
"rehype-external-links": "^3.0.0",
"remark-parse": "^11.0.0",
@ -73,6 +76,7 @@
"satori": "^0.11.2",
"satori-html": "^0.3.2",
"sharp": "^0.33.5",
"shiki": "^3.1.0",
"slugify": "^1.6.6",
"tailwind-merge": "^2.5.3",
"tailwindcss": "^3.4.13",

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

@ -30,7 +30,7 @@
"type": "article"
},
{
"title": "AI engineers: What they do and how to become one",
"title": "AI Engineers: What they do and how to become one",
"url": "https://www.techtarget.com/whatis/feature/How-to-become-an-artificial-intelligence-engineer",
"type": "article"
}
@ -162,17 +162,17 @@
"description": "Retrieval-Augmented Generation (RAG) is an AI approach that combines information retrieval with language generation to create more accurate, contextually relevant outputs. It works by first retrieving relevant data from a knowledge base or external source, then using a language model to generate a response based on that information. This method enhances the accuracy of generative models by grounding their outputs in real-world data, making RAG ideal for tasks like question answering, summarization, and chatbots that require reliable, up-to-date information.\n\nLearn more from the following resources:",
"links": [
{
"title": "What is Retrieval Augmented Generation (RAG)?",
"title": "What is Retrieval Augmented Generation (RAG)? - Datacamp",
"url": "https://www.datacamp.com/blog/what-is-retrieval-augmented-generation-rag",
"type": "article"
},
{
"title": "What is Retrieval-Augmented Generation? Google",
"title": "What is Retrieval-Augmented Generation? - Google",
"url": "https://cloud.google.com/use-cases/retrieval-augmented-generation",
"type": "article"
},
{
"title": "What is Retrieval-Augmented Generation? IBM",
"title": "What is Retrieval-Augmented Generation? - IBM",
"url": "https://www.youtube.com/watch?v=T-D1OfcDW1M",
"type": "video"
}
@ -183,7 +183,7 @@
"description": "Prompt engineering is the process of crafting effective inputs (prompts) to guide AI models, like GPT, to generate desired outputs. It involves strategically designing prompts to optimize the model’s performance by providing clear instructions, context, and examples. Effective prompt engineering can improve the quality, relevance, and accuracy of responses, making it essential for applications like chatbots, content generation, and automated support. By refining prompts, developers can better control the model’s behavior, reduce ambiguity, and achieve more consistent results, enhancing the overall effectiveness of AI-driven systems.\n\nLearn more from the following resources:",
"links": [
{
"title": "Visit DedicatedPrompt Engineering Roadmap",
"title": "Visit Dedicated Prompt Engineering Roadmap",
"url": "https://roadmap.sh/prompt-engineering",
"type": "article"
},
@ -204,7 +204,7 @@
"type": "article"
},
{
"title": "Ai agents and their types",
"title": "AI Agents and Their Types",
"url": "https://play.ht/blog/ai-agents-use-cases/",
"type": "article"
},
@ -359,7 +359,7 @@
"description": "Anthropic's Claude is an AI language model designed to facilitate safe and scalable AI systems. Named after Claude Shannon, the father of information theory, Claude focuses on responsible AI use, emphasizing safety, alignment with human intentions, and minimizing harmful outputs. Built as a competitor to models like OpenAI's GPT, Claude is designed to handle natural language tasks such as generating text, answering questions, and supporting conversations, with a strong focus on aligning AI behavior with user goals while maintaining transparency and avoiding harmful biases.\n\nLearn more from the following resources:",
"links": [
{
"title": "Claude Website",
"title": "Claude",
"url": "https://claude.ai",
"type": "article"
},
@ -439,7 +439,7 @@
"description": "Mistral AI is a company focused on developing open-weight, large language models (LLMs) to provide high-performance AI solutions. Mistral aims to create models that are both efficient and versatile, making them suitable for a wide range of natural language processing tasks, including text generation, translation, and summarization. By releasing open-weight models, Mistral promotes transparency and accessibility, allowing developers to customize and deploy AI solutions more flexibly compared to proprietary models.\n\nLearn more from the resources:",
"links": [
{
"title": "Minstral AI Website",
"title": "Mistral AI",
"url": "https://mistral.ai/",
"type": "article"
},
@ -455,7 +455,7 @@
"description": "Cohere is an AI platform that specializes in natural language processing (NLP) by providing large language models designed to help developers build and deploy text-based applications. Cohere’s models are used for tasks such as text classification, language generation, semantic search, and sentiment analysis. Unlike some other providers, Cohere emphasizes simplicity and scalability, offering an easy-to-use API that allows developers to fine-tune models on custom data for specific use cases. Additionally, Cohere provides robust multilingual support and focuses on ensuring that its NLP solutions are both accessible and enterprise-ready, catering to a wide range of industries.\n\nLearn more from the following resources:",
"links": [
{
"title": "Cohere Website",
"title": "Cohere",
"url": "https://cohere.com/",
"type": "article"
},
@ -482,7 +482,7 @@
"description": "The OpenAI API provides access to powerful AI models like GPT, Codex, DALL-E, and Whisper, enabling developers to integrate capabilities such as text generation, code assistance, image creation, and speech recognition into their applications via a simple, scalable interface.\n\nLearn more from the following resources:",
"links": [
{
"title": "Open AI API",
"title": "OpenAI API",
"url": "https://openai.com/api/",
"type": "article"
}
@ -514,7 +514,7 @@
"type": "article"
},
{
"title": "How to write AI prompts",
"title": "How to Write AI prompts",
"url": "https://www.descript.com/blog/article/how-to-write-ai-prompts",
"type": "article"
},
@ -626,7 +626,7 @@
"type": "article"
},
{
"title": "What is a prompt injection attack?",
"title": "What is a Prompt Injection Attack?",
"url": "https://www.wiz.io/academy/prompt-injection-attack",
"type": "article"
}
@ -706,7 +706,7 @@
"description": "Sending end-user IDs in your requests can be a useful tool to help OpenAI monitor and detect abuse. This allows OpenAI to provide your team with more actionable feedback in the event that we detect any policy violations in your application.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Sending end-user IDs - OpenAi",
"title": "Sending End-user IDs - OpenAI",
"url": "https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids",
"type": "article"
}
@ -792,7 +792,7 @@
"description": "Open-source large language models (LLMs) are models whose source code and architecture are publicly available for use, modification, and distribution. They are built using machine learning algorithms that process and generate human-like text, and being open-source, they promote transparency, innovation, and community collaboration in their development and application.\n\nLearn more from the following resources:",
"links": [
{
"title": "The best large language models (LLMs) in 2024",
"title": "The Best Large Language Models (LLMs) in 2024",
"url": "https://zapier.com/blog/best-llm/",
"type": "article"
},
@ -813,7 +813,7 @@
"type": "course"
},
{
"title": "Hugging Face Website",
"title": "Hugging Face",
"url": "https://huggingface.co",
"type": "article"
},
@ -898,7 +898,7 @@
"description": "Ollama is a platform that offers large language models (LLMs) designed to run locally on personal devices, enabling AI functionality without relying on cloud services. It focuses on privacy, performance, and ease of use by allowing users to deploy models directly on laptops, desktops, or edge devices, providing fast, offline AI capabilities. With tools like the Ollama SDK, developers can integrate these models into their applications for tasks such as text generation, summarization, and more, benefiting from reduced latency, greater data control, and seamless local processing.\n\nLearn more from the following resources:",
"links": [
{
"title": "Ollama Website",
"title": "Ollama",
"url": "https://ollama.com/",
"type": "article"
},
@ -983,12 +983,12 @@
"description": "In the context of embeddings, recommendation systems use vector representations to capture similarities between items, such as products or content. By converting items and user preferences into embeddings, these systems can measure how closely related different items are based on vector proximity, allowing them to recommend similar products or content based on a user's past interactions. This approach improves recommendation accuracy and efficiency by enabling meaningful, scalable comparisons of complex data.\n\nLearn more from the following resources:",
"links": [
{
"title": "What role does AI play in recommendation systems and engines?",
"title": "What Role does AI Play in Recommendation Systems and Engines?",
"url": "https://www.algolia.com/blog/ai/what-role-does-ai-play-in-recommendation-systems-and-engines/",
"type": "article"
},
{
"title": "What is a recommendation engine?",
"title": "What is a Recommendation Engine?",
"url": "https://www.ibm.com/think/topics/recommendation-engine",
"type": "article"
}
@ -1009,6 +1009,11 @@
"title": "Data Classification",
"description": "Once data is embedded, a classification algorithm, such as a neural network or a logistic regression model, can be trained on these embeddings to classify the data into different categories. The advantage of using embeddings is that they capture underlying relationships and similarities between data points, even if the raw data is complex or high-dimensional, improving classification accuracy in tasks like text classification, image categorization, and recommendation systems.\n\nLearn more from the following resources:",
"links": [
{
"title": "What Is Data Classification?",
"url": "https://www.paloaltonetworks.com/cyberpedia/data-classification",
"type": "article"
},
{
"title": "Text Embeddings, Classification, and Semantic Search (w/ Python Code)",
"url": "https://www.youtube.com/watch?v=sNa_uiqSlJo",
@ -1050,10 +1055,10 @@
},
"4GArjDYipit4SLqKZAWDf": {
"title": "Pricing Considerations",
"description": "The pricing for the OpenAI Embedding API is based on the number of tokens processed and the specific embedding model used. Costs are determined by the total tokens needed to generate embeddings, so longer texts will result in higher charges. To manage costs, developers can optimize by shortening inputs or batching requests. Additionally, selecting the right embedding model for your performance and budget requirements, along with monitoring token usage, can help control expenses.",
"description": "The pricing for the OpenAI Embedding API is based on the number of tokens processed and the specific embedding model used. Costs are determined by the total tokens needed to generate embeddings, so longer texts will result in higher charges. To manage costs, developers can optimize by shortening inputs or batching requests. Additionally, selecting the right embedding model for your performance and budget requirements, along with monitoring token usage, can help control expenses.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "OpenAI API Pricing",
"title": "OpenAI Pricing",
"url": "https://openai.com/api/pricing/",
"type": "article"
}
@ -1061,8 +1066,19 @@
},
"apVYIV4EyejPft25oAvdI": {
"title": "Open-Source Embeddings",
"description": "Open-source embeddings are pre-trained vector representations of data, usually text, that are freely available for use and modification. These embeddings capture semantic meanings, making them useful for tasks like semantic search, text classification, and clustering. Examples include Word2Vec, GloVe, and FastText, which represent words as vectors based on their context in large corpora, and more advanced models like Sentence-BERT and CLIP that provide embeddings for sentences and images. Open-source embeddings allow developers to leverage pre-trained models without starting from scratch, enabling faster development and experimentation in natural language processing and other AI applications.",
"links": []
"description": "Open-source embeddings are pre-trained vector representations of data, usually text, that are freely available for use and modification. These embeddings capture semantic meanings, making them useful for tasks like semantic search, text classification, and clustering. Examples include Word2Vec, GloVe, and FastText, which represent words as vectors based on their context in large corpora, and more advanced models like Sentence-BERT and CLIP that provide embeddings for sentences and images. Open-source embeddings allow developers to leverage pre-trained models without starting from scratch, enabling faster development and experimentation in natural language processing and other AI applications.\n\nLearn more from the following resources:",
"links": [
{
"title": "Embeddings",
"url": "https://platform.openai.com/docs/guides/embeddings",
"type": "article"
},
{
"title": "A Guide to Open-Source Embedding Models",
"url": "https://www.bentoml.com/blog/a-guide-to-open-source-embedding-models",
"type": "article"
}
]
},
"ZV_V6sqOnRodgaw4mzokC": {
"title": "Sentence Transformers",
@ -1288,8 +1304,14 @@
},
"ZcbRPtgaptqKqWBgRrEBU": {
"title": "Performing Similarity Search",
"description": "In a similarity search, the process begins by converting the user’s query (such as a piece of text or an image) into an embedding—a vector representation that captures the query’s semantic meaning. This embedding is generated using a pre-trained model, such as BERT for text or a neural network for images. Once the query is converted into a vector, it is compared to the embeddings stored in the vector database.",
"links": []
"description": "In a similarity search, the process begins by converting the user’s query (such as a piece of text or an image) into an embedding—a vector representation that captures the query’s semantic meaning. This embedding is generated using a pre-trained model, such as BERT for text or a neural network for images. Once the query is converted into a vector, it is compared to the embeddings stored in the vector database.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "What is Similarity Search & How Does it work?",
"url": "https://www.truefoundry.com/blog/similarity-search",
"type": "article"
}
]
},
"lVhWhZGR558O-ljHobxIi": {
"title": "RAG & Implementation",
@ -1396,7 +1418,7 @@
"type": "article"
},
{
"title": "Retrieval Augmented Generation (RAG) with vector databases: Expanding AI Capabilities",
"title": "Retrieval Augmented Generation (RAG) with Vector Databases: Expanding AI Capabilities",
"url": "https://objectbox.io/retrieval-augmented-generation-rag-with-vector-databases-expanding-ai-capabilities/",
"type": "article"
}
@ -1508,7 +1530,7 @@
"description": "Replicate is a platform that allows developers to run machine learning models in the cloud without needing to manage infrastructure. It provides a simple API for deploying and scaling models, making it easy to integrate AI capabilities like image generation, text processing, and more into applications. Users can select from a library of pre-trained models or deploy their own, with the platform handling tasks like scaling, monitoring, and versioning.\n\nLearn more from the following resources:",
"links": [
{
"title": "Replicate Website",
"title": "Replicate",
"url": "https://replicate.com/",
"type": "article"
},
@ -1529,7 +1551,7 @@
"type": "article"
},
{
"title": "Ai agents and their types",
"title": "AI agents and their types",
"url": "https://play.ht/blog/ai-agents-use-cases/",
"type": "article"
},
@ -1662,7 +1684,7 @@
"description": "Multimodal AI enhances image understanding by integrating visual data with other types of information, such as text or audio. By combining these inputs, AI models can interpret images more comprehensively, recognizing objects, scenes, and actions, while also understanding context and related concepts. For example, an AI system could analyze an image and generate descriptive captions, or provide explanations based on both visual content and accompanying text.\n\nLearn more from the following resources:",
"links": [
{
"title": "Low or high fidelity image understanding - OpenAI",
"title": "Low or High Fidelity Image Understanding - OpenAI",
"url": "https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding",
"type": "article"
}
@ -1673,7 +1695,7 @@
"description": "Image generation is a process in artificial intelligence where models create new images based on input prompts or existing data. It involves using generative models like GANs (Generative Adversarial Networks), VAEs (Variational Autoencoders), or more recently, transformer-based models like DALL-E and Stable Diffusion.\n\nLearn more from the following resources:",
"links": [
{
"title": "DALL-E Website",
"title": "DALL-E",
"url": "https://openai.com/index/dall-e-2/",
"type": "article"
},
@ -1827,7 +1849,7 @@
"description": "LangChain is a framework designed to build applications that integrate multiple AI models, especially those focusing on language understanding, generation, and multimodal capabilities. For multimodal apps, LangChain facilitates seamless interaction between text, image, and even audio models, enabling developers to create complex workflows that can process and analyze different types of data.\n\nLearn more from the following resources:",
"links": [
{
"title": "LangChain Website",
"title": "LangChain",
"url": "https://www.langchain.com/",
"type": "article"
},
@ -1865,7 +1887,7 @@
},
{
"title": "Aider - AI Pair Programming in Terminal",
"url": "https://github.com/Aider-AI/aider",
"url": "https://aider.chat/",
"type": "article"
},
{

@ -379,8 +379,13 @@
"type": "article"
},
{
"title": "Explore top posts about React Hooks",
"url": "https://app.daily.dev/tags/react-hooks?ref=roadmapsh",
"title": "Angular Lifecycle Hooks — Everything you need to know",
"url": "https://medium.com/@sinanozturk/angular-component-lifecycle-hooks-2f600c48dff3",
"type": "article"
},
{
"title": "Explore top posts about Angular LifeCycle Hooks",
"url": "https://dev.to/search?utf8=%E2%9C%93&q=angular+hook",
"type": "article"
}
]
@ -1155,20 +1160,10 @@
"url": "https://angular.dev/guide/di/creating-injectable-service",
"type": "article"
},
{
"title": "What is an Angular Service",
"url": "https://www.javatpoint.com/what-is-an-angular-service",
"type": "article"
},
{
"title": "Service for API Calls",
"url": "https://www.knowledgehut.com/blog/web-development/make-api-calls-angular",
"type": "article"
},
{
"title": "Service Tutorial with Example",
"url": "https://www.positronx.io/angular-service-tutorial-with-example/",
"type": "article"
}
]
},
@ -1223,11 +1218,6 @@
"url": "https://angular.dev/guide/forms/reactive-forms",
"type": "article"
},
{
"title": "Angular Reactive Forms",
"url": "https://www.javatpoint.com/angular-reactive-forms",
"type": "article"
},
{
"title": "How To Use Reactive Forms in Angular",
"url": "https://www.digitalocean.com/community/tutorials/angular-reactive-forms-introduction",
@ -1250,8 +1240,8 @@
"description": "Since Angular 14, reactive forms are strictly typed by default. You don't have to define extra custom types or add a ton of type annotations to your form declarations to benefit from this extra type safety, as Angular will infer types from the default value of a form control. Non-typed forms are still supported. To use them, you must import the `Untyped` symbols from `@angular/forms`.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Angular Official Docs - @let",
"url": "https://angular.dev/api/core/@let",
"title": "Angular Official Docs - Typed Forms",
"url": "https://angular.dev/guide/forms/typed-forms",
"type": "article"
},
{

@ -176,8 +176,8 @@
"type": "article"
},
{
"title": "Cookies - Mozilla",
"url": "https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies",
"title": "Using HTTP cookies - Mozilla",
"url": "https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies",
"type": "article"
}
]

@ -231,11 +231,6 @@
"title": "Data Structures and Algorithms",
"description": "As the name indicates, a **Data Structure** is a way of organizing the data in the **memory** so it can be used efficiently. Some common data structures are array, linked list, stack, hashtable, queue, tree, heap, and graph.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Data Structures and Algorithms",
"url": "https://www.javatpoint.com/data-structure-tutorial",
"type": "article"
},
{
"title": "C# resources",
"url": "https://dev.to/adavidoaiei/fundamental-data-structures-and-algorithms-in-c-4ocf",
@ -483,7 +478,7 @@
]
},
"qpVxwuyA2oE06MZLtEdP1": {
"title": "Razon Pages",
"title": "Razor Pages",
"description": "Razor Pages is a feature of the [ASP.NET](http://ASP.NET) Core framework that allows developers to build web applications using a combination of Razor markup (a markup syntax for defining dynamic HTML) and C# code. Razor Pages is built on top of the [ASP.NET](http://ASP.NET) Core MVC (Model-View-Controller) framework, and provides a simpler, more intuitive way to build web pages and handle user input.\n\nRazor Pages are useful for building simple, self-contained web pages that do not require a complex navigation or layout structure, and are often used for building small to medium-size web applications.\n\nFor more information, visit the following links:",
"links": [
{
@ -573,8 +568,29 @@
},
"R7Qk5hsEIl9dspQXdaJAJ": {
"title": "StyleCop Rules",
"description": "",
"links": []
"description": "StyleCop is a tool used for developers to standardize their code and ensure they all follow the same syntax principles. With StyleCop, one standard can be defined in a `stylecop.json` file and shared across your team so that each member has the same guidelines when formatting your code. Beyond a single project, StyleCop can also be added as an extension, so all of the projects on your IDE follow the same formatting rules, this is especially useful if your organization follows the same rule standards for all projects.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "StyleCop GitHub official page",
"url": "https://github.com/StyleCop/StyleCop",
"type": "opensource"
},
{
"title": "StyeleCop Analyzers, a more modern version of StyleCop",
"url": "https://github.com/DotNetAnalyzers/StyleCopAnalyzers",
"type": "opensource"
},
{
"title": "StyleCop: A Detailed Guide to Starting and Using It",
"url": "https://blog.submain.com/stylecop-detailed-guide/",
"type": "article"
},
{
"title": "The StyleCop setup and Advantages",
"url": "https://www.youtube.com/watch?v=dmpOKmz3lPw",
"type": "video"
}
]
},
"ipABerBcM9zCte9pYaIse": {
"title": "Minimal APIs",
@ -1610,8 +1626,19 @@
},
"w5RnrhsP4p-AdSOLYVAY9": {
"title": "Gridlify",
"description": "",
"links": []
"description": "Gridify offers a powerful string-based dynamic LINQ query language that is both simple and easy to use. Gridify is a dynamic LINQ library that simplifies the process of converting strings to LINQ queries. Gridify makes it effortless to apply filtering, sorting, and pagination using text-based data. It also has a Javascript/Typescript client to integrate the Gridify with the frontend tables.\n\nFor more information, visit the following links:",
"links": [
{
"title": "Gridify Library",
"url": "https://github.com/alirezanet/Gridify",
"type": "opensource"
},
{
"title": "Working with Dynamic Filters Using Gridify in .NET",
"url": "https://levelup.gitconnected.com/working-with-dynamic-filters-using-gridify-in-net-6bba618dd9f8",
"type": "article"
}
]
},
"YojZ5fpzw-5WgoqqkO6wl": {
"title": "Odata",
@ -1825,8 +1852,14 @@
},
"oMMBzRrHkUymxAR4oqr75": {
"title": "Manual Mapping",
"description": "",
"links": []
"description": "Manual object mapping in [ASP.NET](http://ASP.NET) Core means explicitly assigning values from one object to another without using third-party libraries like AutoMapper. This approach gives you full control over how properties are mapped and allows for custom transformations if needed.\n\nFor instance, if an **Employee** entity has properties such as Id, Name, Email, and Department, and we need to convert it into an **EmployeeDTO** without exposing sensitive data like Id, a manual mapping method can selectively map only the necessary fields. However, it comes with trade-offs, such as increased boilerplate code and the need for manual updates whenever the data model changes. In a real-world [ASP.NET](http://ASP.NET) Core application, manual mapping can be implemented using static helper methods or extension methods that take an entity as input and return a DTO, ensuring that the mapping logic remains centralized and reusable across different parts of the application.\n\nTo learn more, visit the following resources:",
"links": [
{
"title": "Manual vs Automapping in ASP.NET?",
"url": "https://medium.com/@anderson.buenogod/manual-vs-automated-mapping-in-c-which-approach-is-best-for-your-project-50de1fd73bfa",
"type": "article"
}
]
},
"s57tKy1rajlJbKFDVXLqs": {
"title": "Task Scheduling",
@ -2311,10 +2344,31 @@
}
]
},
"azuer-service-bus@gBuaVZfqJ0-g21sKohQtx.md": {
"title": "Azuer Service Bus",
"description": "",
"links": []
"gBuaVZfqJ0-g21sKohQtx": {
"title": "Azure Service Bus",
"description": "Azure Service Bus is a scalable and reliable messaging platform that can handle a high volume of messages, it's also easy to use, has a lot of features like subscription, Topics, Dead Letter, and easy to integrate with other Azure services, and it's a managed service which means Microsoft takes care of the infrastructure and scaling. However, it's worth noting that Azure Service Bus is a paid service and the cost will depend on the number of messages and the size of the data that you are sending and receiving.\n\nTo learn more, visit the following links:",
"links": [
{
"title": "Getting Started With Azure Service Bus and ASP.NET Core",
"url": "https://www.c-sharpcorner.com/article/get-started-with-azure-service-bus-queues-asp-net-core-part-1/",
"type": "article"
},
{
"title": "How to Send & receive messages from Azure Service Bus queue (.NET)?",
"url": "https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues?tabs=passwordless",
"type": "article"
},
{
"title": "What is Azure Service Bus?",
"url": "https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messaging-overview",
"type": "article"
},
{
"title": "Explore top posts about Azure",
"url": "https://app.daily.dev/tags/azure?ref=roadmapsh",
"type": "article"
}
]
},
"SQKIUa_UsJ4cls-Vs9yHU": {
"title": "Mass Transit",

@ -389,6 +389,11 @@
"title": "Git & GitHub Crash Course For Beginners",
"url": "https://www.youtube.com/watch?v=SWYqp7iY_Tc",
"type": "video"
},
{
"title": "Learn Git - Full Course",
"url": "https://www.youtube.com/watch?v=rH3zE7VlIMs",
"type": "video"
}
]
},

@ -336,11 +336,6 @@
"url": "https://roadmap.sh/datastructures-and-algorithms",
"type": "article"
},
{
"title": "Data Structures and Algorithms",
"url": "https://www.javatpoint.com/data-structure-tutorial",
"type": "article"
},
{
"title": "Explore top posts about Data Structures",
"url": "https://app.daily.dev/tags/data-structures?ref=roadmapsh",
@ -1033,7 +1028,7 @@
},
"m0umGQNdvg95UiNpQZsQN": {
"title": "Factorial",
"description": "Factorial complexity algorithms have a runtime of `O(n!)`. This is the worst case scenario for an algorithm. Factorial complexity algorithms are very inefficient and should be avoided.\n\n def generate_permutations(s):\n # Base case: If the string length is 1, return a list containing the string\n if len(s) == 1:\n return [s]\n \n # Initialize the result list\n permutations = []\n \n # Recursively generate all permutations\n for i in range(len(s)):\n # Current character\n current_char = s[i]\n # Remaining characters\n remaining_chars = s[:i] + s[i+1:]\n # Generate all permutations of the remaining characters\n for perm in generate_permutations(remaining_chars):\n # Add the current character to the front of each generated permutation\n permutations.append(current_char + perm)\n \n return permutations",
"description": "Factorial complexity algorithms have a runtime of `O(n!)`. This is the worst case scenario for an algorithm. Factorial complexity algorithms are very inefficient and should be avoided.\n\n def generate_permutations(s):\n # Base case: If the string length is 1, return a list containing the string\n if len(s) == 1:\n return [s]\n \n # Initialize the result list\n permutations = []\n \n # Recursively generate all permutations\n for i in range(len(s)):\n # Current character\n current_char = s[i]\n # Remaining characters\n remaining_chars = s[:i] + s[i + 1 :]\n # Generate all permutations of the remaining characters\n for perm in generate_permutations(remaining_chars):\n # Add the current character to the front of each generated permutation\n permutations.append(current_char + perm)\n \n return permutations",
"links": []
},
"7a6-AnBI-3tAU1dkOvPkx": {
@ -1042,7 +1037,7 @@
"links": [
{
"title": "Top Algorithms and Data Structures",
"url": "https://towardsdatascience.com/top-algorithms-and-data-structures-you-really-need-to-know-ab9a2a91c7b5",
"url": "https://medium.com/data-science/top-algorithms-and-data-structures-you-really-need-to-know-ab9a2a91c7b5",
"type": "article"
}
]
@ -1798,11 +1793,6 @@
"url": "https://www.coursera.org/learn/algorithms-part2/lecture/TAtDr/knuth-morris-pratt",
"type": "course"
},
{
"title": "The Knuth-Morris-Pratt (KMP)Algorithm",
"url": "https://www.javatpoint.com/daa-knuth-morris-pratt-algorithm",
"type": "article"
},
{
"title": "9.1 Knuth-Morris-Pratt KMP String Matching Algorithm",
"url": "https://www.youtube.com/watch?v=V5-7GzOfADQ",
@ -1818,11 +1808,6 @@
"title": "Boyer Moore Algorithm",
"url": "https://www.coursera.org/learn/algorithms-part2/lecture/CYxOT/boyer-moore",
"type": "course"
},
{
"title": "The Boyer-Moore Algorithm",
"url": "https://www.javatpoint.com/daa-boyer-moore-algorithm",
"type": "article"
}
]
},
@ -3365,11 +3350,6 @@
"title": "DCL",
"url": "https://en.wikipedia.org/wiki/Data_Control_Language",
"type": "article"
},
{
"title": "DCL Commands",
"url": "https://www.geeksforgeeks.org/sql-ddl-dql-dml-dcl-tcl-commands/",
"type": "article"
}
]
},
@ -3417,14 +3397,8 @@
},
"q3nRhTYS5wg9tYnQe2sCF": {
"title": "BASE",
"description": "The rise in popularity of NoSQL databases provided a flexible and fluidity with ease to manipulate data and as a result, a new database model was designed, reflecting these properties. The acronym BASE is slightly more confusing than ACID but however, the words behind it suggest ways in which the BASE model is different and acronym BASE stands for:-\n\n* **B**asically **A**vailable\n* **S**oft state\n* **E**ventual consistency\n\nVisit the following resources to learn more:",
"links": [
{
"title": "BASE Model vs. ACID Model",
"url": "https://www.geeksforgeeks.org/acid-model-vs-base-model-for-database/",
"type": "article"
}
]
"description": "The rise in popularity of NoSQL databases provided a flexible and fluidity with ease to manipulate data and as a result, a new database model was designed, reflecting these properties. The acronym BASE is slightly more confusing than ACID but however, the words behind it suggest ways in which the BASE model is different and acronym BASE stands for:-\n\n* **B**asically **A**vailable\n* **S**oft state\n* **E**ventual consistency",
"links": []
},
"uqfeiQ9K--QkGNwks4kjk": {
"title": "CAP Theorem",
@ -4095,29 +4069,8 @@
},
"Ge2nagN86ofa2y-yYR1lv": {
"title": "Scheduling Algorithms",
"description": "CPU Scheduling is the process of selecting a process from the ready queue and allocating the CPU to it. The selection of a process is based on a particular scheduling algorithm. The scheduling algorithm is chosen depending on the type of system and the requirements of the processes.\n\nHere is the list of some of the most commonly used scheduling algorithms:\n\n* **First Come First Serve (FCFS):** The process that arrives first is allocated the CPU first. It is a non-preemptive algorithm.\n* **Shortest Job First (SJF):** The process with the smallest execution time is allocated the CPU first. It is a non-preemptive algorithm.\n* **Shortest Remaining Time First (SRTF):** The process with the smallest remaining execution time is allocated the CPU first. It is a preemptive algorithm.\n* **Round Robin (RR):** The process is allocated the CPU for a fixed time slice. The time slice is usually 10 milliseconds. It is a preemptive algorithm.\n* **Priority Scheduling:** The process with the highest priority is allocated the CPU first. It is a preemptive algorithm.\n* **Multi-level Queue Scheduling:** The processes are divided into different queues based on their priority. The process with the highest priority is allocated the CPU first. It is a preemptive algorithm.\n* **Multi-level Feedback Queue Scheduling:** The processes are divided into different queues based on their priority. The process with the highest priority is allocated the CPU first. If a process is preempted, it is moved to the next queue. It is a preemptive algorithm.\n* **Highest Response Ratio Next(HRRN):** CPU is allotted to the next process which has the highest response ratio and not to the process having less burst time. It is a Non-Preemptive algorithm.\n* **Lottery Scheduling:** The process is allocated the CPU based on a lottery system. It is a preemptive algorithm.\n\nVisit the following resources to learn more",
"links": [
{
"title": "CPU Scheduling in Operating Systems - geeksforgeeks",
"url": "https://www.geeksforgeeks.org/cpu-scheduling-in-operating-systems/",
"type": "article"
},
{
"title": "Lottery Scheduling for Operating Systems - geeksforgeeks",
"url": "https://www.geeksforgeeks.org/lottery-process-scheduling-in-operating-system/",
"type": "article"
},
{
"title": "Program for Round Robin Scheduling for the same Arrival time - geeksforgeeks",
"url": "https://www.geeksforgeeks.org/program-for-round-robin-scheduling-for-the-same-arrival-time/",
"type": "article"
},
{
"title": "Introduction to CPU Scheduling",
"url": "https://youtu.be/EWkQl0n0w5M?si=Lb-PxN_t-rDfn4JL",
"type": "video"
}
]
"description": "CPU Scheduling is the process of selecting a process from the ready queue and allocating the CPU to it. The selection of a process is based on a particular scheduling algorithm. The scheduling algorithm is chosen depending on the type of system and the requirements of the processes.\n\nHere is the list of some of the most commonly used scheduling algorithms:\n\n* **First Come First Serve (FCFS):** The process that arrives first is allocated the CPU first. It is a non-preemptive algorithm.\n* **Shortest Job First (SJF):** The process with the smallest execution time is allocated the CPU first. It is a non-preemptive algorithm.\n* **Shortest Remaining Time First (SRTF):** The process with the smallest remaining execution time is allocated the CPU first. It is a preemptive algorithm.\n* **Round Robin (RR):** The process is allocated the CPU for a fixed time slice. The time slice is usually 10 milliseconds. It is a preemptive algorithm.\n* **Priority Scheduling:** The process with the highest priority is allocated the CPU first. It is a preemptive algorithm.\n* **Multi-level Queue Scheduling:** The processes are divided into different queues based on their priority. The process with the highest priority is allocated the CPU first. It is a preemptive algorithm.\n* **Multi-level Feedback Queue Scheduling:** The processes are divided into different queues based on their priority. The process with the highest priority is allocated the CPU first. If a process is preempted, it is moved to the next queue. It is a preemptive algorithm.\n* **Highest Response Ratio Next(HRRN):** CPU is allotted to the next process which has the highest response ratio and not to the process having less burst time. It is a Non-Preemptive algorithm.\n* **Lottery Scheduling:** The process is allocated the CPU based on a lottery system. It is a preemptive algorithm.",
"links": []
},
"cpQvB0qMDL3-NWret7oeA": {
"title": "CPU Interrupts",

@ -0,0 +1,742 @@
{
"ofwdZm05AUqCIWmfgGHk8": {
"title": "Diamond Inheritance",
"description": "Diamond inheritance is a specific scenario in multiple inheritance where a class is derived from two or more classes, which in turn, are derived from a common base class. It creates an ambiguity that arises from duplicating the common base class, which leads to an ambiguous behavior while calling the duplicate members.\n\nTo resolve this ambiguity, you can use virtual inheritance. A virtual base class is a class that is shared by multiple classes using `virtual` keyword in C++. This ensures that only one copy of the base class is inherited in the final derived class, and thus, resolves the diamond inheritance problem.\n\n_Example:_\n\n #include <iostream>\n \n class Base {\n public:\n void print() {\n std::cout << \"Base class\\n\";\n }\n };\n \n class Derived1 : virtual public Base {\n public:\n void derived1Print() {\n std::cout << \"Derived1 class\\n\";\n }\n };\n \n class Derived2 : virtual public Base {\n public:\n void derived2Print() {\n std::cout << \"Derived2 class\\n\";\n }\n };\n \n class Derived3 : public Derived1, public Derived2 {\n public:\n void derived3Print() {\n std::cout << \"Derived3 class\\n\";\n }\n };\n \n int main() {\n Derived3 d3;\n d3.print(); // Now, there is no ambiguity in calling the base class function\n d3.derived1Print();\n d3.derived2Print();\n d3.derived3Print();\n \n return 0;\n }\n \n\nIn the code above, `Derived1` and `Derived2` are derived from the `Base` class using virtual inheritance. So, when we create an object of `Derived3` and call the `print()` function from the `Base` class, there is no ambiguity, and the code executes without any issues.",
"links": []
},
"ZHjU60uzJTezADRhDTESG": {
"title": "Forward Declaration",
"description": "Forward declaration is a way of declaring a symbol (class, function, or variable) before defining it in the code. It helps the compiler understand the type, size, and existence of the symbol. This declaration is particularly useful when we have cyclic dependencies or to reduce compilation time by avoiding unnecessary header inclusions in the source file.\n\nClass Forward Declaration\n-------------------------\n\nTo use a class type before it is defined, you can declare the class without defining its members, like this:\n\n class ClassA; // forward declaration\n \n\nYou can then use pointers or references to the class in your code before defining the class itself:\n\n void do_something (ClassA& obj);\n \n class ClassB {\n public:\n void another_function(ClassA& obj);\n };\n \n\nHowever, if you try to make an object of `ClassA` or call its member functions without defining the class, you will get a compilation error.\n\nFunction Forward Declaration\n----------------------------\n\nFunctions must be declared before using them, and a forward declaration can be used to declare a function without defining it:\n\n int add(int a, int b); // forward declaration\n \n int main() {\n int result = add(2, 3);\n return 0;\n }\n \n int add(int a, int b) {\n return a + b;\n }\n \n\nEnum and Typedef Forward Declaration\n------------------------------------\n\nFor `enum` and `typedef`, it is not possible to forward declare because they don't have separate declaration and definition stages.\n\nKeep in mind that forward declarations should be used cautiously, as they can make the code more difficult to understand.",
"links": []
},
"NvODRFR0DLINB0RlPSsvt": {
"title": "Introduction to Language",
"description": "C++ is a general-purpose, high-performance programming language. It was developed by Bjarne Stroustrup at Bell Labs starting in 1979. C++ is an extension of the C programming language, adding features such as classes, objects, and exceptions.\n\nBasics of C++ Programming\n-------------------------\n\nHere are some basic components and concepts in C++ programming:\n\nIncluding Libraries\n-------------------\n\nIn C++, we use the `#include` directive to include libraries or header files into our program. For example, to include the standard input/output library, we write:\n\n #include <iostream>\n \n\nMain Function\n-------------\n\nThe entry point of a C++ program is the `main` function. Every C++ program must have a `main` function:\n\n int main() {\n // Your code goes here\n return 0;\n }\n \n\nInput/Output\n------------\n\nTo perform input and output operations in C++, we can use the built-in objects `std::cin` for input and `std::cout` for output, available in the `iostream` library. Here's an example of reading an integer and printing its value:\n\n #include <iostream>\n \n int main() {\n int number;\n std::cout << \"Enter an integer: \";\n std::cin >> number;\n std::cout << \"You entered: \" << number << '\\n';\n return 0;\n }\n \n\nVariables and Data Types\n------------------------\n\nC++ has several basic data types for representing integer, floating-point, and character values:\n\n* `int`: integer values\n* `float`: single-precision floating-point values\n* `double`: double-precision floating-point values\n* `char`: single characters\n* `bool`: boolean values\n\nVariables must be declared with a data type before they can be used:\n\n int x;\n float y;\n double z;\n char c;\n bool b;\n \n\nControl Structures\n------------------\n\nC++ provides control structures for conditional execution and iteration, such as `if`, `else`, `while`, `for`, and `switch` statements.\n\n### If-Else Statement\n\n if (condition) {\n // Code to execute if the condition is true\n } else {\n // Code to execute if the condition is false\n }\n \n\n### While Loop\n\n while (condition) {\n // Code to execute while the condition is true\n }\n \n\n### For Loop\n\n for (initialization; condition; update) {\n // Code to execute while the condition is true\n }\n \n\n### Switch Statement\n\n switch (variable) {\n case value1:\n // Code to execute if variable == value1\n break;\n case value2:\n // Code to execute if variable == value2\n break;\n // More cases...\n default:\n // Code to execute if variable does not match any case value\n }\n \n\nFunctions\n---------\n\nFunctions are reusable blocks of code that can be called with arguments to perform a specific task. Functions are defined with a return type, a name, a parameter list, and a body.\n\n ReturnType functionName(ParameterType1 parameter1, ParameterType2 parameter2) {\n // Function body\n // ...\n return returnValue;\n }\n \n\nFor example, here's a function that adds two integers and returns the result:\n\n int add(int a, int b) {\n return a + b;\n }\n \n int main() {\n int result = add(3, 4);\n std::cout << \"3 + 4 = \" << result << '\\n';\n return 0;\n }\n \n\nThis basic introduction to C++ should provide you with a good foundation for further learning. Explore more topics such as classes, objects, inheritance, polymorphism, templates, and the Standard Template Library (STL) to deepen your understanding of C++ and start writing more advanced programs.\n\nLearn more from the following resources:",
"links": [
{
"title": "LearnC++",
"url": "https://www.learncpp.com/",
"type": "article"
},
{
"title": "C++ Full Course by freeCodeCamp",
"url": "https://youtu.be/vLnPwxZdW4Y",
"type": "video"
}
]
},
"x_28LiDVshqWns_aIBsdx": {
"title": "What is C++?",
"description": "C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language. It was first introduced in 1985 and provides object-oriented features like classes and inheritance. C++ is widely used in various applications like game development, system programming, embedded systems, and high-performance computing.\n\nC++ is a statically-typed language, meaning that the type of a variable is determined during compilation, and has an extensive library called the C++ Standard Library, which provides a rich set of functions, algorithms, and data structures for various tasks.\n\nC++ builds upon the features of C, and thus, most C programs can be compiled and run with a C++ compiler.\n\nCode Example\n------------\n\nHere's a simple example of a C++ program that demonstrates some essential features of the language:\n\n #include <iostream>\n \n // A simple function to add two numbers\n int add(int a, int b) {\n return a + b;\n }\n \n class Calculator {\n public:\n // A member function to multiply two numbers\n int multiply(int a, int b) {\n return a * b;\n }\n };\n \n int main() {\n int x = 5;\n int y = 3;\n \n // Using the standalone function 'add'\n int sum = add(x, y);\n std::cout << \"Sum: \" << sum << '\\n';\n \n // Using a class and member function\n Calculator calc;\n int product = calc.multiply(x, y);\n std::cout << \"Product: \" << product << '\\n';\n \n return 0;\n }\n \n\nIn the above program, we define a simple function `add` and a class `Calculator` with a member function `multiply`. The `main` function demonstrates how to use these to perform basic arithmetic.\n\nLearn more from the following resources:",
"links": [
{
"title": "w3schools C++ tutorial",
"url": "https://www.w3schools.com/cpp/",
"type": "article"
},
{
"title": "Learn C++",
"url": "https://www.learncpp.com/",
"type": "article"
},
{
"title": "Explore top posts about C++",
"url": "https://app.daily.dev/tags/c++?ref=roadmapsh",
"type": "article"
},
{
"title": "C++ Tutorial for Beginners - Full Course",
"url": "https://youtu.be/vLnPwxZdW4Y",
"type": "video"
}
]
},
"tl6VCQ5IEGDVyFcgj7jDm": {
"title": "Why use C++",
"description": "C++ is a popular and widely used programming language for various reasons. Here are some of the reasons why you might choose to utilize C++:\n\nPerformance\n-----------\n\nC++ is designed to provide high performance and efficiency. It offers fine-grained control over system resources, making it easier to optimize your software.\n\nPortability\n-----------\n\nC++ is supported on different computer architectures and operating systems, allowing you to write portable code that runs on various platforms without making major modifications.\n\nObject-Oriented Programming\n---------------------------\n\nC++ supports object-oriented programming (OOP) - a paradigm that allows you to design programs using classes and objects, leading to better code organization and reusability.\n\n class MyClass {\n public:\n void myFunction() {\n // Code here\n }\n };\n \n int main() {\n MyClass obj;\n obj.myFunction();\n }\n \n\nSupport for low-level and high-level programming\n------------------------------------------------\n\nC++ allows you to write both low-level code, like memory manipulation, as well as high-level abstractions, like creating classes and using the Standard Template Library (STL).\n\n #include <iostream>\n #include <vector>\n \n int main() {\n // Low-level programming\n int number = 42;\n int* ptr_number = &number;\n \n // High-level programming\n std::vector<int> myVector = {1, 2, 3};\n for (const auto &i: myVector) {\n std::cout << i << '\\n';\n }\n }\n \n\nExtensive Libraries\n-------------------\n\nC++ offers a vast range of libraries and tools, such as the Standard Template Library (STL), Boost, and Qt, among others, that can aid in the development of your projects and make it more efficient.\n\nCombination with C language\n---------------------------\n\nC++ can be combined with C, offering the capabilities of both languages and allowing you to reuse your existing C code. By incorporating C++ features, you can enhance your code and improve its functionality.\n\nActive Community\n----------------\n\nC++ has been around for a long time and has a large, active community of users who contribute to the growth of the language, express new ideas, and engage in discussions that help develop the language further. This makes finding solutions to any problems you experience much easier.\n\nIn summary, C++ offers a great balance of performance, portability, and feature set, making it a versatile and powerful programming language suitable for many applications. With its extensive libraries, active community, and continuous development, C++ is an excellent choice for any software development project.",
"links": []
},
"2Ag0t3LPryTF8khHLRfy-": {
"title": "C vs C++",
"description": "C and C++ are two popular programming languages with some similarities, but they also have key differences. C++ is an extension of the C programming language, with added features such as object-oriented programming, classes, and exception handling. Although both languages are used for similar tasks, they have their own syntax and semantics, which makes them distinct from each other.\n\nSyntax and Semantics\n--------------------\n\n### C\n\n* C is a procedural programming language.\n* Focuses on functions and structured programming.\n* Does not support objects or classes.\n* Memory management is manual, using functions like `malloc` and `free`.\n\n #include <stdio.h>\n \n void printHello() {\n printf(\"Hello, World!\\n\");\n }\n \n int main() {\n printHello();\n return 0;\n }\n \n\n### C++\n\n* C++ is both procedural and object-oriented.\n* Supports both functions and classes.\n* Incorporates different programming paradigms.\n* Memory management can be manual (like C) or rely on constructors/destructors and smart pointers.\n\n #include <iostream>\n \n class HelloWorld {\n public:\n void printHello() {\n std::cout << \"Hello, World!\\n\";\n }\n };\n \n int main() {\n HelloWorld obj;\n obj.printHello();\n return 0;\n }\n \n\nCode Reusability and Modularity\n-------------------------------\n\n### C\n\n* Code reusability is achieved through functions and modular programming.\n* High cohesion and low coupling are achieved via structured design.\n* Function libraries can be created and included through headers.\n\n### C++\n\n* Offers better code reusability with classes, inheritance, and polymorphism.\n* Code modularity is enhanced through namespaces and well-designed object-oriented hierarchy.\n\nError Handling\n--------------\n\n### C\n\n* Error handling in C is done primarily through return codes.\n* Lacks support for exceptions or any built-in error handling mechanism.\n\n### C++\n\n* Offers exception handling, which can be used to handle errors that may occur during program execution.\n* Enables catching and handling exceptions with `try`, `catch`, and `throw` keywords, providing more control over error handling.\n\nConclusion\n----------\n\nBoth C and C++ are powerful languages with unique features and capabilities. While C is simpler and focuses on procedural programming, C++ offers the versatility of using different programming paradigms and improved code organization. Understanding the differences between these two languages can help you decide which one is more suitable for your specific needs and programming style.",
"links": []
},
"Zc_TTzmM36yWsu3GvOy9x": {
"title": "Setting up your Environment",
"description": "Setting up C++ requires a few steps, including installing a compiler, configuring an Integrated Development Environment (IDE), and creating a new C++ project.\n\n1\\. Installing a Compiler\n-------------------------\n\nA compiler is required to convert C++ code into machine language. Some popular C++ compilers include:\n\n* GCC (GNU Compiler Collection) for Linux and macOS, but can also be used on Windows through MinGW\n* MSVC (Microsoft Visual C++) for Windows\n\nTo install a compiler, simply follow the instructions provided by the respective websites.\n\n2\\. Configuring an IDE\n----------------------\n\nAn IDE is a software application that provides facilities for programming, such as code editing, debugging, and building. Some popular C++ IDEs include:\n\n* [@article@Visual Studio](https://visualstudio.microsoft.com/vs/features/cplusplus/) (Windows, macOS)\n* [@article@Eclipse](https://eclipse.org) (Windows, macOS, Linux)\n* [@article@Code::Blocks](http://www.codeblocks.org) (Windows, macOS, Linux)\n\nAfter downloading and installing an IDE, you might need to configure it to use the installed compiler. Check the documentation of the respective IDE for instructions on how to do this.\n\n3\\. Creating a New C++ Project\n------------------------------\n\nOnce you have your IDE and compiler set up, you can create a new C++ project and start writing code. In general, follow these steps to create a new C++ project:\n\n* Open the IDE and create a new project.\n* Select the project type (C++ Application or Console Application).\n* Specify the project name and location.\n* Let the IDE generate the main.cpp and build files (such as Makefile or CMakeLists.txt) for you.\n\nExample: Hello World in C++\n---------------------------\n\nCreate a new file called `main.cpp` within your project and include this code:\n\n #include <iostream>\n \n int main() {\n std::cout << \"Hello, World!\\n\";\n return 0;\n }\n \n\nThen, follow the IDE's instructions to build and run your program. You should see \"Hello, World!\" displayed in the console.\n\nSummary\n-------\n\nSetting up C++ involves:\n\n* Installing a compiler (e.g. GCC, MinGW, or MSVC)\n* Configuring an IDE (e.g. Visual Studio, Eclipse, or Code::Blocks)\n* Creating a new C++ project and writing code\n\nBy following these steps, you'll be ready to start developing C++ applications!",
"links": []
},
"0J_ltQEJh2g28OE2ZEYJj": {
"title": "Installing C++",
"description": "Before you can start programming in C++, you will need to have a compiler installed on your system. A compiler is a program that converts the C++ code you write into an executable file that your computer can run. There are several popular C++ compilers to choose from, depending on your operating system and preference.\n\n### Windows\n\nFor Windows, one popular option is to install the [Microsoft Visual Studio IDE](https://visualstudio.microsoft.com/vs/), which includes the Microsoft Visual C++ compiler (MSVC).\n\nAlternatively, you can also install the [MinGW-w64](https://mingw-w64.org/) compiler system, which is a Windows port of the GNU Compiler Collection (GCC). To install MinGW-w64, follow these steps:\n\n* Download the installer from [here](https://sourceforge.net/projects/mingw-w64/files/).\n* Run the installer and select your desired architecture, version, and install location.\n* Add the `bin` folder inside the installation directory to your system's `PATH` environment variable.\n\n### macOS\n\nFor macOS, you can install the Apple LLVM `clang` compiler which is part of the Xcode Command Line Tools. To do this, open a terminal and enter:\n\n xcode-select --install\n \n\nThis will prompt a dialog to install the Command Line Tools, which includes the `clang` compiler.\n\n### Linux\n\nOn Linux, you can install the GNU Compiler Collection (GCC) through your distribution's package manager. Here are some examples for popular Linux distributions:\n\n* Ubuntu, Debian, and derivatives:\n\n sudo apt-get install g++ build-essential\n \n\n* Fedora, CentOS, RHEL, and derivatives:\n\n sudo dnf install gcc-c++ make\n \n\n* Arch Linux and derivatives:\n\n sudo pacman -S gcc make\n \n\n### Checking the Installation\n\nTo confirm that the compiler is installed and available on your system, open a terminal/command prompt, and enter the following command:\n\n g++ --version\n \n\nYou should see output displaying the version of your installed C++ compiler.\n\nNow you're ready to start writing and compiling your C++ code!",
"links": []
},
"ew0AfyadpXPRO0ZY3Z19k": {
"title": "Code Editors / IDEs",
"description": "Code editors and IDEs are programs specifically designed for editing, managing and writing source code. They offer a wide range of features that make the development process easier and faster. Here's a brief introduction to some of the most popular code editors and IDEs for C++:\n\n* **Visual Studio**: Visual Studio is an Integrated Development Environment (IDE) for Windows, developed by Microsoft. It includes its own integrated compiler known as Microsoft Visual C++ (MSVC).\n \n* **Visual Studio Code (VSCode)**: Visual Studio Code is a popular, free, open-source, and lightweight code editor developed by Microsoft. It offers an extensive library of extensions that enhance functionality for C++ development.\n \n* **Sublime Text**: Sublime Text is a cross-platform text editor that is quite popular among developers due to its speed and minimalist design. It supports C++ with the help of plugins and has a variety of themes and packages available for customization.\n \n* **CLion**: CLion is an Integrated Development Environment (IDE) developed by JetBrains specifically for C and C++ developers. It provides advanced features like code completion, refactoring support, debugging, and more. It's worth noting that CLion is a commercial IDE, and there is no community version available; users are required to purchase a license for usage.\n \n\nThese are just a few examples, and there are many other code editors available, including Atom, Notepad++, and Geany. They all have their features and may suit different developers' needs. Finding the right code editor is often a matter of personal preference and workflow.\n\nTo work with C++ in your chosen code editor, you often need to install some additional tools and add-ons, such as compilers, linters, and debugger support. Make sure to follow the instructions provided in the editor's documentation to set up C++ correctly.\n\nLearn more from the following resources:",
"links": [
{
"title": "Using C++ on Linux in VSCode",
"url": "https://code.visualstudio.com/docs/cpp/config-linux",
"type": "article"
},
{
"title": "Explore top posts about General Programming",
"url": "https://app.daily.dev/tags/general-programming?ref=roadmapsh",
"type": "article"
}
]
},
"SEq0D2Zg5WTsIDtd1hW9f": {
"title": "Running your First Program",
"description": "In this section, we'll discuss the basic structure of a C++ program, walk you through your first program (the \"Hello, World!\" example), and provide additional explanations of its syntax.\n\nHello, World!\n-------------\n\nThe first program that most people learn to write in any programming language is often a simple one that displays the message \"Hello, World!\" on the screen. Here's the classic \"Hello, World!\" program in C++:\n\n #include <iostream>\n \n int main() {\n std::cout << \"Hello, World!\\n\";\n return 0;\n }\n \n\nLet's break down the different components of this program:\n\nHeader Files & Preprocessor Directives\n--------------------------------------\n\nThe first line of the program `#include <iostream>` is a [preprocessor directive](https://en.cppreference.com/w/cpp/preprocessor) that tells the compiler to include the header file `iostream`. Header files provide function and class declarations that we can use in our C++ programs.\n\n #include <iostream>\n \n\n`main()` Function\n-----------------\n\nIn C++, the `main()` function serves as the entry point of your program. The operating system runs your program by calling this `main()` function. It should be defined only once in your program and must return an integer. The keyword `int` is the return type of this function which is an integer. Unlike C in C++ it is mandatory to have `int` as the return type for the `main` function.\n\n int main() {\n // Your code goes here.\n }\n \n\nOutput to the Console\n---------------------\n\nTo output text to the console, we use the `std::cout` object and the insertion operator `<<`. In the \"Hello, World!\" example, we used the following line to print \"Hello, World!\" to the console:\n\n std::cout << \"Hello, World!\\n\";\n \n\n* `std`: This is the namespace where C++ standard library entities (classes and functions) reside. It stands for \"standard\"\n* `std::cout`: The standard \"character output\" stream that writes to the console\n* `\"Hello, World!\"`: The string literal to print\n* `'\\n'`: The \"end line\" manipulator that inserts a newline character and flushes the output buffer\n\nReturn Statement\n----------------\n\nLastly, the `return 0;` statement informs the operating system that the program executed successfully. Returning any other integer value indicates that an error occurred:\n\n return 0;\n \n\nNow that you understand the basic components of a C++ program, you can write your first program, compile it, and run it to see the \"Hello, World!\" message displayed on the screen.",
"links": []
},
"kl2JI_Wl47c5r8SYzxvCq": {
"title": "Basic Operations",
"description": "Basic operations in C++ refer to the fundamental arithmetic, relational, and logical operations that can be performed using C++ programming language, which are essential for any kind of program or calculation in a real-world scenario.\n\nHere's a summary of the basic operations in C++\n\nArithmetic Operations\n---------------------\n\nThese operations are used for performing calculations in C++ and include the following:\n\n* **Addition (+)**: Adds two numbers.\n\n int a = 5;\n int b = 6;\n int sum = a + b; // sum is 11\n \n\n* **Subtraction (-)**: Subtracts one number from the other.\n\n int a = 10;\n int b = 6;\n int diff = a - b; // diff is 4\n \n\n* **Multiplication (\\*)**: Multiplies two numbers.\n\n int a = 3;\n int b = 4;\n int product = a * b; // product is 12\n \n\n* **Division (/)**: Divides one number by another, yields quotient.\n\n int a = 12;\n int b = 4;\n int quotient = a / b; // quotient is 3\n \n\n* **Modulus (%)**: Divides one number by another, yields remainder.\n\n int a = 15;\n int b = 4;\n int remainder = a % b; // remainder is 3\n \n\nRelational Operators\n--------------------\n\nThese operations compare two values and return a boolean value (true/false) depending on the comparison. The relational operations are:\n\n* **Equal to (==)**: Returns true if both operands are equal.\n\n 5 == 5 // true\n 3 == 4 // false\n \n\n* **Not equal to (!=)**: Returns true if operands are not equal.\n\n 5 != 2 // true\n 1 != 1 // false\n \n\n* **Greater than (>)**: Returns true if the first operand is greater than the second.\n\n 5 > 3 // true\n 2 > 3 // false\n \n\n* **Less than (<)**: Returns true if the first operand is less than the second.\n\n 3 < 5 // true\n 6 < 5 // false\n \n\n* **Greater than or equal to (>=)**: Returns true if the first operand is greater than or equal to the second.\n\n 5 >= 5 // true\n 6 >= 2 // true\n 3 >= 4 // false\n \n\n* **Less than or equal to (<=)**: Returns true if the first operand is less than or equal to the second.\n\n 4 <= 4 // true\n 2 <= 3 // true\n 5 <= 4 // false\n \n\nLogical Operators\n-----------------\n\nLogical operators are used for combining multiple conditions or boolean values.\n\n* **AND (&&)**: Returns true if both operands are true.\n\n true && true // true\n true && false // false\n \n\n* **OR (||)**: Returns true if any one of the operands is true.\n\n true || false // true\n false || false // false\n \n\n* **NOT (!)**: Returns true if the operand is false and vice versa.\n\n !true // false\n !false // true",
"links": []
},
"8aOSpZLWwZv_BEYiurhyR": {
"title": "Arithmetic Operators",
"description": "Arithmetic operators are used to perform mathematical operations with basic variables such as integers and floating-point numbers. Here is a brief summary of the different arithmetic operators in C++:\n\n1\\. Addition Operator (`+`)\n---------------------------\n\nIt adds two numbers together.\n\n int sum = a + b;\n \n\n2\\. Subtraction Operator (`-`)\n------------------------------\n\nIt subtracts one number from another.\n\n int difference = a - b;\n \n\n3\\. Multiplication Operator (`*`)\n---------------------------------\n\nIt multiplies two numbers together.\n\n int product = a * b;\n \n\n4\\. Division Operator (`/`)\n---------------------------\n\nIt divides one number by another. Note that if both operands are integers, it will perform integer division and the result will be an integer.\n\n int quotient = a / b; // integer division\n float quotient = float(a) / float(b); // floating-point division\n \n\n5\\. Modulus Operator (`%`)\n--------------------------\n\nIt calculates the remainder of an integer division.\n\n int remainder = a % b;\n \n\n6\\. Increment Operator (`++`)\n-----------------------------\n\nIt increments the value of a variable by 1. There are two ways to use this operator: prefix (`++x`) and postfix (`x++`). Prefix increments the value before returning it, whereas postfix returns the value first and then increments it.\n\n int x = 5;\n int y = ++x; // x = 6, y = 6\n int z = x++; // x = 7, z = 6\n \n\n7\\. Decrement Operator (`--`)\n-----------------------------\n\nIt decrements the value of a variable by 1. It can also be used in prefix (`--x`) and postfix (`x--`) forms.\n\n int x = 5;\n int y = --x; // x = 4, y = 4\n int z = x--; // x = 3, z = 4\n \n\nThese are the basic arithmetic operators in C++ that allow you to perform mathematical operations on your variables. Use them in combination with other control structures, such as loops and conditionals, to build more complex programs.",
"links": []
},
"Y9gq8WkDA_XGe68JkY2UZ": {
"title": "Logical Operators",
"description": "Logical operators are used to perform logical operations on the given expressions, mostly to test the relationship between different variables or values. They return a boolean value i.e., either true (1) or false (0) based on the result of the evaluation.\n\nC++ provides the following logical operators:\n\n* **AND Operator (&&)** The AND operator checks if both the operands/conditions are true, then the expression is true. If any one of the conditions is false, the whole expression will be false.\n \n (expression1 && expression2)\n \n \n Example:\n \n int a = 5, b = 10;\n if (a > 0 && b > 0) {\n std::cout << \"Both values are positive.\\n\";\n }\n \n \n* **OR Operator (||)** The OR operator checks if either of the operands/conditions are true, then the expression is true. If both the conditions are false, it will be false.\n \n (expression1 || expression2)\n \n \n Example:\n \n int a = 5, b = -10;\n if (a > 0 || b > 0) {\n std::cout << \"At least one value is positive.\\n\";\n }\n \n \n* **NOT Operator (!)** The NOT operator reverses the result of the condition/expression it is applied on. If the condition is true, the NOT operator will make it false and vice versa.\n \n !(expression)\n \n \n Example:\n \n int a = 5;\n if (!(a < 0)) {\n std::cout << \"The value is not negative.\\n\";\n }\n \n \n\nUsing these operators, you can create more complex logical expressions, for example:\n\n int a = 5, b = -10, c = 15;\n \n if (a > 0 && (b > 0 || c > 0)) {\n std::cout << \"At least two values are positive.\\n\";\n }\n \n\nThis covers the essential information about logical operators in C++.",
"links": []
},
"zE4iPSq2KsrDSByQ0sGK_": {
"title": "Bitwise Operators",
"description": "Bitwise operations are operations that directly manipulate the bits of a number. Bitwise operations are useful for various purposes, such as optimizing algorithms, performing certain calculations, and manipulating memory in lower-level programming languages like C and C++.\n\nHere is a quick summary of common bitwise operations in C++:\n\nBitwise AND (`&`)\n-----------------\n\nThe bitwise AND operation (`&`) is a binary operation that takes two numbers, compares them bit by bit, and returns a new number where each bit is set (1) if the corresponding bits in both input numbers are set (1); otherwise, the bit is unset (0).\n\nExample:\n\n int result = 5 & 3; // result will be 1 (0000 0101 & 0000 0011 = 0000 0001)\n \n\nBitwise OR (`|`)\n----------------\n\nThe bitwise OR operation (`|`) is a binary operation that takes two numbers, compares them bit by bit, and returns a new number where each bit is set (1) if at least one of the corresponding bits in either input number is set (1); otherwise, the bit is unset (0).\n\nExample:\n\n int result = 5 | 3; // result will be 7 (0000 0101 | 0000 0011 = 0000 0111)\n \n\nBitwise XOR (`^`)\n-----------------\n\nThe bitwise XOR (exclusive OR) operation (`^`) is a binary operation that takes two numbers, compares them bit by bit, and returns a new number where each bit is set (1) if the corresponding bits in the input numbers are different; otherwise, the bit is unset (0).\n\nExample:\n\n int result = 5 ^ 3; // result will be 6 (0000 0101 ^ 0000 0011 = 0000 0110)\n \n\nBitwise NOT (`~`)\n-----------------\n\nThe bitwise NOT operation (`~`) is a unary operation that takes a single number, and returns a new number where each bit is inverted (1 becomes 0, and 0 becomes 1).\n\nExample:\n\n int result = ~5; // result will be -6 (1111 1010)\n \n\nBitwise Left Shift (`<<`)\n-------------------------\n\nThe bitwise left shift operation (`<<`) is a binary operation that takes two numbers, a value and a shift amount, and returns a new number by shifting the bits of the value to the left by the specified shift amount. The vacated bits are filled with zeros.\n\nExample:\n\n int result = 5 << 1; // result will be 10 (0000 0101 << 1 = 0000 1010)\n \n\nBitwise Right Shift (`>>`)\n--------------------------\n\nThe bitwise right shift operation (`>>`) is a binary operation that takes two numbers, a value and a shift amount, and returns a new number by shifting the bits of the value to the right by the specified shift amount. The vacated bits are filled with zeros or sign bit depending on the input value being signed or unsigned.\n\nExample:\n\n int result = 5 >> 1; // result will be 2 (0000 0101 >> 1 = 0000 0010)\n \n\nThese were the most common bitwise operations in C++. Remember to use them carefully and understand their behavior when applied to specific data types and scenarios.\n\nLearn more from the following resources:",
"links": [
{
"title": "Intro to Binary and Bitwise Operators in C++",
"url": "https://youtu.be/KXwRt7og0gI",
"type": "video"
},
{
"title": "Bitwise AND (&), OR (|), XOR (^) and NOT (~) in C++",
"url": "https://youtu.be/HoQhw6_1NAA",
"type": "video"
}
]
},
"s5Gs4yF9TPh-psYmtPzks": {
"title": "Control Flow & Statements",
"description": "",
"links": []
},
"_IP_e1K9LhNHilYTDh7L5": {
"title": "for / while / do while loops",
"description": "Loops are an essential concept in programming that allow you to execute a block of code repeatedly until a specific condition is met. In C++, there are three main types of loops: `for`, `while`, and `do-while`.\n\nFor Loop\n--------\n\nA `for` loop is used when you know the number of times you want to traverse through a block of code. It consists of an initialization statement, a condition, and an increment/decrement operation.\n\nHere's the syntax for a `for` loop:\n\n for (initialization; condition; increment/decrement) {\n // block of code to execute\n }\n \n\nFor example:\n\n #include <iostream>\n \n int main() {\n for (int i = 0; i < 5; i++) {\n std::cout << \"Iteration: \" << i << '\\n';\n }\n return 0;\n }\n \n\nWhile Loop\n----------\n\nA `while` loop runs as long as a specified condition is `true`. The loop checks for the condition before entering the body of the loop.\n\nHere's the syntax for a `while` loop:\n\n while (condition) {\n // block of code to execute\n }\n \n\nFor example:\n\n #include <iostream>\n \n int main() {\n int i = 0;\n while (i < 5) {\n std::cout << \"Iteration: \" << i << '\\n';\n i++;\n }\n return 0;\n }\n \n\nDo-While Loop\n-------------\n\nA `do-while` loop is similar to a `while` loop, with the key difference being that the loop body is executed at least once, even when the condition is `false`.\n\nHere's the syntax for a `do-while` loop:\n\n do {\n // block of code to execute\n } while (condition);\n \n\nFor example:\n\n #include <iostream>\n \n int main() {\n int i = 0;\n do {\n std::cout << \"Iteration: \" << i << '\\n';\n i++;\n } while (i < 5);\n return 0;\n }\n \n\nIn summary, loops are an integral part of C++ programming that allow you to execute a block of code multiple times. The three types of loops in C++ are `for`, `while`, and `do-while`. Each type has its own specific use case and can be chosen depending on the desired behavior.\n\nLearn more from the following resources:",
"links": [
{
"title": "C++ For Loop",
"url": "https://www.w3schools.com/cpp/cpp_for_loop.asp",
"type": "article"
}
]
},
"bjpFWxiCKGz28E-ukhZBp": {
"title": "if else / switch / goto",
"description": "",
"links": []
},
"oYi3YOc1GC2Nfp71VOkJt": {
"title": "Functions",
"description": "A **function** is a group of statements that perform a specific task, organized as a separate unit in a program. Functions help in breaking the code into smaller, manageable, and reusable blocks.\n\nThere are mainly two types of functions in C++:\n\n* **Standard library functions**: Pre-defined functions available in the C++ standard library, such as `sort()`, `strlen()`, `sqrt()`, and many more. These functions are part of the standard library, so you need to include the appropriate header file to use them.\n \n* **User-defined functions**: Functions created by the programmer to perform a specific task. To create a user-defined function, you need to define the function and call it in your code.\n \n\nDefining a Function\n-------------------\n\nThe general format for defining a function in C++ is:\n\n return_type function_name(parameter list) {\n // function body\n }\n \n\n* `return_type`: Data type of the output produced by the function. It can be `void`, indicating that the function doesn't return any value.\n* `function_name`: Name given to the function, following C++ naming conventions.\n* `parameter list`: List of input parameters/arguments that are needed to perform the task. It is optional, you can leave it blank when no parameters are needed.\n\nExample\n-------\n\n #include <iostream>\n \n // Function to add two numbers\n int addNumbers(int a, int b) {\n int sum = a + b;\n return sum;\n }\n \n int main() {\n int num1 = 5, num2 = 10;\n int result = addNumbers(num1, num2); // Calling the function\n std::cout << \"The sum is: \" << result << '\\n';\n return 0;\n }\n \n\nIn this example, the function `addNumbers` takes two integer parameters, `a` and `b`, and returns the sum of the numbers. We then call this function from the `main()` function and display the result.\n\nFunction Prototypes\n-------------------\n\nIn some cases, you might want to use a function before actually defining it. To do this, you need to declare a **function prototype** at the beginning of your code.\n\nA function prototype is a declaration of the function without its body, and it informs the compiler about the function's name, return type, and parameters.\n\n #include <iostream>\n \n // Function prototype\n int multiplyNumbers(int x, int y);\n \n int main() {\n int num1 = 3, num2 = 7;\n int result = multiplyNumbers(num1, num2); // Calling the function\n std::cout << \"The product is: \" << result << '\\n';\n return 0;\n }\n \n // Function definition\n int multiplyNumbers(int x, int y) {\n int product = x * y;\n return product;\n }\n \n\nIn this example, we use a function prototype for `multiplyNumbers()` before defining it. This way, we can call the function from the `main()` function even though it hasn't been defined yet in the code.\n\nLearn more from the following resources:",
"links": [
{
"title": "introduction to functions in c++",
"url": "https://www.learncpp.com/cpp-tutorial/introduction-to-functions/",
"type": "article"
}
]
},
"obZIxRp0eMWdG7gplNIBc": {
"title": "Static Polymorphism",
"description": "Static polymorphism, also known as compile-time polymorphism, is a type of polymorphism that resolves the types and method calls at compile time rather than at runtime. This is commonly achieved through the use of function overloading and templates in C++.\n\nFunction Overloading\n--------------------\n\nFunction overloading is a way to create multiple functions with the same name but different parameter lists. The compiler determines the correct function to call based on the types and number of arguments used when the function is called.\n\nExample:\n\n #include <iostream>\n \n void print(int i) {\n std::cout << \"Printing int: \" << i << '\\n';\n }\n \n void print(double d) {\n std::cout << \"Printing double: \" << d << '\\n';\n }\n \n void print(const char* s) {\n std::cout << \"Printing string: \" << s << '\\n';\n }\n \n int main() {\n print(5); // Calls print(int i)\n print(3.14); // Calls print(double d)\n print(\"Hello\"); // Calls print(const char* s)\n \n return 0;\n }\n \n\nTemplates\n---------\n\nTemplates are a powerful feature in C++ that allows you to create generic functions or classes. The actual code for specific types is generated at compile time, which avoids the overhead of runtime polymorphism. The use of templates is the main technique to achieve static polymorphism in C++.\n\nExample:\n\n #include <iostream>\n \n // Template function to print any type\n template<typename T>\n void print(const T& value) {\n std::cout << \"Printing value: \" << value << '\\n';\n }\n \n int main() {\n print(42); // int\n print(3.14159); // double\n print(\"Hello\"); // const char*\n \n return 0;\n }\n \n\nIn conclusion, static polymorphism achieves polymorphic behavior during compile time using function overloading and templates, instead of relying on runtime information like dynamic polymorphism does. This can result in more efficient code since method calls are resolved at compile time.",
"links": []
},
"sgfqb22sdN4VRJYkhAVaf": {
"title": "Function Overloading",
"description": "",
"links": []
},
"llCBeut_uc9IAe2oi4KZ9": {
"title": "Operator Overloading",
"description": "Operators in C++ are symbols that perform various operations on data, such as arithmetic, comparison, and logical operations. They are used to manipulate and evaluate expressions and variables.\n\nHere is a list of the commonly used operator types in C++:\n\n* **Arithmetic Operators**: These are used for performing arithmetic operations like addition, subtraction, multiplication, and division.\n \n * `+`: addition\n \n int sum = 5 + 3; // sum will be 8\n \n \n * `-`: subtraction\n \n int difference = 5 - 3; // difference will be 2\n \n \n * `*`: multiplication\n \n int product = 5 * 3; // product will be 15\n \n \n * `/`: division\n \n int quotient = 15 / 3; // quotient will be 5\n \n \n * `%`: modulo (remainder)\n \n int remainder = 7 % 3; // remainder will be 1\n \n \n* **Comparison (Relational) Operators**: These are used to compare two values and return true or false based on the comparison.\n \n * `==`: equal to\n \n bool isEqual = (5 == 3); // isEqual will be false\n \n \n * `!=`: not equal to\n \n bool isNotEqual = (5 != 3); // isNotEqual will be true\n \n \n * `<`: less than\n \n bool isLess = (5 < 3); // isLess will be false\n \n \n * `>`: greater than\n \n bool isGreater = (5 > 3); // isGreater will be true\n \n \n * `<=`: less than or equal to\n \n bool isLessOrEqual = (5 <= 3); // isLessOrEqual will be false\n \n \n * `>=`: greater than or equal to\n \n bool isGreaterOrEqual = (5 >= 3); // isGreaterOrEqual will be true\n \n \n* **Logical Operators**: These operators are used to perform logical operations such as AND (&&), OR (||), and NOT (!) on boolean values.\n \n * `&&`: logical AND\n \n bool result = (true && false); // result will be false\n \n \n * `||`: logical OR\n \n bool result = (true || false); // result will be true\n \n \n * `!`: logical NOT\n \n bool result = !false; // result will be true\n \n \n* **Assignment Operators**: These are used to assign values to variables.\n \n * `=`: simple assignment\n \n int x = 5; // x gets the value 5\n \n \n * `+=`: addition assignment\n \n int x = 5;\n x += 3; // x gets the value 8 (5 + 3)\n \n \n * `-=`: subtraction assignment\n \n int x = 5;\n x -= 3; // x gets the value 2 (5 - 3)\n \n \n * `*=`: multiplication assignment\n \n int x = 5;\n x *= 3; // x gets the value 15 (5 * 3)\n \n \n * `/=`: division assignment\n \n int x = 15;\n x /= 3; // x gets the value 5 (15 / 3)\n \n \n * `%=`: modulo assignment\n \n int x = 7;\n x %= 3; // x gets the value 1 (7 % 3)\n \n \n\nThese are some of the main operator categories in C++. Each operator allows you to perform specific operations, making your code more efficient and concise.",
"links": []
},
"xjiFBVe-VGqCqWfkPVGKf": {
"title": "Lambdas",
"description": "A lambda function, or simply \"lambda\", is an anonymous (unnamed) function that is defined in place, within your source code, and with a concise syntax. Lambda functions were introduced in C++11 and have since become a widely used feature, especially in combination with the Standard Library algorithms.\n\nSyntax\n------\n\nHere is a basic syntax of a lambda function in C++:\n\n [capture-list](parameters) -> return_type {\n // function body\n };\n \n\n* **capture-list**: A list of variables from the surrounding scope that the lambda function can access.\n* **parameters**: The list of input parameters, just like in a regular function. Optional.\n* **return\\_type**: The type of the value that the lambda function will return. This part is optional, and the compiler can deduce it in many cases.\n* **function body**: The code that defines the operation of the lambda function.\n\nUsage Examples\n--------------\n\nHere are a few examples to demonstrate the use of lambda functions in C++:\n\n* Lambda function with no capture, parameters, or return type.\n\n auto printHello = []() {\n std::cout << \"Hello, World!\\n\";\n };\n printHello(); // Output: Hello, World!\n \n\n* Lambda function with parameters.\n\n auto add = [](int a, int b) {\n return a + b;\n };\n int result = add(3, 4); // result = 7\n \n\n* Lambda function with capture-by-value.\n\n int multiplier = 3;\n auto times = [multiplier](int a) {\n return a * multiplier;\n };\n int result = times(5); // result = 15\n \n\n* Lambda function with capture-by-reference.\n\n int expiresInDays = 45;\n auto updateDays = [&expiresInDays](int newDays) {\n expiresInDays = newDays;\n };\n updateDays(30); // expiresInDays = 30\n \n\nNote that, when using the capture by reference, any change made to the captured variable _inside_ the lambda function will affect its value in the surrounding scope.\n\nLearn more from the following resources:",
"links": [
{
"title": "Lambda Expressions",
"url": "https://en.cppreference.com/w/cpp/language/lambda",
"type": "article"
},
{
"title": "Explore top posts about AWS Lambda",
"url": "https://app.daily.dev/tags/aws-lambda?ref=roadmapsh",
"type": "article"
},
{
"title": "Lambdas in C++",
"url": "https://youtu.be/MH8mLFqj-n8",
"type": "video"
}
]
},
"MwznA4qfpNlv6sqSNjPZi": {
"title": "Data Types",
"description": "In C++, data types are used to categorize different types of data that a program can process. They are essential for determining the type of value a variable can hold and how much memory space it will occupy. Some basic data types in C++ include integers, floating-point numbers, characters, and booleans.\n\nFundamental Data Types\n----------------------\n\nInteger (int)\n-------------\n\nIntegers are whole numbers that can store both positive and negative values. The size of `int` depends on the system architecture (usually 4 bytes).\n\nExample:\n\n int num = 42;\n \n\nThere are variants of `int` that can hold different ranges of numbers:\n\n* short (`short int`): Smaller range than `int`.\n* long (`long int`): Larger range than `int`.\n* long long (`long long int`): Even larger range than `long int`.\n\nFloating-Point (float, double)\n------------------------------\n\nFloating-point types represent real numbers, i.e., numbers with a decimal point. There are two main floating-point types:\n\n* **float**: Provides single-precision floating-point numbers. It typically occupies 4 bytes of memory.\n\nExample:\n\n float pi = 3.14f;\n \n\n* **double**: Provides double-precision floating-point numbers. It consumes more memory (usually 8 bytes) but has a higher precision than `float`.\n\nExample:\n\n double pi_high_precision = 3.1415926535;\n \n\nCharacter (char)\n----------------\n\nCharacters represent a single character, such as a letter, digit, or symbol. They are stored using the ASCII value of the symbol and typically occupy 1 byte of memory.\n\nExample:\n\n char letter = 'A';\n \n\nBoolean (bool)\n--------------\n\nBooleans represent logical values: `true` or `false`. They usually occupy 1 byte of memory.\n\nExample:\n\n bool is_cpp_great = true;\n \n\nDerived Data Types\n------------------\n\nDerived data types are types that are derived from fundamental data types. Some examples include:\n\nArrays\n------\n\nArrays are used to store multiple values of the same data type in consecutive memory locations.\n\nExample:\n\n int numbers[5] = {1, 2, 3, 4, 5};\n \n\nPointers\n--------\n\nPointers are used to store the memory address of a variable.\n\nExample:\n\n int num = 42;\n int* pNum = &num;\n \n\nReferences\n----------\n\nReferences are an alternative way to share memory locations between variables, allowing you to create an alias for another variable.\n\nExample:\n\n int num = 42;\n int& numRef = num;\n \n\nUser-Defined Data Types\n-----------------------\n\nUser-defined data types are types that are defined by the programmer, such as structures, classes, and unions.\n\nStructures (struct)\n-------------------\n\nStructures are used to store different data types under a single variable and accessibility of member variables and methods are public.\n\nExample:\n\n struct Person {\n std::string name;\n int age;\n float height;\n };\n \n Person p1 = {\"John Doe\", 30, 5.9};\n \n\nClasses (class)\n---------------\n\nClasses are similar to structures, but the accessibility of the member data and function are governed by access specifiers. By default access to members of a class is private.\n\nExample:\n\n class Person {\n public:\n std::string name;\n int age;\n \n void printInfo() {\n std::cout << \"Name: \" << name << \", Age: \" << age << '\\n';\n };\n };\n \n Person p1;\n p1.name = \"John Doe\";\n p1.age = 30;\n \n\nUnions (union)\n--------------\n\nUnions are used to store different data types in the same memory location.\n\nExample:\n\n union Data {\n int num;\n char letter;\n float decimal;\n };\n \n Data myData;\n myData.num = 42;",
"links": []
},
"f1djN0GxoeVPr_0cl6vMq": {
"title": "Static Typing",
"description": "In C++, static typing means that the data type of a variable is determined at compile time, before the program is executed. This means that a variable can only be used with data of a specific type, and the compiler ensures that the operations performed with the variable are compatible with its type. If there is a mismatch , the compiler will adjust the data type of variable to match another provided it's feasible . This process is known as `Type Conversion`. If compiler not able to achieve type conversion , `Invalid Type Conversion` error will be raised during compilation of the code .\n\nC++ is a statically typed language, which means that it uses static typing to determine data types and perform type checking during compile time. This helps with ensuring type safety and can prevent certain types of errors from occurring during the execution of the program.\n\nHere's a simple code example to demonstrate static typing in C++:\n\n #include <iostream>\n \n int main() {\n int num = 65; // 'num' is statically typed as an integer\n double pi = 3.14159; // 'pi' is statically typed as a double\n char c = 'c'; // 'c' is statically typed as a char\n \n c = num; // This asssigment would convert num's value to ASCII equivalent character\n num = pi; // This assignment would convert pi's value from double type to int type\n \n std::cout << \"The value of num is: \" << num << '\\n';\n std::cout << \"The value of pi is: \" << pi << '\\n';\n std::cout << \"The value of c is: \"<< c << '\\n';\n return 0;\n }\n \n\nIn the code above, the variable `num` is statically typed as an `int`, `pi` is statically typed as a `double`, and `c` is statically typed as a `char`. If you attempt to assign the value of `pi` to `num`, the value `3.14159` will be converted to the integer `3` and assigned to `num`. Similarly, when the value of `num` is assigned to `c`, the compiler will convert the value `65` to its corresponding [ASCII](https://www.ascii-code.com) code, which is `A`.\n\nLearn more from the following resources:",
"links": [
{
"title": "Type-Coversion",
"url": "https://www.programiz.com/cpp-programming/type-conversion",
"type": "article"
},
{
"title": "Static Vs Dynamic",
"url": "https://www.techtarget.com/searchapparchitecture/tip/Static-vs-dynamic-typing-The-details-and-differences",
"type": "article"
}
]
},
"i0EAFEUB-F0wBJWOtrl1A": {
"title": "Dynamic Typing",
"description": "C++ is known as a statically-typed language, which means the data types of its variables are determined at compile time. However, C++ also provides concepts to have certain level of _dynamic typing_, which means determining the data types of variables at runtime.\n\nHere is a brief overview of two ways to achieve dynamic typing in C++:\n\n`void*` Pointers\n----------------\n\nA `void*` pointer is a generic pointer that can point to objects of any data type. They can be used to store a reference to any type of object without knowing the specific type of the object.\n\nExample:\n\n #include <iostream>\n \n int main() {\n int x = 42;\n float y = 3.14f;\n std::string z = \"Hello, world!\";\n \n void* void_ptr;\n \n void_ptr = &x;\n std::cout << \"int value: \" << *(static_cast<int*>(void_ptr)) << '\\n';\n \n void_ptr = &y;\n std::cout << \"float value: \" << *(static_cast<float*>(void_ptr)) << '\\n';\n \n void_ptr = &z;\n std::cout << \"string value: \" << *(static_cast<std::string*>(void_ptr)) << '\\n';\n \n return 0;\n }\n \n\n`std::any` (C++17)\n------------------\n\nC++17 introduced the `std::any` class which represents a generalized type-safe container for single values of any type.\n\nExample:\n\n #include <iostream>\n #include <any>\n \n int main() {\n std::any any_value;\n \n any_value = 42;\n std::cout << \"int value: \" << std::any_cast<int>(any_value) << '\\n';\n \n any_value = 3.14;\n std::cout << \"double value: \" << std::any_cast<double>(any_value) << '\\n';\n \n any_value = std::string(\"Hello, world!\");\n std::cout << \"string value: \" << std::any_cast<std::string>(any_value) << '\\n';\n \n return 0;\n }\n \n\nKeep in mind that both `void*` pointers and `std::any` have performance implications due to the additional type checking and casting that take place during runtime. They should be used carefully and only when absolutely necessary.",
"links": []
},
"r0yD1gfn03wTpEBi6zNsu": {
"title": "RTTI",
"description": "Run-Time Type Identification (RTTI) is a feature in C++ that allows you to obtain the type information of an object during program execution. This can be useful when using dynamic typing, where the type of an object can change at runtime.\n\nThere are two main mechanisms for RTTI in C++:\n\n* `typeid` operator\n* `dynamic_cast` operator\n\ntypeid operator\n---------------\n\n`typeid` is an operator that returns a reference to an object of type `std::type_info`, which contains information about the type of the object. The header file `<typeinfo>` should be included to use `typeid`.\n\nHere is an example:\n\n #include <iostream>\n #include <typeinfo>\n \n class Base { virtual void dummy() {} };\n class Derived : public Base { /* ... */ };\n \n int main() {\n Base* base_ptr = new Derived;\n \n // Using typeid to get the type of the object\n std::cout << \"Type: \" << typeid(*base_ptr).name() << '\\n';\n \n delete base_ptr;\n return 0;\n }\n \n\ndynamic\\_cast operator\n----------------------\n\n`dynamic_cast` is a type-casting operator that performs a runtime type check and safely downcasts a base pointer or reference to a derived pointer or reference. It returns null or throws a bad\\_cast exception (if casting references) when the casting fails.\n\nHere is an example:\n\n #include <iostream>\n \n class Base { virtual void dummy() {} };\n class Derived1 : public Base { /* ... */ };\n class Derived2 : public Base { /* ... */ };\n \n int main() {\n Base* base_ptr = new Derived1;\n \n // Using dynamic_cast to safely downcast the pointer\n Derived1* derived1_ptr = dynamic_cast<Derived1*>(base_ptr);\n if (derived1_ptr) {\n std::cout << \"Downcast to Derived1 successful\\n\";\n }\n else {\n std::cout << \"Downcast to Derived1 failed\\n\";\n }\n \n Derived2* derived2_ptr = dynamic_cast<Derived2*>(base_ptr);\n if (derived2_ptr) {\n std::cout << \"Downcast to Derived2 successful\\n\";\n }\n else {\n std::cout << \"Downcast to Derived2 failed\\n\";\n }\n \n delete base_ptr;\n return 0;\n }\n \n\nPlease note that the use of RTTI can have some performance overhead, as it requires additional compiler-generated information to be stored and processed during runtime.",
"links": []
},
"DWw8NxkLpIpiOSUaZZ1oA": {
"title": "Pointers and References",
"description": "A pointer is a variable that stores the memory address of another variable (or function). It points to the location of the variable in memory, and it allows you to access or modify the value indirectly. Here's a general format to declare a pointer:\n\n dataType *pointerName;\n \n\n**Initializing a pointer:**\n\n int num = 10;\n int *ptr = &num; // Pointer 'ptr' now points to the memory address of 'num'\n \n\n**Accessing value using a pointer:**\n\n int value = *ptr; // Value now contains the value of the variable that 'ptr' points to (i.e., 10)\n \n\n**Function pointer:**\n\n int add(int a, int b)\n {\n return a + b;\n }\n \n int main()\n {\n int (*funcptr) (int, int) = add; // Pointer 'funcptr' now points to the functions 'add'\n funcptr(4, 5); // Return 9\n }\n \n\nReferences\n----------\n\nA reference is an alias for an existing variable, meaning it's a different name for the same memory location. Unlike pointers, references cannot be null, and they must be initialized when they are declared. Once a reference is initialized, it cannot be changed to refer to another variable.\n\nHere's a general format to declare a reference:\n\n dataType &referenceName = existingVariable;\n \n\n**Example:**\n\n int num = 10;\n int &ref = num; // Reference 'ref' is now an alias of 'num'\n \n\nModifying the value of `ref` will also modify the value of `num` because they share the same memory location.\n\n**Note:** References are generally used when you want to pass a variable by reference in function arguments or when you want to create an alias for a variable without the need for pointer syntax.\n\nLearn more from the following resources:",
"links": [
{
"title": "Function Pointer in C++",
"url": "https://www.scaler.com/topics/cpp/function-pointer-cpp/",
"type": "article"
}
]
},
"uUzRKa9wGzdUwwmAg3FWr": {
"title": "References",
"description": "A reference can be considered as a constant pointer (not to be confused with a pointer to a constant value) which always points to (references) the same object. They are declared using the `&` (ampersand) symbol.\n\nDeclaration and Initialization\n------------------------------\n\nTo declare a reference, use the `&` symbol followed by the variable type and the reference's name. Note that you must initialize a reference when you declare it.\n\n int var = 10; // Declare an integer variable\n int& ref = var; // Declare a reference that \"points to\" var\n \n\nUsage\n-----\n\nYou can use the reference just like you'd use the original variable. When you change the value of the reference, the value of the original variable also changes, because they both share the same memory location.\n\n var = 20; // Sets the value of var to 20\n std::cout << ref << '\\n'; // Outputs 20\n \n ref = 30; // Sets the value of ref to 30\n std::cout << var << '\\n'; // Outputs 30\n \n\nFunction Parameters\n-------------------\n\nYou can use references as function parameters to create an alias for an argument. This is commonly done when you need to modify the original variable or when passing an object of considerable size to avoid the cost of copying.\n\n void swap(int& a, int& b) {\n int temp = a;\n a = b;\n b = temp;\n }\n \n int main() {\n int x = 5, y = 10;\n std::cout << \"Before Swap: x = \" << x << \" y = \" << y << '\\n'; // Outputs 5 10\n \n swap(x, y);\n std::cout << \"After Swap: x = \" << x << \" y = \" << y << '\\n'; // Outputs 10 5\n }",
"links": []
},
"mSFwsTYvmg-GwG4_DEIEf": {
"title": "Memory Model",
"description": "The memory model in C++ defines how the program stores and accesses data in computer memory. It consists of different segments, such as the Stack, Heap, Data and Code segments. Each of these segments is used to store different types of data and has specific characteristics.\n\nStack Memory\n------------\n\nStack memory is used for automatic storage duration variables, such as local variables and function call data. Stack memory is managed by the compiler, and it's allocation and deallocation are done automatically. The stack memory is also a LIFO (Last In First Out) data structure, meaning that the most recent data allocated is the first to be deallocated.\n\n void functionExample() {\n int x = 10; // x is stored in the stack memory\n }\n \n\nHeap Memory\n-----------\n\nHeap memory is used for dynamic storage duration variables, such as objects created using the `new` keyword. The programmer has control over the allocation and deallocation of heap memory using `new` and `delete` operators. Heap memory is a larger pool of memory than the stack, but has a slower access time.\n\n void functionExample() {\n int* p = new int; // dynamically allocated int in heap memory\n *p = 10;\n // more code\n delete p; // deallocate memory\n }\n \n\nData Segment\n------------\n\nThe Data segment is composed of two parts: the initialized data segment and the uninitialized data segment. The initialized data segment stores global, static, and constant variables with initial values, whereas the uninitialized segment stores uninitialized global and static variables.\n\n // Initialized data segment\n int globalVar = 10; // global variables\n static int staticVar = 10; // static local variables\n const int constVar = 10; // constant variables with value\n \n // Uninitialized data segment\n int globalVar; // uninitialized global variables\n \n\nCode Segment\n------------\n\nThe Code segment (also known as the Text segment) stores the executable code (machine code) of the program. It's usually located in a read-only area of memory to prevent accidental modification.\n\n void functionExample() {\n // The machine code for this function is stored in the code segment.\n }\n \n\nIn summary, understanding the memory model in C++ helps to optimize the usage of memory resources and improves overall program performance.",
"links": []
},
"9aA_-IfQ9WmbPgwic0mFN": {
"title": "Lifetime of Objects",
"description": "Object lifetime refers to the time during which an object exists, from the moment it is created until it is destroyed. In C++, an object's lifetime can be classified into four categories:\n\n* **Static Storage Duration**: Objects with static storage duration exist for the entire run of the program. These objects are allocated at the beginning of the program's run and deallocated when the program terminates. Global variables, static data members, and static local variables fall into this category.\n \n int global_var; // Static storage duration\n class MyClass {\n static int static_var; // Static storage duration\n };\n void myFunction() {\n static int local_var; // Static storage duration\n }\n \n \n* **Thread Storage Duration**: Objects with thread storage duration exist for the lifetime of the thread they belong to. They are created when a thread starts and destroyed when the thread exits. Thread storage duration can be specified using the `thread_local` keyword.\n \n thread_local int my_var; // Thread storage duration\n \n \n* **Automatic Storage Duration**: Objects with automatic storage duration are created at the point of definition and destroyed when the scope in which they are declared is exited. These objects are also known as \"local\" or \"stack\" objects. Function parameters and local non-static variables fall into this category.\n \n void myFunction() {\n int local_var; // Automatic storage duration\n }\n \n \n* **Dynamic Storage Duration**: Objects with dynamic storage duration are created at runtime, using memory allocation functions such as `new` or `malloc`. The lifetime of these objects must be managed manually, as they are not automatically deallocated when the scope is exited. Instead, it is the programmer's responsibility to destroy the objects using the `delete` or `free` functions when they are no longer needed, to avoid memory leaks.\n \n int* ptr = new int; // Dynamic storage duration\n delete ptr;\n \n \n\nUnderstanding object lifetimes is essential for managing memory efficiently in C++ programs and avoiding common issues like memory leaks and undefined behavior.\n\nKeep in mind that a proper understanding of constructors and destructors for classes is also essential when working with objects of varying lifetimes, as they allow you to control the behavior of object creation and destruction.",
"links": []
},
"ulvwm4rRPgkpgaqGgyH5a": {
"title": "Smart Pointers",
"description": "",
"links": []
},
"vUwSS-uX36OWZouO0wOcy": {
"title": "weak_ptr",
"description": "",
"links": []
},
"b5jZIZD_U_CPg-_bdndjz": {
"title": "shared_ptr",
"description": "",
"links": []
},
"k9c5seRkhgm_yHPpiz2X0": {
"title": "unique_ptr",
"description": "",
"links": []
},
"uEGEmbxegATIrvGfobJb9": {
"title": "Raw Pointers",
"description": "",
"links": []
},
"Gld0nRs0sM8kRe8XmYolu": {
"title": "New/Delete Operators",
"description": "",
"links": []
},
"6w0WExQ4lGIGgok6Thq0s": {
"title": "Memory Leakage",
"description": "",
"links": []
},
"Zw2AOTK5uc9BoKEpY7W1C": {
"title": "Structuring Codebase",
"description": "Structuring codebase is an essential part of software development that deals with organizing and modularizing your code to make it more maintainable, efficient, and easier to understand. A well-structured codebase enhances collaboration, simplifies adding new features, and makes debugging faster. In C++, there are various techniques to help you structure your codebase effectively.\n\nNamespaces\n----------\n\nNamespaces are one of the tools in C++ to organize your code by providing a named scope for different identifiers you create, like functions, classes, and variables. They help avoid name clashes and make your code more modular.\n\n namespace MyNamespace {\n int aFunction() {\n // function implementation\n }\n }\n // to use the function\n MyNamespace::aFunction();\n \n\nInclude Guards\n--------------\n\nInclude guards are a tool for preventing multiple inclusions of a header file in your project. They consist of preprocessor directives that conditionally include the header file only once, even if it's included in multiple places.\n\n #ifndef MY_HEADER_FILE_H\n #define MY_HEADER_FILE_H\n \n // Your code here\n \n #endif // MY_HEADER_FILE_H\n \n\nHeader and Source Files\n-----------------------\n\nSeparating your implementation and declarations into header (_.h) and source (_.cpp) files is a key aspect of structuring your codebase in C++. Header files usually contain class and function declarations, while source files contain their definitions.\n\n// MyClass.h\n\n #ifndef MY_CLASS_H\n #define MY_CLASS_H\n \n class MyClass\n {\n public:\n MyClass();\n int myMethod();\n };\n \n #endif // MY_CLASS_H\n \n\n// MyClass.cpp\n\n #include \"MyClass.h\"\n \n MyClass::MyClass() {\n // constructor implementation\n }\n \n int MyClass::myMethod() {\n // method implementation\n }\n \n\nCode Formatting\n---------------\n\nConsistent code formatting and indentation play a crucial role in structuring your codebase, making it easier to read and understand for both you and other developers. A style guide such as the [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) can help you maintain consistent formatting throughout your project.",
"links": []
},
"dKCYmxDNZubCVcR5rf8b-": {
"title": "Scope",
"description": "**Scope** refers to the visibility and accessibility of variables, functions, classes, and other identifiers in a C++ program. It determines the lifetime and extent of these identifiers. In C++, there are four types of scope:\n\n* **Global scope:** Identifiers declared outside any function or class have a global scope. They can be accessed from any part of the program (unless hidden by a local identifier with the same name). The lifetime of a global identifier is the entire duration of the program.\n\n #include <iostream>\n \n int globalVar; // This is a global variable\n \n int main() {\n std::cout << \"Global variable: \" << globalVar << '\\n';\n }\n \n\n* **Local scope:** Identifiers declared within a function or a block have a local scope. They can be accessed only within the function or the block they were declared in. Their lifetime is limited to the duration of the function/block execution.\n\n #include <iostream>\n \n void localExample() {\n int localVar; // This is a local variable\n localVar = 5;\n std::cout << \"Local variable: \" << localVar << '\\n';\n }\n \n int main() {\n localExample();\n // std::cout << localVar << '\\n'; //error: ‘localVar’ was not declared in this scope\n }\n \n\n* **Namespace scope:** A namespace is a named scope that groups related identifiers together. Identifiers declared within a namespace have the namespace scope. They can be accessed using the namespace name and the scope resolution operator `::`.\n\n #include <iostream>\n \n namespace MyNamespace {\n int namespaceVar = 42;\n }\n \n int main() {\n std::cout << \"Namespace variable: \" << MyNamespace::namespaceVar << '\\n';\n }\n \n\n* **Class scope:** Identifiers declared within a class have a class scope. They can be accessed using the class name and the scope resolution operator `::` or, for non-static members, an object of the class and the dot `.` or arrow `->` operator.\n\n #include <iostream>\n \n class MyClass {\n public:\n static int staticMember;\n int nonStaticMember;\n \n MyClass(int value) : nonStaticMember(value) {}\n };\n \n int MyClass::staticMember = 7;\n \n int main() {\n MyClass obj(10);\n std::cout << \"Static member: \" << MyClass::staticMember << '\\n';\n std::cout << \"Non-static member: \" << obj.nonStaticMember << '\\n';\n }\n \n\nUnderstanding various types of scope in C++ is essential for effective code structuring and management of resources in a codebase.",
"links": []
},
"iIdC7V8sojwyEqK1xMuHn": {
"title": "Namespaces",
"description": "In C++, a namespace is a named scope or container that is used to organize and enclose a collection of code elements, such as variables, functions, classes, and other namespaces. They are mainly used to divide and manage the code base, giving developers control over name collisions and the specialization of code.\n\nSyntax\n------\n\nHere's the syntax for declaring a namespace:\n\n namespace identifier {\n // code elements\n }\n \n\nUsing Namespaces\n----------------\n\nTo access elements within a namespace, you can use the scope resolution operator `::`. Here are some examples:\n\n### Declaring and accessing a namespace\n\n #include <iostream>\n \n namespace animals {\n std::string dog = \"Bobby\";\n std::string cat = \"Lilly\";\n }\n \n int main() {\n std::cout << \"Dog's name: \" << animals::dog << '\\n';\n std::cout << \"Cat's name: \" << animals::cat << '\\n';\n \n return 0;\n }\n \n\n### Nesting namespaces\n\nNamespaces can be nested within other namespaces:\n\n #include <iostream>\n \n namespace outer {\n int x = 10;\n \n namespace inner {\n int y = 20;\n }\n }\n \n int main() {\n std::cout << \"Outer x: \" << outer::x << '\\n';\n std::cout << \"Inner y: \" << outer::inner::y << '\\n';\n \n return 0;\n }\n \n\n`using` Keyword\n---------------\n\nYou can use the `using` keyword to import namespaced elements into the current scope. However, this might lead to name conflicts if multiple namespaces have elements with the same name.\n\n### Using a single element from a namespace\n\n #include <iostream>\n \n namespace animals {\n std::string dog = \"Bobby\";\n std::string cat = \"Lilly\";\n }\n \n int main() {\n using animals::dog;\n \n std::cout << \"Dog's name: \" << dog << '\\n';\n \n return 0;\n }\n \n\n### Using the entire namespace\n\n #include <iostream>\n \n namespace animals {\n std::string dog = \"Bobby\";\n std::string cat = \"Lilly\";\n }\n \n int main() {\n using namespace animals;\n \n std::cout << \"Dog's name: \" << dog << '\\n';\n std::cout << \"Cat's name: \" << cat << '\\n';\n \n return 0;\n }\n \n\nIn conclusion, namespaces are a useful mechanism in C++ to organize code, avoid naming conflicts, and manage the visibility of code elements.",
"links": []
},
"CK7yf8Bo7kfbV6x2tZTrh": {
"title": "Headers / CPP Files",
"description": "Code splitting refers to the process of breaking down a large code base into smaller, more manageable files or modules. This helps improve the organization, maintainability, and readability of the code. In C++, code splitting is generally achieved through the use of separate compilation, header files, and source files.\n\n### Header Files (.h or .hpp)\n\nHeader files, usually with the `.h` or `.hpp` extension, are responsible for declaring classes, functions, and variables that are needed by multiple source files. They act as an interface between different parts of the code, making it easier to manage dependencies and reduce the chances of duplicated code.\n\nExample of a header file:\n\n // example.h\n #ifndef EXAMPLE_H\n #define EXAMPLE_H\n \n class Example {\n public:\n void printMessage();\n };\n \n #endif\n \n\n### Source Files (.cpp)\n\nSource files, with the `.cpp` extension, are responsible for implementing the actual functionality defined in the corresponding header files. They include the header files as needed and provide the function and class method definitions.\n\nExample of a source file:\n\n // example.cpp\n #include \"example.h\"\n #include <iostream>\n \n void Example::printMessage() {\n std::cout << \"Hello, code splitting!\\n\";\n }\n \n\n### Separate Compilation\n\nC++ allows for separate compilation, which means that each source file can be compiled independently into an object file. These object files can then be linked together to form the final executable. This provides faster build times when making changes to a single source file since only that file needs to be recompiled, and the other object files can be reused.\n\nExample of separate compilation and linking:\n\n # Compile each source file into an object file\n g++ -c main.cpp -o main.o\n g++ -c example.cpp -o example.o\n \n # Link object files together to create the executable\n g++ main.o example.o -o my_program\n \n\nBy following the code splitting technique, you can better organize your C++ codebase, making it more manageable and maintainable.",
"links": []
},
"CMlWNQwpywNhO9B6Yj6Me": {
"title": "Structures and Classes",
"description": "Structures and classes are user-defined data types in C++ that allow for the grouping of variables of different data types under a single name. They make it easier to manage and organize complex data by creating objects that have particular attributes and behaviors. The main difference between a structure and a class is their default access specifier: members of a structure are public by default, while members of a class are private.\n\nStructures\n----------\n\nA structure is defined using the `struct` keyword, followed by the structure's name and a set of curly braces `{}` enclosing the members (variables and/or functions) of the structure. The members can be of different data types. To create an object of the structure's type, use the structure name followed by the object name.\n\nHere's an example of defining a structure and creating an object:\n\n struct Employee {\n int id;\n std::string name;\n float salary;\n };\n \n Employee e1; // create an object of the 'Employee' structure\n \n\nYou can access the members of a structure using the dot operator `.`:\n\n e1.id = 1;\n e1.name = \"John Doe\";\n e1.salary = 40000;\n \n\nClasses\n-------\n\nA class is defined using the `class` keyword, followed by the class's name and a set of curly braces `{}` enclosing the members (variables and/or functions) of the class. Like structures, class members can be of different data types. You can create objects of a class using the class name followed by the object name.\n\nHere's an example of a class definition and object creation:\n\n class Student {\n int roll_no;\n std::string name;\n float marks;\n \n public:\n void set_data(int r, std::string n, float m) {\n roll_no = r;\n name = n;\n marks = m;\n }\n \n void display() {\n std::cout << \"Roll no: \" << roll_no\n << \"\\nName: \" << name\n << \"\\nMarks: \" << marks << '\\n';\n }\n };\n \n Student s1; // create an object of the 'Student' class\n \n\nSince the data members of a class are private by default, we cannot access them directly using the dot operator from outside the class. Instead, we use public member functions to set or get their values:\n\n s1.set_data(1, \"Alice\", 95.0);\n s1.display();\n \n\nThat's a brief summary of structures and classes in C++. Remember that while they may seem similar, classes provide more control over data encapsulation and can be used to implement more advanced features like inheritance and polymorphism.",
"links": []
},
"7sdEzZCIoarzznwO4XcCv": {
"title": "Rule of Zero, Five, Three",
"description": "**Rule of Zero, Three, and Five in C++**\n\nThe Rule of Zero, Three, and Five is a set of guidelines for managing object resources in modern C++, related to structures and classes. These rules deal with the default behavior of constructors, destructors, and other special member functions that are necessary for proper resource management.\n\n**Rule of Zero**\n\nThe Rule of Zero states that if a class or structure does not explicitly manage resources, it should not define any of the special member functions, i.e., destructor, copy constructor, copy assignment operator, move constructor, and move assignment operator. The compiler will automatically generate these functions, and the behavior will be correct for managing resources like memory and file handles.\n\n_Example:_\n\n struct MyResource {\n std::string name;\n int value;\n };\n \n\nIn this example, MyResource is a simple structure that does not manage any resources, so it does not define any special member functions. The compiler will generate them automatically, and the behavior will be correct.\n\n**Rule of Three**\n\nThe Rule of Three states that a class or structure that manages resources should define the following three special member functions:\n\n* Destructor\n* Copy constructor\n* Copy assignment operator\n\nThese functions are necessary for proper resource management, such as releasing memory or correctly handling deep copies.\n\n_Example:_\n\n class MyResource {\n public:\n // Constructor and destructor\n MyResource() : data(new int[100]) {} \n ~MyResource() { delete[] data; } \n \n // Copy constructor\n MyResource(const MyResource& other) : data(new int[100]) {\n std::copy(other.data, other.data + 100, data);\n }\n \n // Copy assignment operator\n MyResource& operator=(const MyResource& other) {\n if (&other == this) { return *this; }\n std::copy(other.data, other.data + 100, data);\n return *this;\n }\n \n private:\n int* data;\n };\n \n\nIn this example, MyResource is a class that manages a resource (an array of integers), so it defines the destructor, copy constructor, and copy assignment operator.\n\n**Rule of Five**\n\nThe Rule of Five extends the Rule of Three to include two additional special member functions:\n\n* Move constructor\n* Move assignment operator\n\nModern C++ introduces move semantics, which allows for more efficient handling of resources by transferring ownership without necessarily copying all the data.\n\n_Example:_\n\n class MyResource {\n public:\n // Constructors and destructor\n MyResource() : data(new int[100]) {}\n ~MyResource() { delete[] data; }\n \n // Copy constructor\n MyResource(const MyResource& other) : data(new int[100]) {\n std::copy(other.data, other.data + 100, data);\n }\n \n // Copy assignment operator\n MyResource& operator=(const MyResource& other) {\n if (&other == this) { return *this; }\n std::copy(other.data, other.data + 100, data);\n return *this;\n }\n \n // Move constructor\n MyResource(MyResource&& other) noexcept : data(other.data) {\n other.data = nullptr;\n }\n \n // Move assignment operator\n MyResource& operator=(MyResource&& other) noexcept {\n if (&other == this) { return *this; }\n delete[] data;\n data = other.data;\n other.data = nullptr;\n return *this;\n }\n \n private:\n int* data;\n };\n \n\nIn this example, MyResource is a class that manages a resource (an array of integers), so it defines all five special member functions for proper resource management and move semantics.",
"links": []
},
"WjHpueZDK-d3oDNMVZi9w": {
"title": "Multiple Inheritance",
"description": "Multiple inheritance is a feature in C++ where a class can inherit characteristics (data members and member functions) from more than one parent class. The concept is similar to single inheritance (where a class inherits from a single base class), but in multiple inheritance, a class can have multiple base classes.\n\nWhen a class inherits multiple base classes, it becomes a mixture of their properties and behaviors, and can override or extend them as needed.\n\nSyntax\n------\n\nHere is the syntax to declare a class with multiple inheritance:\n\n class DerivedClass : access-specifier BaseClass1, access-specifier BaseClass2, ...\n {\n // class body\n };\n \n\nThe `DerivedClass` will inherit members from both `BaseClass1` and `BaseClass2`. The `access-specifier` (like `public`, `protected`, or `private`) determines the accessibility of the inherited members.\n\nExample\n-------\n\nHere is an example of multiple inheritance in action:\n\n #include <iostream>\n \n // Base class 1\n class Animal\n {\n public:\n void eat()\n {\n std::cout << \"I can eat!\\n\";\n }\n };\n \n // Base class 2\n class Mammal\n {\n public:\n void breath()\n {\n std::cout << \"I can breathe!\\n\";\n }\n };\n \n // Derived class inheriting from both Animal and Mammal\n class Dog : public Animal, public Mammal\n {\n public:\n void bark()\n {\n std::cout << \"I can bark! Woof woof!\\n\";\n }\n };\n \n int main()\n {\n Dog myDog;\n \n // Calling members from both base classes\n myDog.eat();\n myDog.breath();\n \n // Calling a member from the derived class\n myDog.bark();\n \n return 0;\n }\n \n\nNote\n----\n\nIn some cases, multiple inheritance can lead to complications such as ambiguity and the \"diamond problem\". Ensure that you use multiple inheritance judiciously and maintain well-structured and modular classes to prevent issues.\n\nFor more information on C++ multiple inheritance and related topics, refer to C++ documentation or a comprehensive C++ programming guide.",
"links": []
},
"b3-QYKNcW3LYCNOza3Olf": {
"title": "Object Oriented Programming",
"description": "Object-oriented programming (OOP) is a programming paradigm that uses objects, which are instances of classes, to perform operations and interact with each other. In C++, you can achieve OOP through the use of classes and objects.\n\nClasses\n-------\n\nA class is a blueprint for creating objects. It defines the structure (data members) and behavior (member functions) for a type of object. Here's an example of a simple class:\n\n class Dog {\n public:\n std::string name;\n int age;\n \n void bark() {\n std::cout << name << \" barks!\\n\";\n }\n };\n \n\nThis `Dog` class has two data members: `name` and `age`, and one member function `bark`. You can create an object of this class and access its members like this:\n\n Dog myDog;\n myDog.name = \"Fido\";\n myDog.age = 3;\n myDog.bark(); // Output: Fido barks!\n \n\nEncapsulation\n-------------\n\nEncapsulation is the concept of bundling data and functions that operate on that data within a single unit, such as a class. It helps to hide the internal implementation details of a class and expose only the necessary information and functionalities. In C++, you can use access specifiers like `public`, `private`, and `protected` to control the visibility and accessibility of class members. For example:\n\n class Dog {\n private:\n std::string name;\n int age;\n \n public:\n void setName(std::string n) {\n name = n;\n }\n \n void setAge(int a) {\n age = a;\n }\n \n void bark() {\n std::cout << name << \" barks!\\n\";\n }\n };\n \n\nIn this example, we've made the `name` and `age` data members `private` and added public member functions `setName` and `setAge` to modify them. This way, the internal data of the `Dog` class is protected and only accessible through the provided functions.\n\nInheritance\n-----------\n\nInheritance is the concept of deriving new classes from existing ones, which enables code reusability and organization. In C++, inheritance is achieved by using a colon `:` followed by the base class' access specifier and the base class name. For example:\n\n class Animal {\n public:\n void breathe() {\n std::cout << \"I can breathe\\n\";\n }\n };\n \n class Dog : public Animal {\n public:\n void bark() {\n std::cout << \"Dog barks!\\n\";\n }\n };\n \n\nIn this example, the `Dog` class inherits from the `Animal` class, so the `Dog` class can access the `breathe` function from the `Animal` class. When you create a `Dog` object, you can use both `breathe` and `bark` functions.\n\n Dog myDog;\n myDog.breathe(); // Output: I can breathe\n myDog.bark(); // Output: Dog barks!\n \n\nPolymorphism\n------------\n\nPolymorphism allows you to use a single interface to represent different types. In C++, it's mainly achieved using function overloading, virtual functions, and overriding. For example:\n\n class Animal {\n public:\n virtual void makeSound() {\n std::cout << \"The Animal makes a sound\\n\";\n }\n };\n \n class Dog : public Animal {\n public:\n void makeSound() override {\n std::cout << \"Dog barks!\\n\";\n }\n };\n \n class Cat : public Animal {\n public:\n void makeSound() override {\n std::cout << \"Cat meows!\\n\";\n }\n };\n \n\nIn this example, we have an `Animal` base class with a virtual `makeSound` function. We then derive two classes, `Dog` and `Cat`, which override the `makeSound` function. This enables polymorphic behavior, where an `Animal` pointer or reference can be used to access the correct `makeSound` function depending on the derived class type.\n\n Animal *animals[2] = {new Dog, new Cat};\n animals[0]->makeSound(); // Output: Dog barks!\n animals[1]->makeSound(); // Output: Cat meows!\n \n\nThat's a brief overview of object-oriented programming concepts in C++.",
"links": []
},
"hNBErGNiegLsUJn_vgcOR": {
"title": "Virtual Methods",
"description": "",
"links": []
},
"s99ImazcwCgAESxZd8ksa": {
"title": "Virtual Tables",
"description": "",
"links": []
},
"7h1VivjCPDwriL7FirtFv": {
"title": "Dynamic Polymorphism",
"description": "Dynamic polymorphism is a programming concept in object-oriented languages like C++ where a derived class can override or redefine methods of its base class. This means that a single method call can have different implementations based on the type of object it is called on.\n\nDynamic polymorphism is achieved through **virtual functions**, which are member functions of a base class marked with the `virtual` keyword. When you specify a virtual function in a base class, it can be overridden in any derived class to provide a different implementation.\n\nExample\n-------\n\nHere's an example in C++ demonstrating dynamic polymorphism.\n\n #include <iostream>\n \n // Base class\n class Shape {\n public:\n virtual void draw() {\n std::cout << \"Drawing a shape\\n\"; \n }\n };\n \n // Derived class 1\n class Circle : public Shape {\n public:\n void draw() override {\n std::cout << \"Drawing a circle\\n\"; \n }\n };\n \n // Derived class 2\n class Rectangle : public Shape {\n public:\n void draw() override {\n std::cout << \"Drawing a rectangle\\n\";\n }\n };\n \n int main() {\n Shape* shape;\n Circle circle;\n Rectangle rectangle;\n \n // Storing the address of circle\n shape = &circle;\n \n // Call circle draw function\n shape->draw();\n \n // Storing the address of rectangle\n shape = &rectangle;\n \n // Call rectangle draw function\n shape->draw();\n \n return 0;\n }\n \n\nThis code defines a base class `Shape` with a virtual function `draw`. Two derived classes `Circle` and `Rectangle` both override the `draw` function to provide their own implementations. Then in the `main` function, a pointer of type `Shape` is used to call the respective `draw` functions of `Circle` and `Rectangle` objects. The output of this program will be:\n\n Drawing a circle\n Drawing a rectangle\n \n\nAs you can see, using dynamic polymorphism, we can determine at runtime which `draw` method should be called based on the type of object being used.",
"links": []
},
"B2SGBENzUMl0SAjG4j91V": {
"title": "Exception Handling",
"description": "Exception handling in C++ is a mechanism to handle errors, anomalies, or unexpected events that can occur during the runtime execution of a program. This allows the program to continue running or exit gracefully when encountering errors instead of crashing abruptly.\n\nC++ provides a set of keywords and constructs for implementing exception handling:\n\n* `try`: Defines a block of code that should be monitored for exceptions.\n* `catch`: Specifies the type of exception to be caught and the block of code that shall be executed when that exception occurs.\n* `throw`: Throws an exception that will be caught and handled by the appropriate catch block.\n* `noexcept`: Specifies a function that doesn't throw exceptions or terminates the program if an exception is thrown within its scope.\n\nExample\n-------\n\nHere's an example demonstrating the basic usage of exception handling:\n\n #include <iostream>\n \n int divide(int a, int b) {\n if (b == 0) {\n throw \"Division by zero!\";\n }\n return a / b;\n }\n \n int main() {\n int num1, num2;\n \n std::cout << \"Enter two numbers for division: \";\n std::cin >> num1 >> num2;\n \n try {\n int result = divide(num1, num2);\n std::cout << \"The result is: \" << result << '\\n';\n } catch (const char* msg) {\n std::cerr << \"Error: \" << msg << '\\n';\n }\n \n return 0;\n }\n \n\nIn this example, we define a function `divide` that throws an exception if `b` is zero. In the `main` function, we use a `try` block to call `divide` and output the result. If an exception is thrown, it is caught inside the `catch` block, which outputs an error message. This way, we can handle the error gracefully rather than letting the program crash when attempting to divide by zero.\n\nStandard Exceptions\n-------------------\n\nC++ provides a standard set of exception classes under the `<stdexcept>` library which can be used as the exception type for more specific error handling. Some of these classes include:\n\n* `std::exception`: Base class for all standard exceptions.\n* `std::logic_error`: Represents errors which can be detected statically by the program.\n* `std::runtime_error`: Represents errors occurring during the execution of a program.\n\nHere's an example showing how to use standard exceptions:\n\n #include <iostream>\n #include <stdexcept>\n \n int divide(int a, int b) {\n if (b == 0) {\n throw std::runtime_error(\"Division by zero!\");\n }\n return a / b;\n }\n \n int main() {\n int num1, num2;\n \n std::cout << \"Enter two numbers for division: \";\n std::cin >> num1 >> num2;\n \n try {\n int result = divide(num1, num2);\n std::cout << \"The result is: \" << result << '\\n';\n } catch (const std::exception& e) {\n std::cerr << \"Error: \" << e.what() << '\\n';\n }\n \n return 0;\n }\n \n\nIn this example, we modified the `divide` function to throw a `std::runtime_error` instead of a simple string. The catch block now catches exceptions derived from `std::exception` and uses the member function `what()` to display the error message.",
"links": []
},
"oWygnpwHq2poXQMTTSCpl": {
"title": "Exit Codes",
"description": "Exit codes, also known as \"return codes\" or \"status codes\", are numeric values that a program returns to the calling environment (usually the operating system) when it finishes execution. These codes are used to indicate the success or failure of a program's execution.\n\n0 is the standard exit code for a successful execution, while non-zero exit codes typically indicate errors or other exceptional situations. The actual meanings of non-zero exit codes can vary between different applications or systems.\n\nIn C++, you can return an exit code from the `main` function by using the `return` statement, or you can use the `exit()` function, which is part of the C++ Standard Library.\n\nExample: Using return in `main`\n-------------------------------\n\n #include <iostream>\n \n int main() {\n // Some code here...\n \n if (/*some error condition*/) {\n std::cout << \"An error occurred.\\n\";\n return 1;\n }\n \n // More code here...\n \n if (/*another error condition*/) {\n std::cout << \"Another error occurred.\\n\";\n return 2;\n }\n \n return 0; // Successful execution\n }\n \n\nExample: Using the `exit()` function\n------------------------------------\n\n #include <iostream>\n #include <cstdlib>\n \n void some_function() {\n // Some code here...\n \n if (/*some error condition*/) {\n std::cout << \"An error occurred.\\n\";\n std::exit(1);\n }\n \n // More code here...\n }\n \n int main() {\n some_function();\n \n // Some other code here...\n \n return 0; // Successful execution\n }\n \n\nIn both examples above, the program returns exit codes depending on different error conditions encountered during execution. The codes 1 and 2 are used to distinguish between the two error conditions.",
"links": []
},
"NJud5SXBAUZ6Sr78kZ7jx": {
"title": "Exceptions",
"description": "Exception handling is a method used to tackle runtime errors so that normal flow of the program can be maintained. In C++, this is accomplished using three keywords: `try`, `catch`, and `throw`.\n\ntry { ... }\n-----------\n\nIn the `try` block, you write the code that can possibly generate an exception. If an exception is encountered, the control is passed to the relevant `catch` block to handle the issue.\n\nExample:\n\n try {\n // code that might throw an exception\n }\n \n\ncatch (...) { ... }\n-------------------\n\nThe `catch` block follows the `try` block and is responsible for handling the exceptions thrown by the `try` block. There can be multiple `catch` blocks to handle different types of exceptions.\n\nExample:\n\n catch (int e) {\n // handle exception of type int\n }\n catch (char e) {\n // handle exception of type char\n }\n catch (...) {\n // handle any other exception\n }\n \n\nthrow ... ;\n-----------\n\nIn case an error occurs within the `try` block, you can use the `throw` keyword to generate an exception of the specific type. This will then be caught and handled by the corresponding `catch` block.\n\nExample:\n\n try {\n int num1 = 10, num2 = 0;\n if (num2 == 0) {\n throw \"Division by zero not allowed!\";\n } else {\n int result = num1 / num2;\n std::cout << \"Result: \" << result << '\\n';\n }\n }\n catch (const char* e) {\n std::cout << \"Error: \" << e << '\\n';\n }\n \n\nIn summary, exception handling in C++ is a technique to handle runtime errors while maintaining the normal flow of the program. The `try`, `catch`, and `throw` keywords are used together to create the structure to deal with exceptions as they occur.",
"links": []
},
"y4-P4UNC--rE1vni8HdTn": {
"title": "Access Violations",
"description": "An access violation is a specific type of error that occurs when a program attempts to access an illegal memory location. In C++, access violations are most commonly caused by:\n\n* **Dereferencing a null or invalid pointer.**\n* **Accessing an array out of bounds.**\n* **Reading or writing to memory freed by the user or the operating system.**\n\nIt is crucial to identify access violations because they can lead to unpredictable behavior, application crashes, or corruption of data.\n\nSome examples of access violations are:\n\nDereferencing null or invalid pointer\n-------------------------------------\n\n int *p = nullptr;\n int x = *p; // Access violation: trying to access null pointer's content\n \n\nAccessing an array out of bounds\n--------------------------------\n\n int arr[5] = {1, 2, 3, 4, 5};\n int y = arr[5]; // Access violation: index out of bounds (valid indices are 0-4)\n \n\nReading or writing to freed memory\n----------------------------------\n\n int* p2 = new int[10];\n delete[] p2;\n p2[3] = 42; // Access violation: writing to memory that has been freed\n \n\n### Debugging Access Violations\n\nTools like _debuggers_, _static analyzers_, and _profilers_ can help identify access violations in your code. For example:\n\n* **Microsoft Visual Studio**: Use the built-in debugger to identify the line of code responsible for the access violation error.\n \n* **Valgrind**: A popular Linux tool that detects memory leaks and access violations in your C++ programs.\n \n* **AddressSanitizer**: A runtime memory error detector for C++ that can detect out-of-bounds accesses, memory leaks, and use-after-free errors.",
"links": []
},
"-6fwJQOfsorgHkoQGp4T3": {
"title": "Language Concepts",
"description": "C++ is a powerful, high-level, object-oriented programming language that offers several key language concepts. These concepts provide the foundation upon which you can build efficient, reliable, and maintainable programs. Here's a brief summary of some important language concepts in C++.\n\nVariables and Data Types\n------------------------\n\nC++ provides various fundamental data types such as `int`, `float`, `double`, `char`, and `bool` to declare and manipulate variables in a program.\n\nExample:\n\n int age = 25;\n float height = 1.7f;\n double salary = 50000.0;\n char grade = 'A';\n bool isEmployed = true;\n \n\nControl Structures\n------------------\n\nControl structures enable you to control the flow of execution of a program. Key control structures in C++ include:\n\n* Conditional statement: `if`, `else`, and `else if`\n* Loop constructs: `for`, `while`, and `do-while`\n* Switch-case construct\n\nExample:\n\n // If-else statement\n if (age > 18) {\n std::cout << \"You are eligible to vote.\";\n } else {\n std::cout << \"You are not eligible to vote.\";\n }\n \n // For loop\n for (int i = 0; i < 5; i++) {\n std::cout << \"Hello World!\";\n }\n \n\nFunctions\n---------\n\nFunctions in C++ allow you to break down a large program into small, manageable, and reusable pieces of code.\n\nExample:\n\n int add(int a, int b) {\n return a + b;\n }\n \n int main() {\n int sum = add(10, 20);\n std::cout << \"The sum is: \" << sum;\n return 0;\n }\n \n\nArrays and Vectors\n------------------\n\nArrays and Vectors are commonly used data structures to store and manipulate a collection of elements of the same datatype.\n\nExample:\n\n // Array\n int marks[] = {90, 80, 95, 85};\n \n // Vector\n std::vector<int> scores = {10, 20, 30, 40};\n \n\nPointers\n--------\n\nPointers are variables that store memory addresses of other variables. They enable more efficient handling of memory, and are useful for working with dynamic data structures.\n\nExample:\n\n int num = 10;\n int* p = &num; // p stores the address of num\n \n\nStructures and Classes\n----------------------\n\nStructures and Classes are user-defined data types that allow grouping of variables and functions under a single name.\n\nExample:\n\n // Structure\n struct Student {\n std::string name;\n int age;\n };\n \n // Class\n class Employee {\n public:\n std::string name;\n int age;\n void displayInfo() {\n std::cout << \"Name: \" << name << \"\\nAge: \" << age;\n }\n };\n \n\nInheritance and Polymorphism\n----------------------------\n\nInheritance is a mechanism that allows a class to inherit properties and methods from a base class. Polymorphism enables you to use a base class type to represent derived class objects.\n\nExample:\n\n class Base {\n public:\n void display() {\n std::cout << \"This is the base class.\";\n }\n };\n \n class Derived : public Base {\n public:\n void display() {\n std::cout << \"This is the derived class.\";\n }\n };\n \n\nException Handling\n------------------\n\nC++ provides a mechanism to handle exceptions(runtime errors) gracefully using `try`, `catch`, and `throw` constructs.\n\nExample:\n\n try {\n // Code that might throw an exception\n int result = a / b;\n } catch (const exception &e) {\n std::cout << \"Caught an exception: \" << e.what();\n }\n \n\nThese are some of the key language concepts in C++, which will help you to understand the language better and develop efficient and maintainable applications.",
"links": []
},
"CG01PTVgHtjfKvsJkJLGl": {
"title": "auto (Automatic Type Deduction)",
"description": "**Auto**\n\n`auto` is a keyword in C++ language introduced in C++11, which is used for automatic type deduction. It automatically deduces the type of a variable from the type of its initializer expression at compile time.\n\nThe `auto` keyword is useful when you are dealing with complex types or when the type of a variable is hard to predict. It can help in writing cleaner and less error-prone code.\n\nHere's a simple example of using `auto` for type deduction:\n\n #include <iostream>\n #include <vector>\n \n int main() {\n // Traditional way of declaring a variable:\n int myInt = 5;\n \n // Using auto for type deduction:\n auto myAutoInt = 5; // Automatically deduces the type as 'int'\n \n // Example with more complex types:\n std::vector<int> myVector = {1, 2, 3, 4, 5};\n \n // Without auto, iterating the vector would look like this:\n for (std::vector<int>::iterator it = myVector.begin(); it != myVector.end(); ++it) {\n std::cout << *it << '\\n';\n }\n \n // With auto, the iterator declaration becomes simpler:\n for (auto it = myVector.begin(); it != myVector.end(); ++it) {\n std::cout << *it << '\\n';\n }\n }\n \n\nKeep in mind that `auto` deduces the type based on the initializer expression, so if you don't provide an initial value, you will get a compile-time error:\n\n auto myVar; // Error: Cannot deduce the type without initializer\n \n\nIn C++14, you can also use `auto` with function return types to let the compiler automatically deduce the return type based on the returned expression:\n\n auto add(int x, int y) {\n return x + y; // The compiler deduces the return type as 'int'\n }",
"links": []
},
"PiMhw1oP9-NZEa6I9u4lX": {
"title": "Type Casting",
"description": "Type casting is the process of converting a value from one data type to another. In C++, there are four different methods of type casting:\n\n* **C-style casting**: It is the syntax inherited from C, and it is done by simply putting the target data type in parentheses before the value to cast. Example:\n \n int a = 10;\n float b = (float)a; // C-style cast from int to float\n \n \n* **`static_cast`**: This is the most commonly used method for type casting in C++. It is performed at compile time, and you should use it when you have an explicit conversion between data types. Example:\n \n int a = 10;\n float b = static_cast<float>(a); // static_cast from int to float\n \n \n* **`dynamic_cast`**: This method is specifically used for safely converting pointers and references between base and derived classes in a class hierarchy. Example:\n \n class Base {};\n class Derived : public Base {};\n \n Base* base_ptr = new Derived();\n Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr); // dynamic_cast from Base* to Derived*\n \n \n* **`reinterpret_cast`**: This cast changes the type of a pointer, reference, or an integer value. It is also called a bitwise cast because it changes how the compiler interprets the underlying bits. Use `reinterpret_cast` only when you have a deep understanding of what you're doing, as it does not guarantee that the resulting value will be meaningful. Example:\n \n int* a = new int(42);\n long b = reinterpret_cast<long>(a); // reinterpret_cast from int* to long\n \n \n* **`const_cast`**: This casting method is used to remove the `const` qualifier from a variable. It is generally not recommended, but can be useful in certain situations where you have no control over the constness of a variable. Example:\n \n const int a = 10;\n int* ptr = const_cast<int*>(&a); // const_cast from const int* to int*\n *ptr = 20; // Not recommended, use with caution\n \n \n\nRemember to use the right type of casting based on the specific situation and follow good programming practices in order to ensure a safe and efficient code.\n\nLearn more from the following resources:",
"links": [
{
"title": "Casting in C++",
"url": "https://youtu.be/pWZS1MtxI-A",
"type": "video"
}
]
},
"_XB2Imyf23-6AOeoNLhYQ": {
"title": "static_cast",
"description": "`static_cast` is one of the casting operators in C++ that allows you to convert between different data types, such as integer and float, or between pointer types. This type of cast performs a compile-time check and gives an error if there is no valid conversion possible between given types. `static_cast` is generally safer than C-style casts since it does not perform an unsafe reinterpretation of data and allows for better type checking.\n\nSyntax\n------\n\nThe syntax for `static_cast` is as follows:\n\n static_cast<new_type>(expression)\n \n\nExamples\n--------\n\n* Converting between basic data types:\n\n int i = 42;\n float f = static_cast<float>(i); // Converts integer i to float f\n \n\n* Casting pointers of different object types in an inheritance hierarchy:\n\n class Base { /* ... */ };\n class Derived : public Base { /* ... */ };\n \n Base *bPtr = new Derived;\n Derived *dPtr = static_cast<Derived *>(bPtr); // Converts Base pointer bPtr to Derived pointer dPtr\n \n\n* Converting an integer to an enumeration:\n\n enum Color { RED, GREEN, BLUE };\n int value = 1;\n Color color = static_cast<Color>(value); // Converts integer value to corresponding Color enumeration\n \n\nKeep in mind that `static_cast` should be used with caution when casting pointers between different object types. If the original type of the pointer does not match the target type, the result of the cast can be incorrect or cause unexpected behavior.",
"links": []
},
"5g22glc97siQOcTkHbwan": {
"title": "const_cast",
"description": "`const_cast` is a type of casting in C++ that allows you to remove or add constness to a variable. In other words, it enables you to modify a `const` or `volatile` object, or change a pointer or reference to a `const` or `volatile` type. This is useful in certain scenarios when you need to pass a `const` variable as an argument or when a function parameter requires a non-const type, but you want to make sure the variable remains constant throughout the code.\n\nKeep in mind that using `const_cast` to modify a truly `const` variable can lead to undefined behavior, so it is best to use this feature only when absolutely necessary.\n\nExample\n-------\n\nHere's a code example showing how to use `const_cast`:\n\n #include <cassert>\n #include <iostream>\n \n void modifyVariable(int* ptr) {\n *ptr = 42;\n }\n \n int main() {\n const int original_value = 10;\n int* non_const_value_ptr = const_cast<int*>(&original_value);\n std::cout << \"Original value: \" << original_value << '\\n';\n \n modifyVariable(non_const_value_ptr);\n std::cout << \"Modified value: \" << *non_const_value_ptr << \", original_value: \" << original_value << '\\n';\n \n assert(non_const_value_ptr == &original_value);\n \n return 0;\n }\n \n \n\nIn this example, we first create a `const` variable, `original_value`. Then we use `const_cast` to remove the constness of the variable and assign it to a non-const pointer, `non_const_value_ptr`. The `modifyVariable` function takes an `int*` as an argument and modifies the value pointed to by the pointer, which would not have been possible if we passed the original `const int` directly. Finally, we print the `original_value` and the `*non_const_value_ptr`, which shows that the value has been modified using `const_cast`.\n\nPlease note that this example comes with some risks, as it touches undefined behavior. \\*/",
"links": []
},
"4BdFcuQ5KNW94cu2jz-vE": {
"title": "dynamic_cast",
"description": "`dynamic_cast` is a type of casting operator in C++ that is used specifically for polymorphism. It safely converts pointers and references of a base class to its derived class and checks the validity of the conversion during runtime. If the conversion is not valid (i.e., the object is not of the target type), it returns a null pointer instead of producing undefined behavior. Therefore, `dynamic_cast` can prevent potential crashes and errors when using polymorphism.\n\nHere is a basic example of how `dynamic_cast` can be used:\n\n #include <iostream>\n \n class BaseClass {\n public:\n virtual void display() {\n std::cout << \"BaseClass\\n\";\n }\n };\n \n class DerivedClass : public BaseClass {\n public:\n void display() {\n std::cout << \"DerivedClass\\n\";\n }\n };\n \n int main() {\n BaseClass *basePtr = new DerivedClass(); // Upcasting\n DerivedClass *derivedPtr;\n \n derivedPtr = dynamic_cast<DerivedClass *>(basePtr); // Downcasting\n if (derivedPtr) {\n derivedPtr->display(); // Output: DerivedClass\n } else {\n std::cout << \"Invalid type conversion.\";\n }\n \n delete basePtr;\n return 0;\n }\n \n\nIn this example, a pointer to a `DerivedClass` object is assigned to a `BaseClass` pointer (`basePtr`). Then, we attempt to downcast it back to a `DerivedClass` pointer using `dynamic_cast`. If the casting is successful, we can access the `DerivedClass` functionality through the new pointer (`derivedPtr`).",
"links": []
},
"ZMyFDJrpCauGrY5NZkOwg": {
"title": "reinterpret_cast",
"description": "`reinterpret_cast` is a type of casting in C++ that allows you to change the type of a pointer or an integer without altering the representation of the data. It is generally used when the conversion required is too low-level or not supported by other casting methods, such as `static_cast`.\n\nUsing `reinterpret_cast` should be handled with care, as it can lead to undefined behavior and severe problems if used incorrectly.\n\nHere's an example of usage:\n\n #include <iostream>\n \n int main() {\n int num = 42;\n int *num_ptr = &num;\n \n // Disguise the integer pointer as a char pointer\n char *char_ptr = reinterpret_cast<char *>(num_ptr);\n \n for (size_t i = 0; i < sizeof(int); ++i) {\n // Print the individual bytes of the integer as characters\n std::cout << \"Byte \" << i << \": \" << char_ptr[i] << '\\n';\n }\n \n return 0;\n }\n \n\nIn this example, we're using `reinterpret_cast` to change the type of a pointer from `int *` to `char *`, effectively treating the integer as an array of characters and printing each byte.\n\nRemember that when using `reinterpret_cast`, you should be cautious about dereferencing the converted pointers. The behavior can be unpredictable, and it can lead to issues, such as accessing memory regions that are not intended to be accessed. `reinterpret_cast` should be used sparingly and only when a low-level conversion is necessary.",
"links": []
},
"IDOlquv6jlfecwQoBwkGZ": {
"title": "Undefined Behavior (UB)",
"description": "**Undefined Behavior**\n----------------------\n\nUndefined behavior in C++ refers to a situation where a program's behavior cannot be predicted due to any violation of the language rules. It is a result of various factors like uninitialized variables, using pointers to deallocated memory, out-of-bounds memory access, etc. The C++ standard does not define the behavior in such cases, which means the compiler or the runtime system is free to handle these situations in any way it wants.\n\nSome common examples of Undefined Behavior are:\n\n* **Uninitialized Variables**: Accessing the value of an uninitialized variable can lead to undefined behavior. The value of an uninitialized variable is arbitrary and depends on what was in the memory location before the variable was declared.\n \n int x;\n int y = x + 5; // Undefined behavior since x is uninitialized\n \n \n* **Out-of-bounds Memory Access**: Accessing memory outside the boundaries of an array or buffer may result in undefined behavior.\n \n int arr[5];\n int val = arr[5]; // Undefined behavior since the valid indices are 0 to 4\n \n \n* **Null Pointer Dereference**: Dereferencing a null pointer may lead to undefined behavior.\n \n int *ptr = nullptr;\n int val = *ptr; // Undefined behavior since ptr is a null pointer\n \n \n* **Division by Zero**: Performing a division operation by zero is undefined behavior in C++.\n \n int x = 5;\n int y = 0;\n int z = x / y; // Undefined behavior since division by zero is not allowed\n \n \n\nIt is crucial to detect and fix the root cause of undefined behavior in your programs since it can lead to unpredictable results, data corruption, and security vulnerabilities. To mitigate undefined behavior, you can utilize tools like static code analyzers, dynamic analysis tools, and compiler options that help detect potential issues.",
"links": []
},
"YSWN7nS8vA9nMldSUrZRT": {
"title": "Argument Dependent Lookup (ADL)",
"description": "Argument Dependent Lookup (ADL) or Koenig Lookup is a mechanism in C++ that allows the compiler to search for the appropriate function to call based on the types of arguments provided. It is particularly helpful when using overloaded functions or operators in a namespace.\n\nADL allows the compiler to find functions in the same namespace as the arguments, even if the function is not declared at the point of use or within the namespace provided. This is especially useful when working with templates or generic programming.\n\nExample\n-------\n\nConsider the following example using a namespace and overloaded `operator<<()`:\n\n namespace MyNamespace {\n class MyClass {\n public:\n int value;\n };\n \n std::ostream& operator<<(std::ostream& os, const MyClass& obj) {\n os << \"MyClass: \" << obj.value;\n return os;\n }\n }\n \n int main() {\n MyNamespace::MyClass obj;\n obj.value = 42;\n using std::cout; // Required to use 'cout' without fully qualifying it.\n cout << obj << '\\n'; // ADL is used to find the correct overloaded 'operator<<'.\n }\n \n\nIn this example, when you call `cout << obj;` in `main()`, ADL is used to find the correct `operator<<()` in the `MyNamespace` namespace because the argument `obj` is of type `MyNamespace::MyClass`.",
"links": []
},
"Lt7ss59KZw9Jwqj234jm2": {
"title": "Name Mangling",
"description": "Name mangling, also known as name decoration, is a technique used by compilers to encode additional information about the scope, type, linkage, or other identifying information of an identifier (function names, variable names, etc.) within its name. The primary purpose of name mangling is to support function overloading, which allows multiple functions with the same name but different parameter lists to coexist in a single program.\n\nIn C++, the compiler generates a mangled name for each function and variable based on their scopes and types. The mangled name is usually formed by concatenating the original name, parameter types, and other information, often using a prefix or suffix.\n\nFor example, suppose you have the following function:\n\n int add(int a, int b)\n {\n return a + b;\n }\n \n\nThe compiler might generate a mangled name such as `_Z3addii`, which encodes the function name `add` and its two `int` parameters.\n\nThe exact rules for name mangling are implementation and platform dependent. Different compilers may mangle names differently, which can lead to incompatibilities when attempting to link together object files or libraries compiled with different compilers.\n\nSome tools, such as c++filt (included in GCC and Clang), can be used to demangle a mangled name back to the original identifier, which can be useful when debugging or working with symbol tables.\n\n $ echo \"_Z3addii\" | c++filt\n add(int, int)\n \n\nIn general, it is not necessary for you to understand the details of name mangling when writing code in C++, as the compiler handles it automatically. However, it can affect program behavior in some cases, such as when using external libraries or linking object files from different compilers.",
"links": []
},
"zKdlfZTRHwjtmRUGW9z9-": {
"title": "Macros",
"description": "Macros are preprocessing directives in C++ used by the preprocessor to perform text substitution. They are defined using the `#define` directive, followed by the macro name and the value to be substituted.\n\nMacros can be used to define constants, create function-like macros, or perform conditional compilation.\n\nConstant Macros\n---------------\n\nConstant macros are used to define symbolic constants for use in code. They do not use any memory and are replaced by the preprocessor before the compilation process.\n\nExample:\n\n #define PI 3.14159\n \n\nThis macro defines a symbolic constant `PI`. You can use it in your code as if it were a regular variable.\n\n double circumference = 2 * PI * radius;\n \n\nFunction-like Macros\n--------------------\n\nFunction-like macros are similar to regular functions. They take a list of arguments and perform text substitution.\n\nExample:\n\n #define SQUARE(x) ((x) * (x))\n \n\nThis macro defines a function-like macro `SQUARE` that calculates the square of a number.\n\n int square_of_five = SQUARE(5); // expands to ((5) * (5))\n \n\nConditional Compilation\n-----------------------\n\nMacros can be used for conditional compilation using the `#ifdef`, `#ifndef`, `#if`, `#else`, `#elif`, and `#endif` directives.\n\nExample:\n\n #define DEBUG_MODE\n \n #ifdef DEBUG_MODE\n // Code to be compiled only in debug mode\n #else\n // Code to be compiled only if DEBUG_MODE is not defined\n #endif\n \n\nThis example demonstrates how you can use macros to control the parts of code that are being compiled, depending on the presence or absence of a macro definition.",
"links": []
},
"DHdNBP7_ixjr6h-dIQ7g6": {
"title": "Standard Library + STL",
"description": "The C++ Standard Template Library (STL) is a collection of header files that provide several data structures, algorithms, and functions to simplify your C++ coding experience. The primary purpose of the STL is to save time and increase efficiency by providing a ready-to-use set of useful tools. The most commonly used features of the STL can be divided into three main categories: containers, algorithms, and iterators.\n\nContainers\n----------\n\nContainers are the data structures used for data storage and manipulation in C++. They are classified into four types: sequence containers, associative containers, unordered associative containers, and container adaptors.\n\n* **Sequence Containers**: These are linear data structures that store elements in a sequential manner. Examples include:\n \n * `std::vector`: A dynamic array that grows and shrinks at runtime.\n \n std::vector<int> my_vector;\n \n \n * `std::list`: A doubly linked list.\n \n std::list<int> my_list;\n \n \n * `std::deque`: A double-ended queue allowing insertion and deletion at both ends.\n \n std::deque<int> my_deque;\n \n \n* **Associative Containers**: These containers store data in a sorted manner with unique keys. Examples include:\n \n * `std::set`: A collection of unique elements sorted by keys.\n \n std::set<int> my_set;\n \n \n * `std::map`: A collection of key-value pairs sorted by keys.\n \n std::map<std::string, int> my_map;\n \n \n* **Unordered Associative Containers**: These containers store data in an unordered manner using hash tables. Examples include:\n \n * `std::unordered_set`: A collection of unique elements in no specific order.\n \n std::unordered_set<int> my_unordered_set;\n \n \n * `std::unordered_map`: A collection of key-value pairs in no specific order.\n \n std::unordered_map<std::string, int> my_unordered_map;\n \n \n* **Container Adaptors**: These are containers based on other existing containers. Examples include:\n \n * `std::stack`: A LIFO data structure based on deque or list.\n \n std::stack<int> my_stack;\n \n \n * `std::queue`: A FIFO data structure based on deque or list.\n \n std::queue<int> my_queue;\n \n \n * `std::priority_queue`: A sorted queue based on vector or deque.\n \n std::priority_queue<int> my_priority_queue;\n \n \n\nAlgorithms\n----------\n\nThe STL provides several generic algorithms that can be used to perform various operations on the data stored in containers. They are divided into five categories: non-modifying sequence algorithms, modifying sequence algorithms, sorting algorithms, sorted range algorithms, and numeric algorithms.\n\nSome examples include `std::find`, `std::replace`, `std::sort`, and `std::binary_search`.\n\nFor example, to sort a vector, you can use the following code:\n\n std::vector<int> my_vec = {4, 2, 5, 1, 3};\n std::sort(my_vec.begin(), my_vec.end());\n \n\nIterators\n---------\n\nIterators are a fundamental concept in the STL, as they provide a unified way to access elements in containers. Iterators can be thought of as an advanced form of pointers.\n\nEach container has its own iterator type, which can be used to traverse elements and modify values. The most common iterator operations are `begin()` and `end()` for getting iterators pointing to the first and one past the last element of a container, respectively.\n\nFor example, to iterate through a vector and print its elements, you can use the following code:\n\n std::vector<int> my_vec = {1, 2, 3, 4, 5};\n for (auto it = my_vec.begin(); it != my_vec.end(); ++it) {\n std::cout << *it << \" \";\n }\n \n\nThis is just a brief overview of the C++ Standard Template Library. There are many other features and functions available in the STL, and familiarizing yourself with them is crucial for efficient C++ programming.",
"links": []
},
"Ebu8gzbyyXEeJryeE0SpG": {
"title": "Iterators",
"description": "Iterators are objects in the C++ Standard Library (`STL`) that help us traverse containers like arrays, lists, and vectors. Essentially, they act as a bridge between container classes and algorithms. Iterators behave similar to pointers but provide a more generalized and abstract way of accessing elements in a container.\n\nThere are different types of iterators which you would encounter depending on their use cases:\n\n* **Input Iterator**: Used to read elements in a container only once, in a forward direction. They cannot modify elements.\n\nExample:\n\n std::vector<int> nums = {1, 2, 3, 4};\n std::istream_iterator<int> input(std::cin);\n std::copy(input, std::istream_iterator<int>(), std::back_inserter(nums));\n \n\n* **Output Iterator**: Used to write elements in a container only once, in a forward direction. They cannot re-write elements.\n\nExample:\n\n std::vector<int> nums = {1, 2, 3, 4};\n std::ostream_iterator<int> output(std::cout, \", \");\n std::copy(nums.begin(), nums.end(), output);\n \n\n* **Forward Iterator**: Similar to input iterators but can be used for multiple passes over the elements in a container. They cannot move backward.\n\nExample:\n\n std::forward_list<int> nums = {1, 2, 3, 4};\n std::forward_list<int>::iterator itr = nums.begin();\n while (itr != nums.end()) {\n std::cout << *itr << \" \";\n ++itr;\n }\n \n\n**Reverse Iterator**: Similar to input iterators but can be used for multiple passes over the elements in a container. They cannot move forward.\n\nExample:\n\n std::list<int> nums = {1, 2, 3, 4};\n std::list<int>::reverse_iterator itr = nums.rbegin();\n while (itr != nums.rend()) {\n std::cout << *itr << \" \";\n ++itr;\n }\n \n\n* **Bidirectional Iterator**: These iterators offer the ability to move both forward and backward in a container. List and set containers have bi-directional iterators.\n\nExample:\n\n std::list<int> nums = {1, 2, 3, 4};\n std::list<int>::iterator itr;\n for (itr = nums.begin(); itr != nums.end(); ++itr) {\n std::cout << *itr << \" \";\n }\n for (--itr; itr != nums.begin(); --itr) {\n std::cout << *itr << \" \";\n }\n \n\n* **Random Access Iterator**: These iterators provide the most flexible ways to access elements in a container. They can move forwards, backwards, jump directly to other elements, and access elements at a given index.\n\nExample:\n\n std::vector<int> nums = {1, 2, 3, 4};\n std::vector<int>::iterator itr;\n for (itr = nums.begin(); itr != nums.end(); ++itr) {\n std::cout << *itr << \" \";\n }\n for (itr -= 1; itr != nums.begin() - 1; --itr) {\n std::cout << *itr << \" \";\n }\n \n\nFor most cases, you would want to start with the `auto` keyword and the appropriate container methods (like `begin()` and `end()`) to work with iterators.\n\nExample:\n\n std::vector<int> nums = {1, 2, 3, 4};\n for (auto itr = nums.begin(); itr != nums.end(); ++itr) {\n std::cout << *itr << \" \";\n }\n \n\nWhen working with algorithms, remember that the C++ Standard Library provides various algorithms that already utilize iterators for tasks like searching, sorting, and manipulating elements.",
"links": []
},
"VeVxZ230xkesQsIDig8zQ": {
"title": "iostream",
"description": "`iostream` is a header in the C++ Standard Library that provides functionality for basic input and output (I/O) operations. The I/O streams facilitate communication between your program and various sources, such as the console, files, or other programs.\n\n`iostream` includes the following classes:\n\n* `istream`: for input operations from an input source.\n* `ostream`: for output operations to an output target.\n* `iostream`: a combination of `istream` and `ostream` for both input and output operations.\n\nThese classes inherit from base classes `ios` and `ios_base`.\n\nAdditionally, `iostream` defines several objects that are instances of these classes and represent the standard input and output streams:\n\n* `cin`: an `istream` object to read from the standard input, typically corresponding to the keyboard.\n* `cout`: an `ostream` object to write to the standard output, typically the console.\n* `cerr`: an `ostream` object to write to the standard error output, typically used for displaying error messages.\n* `clog`: an `ostream` object, similar to `cerr`, but its output can be buffered.\n\nHere are some code examples on using `iostream` for input and output operations:\n\n #include <iostream>\n \n int main() {\n int a;\n std::cout << \"Enter a number: \";\n std::cin >> a;\n std::cout << \"You entered: \" << a << '\\n';\n return 0;\n }\n \n\n #include <iostream>\n \n int main() {\n std::cerr << \"An error occurred.\\n\";\n std::clog << \"Logging information.\\n\";\n return 0;\n }\n \n\nRemember to include the `iostream` header when using these features:\n\n #include <iostream>",
"links": []
},
"whyj6Z4RXFsVQYRfYYn7B": {
"title": "Algorithms",
"description": "The Standard Template Library (STL) in C++ provides a collection of generic algorithms that are designed to work with various container classes. These algorithms are implemented as functions and can be applied to different data structures, such as arrays, vectors, lists, and others. The primary header file for algorithms is `<algorithm>`.\n\nKey Concepts\n------------\n\nSorting\n-------\n\nSorting refers to arranging a sequence of elements in a specific order. The STL provides several sorting algorithms, such as `std::sort`, `std::stable_sort`, and `std::partial_sort`.\n\n### std::sort\n\n`std::sort` is used to sort a range of elements \\[first, last) in non-descending order (by default). You can also use custom comparison functions or lambda expressions to change the sorting order.\n\nExample:\n\n #include <algorithm>\n #include <vector>\n #include <iostream>\n \n int main() {\n std::vector<int> nums = {10, 9, 8, 7, 6, 5};\n std::sort(nums.begin(), nums.end());\n \n for (int num : nums) {\n std::cout << num << ' ';\n }\n // Output: 5 6 7 8 9 10\n }\n \n\nSearching\n---------\n\nSearching refers to finding if a particular element is present within a given range of elements. STL provides various searching algorithms, such as `std::find`, `std::binary_search`, and `std::find_if`.\n\n### std::find\n\n`std::find` is used to find the iterator of the first occurrence of a given value within the range \\[first, last).\n\nExample:\n\n #include <algorithm>\n #include <vector>\n #include <iostream>\n \n int main() {\n std::vector<int> nums = {5, 6, 7, 8, 9, 10};\n auto it = std::find(nums.begin(), nums.end(), 9);\n \n if (it != nums.end()) {\n std::cout << \"Found 9 at position: \" << (it - nums.begin());\n } else {\n std::cout << \"9 not found\";\n }\n // Output: Found 9 at position: 4\n }\n \n\nModifying Sequences\n-------------------\n\nThe STL also provides algorithms for modifying sequences, such as `std::remove`, `std::replace`, and `std::unique`.\n\n### std::remove\n\n`std::remove` is used to remove all instances of a value from a container within the given range \\[first, last). Note that the function does not resize the container after removing elements.\n\nExample:\n\n #include <algorithm>\n #include <vector>\n #include <iostream>\n \n int main() {\n std::vector<int> nums = {5, 6, 7, 6, 8, 6, 9, 6, 10};\n nums.erase(std::remove(nums.begin(), nums.end(), 6), nums.end());\n \n for (int num : nums) {\n std::cout << num << ' ';\n }\n // Output: 5 7 8 9 10\n }\n \n\nSummary\n-------\n\nSTL algorithms in C++ provide a set of useful functions for key operations such as sorting, searching, and modifying sequences. The algorithms can be used with a variety of container classes, making them highly versatile and an essential part of C++ programming.",
"links": []
},
"yGvE6eHKlPMBB6rde0llR": {
"title": "Date / Time",
"description": "In C++, you can work with dates and times using the `chrono` library, which is part of the Standard Library (STL). The `chrono` library provides various data types and functions to represent and manipulate time durations, time points, and clocks.\n\nDuration\n--------\n\nA `duration` represents a span of time, which can be expressed in various units such as seconds, minutes, hours, etc. To create a duration, use the `std::chrono::duration` template class. Common predefined duration types are:\n\n* `std::chrono::seconds`\n* `std::chrono::minutes`\n* `std::chrono::hours`\n\n**Example:**\n\n #include <iostream>\n #include <chrono>\n \n int main() {\n std::chrono::seconds sec(5);\n std::chrono::minutes min(2);\n std::chrono::hours hr(1);\n return 0;\n }\n \n\nTime Point\n----------\n\nA `time_point` represents a specific point in time. It is usually created using a combination of duration and a clock. In C++, there are three clock types provided by the `chrono` library:\n\n* `std::chrono::system_clock`: Represents the system-wide real time wall clock.\n* `std::chrono::steady_clock`: Represents a monotonic clock that is guaranteed to never be adjusted.\n* `std::chrono::high_resolution_clock`: Represents the clock with the shortest tick period.\n\n**Example:**\n\n #include <iostream>\n #include <chrono>\n \n int main() {\n std::chrono::system_clock::time_point tp = std::chrono::system_clock::now();\n return 0;\n }\n \n\nClock\n-----\n\nA clock provides access to the current time. It consists of the following elements:\n\n* `time_point`: A specific point in time.\n* `duration`: The time duration between two time points.\n* `now()`: A static function that returns the current time point.\n\n**Example:**\n\n #include <iostream>\n #include <chrono>\n \n int main() {\n // Get the current time_point using system_clock\n std::chrono::system_clock::time_point now = std::chrono::system_clock::now();\n \n // Get the time_point 1 hour from now\n std::chrono::system_clock::time_point one_hour_from_now = now + std::chrono::hours(1);\n return 0;\n }\n \n\nConverting Time Points to Calendar Time\n---------------------------------------\n\nTo convert a time point to calendar representation, you can use the `std::chrono::system_clock::to_time_t` function.\n\n**Example:**\n\n #include <iostream>\n #include <chrono>\n #include <ctime>\n \n int main() {\n std::chrono::system_clock::time_point now = std::chrono::system_clock::now();\n std::time_t now_c = std::chrono::system_clock::to_time_t(now);\n std::cout << \"Current time: \" << std::ctime(&now_c) << '\\n';\n return 0;\n }\n \n\nThis summarizes the basic functionality of working with date and time in C++ using the `chrono` library. You can find more advanced features, such as casting durations and time arithmetic, in the [C++ reference](https://en.cppreference.com/w/cpp/chrono).",
"links": []
},
"OXQUPqxzs1-giAACwl3X1": {
"title": "Multithreading",
"description": "Multithreading is the concurrent execution of multiple threads within a single process or program. It improves the performance and efficiency of an application by allowing multiple tasks to be executed in parallel.\n\nIn C++, multithreading support is available through the `thread` library introduced in the C++11 standard.\n\nBasic Thread Creation\n---------------------\n\nTo create a new thread, include the `<thread>` header file and create an instance of `std::thread` that takes a function as an argument. The function will be executed in a new thread.\n\n #include <iostream>\n #include <thread>\n \n void my_function() {\n std::cout << \"This function is executing in a separate thread\\n\";\n }\n \n int main() {\n std::thread t(my_function);\n t.join(); // waits for the thread to complete\n return 0;\n }\n \n\nThread with Arguments\n---------------------\n\nYou can pass arguments to the thread function by providing them as additional arguments to the `std::thread` constructor.\n\n #include <iostream>\n #include <thread>\n \n void print_sum(int a, int b) {\n std::cout << \"The sum is: \" << a + b << '\\n';\n }\n \n int main() {\n std::thread t(print_sum, 3, 5);\n t.join();\n return 0;\n }\n \n\nMutex and Locks\n---------------\n\nWhen multiple threads access shared resources, there is a possibility of a data race. To avoid this, use mutex and locks to synchronize shared resource access.\n\n #include <iostream>\n #include <mutex>\n #include <thread>\n \n std::mutex mtx;\n \n void print_block(int n, char c) {\n {\n std::unique_lock<std::mutex> locker(mtx);\n for (int i = 0; i < n; ++i) {\n std::cout << c;\n }\n std::cout << '\\n';\n }\n }\n \n int main() {\n std::thread t1(print_block, 50, '*');\n std::thread t2(print_block, 50, '$');\n \n t1.join();\n t2.join();\n \n return 0;\n }\n \n\nThis short introduction should help you get started with basic multithreading techniques in C++. There is a lot more to learn, such as thread pools, condition variables, and atomic operations for advanced synchronization and performance tuning.",
"links": []
},
"1pydf-SR0QUfVNuBEyvzc": {
"title": "Containers",
"description": "C++ Containers are a part of the Standard Template Library (STL) that provide data structures to store and organize data. There are several types of containers, each with its own characteristics and use cases. Here, we discuss some of the commonly used containers:\n\n1\\. Vector\n----------\n\nVectors are dynamic arrays that can resize themselves as needed. They store elements in a contiguous memory location, allowing fast random access using indices.\n\nExample\n-------\n\n #include <iostream>\n #include <vector>\n \n int main() {\n std::vector<int> vec = {1, 2, 3, 4, 5};\n \n vec.push_back(6); // Add an element to the end\n \n std::cout << \"Vector contains:\";\n for (int x : vec) {\n std::cout << ' ' << x;\n }\n std::cout << '\\n';\n }\n \n\n2\\. List\n--------\n\nA list is a doubly-linked list that allows elements to be inserted or removed from any position in constant time. It does not support random access. Lists are better than vectors for scenarios where you need to insert or remove elements in the middle frequently.\n\nExample\n-------\n\n #include <iostream>\n #include <list>\n \n int main() {\n std::list<int> lst = {1, 2, 3, 4, 5};\n \n lst.push_back(6); // Add an element to the end\n \n std::cout << \"List contains:\";\n for (int x : lst) {\n std::cout << ' ' << x;\n }\n std::cout << '\\n';\n }\n \n\n3\\. Map\n-------\n\nA map is an associative container that stores key-value pairs. It supports the retrieval of values based on their keys. The keys are sorted in ascending order by default.\n\nExample\n-------\n\n #include <iostream>\n #include <map>\n \n int main() {\n std::map<std::string, int> m;\n \n m[\"one\"] = 1;\n m[\"two\"] = 2;\n \n std::cout << \"Map contains:\\n\";\n for (const auto &pair : m) {\n std::cout << pair.first << \": \" << pair.second << '\\n';\n }\n }\n \n\n4\\. Unordered\\_map\n------------------\n\nSimilar to a map, an unordered map stores key-value pairs, but it is implemented using a hash table. This means unordered\\_map has faster average-case performance compared to map, since it does not maintain sorted order. However, worst-case performance can be worse than map.\n\nExample\n-------\n\n #include <iostream>\n #include <unordered_map>\n \n int main() {\n std::unordered_map<std::string, int> um;\n \n um[\"one\"] = 1;\n um[\"two\"] = 2;\n \n std::cout << \"Unordered map contains:\\n\";\n for (const auto &pair : um) {\n std::cout << pair.first << \": \" << pair.second << '\\n';\n }\n }\n \n\nThese are just a few examples of C++ containers. There are other container types, such as `set`, `multiset`, `deque`, `stack`, `queue`, and `priority_queue`. Each container has its own use cases and unique characteristics. Learning about these containers and when to use them can greatly improve your efficiency and effectiveness in using C++.",
"links": []
},
"-6AOrbuOE7DJCmxlcgCay": {
"title": "Templates",
"description": "Templates in C++ are a powerful feature that allows you to write generic code, meaning that you can write a single function or class that can work with different data types. This means you do not need to write separate functions or classes for each data type you want to work with.\n\nTemplate Functions\n------------------\n\nTo create a template function, you use the `template` keyword followed by the type parameters or placeholders enclosed in angle brackets (`< >`). Then, you define your function as you normally would, using the type parameters to specify the generic types.\n\nHere's an example of a simple template function that takes two arguments and returns the larger of the two:\n\n template <typename T>\n T max(T a, T b) {\n return (a > b) ? a : b;\n }\n \n\nTo use this function, you can either explicitly specify the type parameter:\n\n int result = max<int>(10, 20);\n \n\nOr, you can let the compiler deduce the type for you:\n\n int result = max(10, 20);\n \n\nTemplate Classes\n----------------\n\nSimilarly, you can create template classes using the `template` keyword. Here's an example of a simple template class that represents a pair of values:\n\n template <typename T1, typename T2>\n class Pair {\n public:\n T1 first;\n T2 second;\n \n Pair(T1 first, T2 second) : first(first), second(second) {}\n };\n \n\nTo use this class, you need to specify the type parameters when creating an object:\n\n Pair<int, std::string> pair(1, \"Hello\");\n \n\nTemplate Specialization\n-----------------------\n\nSometimes, you may need special behavior for a specific data type. In this case, you can use template specialization. For example, you can specialize the `Pair` class for a specific type, like `char`:\n\n template <>\n class Pair<char, char> {\n public:\n char first;\n char second;\n \n Pair(char first, char second) : first(first), second(second) {\n // Special behavior for characters (e.g., convert to uppercase)\n this->first = std::toupper(this->first);\n this->second = std::toupper(this->second);\n }\n };\n \n\nNow, when you create a `Pair` object with `char` template arguments, the specialized behavior will be used:\n\n Pair<char, char> charPair('a', 'b');\n \n\nIn summary, templates in C++ allow you to write generic functions and classes that can work with different data types, reducing code duplication and making your code more flexible and reusable.",
"links": []
},
"w4EIf58KP-Pq-yc0HlGxc": {
"title": "Variadic Templates",
"description": "Variadic templates are a feature in C++11 that allows you to define a template with a variable number of arguments. This is especially useful when you need to write a function or class that can accept different numbers and types of arguments.\n\nSyntax\n------\n\nThe syntax for variadic templates is very simple. To define a variadic template, use the `...` (ellipsis) notation:\n\n template <typename... Args>\n \n\nThis notation represents a parameter pack, which can contain zero or more arguments. You can use this parameter pack as a variable list of template parameters in your template definition.\n\nExamples\n--------\n\n### Summing Multiple Arguments Using Variadic Templates\n\n #include <iostream>\n \n // Base case for recursion\n template <typename T>\n T sum(T t) {\n return t;\n }\n \n // Variadic template\n template <typename T, typename... Args>\n T sum(T t, Args... args) {\n return t + sum(args...);\n }\n \n int main() {\n int result = sum(1, 2, 3, 4, 5); // expands to 1 + 2 + 3 + 4 + 5\n std::cout << \"The sum is: \" << result << '\\n';\n \n return 0;\n }\n \n\n### Tuple Class Using Variadic Templates\n\n template <typename... Types>\n class Tuple;\n \n // Base case: empty tuple\n template <>\n class Tuple<> {};\n \n // Recursive case: Tuple with one or more elements\n template <typename Head, typename... Tail>\n class Tuple<Head, Tail...> : public Tuple<Tail...> {\n public:\n Tuple(Head head, Tail... tail) : Tuple<Tail...>(tail...), head_(head) {}\n \n Head head() const { return head_; }\n \n private:\n Head head_;\n };\n \n int main() {\n Tuple<int, float, double> tuple(1, 2.0f, 3.0);\n std::cout << \"First element: \" << tuple.head() << '\\n';\n return 0;\n }\n \n\nPlease note that the examples shown are for educational purposes and might not be the most efficient or production-ready implementations. With C++17 and onward, there are even more concise ways to handle variadic templates, like using fold expressions.",
"links": []
},
"sObOuccY0PDeGG-9GrFDF": {
"title": "Template Specialization",
"description": "Template specialization is a way to customize or modify the behavior of a template for a specific type or a set of types. This can be useful when you want to optimize the behavior or provide specific implementation for a certain type, without affecting the overall behavior of the template for other types.\n\nThere are two main ways you can specialize a template:\n\n* **Full specialization:** This occurs when you provide a specific implementation for a specific type or set of types.\n \n* **Partial specialization:** This occurs when you provide a more general implementation for a subset of types that match a certain pattern or condition.\n \n\nFull Template Specialization\n----------------------------\n\nFull specialization is used when you want to create a separate implementation of a template for a specific type. To do this, you need to use keyword `template<>` followed by the function template with the desired specialized type.\n\nHere is an example:\n\n #include <iostream>\n \n template <typename T>\n void printData(const T& data) {\n std::cout << \"General template: \" << data << '\\n';\n }\n \n template <>\n void printData(const char* const & data) {\n std::cout << \"Specialized template for const char*: \" << data << '\\n';\n }\n \n int main() {\n int a = 5;\n const char* str = \"Hello, world!\";\n printData(a); // General template: 5\n printData(str); // Specialized template for const char*: Hello, world!\n }\n \n\nPartial Template Specialization\n-------------------------------\n\nPartial specialization is used when you want to create a separate implementation of a template for a subset of types that match a certain pattern or condition.\n\nHere is an example of how you can partially specialize a template class:\n\n #include <iostream>\n \n template <typename K, typename V>\n class MyPair {\n public:\n MyPair(K k, V v) : key(k), value(v) {}\n \n void print() const {\n std::cout << \"General template: key = \" << key << \", value = \" << value << '\\n';\n }\n \n private:\n K key;\n V value;\n };\n \n template <typename T>\n class MyPair<T, int> {\n public:\n MyPair(T k, int v) : key(k), value(v) {}\n \n void print() const {\n std::cout << \"Partial specialization for int values: key = \" << key\n << \", value = \" << value << '\\n';\n }\n \n private:\n T key;\n int value;\n };\n \n int main() {\n MyPair<double, std::string> p1(3.2, \"example\");\n MyPair<char, int> p2('A', 65);\n p1.print(); // General template: key = 3.2, value = example\n p2.print(); // Partial specialization for int values: key = A, value = 65\n }\n \n\nIn this example, the `MyPair` template class is partially specialized to provide a different behavior when the second template parameter is of type `int`.",
"links": []
},
"WptReUOwVth3C9-AVmMHF": {
"title": "Type Traits",
"description": "Type Traits are a set of template classes in C++ that help in getting the information about the type's properties, behavior, or characteristics. They can be found in the `<type_traits>` header file. By using Type Traits, you can adapt your code depending on the properties of a given type, or even enforce specific properties for your type parameters in template code.\n\nSome common type traits are:\n\n* `std::is_pointer`: Checks if a given type is a pointer type.\n* `std::is_arithmetic`: Checks if the given type is an arithmetic type.\n* `std::is_function`: Checks if the given type is a function type.\n* `std::decay`: Applies decltype rules to the input type ( strips references, cv-qualifiers, etc. ).\n\nUsage\n-----\n\nYou can use type traits like this:\n\n #include <iostream>\n #include <type_traits>\n \n int main() {\n int a;\n int* a_ptr = &a;\n \n std::cout << \"Is 'a' a pointer? \" << std::boolalpha << std::is_pointer<decltype(a)>::value << '\\n';\n std::cout << \"Is 'a_ptr' a pointer? \" << std::boolalpha << std::is_pointer<decltype(a_ptr)>::value << '\\n';\n \n return 0;\n }\n \n\nComposing Type Traits\n---------------------\n\nSome type traits help you compose other traits or modify them, such as:\n\n* `std::conditional`: If a given boolean value is true, use type A; otherwise, use type B.\n* `std::enable_if`: If a given boolean value is true, use type A; otherwise, there is no nested type.\n\n #include <iostream>\n #include <type_traits>\n \n template <typename T>\n typename std::enable_if<std::is_arithmetic<T>::value, T>::type find_max(T a, T b) {\n return a > b ? a : b;\n }\n \n int main() {\n int max = find_max(10, 20);\n std::cout << \"Max: \" << max << '\\n';\n \n return 0;\n }\n \n\nIn this example, the `find_max` template function is only defined when T is an arithmetic type (e.g., int, float, double). This prevents unintended usage of the `find_max` function with non-arithmetic types.\n\nOverall, type traits are a powerful tool to create more generic, extensible, and efficient C++ code, providing a way to query and adapt your code based on type characteristics.",
"links": []
},
"3C5UfejDX-1Z8ZF6C53xD": {
"title": "SFINAE",
"description": "SFINAE is a principle in C++ template metaprogramming that allows the compiler to select the appropriate function or class when a specific template specialization fails during substitution. The term \"substitution failure\" refers to the process where the compiler tries to substitute template arguments into a function template or class template. If the substitution causes an error, the compiler won't consider that specific specialization as a candidate and will continue searching for a valid one.\n\nThe key idea behind SFINAE is that if a substitution error occurs, it is silently ignored, and the compiler continues to explore other template specializations or overloads. This allows you to write more flexible and generic code, as it enables you to have multiple specializations for different scenarios.\n\nCode Example\n------------\n\nHere's an example that demonstrates SFINAE in action:\n\n #include <iostream>\n #include <type_traits>\n \n template <typename T, typename = void>\n struct foo_impl {\n void operator()(T t) {\n std::cout << \"Called when T is not arithmetic\\n\";\n }\n };\n \n template <typename T>\n struct foo_impl<T, std::enable_if_t<std::is_arithmetic<T>::value>> {\n void operator()(T t) {\n std::cout << \"Called when T is arithmetic\\n\";\n }\n };\n \n template <typename T>\n void foo(T t) {\n foo_impl<T>()(t);\n }\n \n int main() {\n int a = 5;\n foo(a); // output: Called when T is arithmetic\n \n std::string s = \"example\";\n foo(s); // output: Called when T is not arithmetic\n }\n \n\nIn this example, we define two `foo_impl` functions are specialized based on the boolean value of `std::is_arithmetic<T>`. The first one is enabled when `T` is an arithmetic type, while the second one is enabled when `T` is not an arithmetic type. The `foo` function then calls the appropriate `foo_impl` specialization based on the result of the type trait.\n\nWhen calling `foo(a)` with an integer, the first specialization is selected, and when calling `foo(s)` with a string, the second specialization is selected. If there is no valid specialization, the code would fail to compile.",
"links": []
},
"6hTcmJwNnQstbWWzNCfTe": {
"title": "Full Template Specialization",
"description": "Full template specialization allows you to provide a specific implementation, or behavior, for a template when used with a certain set of type parameters. It is useful when you want to handle special cases or optimize your code for specific types.\n\nSyntax\n------\n\nTo create a full specialization of a template, you need to define the specific type for which the specialization should happen. The syntax looks as follows:\n\n template <> //Indicates that this is a specialization\n className<specificType> //The specialized class for the specific type\n \n\nExample\n-------\n\nConsider the following example to demonstrate full template specialization:\n\n // Generic template\n template <typename T>\n class MyContainer {\n public:\n void print() {\n std::cout << \"Generic container.\\n\";\n }\n };\n \n // Full template specialization for int\n template <>\n class MyContainer<int> {\n public:\n void print() {\n std::cout << \"Container for integers.\\n\";\n }\n };\n \n int main() {\n MyContainer<double> d;\n MyContainer<int> i;\n \n d.print(); // Output: Generic container.\n i.print(); // Output: Container for integers.\n \n return 0;\n }\n \n\nIn this example, we defined a generic `MyContainer` template class along with a full specialization for `int` type. When we use the container with the `int` type, the specialized implementation's `print` method is called. For other types, the generic template implementation will be used.",
"links": []
},
"1NYJtbdcdOB4-vIrnq4yX": {
"title": "Partial Template Specialization",
"description": "Partial template specialization is a concept in C++ templates, which allows you to specialize a template for a subset of its possible type arguments. It is particularly useful when you want to provide a customized implementation for a particular group of types without having to define separate specializations for all types in that group.\n\nPartial template specialization is achieved by providing a specialization of a template with a new set of template parameters. This new template will be chosen when the compiler deduces the types that match the partial specialization.\n\nHere is a code example that demonstrates partial template specialization:\n\n // Primary template\n template <typename T>\n struct MyTemplate {\n static const char* name() {\n return \"General case\";\n }\n };\n \n // Partial specialization for pointers\n template <typename T>\n struct MyTemplate<T*> {\n static const char* name() {\n return \"Partial specialization for pointers\";\n }\n };\n \n // Full specialization for int\n template <>\n struct MyTemplate<int> {\n static const char* name() {\n return \"Full specialization for int\";\n }\n };\n \n int main() {\n MyTemplate<double> t1; // General case\n MyTemplate<double*> t2; // Partial specialization for pointers\n MyTemplate<int> t3; // Full specialization for int\n \n std::cout << t1.name() << '\\n';\n std::cout << t2.name() << '\\n';\n std::cout << t3.name() << '\\n';\n \n return 0;\n }\n \n\nIn the example above, we have defined a primary template `MyTemplate` with a single type parameter `T`. We then provide a partial template specialization for pointer types by specifying `MyTemplate<T*>`. This means that the partial specialization will be chosen when the type argument is a pointer type.\n\nLastly, we provide a full specialization for the `int` type by specifying `MyTemplate<int>`. This will be chosen when the type argument is `int`.\n\nWhen running this example, the output will be:\n\n General case\n Partial specialization for pointers\n Full specialization for int\n \n\nThis demonstrates that the partial specialization works as expected, and is chosen for pointer types, while the full specialization is chosen for the `int` type.",
"links": []
},
"fb3bnfKXjSIjPAk4b95lg": {
"title": "Idioms",
"description": "C++ idioms are well-established patterns or techniques that are commonly used in C++ programming to achieve a specific outcome. They help make code efficient, maintainable, and less error-prone. Here are some of the common C++ idioms:\n\n1\\. Resource Acquisition is Initialization (RAII)\n-------------------------------------------------\n\nThis idiom ensures that resources are always properly acquired and released by tying their lifetime to the lifetime of an object. When the object gets created, it acquires the resources and when it gets destroyed, it releases them.\n\n class Resource {\n public:\n Resource() { /* Acquire resource */ }\n ~Resource() { /* Release resource */ }\n };\n \n void function() {\n Resource r; // Resource is acquired\n // ...\n } // Resource is released when r goes out of scope\n \n\n2\\. Rule of Three\n-----------------\n\nIf a class defines any one of the following, it should define all three: copy constructor, copy assignment operator, and destructor.\n\n class MyClass {\n public:\n MyClass();\n MyClass(const MyClass& other); // Copy constructor\n MyClass& operator=(const MyClass& other); // Copy assignment operator\n ~MyClass(); // Destructor\n };\n \n\n3\\. Rule of Five\n----------------\n\nWith C++11, the rule of three was extended to five, covering move constructor and move assignment operator.\n\n class MyClass {\n public:\n MyClass();\n MyClass(const MyClass& other); // Copy constructor\n MyClass(MyClass&& other); // Move constructor\n MyClass& operator=(const MyClass& other); // Copy assignment operator\n MyClass& operator=(MyClass&& other); // Move assignment operator\n ~MyClass(); // Destructor\n };\n \n\n4\\. PImpl (Pointer to Implementation) Idiom\n-------------------------------------------\n\nThis idiom is used to separate the implementation details of a class from its interface, resulting in faster compile times and the ability to change implementation without affecting clients.\n\n // header file\n class MyClass {\n public:\n MyClass();\n ~MyClass();\n void someMethod();\n \n private:\n class Impl;\n Impl* pImpl;\n };\n \n // implementation file\n class MyClass::Impl {\n public:\n void someMethod() { /* Implementation */ }\n };\n \n MyClass::MyClass() : pImpl(new Impl()) {}\n MyClass::~MyClass() { delete pImpl; }\n void MyClass::someMethod() { pImpl->someMethod(); }\n \n\n5\\. Non-Virtual Interface (NVI)\n-------------------------------\n\nThis enforces a fixed public interface and allows subclasses to only override specific private or protected virtual methods.\n\n class Base {\n public:\n void publicMethod() {\n // Common behavior\n privateMethod(); // Calls overridden implementation\n }\n \n protected:\n virtual void privateMethod() = 0; // Pure virtual method\n };\n \n class Derived : public Base {\n protected:\n virtual void privateMethod() override {\n // Derived implementation\n }\n };\n \n\nThese are just a few examples of the many idioms in C++ programming. They can provide guidance when designing and implementing your code, but it's essential to understand the underlying concepts to adapt them to different situations.",
"links": []
},
"xjUaIp8gGxkN-cp8emJ2M": {
"title": "Non-Copyable / Non-Moveable",
"description": "The non-copyable idiom is a C++ design pattern that prevents objects from being copied or assigned. It's usually applied to classes that manage resources, like file handles or network sockets, where copying the object could cause issues like resource leaks or double deletions.\n\nTo make a class non-copyable, you need to delete the copy constructor and the copy assignment operator. This can be done explicitly in the class declaration, making it clear to other programmers that copying is not allowed.\n\nHere's an example of how to apply the non-copyable idiom to a class:\n\n class NonCopyable {\n public:\n NonCopyable() = default;\n ~NonCopyable() = default;\n \n // Delete the copy constructor\n NonCopyable(const NonCopyable&) = delete;\n \n // Delete the copy assignment operator\n NonCopyable& operator=(const NonCopyable&) = delete;\n };\n \n\nTo use the idiom, simply inherit from the `NonCopyable` class:\n\n class MyClass : private NonCopyable {\n // MyClass is now non-copyable\n };\n \n\nThis ensures that any attempt to copy or assign objects of `MyClass` will result in a compilation error, thus preventing unwanted behavior.",
"links": []
},
"YvmjrZSAOmjhVPo05MJqN": {
"title": "Erase-Remove",
"description": "The erase-remove idiom is a common C++ technique to efficiently remove elements from a container, particularly from standard sequence containers like `std::vector`, `std::list`, and `std::deque`. It leverages the standard library algorithms `std::remove` (or `std::remove_if`) and the member function `erase()`.\n\nThe idiom consists of two steps:\n\n* `std::remove` (or `std::remove_if`) moves the elements to be removed towards the end of the container and returns an iterator pointing to the first element to remove.\n* `container.erase()` removes the elements from the container using the iterator obtained in the previous step.\n\nHere's an example:\n\n #include <algorithm>\n #include <vector>\n #include <iostream>\n \n int main() {\n std::vector<int> numbers = {1, 3, 2, 4, 3, 5, 3};\n \n // Remove all occurrences of 3 from the vector.\n numbers.erase(std::remove(numbers.begin(), numbers.end(), 3), numbers.end());\n \n for (int number : numbers) {\n std::cout << number << \" \";\n }\n \n return 0;\n }\n \n\nOutput:\n\n 1 2 4 5\n \n\nIn this example, we used the `std::remove` algorithm to remove all occurrences of the number 3 from the `std::vector<int> numbers`. After the removal, the vector contains only 1, 2, 4, and 5, as the output shows.",
"links": []
},
"lxAzI42jQdaofzQ5MXebG": {
"title": "Copy and Swap",
"description": "Copy-swap is a C++ idiom that leverages the copy constructor and swap function to create an assignment operator. It follows a simple, yet powerful paradigm: create a temporary copy of the right-hand side object, and swap its contents with the left-hand side object.\n\nHere's a brief summary:\n\n* **Copy**: Create a local copy of the right-hand side object. This step leverages the copy constructor, providing exception safety and code reuse.\n* **Swap**: Swap the contents of the left-hand side object with the temporary copy. This step typically involves swapping internal pointers or resources, without needing to copy the full contents again.\n* **Destruction**: Destroy the temporary copy. This happens upon the exit of the assignment operator.\n\nHere's a code example for a simple `String` class:\n\n class String {\n // ... rest of the class ...\n \n String(const String& other);\n \n friend void swap(String& first, String& second) {\n using std::swap; // for arguments-dependent lookup (ADL)\n swap(first.size_, second.size_);\n swap(first.buffer_, second.buffer_);\n }\n \n String& operator=(String other) {\n swap(*this, other);\n return *this;\n }\n };\n \n\nUsing the copy-swap idiom:\n\n* The right-hand side object is copied when passed by value to the assignment operator.\n* The left-hand side object's contents are swapped with the temporary copy.\n* The temporary copy is destroyed, releasing any resources that were previously held by the left-hand side object.\n\nThis approach simplifies the implementation and provides strong exception safety, while reusing the copy constructor and destructor code.",
"links": []
},
"O2Du5gHHxFxAI2u5uO8wu": {
"title": "Copy on Write",
"description": "The Copy-Write idiom, sometimes called the Copy-on-Write (CoW) or \"lazy copying\" idiom, is a technique used in programming to minimize the overhead of copying large objects. It helps in reducing the number of actual copy operations by using shared references to objects and only copying the data when it's required for modification.\n\nLet's understand this with a simple example:\n\n #include <iostream>\n #include <memory>\n \n class MyString {\n public:\n MyString(const std::string &str) : data(std::make_shared<std::string>(str)) {}\n \n // Use the same shared data for copying.\n MyString(const MyString &other) : data(other.data) { \n std::cout << \"Copied using the Copy-Write idiom.\\n\";\n }\n \n // Make a copy only if we want to modify the data.\n void write(const std::string &str) {\n // Check if there's more than one reference.\n if (data.use_count() > 1) {\n data = std::make_shared<std::string>(*data);\n std::cout << \"Copy is actually made for writing.\\n\";\n }\n *data = str;\n }\n \n private:\n std::shared_ptr<std::string> data;\n };\n \n int main() {\n MyString str1(\"Hello\");\n MyString str2 = str1; // No copy operation, just shared references.\n \n str1.write(\"Hello, World!\"); // This is where the actual duplication happens.\n return 0;\n }\n \n\nIn this example, we have a class `MyString` that simulates the Copy-Write idiom. When a `MyString` object is created, it constructs a `shared_ptr` pointing to a string. When a `MyString` object is copied, it does not perform any actual copy operation, but simply increases the reference count of the shared object. Finally, when the `write` function is called, it checks if there's more than one reference to the data and if so, it actually creates a new copy and updates the reference. This way, unnecessary copies can be avoided until they are actually needed for modification.",
"links": []
},
"OmHDlLxCnH8RDdu5vx9fl": {
"title": "RAII",
"description": "RAII is a popular idiom in C++ that focuses on using the object's life cycle to manage resources. It encourages binding the resource lifetime to the scope of a corresponding object so that it's automatically acquired when an object is created and released when the object is destroyed. This helps in simplifying the code, avoiding leaks and managing resources efficiently.\n\nCode Examples\n-------------\n\nHere's an example of using RAII to manage resources, specifically a dynamically allocated array:\n\n class ManagedArray {\n public:\n ManagedArray(size_t size) : size_(size), data_(new int[size]) {\n }\n \n ~ManagedArray() {\n delete[] data_;\n }\n \n // Access function\n int& operator [](size_t i) {\n return data_[i];\n }\n \n private:\n size_t size_;\n int* data_;\n };\n \n\nUsages:\n\n {\n ManagedArray arr(10);\n arr[0] = 42;\n \n // No need to explicitly free memory, it will be automatically released when arr goes out of scope.\n }\n \n\nAnother common use case is managing a mutex lock:\n\n class Lock {\n public:\n Lock(std::mutex& mtx) : mutex_(mtx) {\n mutex_.lock();\n }\n \n ~Lock() {\n mutex_.unlock();\n }\n \n private:\n std::mutex& mutex_;\n };\n \n\nUsages:\n\n std::mutex some_mutex;\n \n void protected_function() {\n Lock lock(some_mutex);\n \n // Do some work that must be synchronized\n \n // No need to explicitly unlock the mutex, it will be automatically unlocked when lock goes out of scope.\n }\n \n\nIn both examples, the constructor acquires the resource (memory for the array and the lock for the mutex), and the destructor takes care of releasing them. This way, the resource management is tied to the object's lifetime, and the resource is correctly released even in case of an exception being thrown.",
"links": []
},
"MEoWt8NKjPLVTeGgYf3cR": {
"title": "Pimpl",
"description": "Pimpl (Pointer-to-Implementation) idiom, also known as a private class data, compiler firewall, or handle classes, is a technique used in C++ to hide the implementation details of a class by using a forward declaration to a private structure or class, keeping the public interface of the class clean, and reducing compile-time dependencies.\n\nImplementation\n--------------\n\nHere is a simple example illustrating the Pimpl idiom:\n\n**my\\_class.h**\n\n class MyClass_Impl; // forward declaration\n \n class MyClass\n {\n public:\n MyClass();\n ~MyClass();\n void some_method();\n \n private:\n MyClass_Impl *pimpl; // pointer to the implementation\n };\n \n\n**my\\_class.cpp**\n\n #include \"my_class.h\"\n #include <iostream>\n \n class MyClass_Impl // the actual implementation\n {\n public:\n void some_method()\n {\n std::cout << \"Implementation method called!\\n\";\n }\n };\n \n MyClass::MyClass() : pimpl(new MyClass_Impl()) {} // constructor\n \n MyClass::~MyClass() { delete pimpl; } // destructor\n \n void MyClass::some_method()\n {\n pimpl->some_method(); // delegation to the implementation\n }\n \n\nNow, all the public methods of `MyClass` will delegate the calls to the corresponding methods of `MyClass_Impl`. By doing this, you can hide the details of class implementation, reduce the compile-time dependencies, and ease the maintenance of your code.",
"links": []
},
"ttt-yeIi4BPWrgvW324W7": {
"title": "CRTP",
"description": "**Curiously Recurring Template Pattern (CRTP)**\n\nThe Curiously Recurring Template Pattern (CRTP) is a C++ idiom that involves a class template being derived from its own specialization. This pattern allows for the creation of static polymorphism, which differs from regular runtime polymorphism that relies on virtual functions and inheritance.\n\nCRTP is usually employed when you want to customize certain behavior in the base class without adding the overhead of a virtual function call. In short, CRTP can be used for achieving compile-time polymorphism without the runtime performance cost.\n\nHere's an example demonstrating CRTP:\n\n template <typename Derived>\n class Base {\n public:\n void interface() {\n static_cast<Derived*>(this)->implementation();\n }\n \n void implementation() {\n std::cout << \"Default implementation in Base\\n\";\n }\n };\n \n class Derived1 : public Base<Derived1> {\n public:\n void implementation() {\n std::cout << \"Custom implementation in Derived1\\n\";\n }\n };\n \n class Derived2 : public Base<Derived2> {\n // No custom implementation, so Base::implementation will be used.\n };\n \n int main() {\n Derived1 d1;\n d1.interface(); // Output: \"Custom implementation in Derived1\"\n \n Derived2 d2;\n d2.interface(); // Output: \"Default implementation in Base\"\n \n return 0;\n }\n \n\nIn this example, the `Base` class is a template that takes a single type parameter. `Derived1` and `Derived2` are derived from their respective specialization of `Base`. CRTP is employed to allow custom implementations of the `implementation()` function in derived classes while providing a default behavior in the `Base` class. The `interface()` function in the `Base` class is a template for the derived class's behavior and calls the corresponding `implementation()` function based on the static type.\n\nThis pattern enables you to override certain behavior in derived classes with additional functionality, all while avoiding the overhead of virtual function calls and, in turn, achieving a higher degree of efficiency at runtime.",
"links": []
},
"vvE1aUsWbF1OFcmMUHbJa": {
"title": "Standardds",
"description": "C++ standards are a set of rules and guidelines that define the language's features, syntax, and semantics. The International Organization for Standardization (ISO) is responsible for maintaining and updating the C++ standards. The main purpose of the standards is to ensure consistency, efficiency, and maintainability across multiple platforms and compilers.\n\nHere's a brief summary of the different C++ standards released to date:\n\n* **C++98/C++03**: The first standardized version of C++, which introduced many features like templates, exceptions, and the Standard Template Library (STL). C++03 is a minor update to C++98 with some bug fixes and performance improvements.\n \n* **C++11**: A major upgrade to the language, which introduced features such as:\n \n * Lambda expressions:\n \n auto sum = [](int a, int b) -> int { return a + b; };\n \n \n * Range-based for loops:\n \n std::vector<int> numbers = {1, 2, 3, 4};\n for (int num : numbers) {\n std::cout << num << '\\n';\n }\n \n \n * Smart pointers like `std::shared_ptr` and `std::unique_ptr`.\n* **C++14**: A minor update to C++11, which added features such as:\n \n * Generic lambda expressions:\n \n auto generic_sum = [](auto a, auto b) { return a + b; };\n \n \n * Binary literals:\n \n int binary_number = 0b1010;\n \n \n* **C++17**: Another major update that introduced features such as:\n \n * `if` and `switch` with initializers:\n \n if (auto it = my_map.find(key); it != my_map.end()) {\n // use 'it' here\n }\n \n \n * Structured bindings:\n \n std::map<std::string, int> my_map = {{\"A\", 1}, {\"B\", 2}};\n for (const auto& [key, value] : my_map) {\n // use 'key' and 'value' here\n }\n \n \n* **C++20**: The latest major update to the language, with features such as:\n \n * Concepts:\n \n template<typename T>\n concept Addable = requires(T a, T b) {\n { a + b } -> std::same_as<T>;\n };\n \n \n * Ranges:\n \n std::vector<int> numbers = {1, 2, 3, 4};\n auto doubled = numbers | std::views::transform([](int n) { return n * 2; });\n \n \n * Coroutines and more.\n\nRemember that to use these language features, you might need to configure your compiler to use the specific C++ standard version. For example, with GCC or Clang, you can use the `-std=c++11`, `-std=c++14`, `-std=c++17`, or `-std=c++20` flags.",
"links": []
},
"T6rCTv9Dxkm-tEA-l9XEv": {
"title": "C++ 11 / 14",
"description": "**C++11** The C++11 standard, also known as C++0x, was officially released in September 2011. It introduced several new language features and improvements, including:\n\n* **Auto**: Allows compiler to infer the variable type based on its initializing expression.\n \n auto integer = 42; // integer is of int type\n auto floating = 3.14; // floating is of double type\n \n \n* **Range-Based for Loop**: Provides foreach-like semantics for iterating through a container or array.\n \n std::vector<int> numbers {1, 2, 3, 4};\n for (int number : numbers) {\n std::cout << number << '\\n';\n }\n \n \n* **Lambda Functions**: Anonymous functions that allow the creation of function objects more easily.\n \n auto add = [](int a, int b) -> int { return a + b; };\n int sum = add(42, 13); // sum is equal to 55\n \n \n* **nullptr**: A new keyword to represent null pointers, more type-safe than using a literal '0' or \"NULL\".\n \n int *ptr = nullptr;\n \n \n* **Thread Support Library**: Provides a standard way to work with threads and synchronize data access across threads.\n \n std::thread t([]() { std::cout << \"Hello from another thread\\n\"; });\n t.join();\n \n \n\n**C++14** The C++14 standard was officially released in December 2014 as a small extension over C++11, focusing more on fine-tuning language features and fixing issues. Some of the new features introduced:\n\n* **Generic Lambdas**: Allows lambda function parameters to be declared with 'auto' type placeholders.\n \n auto add = [](auto a, auto b) { return a + b; };\n auto sum_i = add(42, 13); // Still works with integers\n auto sum_f = add(3.14, 2.72); // Now works with doubles too\n \n \n* **Binary Literals**: Allow you to input integers as binary literals for better readability.\n \n int b = 0b110101; // Decimal value is 53\n \n \n* **decltype(auto)**: Deduces the type of variable to match that of the expression it is initialized with.\n \n auto func = [](auto a, auto b) { return a * b; };\n decltype(auto) result = func(5, 3.14); // decltype(auto) deduces to \"double\"\n \n \n* **Variable Templates**: Allows you to define variables with template parameters.\n \n template <typename T>\n constexpr T pi = T(3.1415926535897932385);\n float r = pi<float>; // Instantiated as a float\n double d = pi<double>; // Instantiated as a double",
"links": []
},
"R2-qWGUxsTOeSHRuUzhd2": {
"title": "C++ 17",
"description": "C++17, also known as C++1z, is the version of the C++ programming language published in December 2017. It builds upon the previous standard, C++14, and adds various new features and enhancements to improve the language's expressiveness, performance, and usability.\n\nKey Features:\n-------------\n\n* If-init-statement: Introduces a new syntax for writing conditions with scope inside if and switch statements.\n\n if (auto it = map.find(key); it != map.end())\n {\n // Use it\n }\n \n\n* Structured Binding Declarations: Simplify the process of unpacking a tuple, pair, or other aggregate types.\n\n map<string, int> data;\n auto [iter, success] = data.emplace(\"example\", 42);\n \n\n* Inline variables: Enables `inline` keyword for variables and allows single definition of global and class static variables in header files.\n\n inline int globalVar = 0;\n \n\n* Folds expressions: Introduce fold expressions for variadic templates.\n\n template <typename... Ts>\n auto sum(Ts... ts)\n {\n return (ts + ...);\n }\n \n\n* constexpr if statement: Allows conditional compilation during compile time.\n\n template <typename T>\n auto get_value(T t)\n {\n if constexpr (std::is_pointer_v<T>)\n {\n return *t;\n }\n else\n {\n return t;\n }\n }\n \n\n* Improved lambda expression: Allows lambda to capture a single object without changing its type or constness.\n\n auto func = [x = std::move(obj)] { /* use x */ };\n \n\n* Standard file system library: `std::filesystem` as a standardized way to manipulate paths, directories, and files.\n \n* New Standard Library additions: `<string_view>` (non-owning string reference), `<any>` (type-safe discrimination union), `<optional>` (optional value wrapper), `<variant>` (type-safe sum type), and `<memory_resource>` (library for polymorphic allocators).\n \n* Parallel Algorithms: Adds support for parallel execution of Standard Library algorithms.\n \n\nThis is a brief summary of the key features of C++17; it includes more features and library updates. For a complete list, you can refer to the [full list of C++17 features and changes](https://en.cppreference.com/w/cpp/17).",
"links": []
},
"o3no4a5_iMFzEAGs56-BJ": {
"title": "C++ 20",
"description": "C++20 is the latest standard of the C++ programming language, which brings significant improvements and new features to the language. This version is aimed at facilitating better software development practices and enabling developers to write more efficient, readable, and maintainable code.\n\nHere are some of the key features introduced in C++20:\n\nConcepts\n--------\n\nConcepts are a way to enforce specific requirements on template parameters, allowing you to write more expressive and understandable code. They improve the error messages when using templates and ensure that the template parameters fulfill specific criteria.\n\n template <typename T>\n concept Addable = requires (T a, T b) {\n { a + b } -> std::same_as<T>;\n };\n \n template <Addable T>\n T add(T a, T b) {\n return a + b;\n }\n \n\nRanges\n------\n\nRanges provide a new way to work with sequences of values, enhancing the power and expressiveness of the Standard Library algorithms. The range-based algorithms make it easier and more convenient to work with sequences.\n\n #include <algorithm>\n #include <iostream>\n #include <ranges>\n #include <vector>\n \n int main() {\n std::vector<int> numbers = { 1, 2, 3, 4, 5 };\n \n auto even_numbers = numbers | std::views::filter([](int n) { return n % 2 == 0; });\n \n for (int n : even_numbers) {\n std::cout << n << ' ';\n }\n }\n \n\nCoroutines\n----------\n\nCoroutines are a new way to write asynchronous and concurrent code with improved readability. They allow functions to be suspended and resumed, enabling you to write more efficient, non-blocking code.\n\n #include <coroutine>\n #include <iostream>\n #include <future>\n \n std::future<int> async_value(int value) {\n co_await std::chrono::seconds(1);\n co_return value * 2;\n }\n \n int main() {\n auto result = async_value(42);\n std::cout << \"Result: \" << result.get() << '\\n';\n }\n \n\nThe `constexpr` and `consteval` Keywords\n----------------------------------------\n\nBoth `constexpr` and `consteval` are related to compile-time evaluation. Functions marked with `constexpr` can be executed at compile-time or runtime, while functions marked with `consteval` can only be executed at compile-time.\n\n constexpr int add(int a, int b) {\n return a + b;\n }\n \n consteval int square(int x) {\n return x * x;\n }\n \n int main() {\n constexpr int result1 = add(3, 4); // evaluated at compile-time\n int result2 = add(5, 6); // evaluated at runtime\n constexpr int result3 = square(7); // evaluated at compile-time\n }\n \n\nThese are just some of the highlights of the C++20 standard. It also includes many other features and improvements, like structured bindings, improved lambdas, and new standard library components. Overall, C++20 makes it easier for developers to write clean, efficient, and expressive code.",
"links": []
},
"sxbbKtg7kMNbkx7fXhjR9": {
"title": "Newest",
"description": "C++20 is the newest standard of the C++ programming language, which was officially published in December 2020. It introduces many new features, enhancements, and improvements over the previous standards. Here is a brief summary of some key features in C++20.\n\n* **Concepts**: Concepts provide a way to specify constraints on template parameters, ensuring that they meet a specific set of requirements. This allows for better compile-time error messages and code readability.\n \n Example:\n \n template<typename T>\n concept Printable = requires(T x) {\n {std::cout << x};\n };\n \n template<Printable T>\n void print(const T& x) {\n std::cout << x << '\\n';\n }\n \n \n* **Ranges**: Ranges build on the iterator concept and provide a more usable and composable framework for dealing with sequences of values. They simplify the way algorithms can be applied to collections of data.\n \n Example:\n \n #include <iostream>\n #include <vector>\n #include <ranges>\n \n int main() {\n std::vector<int> numbers{1, 2, 3, 4, 5};\n auto even_view = numbers | std::views::filter([](int n) { return n % 2 == 0; });\n \n for (int n : even_view) {\n std::cout << n << ' ';\n }\n }\n \n \n* **Coroutines**: Coroutines offer a way to split complex, long-running functions into smaller, more manageable chunks, allowing them to be suspended and resumed at specific points.\n \n Example:\n \n #include <iostream>\n #include <coroutine>\n \n std::generator<int> generator() {\n for (int i = 0; i < 5; ++i)\n co_yield i;\n }\n \n int main() {\n for (int value : generator())\n std::cout << value << ' ';\n }\n \n \n* **Lambdas with template parameters**: C++20 enables using `auto` as a lambda parameter, allowing for generic lambdas with templated parameters.\n \n Example:\n \n auto sum = [](auto a, auto b) {\n return a + b;\n };\n \n int res1 = sum(1, 2); // int\n double res2 = sum(1.0, 2.0); // double\n \n \n* **Constexpr enhancements**: `constexpr` support is extended with additional features, such as `constexpr` dynamic allocations, `constexpr` try-catch blocks, and `constexpr` lambdas.\n \n Example:\n \n struct Point {\n constexpr Point(int x, int y): x_{x}, y_{y} {}\n int x_, y_;\n };\n \n constexpr auto create_points() {\n Point points[3]{};\n \n for (int i = 0; i < 3; ++i) {\n points[i] = Point{i, i * i};\n }\n \n return points;\n }\n \n constexpr auto points = create_points();\n \n \n\nThere are many other features in C++20, such as new standard library improvements, `std::format`, improvements to compile-time programming, and more. These are just a few highlights that showcase the versatility and power of the newest standard of C++.",
"links": []
},
"PPg0V5EzGBeJsysg1215V": {
"title": "C++ 0x",
"description": "`cpp0x` refers to the working name for [C++11](https://en.cppreference.com/w/cpp/11), which was previously known as C++0x before its final release. C++11 is a major revision of the C++ language standard, published in 2011, and brought several new features and improvements to the language.\n\nSome of the notable features in C++11 include:\n\n* **Auto** keyword for automatic type inference.\n \n auto i = 42; // i is an int\n auto s = \"hello\"; // s is a const char*\n \n \n* **Range-based for loop** for easier iteration over containers.\n \n std::vector<int> vec = {1, 2, 3};\n for (int i : vec) {\n std::cout << i << '\\n';\n }\n \n \n* **Lambda functions** for creating anonymous functions.\n \n auto add = [](int a, int b) { return a + b; };\n int result = add(3, 4); // result is 7\n \n \n* **nullptr** for representing null pointer values, instead of using `NULL`.\n \n int* p = nullptr;\n \n \n* **Rvalue references and move semantics** to optimize the handling of temporary objects.\n \n std::string str1 = \"hello\";\n std::string str2 = std::move(str1); // move the content of str1 to str2\n \n \n* **Variadic templates** for creating templates that take a variable number of arguments.\n \n template <typename... Args>\n void printArgs(Args... args) {\n // function body\n }\n \n \n* **Static assertions** for compile-time assertions.\n \n static_assert(sizeof(int) == 4, \"This code requires int to be 4 bytes.\");\n \n \n* **Thread support** for multithreading programming.\n \n #include <thread>\n \n void my_function() {\n // thread function body\n }\n \n int main() {\n std::thread t(my_function);\n t.join();\n return 0;\n }\n \n \n\nThese are just a few examples of the many new features introduced in C++11. For a comprehensive list, you can refer to the [C++11 documentation](https://en.cppreference.com/w/cpp/11).",
"links": []
},
"qmHs6_BzND_xpMmls5YUH": {
"title": "Debuggers",
"description": "Debuggers are essential tools for any C++ programmer, as they help in detecting, diagnosing, and fixing bugs in the code. They serve as an invaluable resource in identifying and understanding potential errors in the program.\n\nTypes of Debuggers\n------------------\n\nThere are several debuggers available for use with C++:\n\n* **GDB (GNU Debugger):** This is the most widely used C++ debugger in the Linux environment. It can debug many languages, including C and C++.\n \n Example usage:\n \n g++ -g main.cpp -o main # compile the code with debug info\n gdb ./main # start gdb session\n b main # set a breakpoint at the start of the main function\n run # run the program\n next # step to the next line\n \n \n* **LLDB:** This is the debugger developed by LLVM. It supports multiple languages and is popular among macOS and iOS developers.\n \n Example usage:\n \n clang++ -g main.cpp -o main # compile the code with debug info\n lldb ./main # start lldb session\n breakpoint set --name main # set a breakpoint at the start of the main function\n run # run the program\n next # step to the next line\n \n \n* **Microsoft Visual Studio Debugger:** This debugger is built into Visual Studio and is typically used in a graphical interface on Windows systems.\n \n Example usage:\n \n Open your Visual Studio project and go to Debug > Start Debugging. Then use the step over (F10), step into (F11), or continue (F5) commands to navigate through the code.\n \n \n* **Intel Debugger (IDB):** This debugger is part of Intel's parallel development suite and is popular for high-performance applications.\n \n* **TotalView Debugger:** Developed by Rogue Wave Software, TotalView Debugger is a commercial debugger designed for parallel, high-performance, and enterprise applications.\n \n\nEach debugger has its advantages and unique features, so it's essential to choose the one that best suits your needs and works well with your development environment.",
"links": []
},
"VtPb8-AJKzhTB0QbMtoU4": {
"title": "Understanding Debugger Messages",
"description": "Debugger messages are notifications or alerts provided by a debugger to help you identify problems or errors in your C++ code. These messages can be warnings or error messages and can provide helpful information about the state of your program and specific issues encountered during the debugging process.\n\nTypes of Debugger Messages\n--------------------------\n\n* **Error Messages:** Notify you about issues in the code that prevent the program from running or compiling correctly. These messages typically include information about the file and the line number where the error is detected, followed by a description of the issue.\n \n Example:\n \n test.cpp: In function 'int main()':\n test.cpp:6:5: error: 'cout' was not declared in this scope\n cout << \"Hello World!\";\n ^~~~\n \n \n* **Warning Messages:** Inform you about potential issues or risky programming practices that may not necessarily cause errors but could lead to problems later on. Like error messages, warning messages usually include information about the file and line number where the issue is found, along with a description of the problem.\n \n Example:\n \n test.cpp: In function 'int main()':\n test.cpp:6:17: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]\n if (a < size)\n ^\n \n \n* **Informational Messages:** Provide general information about the execution of the program, such as breakpoints, watchpoints, and variable values. These messages can also reveal the current state of the program, including the call stack and the list of active threads.\n \n Example (_assuming you are using GDB as debugger_):\n \n (gdb) break main\n Breakpoint 1 at 0x40055f: file test.cpp, line 5.\n (gdb) run\n Starting program: /path/to/test\n Breakpoint 1, main () at test.cpp:5\n 5 int a = 5;\n \n \n\nCode Examples\n-------------\n\nTo make use of debugger messages, you need to employ a debugger, such as GDB or Visual Studio Debugger, and include specific flags during the compilation process.\n\nExample using GDB:\n\n // test.cpp\n \n #include <iostream>\n \n int main() {\n int num1 = 10;\n int num2 = 0;\n int result = num1 / num2;\n \n std::cout << \"Result: \" << result << '\\n';\n \n return 0;\n }\n \n\n $ g++ -g -o test test.cpp // Compile with -g flag to include debugging information\n $ gdb ./test // Run the GDB debugger\n (gdb) run // Execute the program inside GDB\n \n\nAt this point, the debugger will show an error message triggered by the division by zero:\n\n Program received signal SIGFPE, Arithmetic exception.\n 0x00005555555546fb in main () at test.cpp:7\n 7 int result = num1 / num2;\n \n\nNow you can make appropriate changes to fix the issue in your C++ code.",
"links": []
},
"sR_FxGZHoMCV9Iv7z2_SX": {
"title": "Debugging Symbols",
"description": "Debugger symbols are additional information embedded within the compiled program's binary code, that help debuggers in understanding the structure, source code, and variable representations at a particular point in the execution process.\n\nThere are generally two types of debugging symbols:\n\n* **Internal Debugging Symbols**: These symbols reside within the compiled binary code itself. When using internal debugging symbols, it is essential to note that the size of the binary increases, which may not be desirable for production environments.\n \n* **External Debugging Symbols**: The debugging symbols are kept in separate files apart from the binary code, usually with file extensions such as `.pdb` (Program Database) in Windows or `.dSYM` (DWARF Symbol Information) in macOS.\n \n\nGenerating Debugger Symbols\n---------------------------\n\nTo generate debugger symbols in C++, you need to specify specific options during the compilation process. We will use `g++` compiler as an example.\n\n**Internal Debugging Symbols (g++)**\n\nTo create a debug build with internal debugging symbols, use the `-g` flag:\n\n g++ -g -o my_program my_program.cpp\n \n\nThis command compiles `my_program.cpp` into an executable named `my_program` with internal debugging symbols.\n\n**External Debugging Symbols (g++)**\n\nIn case you want to generate a separate file containing debugging symbols, you can use the `-gsplit-dwarf` flag:\n\n g++ -g -gsplit-dwarf -o my_program my_program.cpp\n \n\nThis command compiles `my_program.cpp` into an executable named `my_program` and generates a separate file named `my_program.dwo` containing the debugging symbols.\n\nWhen sharing your compiled binary to end-users, you can remove the debugging symbols using the `strip` command:\n\n strip --strip-debug my_program\n \n\nThis command removes internal debug symbols, resulting in a smaller binary size while keeping the `.dwo` file for debugging purposes when needed.\n\nRemember that the availability and syntax of these options may vary between different compilers and platforms. Be sure to consult your compiler's documentation to ensure proper usage of the debugging options.",
"links": []
},
"y8VCbGDUco9bzGRfIBD8R": {
"title": "WinDBg",
"description": "WinDbg is a powerful debugger for Windows applications, which is included in the Microsoft Windows SDK. It provides an extensive set of features to help you analyze and debug complex programs, kernel mode, and user-mode code. With a user-friendly graphical interface, WinDbg can help in analyzing crash dumps, setting breakpoints, and stepping through code execution.\n\nGetting Started\n---------------\n\nTo begin using WinDbg, you first need to install it. You can download the [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk/) and install it to get the WinDbg.\n\nLoading Symbols\n---------------\n\nWinDbg relies on symbol files (\\*.pdb) to provide more useful information about a program's internal structures, functions, and variables. To load symbols properly, you may need to configure the symbol path:\n\n !sym noisy\n .sympath SRV*C:\\symbols*http://msdl.microsoft.com/download/symbols\n .reload /f\n \n\nOpening Executables and Crash Dumps\n-----------------------------------\n\nTo debug an executable using WinDbg, go to `File > Open Executable...`, then locate and open the target program. To analyze a crash dump, use `File > Open Crash Dump...` instead.\n\nBasic Commands\n--------------\n\nSome common commands you might use in WinDbg:\n\n* `g`: Execute the program until the next breakpoint or exception\n* `bp <address>`: Set a breakpoint at a given address\n* `bl`: List all breakpoints\n* `bd <breakpoint_id>`: Disable a breakpoint\n* `be <breakpoint_id>`: Enable a breakpoint\n* `bc <breakpoint_id>`: Clear a breakpoint\n* `t`: Single-step through instructions (trace)\n* `p`: Step over instructions (proceed)\n* `k`: Display call stack\n* `dd`: Display memory contents in 4-byte units (double words)\n* `da`: Display memory contents as ASCII strings\n* `!analyze -v`: Analyze the program state and provide detailed information\n\nExample Usage\n-------------\n\nDebugging a simple program:\n\n* Open the executable in WinDbg\n* Set a breakpoint using `bp <address>`\n* Run the program using `g`\n* Once the breakpoint is hit, use `t` or `p` to step through the code\n* Try `k` to view the call stack, or `dd`, `da` to inspect memory\n* Remove the breakpoint and continue debugging with other commands as needed\n\nRemember that WinDbg has a wealth of commands and functionality, so it's essential to get comfortable with the [documentation](https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-download-tools) and explore the wealth of available resources specific to your debugging tasks.",
"links": []
},
"BmWsoL9c_Aag5nVlMsKm2": {
"title": "GDB",
"description": "GDB, or the GNU Project Debugger, is a powerful command-line debugger used primarily for C, C++, and other languages. It can help you find runtime errors, examine the program's execution state, and manipulate the flow to detect and fix bugs easily.\n\nGetting started with GDB\n------------------------\n\nTo start using GDB, you first need to compile your code with the `-g` flag, which includes debugging information in the executable:\n\n g++ -g myfile.cpp -o myfile\n \n\nNow, you can load your compiled program into GDB:\n\n gdb myfile\n \n\nBasic GDB Commands\n------------------\n\nHere are some common GDB commands you'll find useful when debugging:\n\n* `run`: Start your program.\n* `break [function/line number]`: Set a breakpoint at the specified function or line.\n* `continue`: Continue the program execution after stopping on a breakpoint.\n* `next`: Execute the next line of code, stepping over function calls.\n* `step`: Execute the next line of code, entering function calls.\n* `print [expression]`: Evaluate an expression in the current context and display its value.\n* `backtrace`: Show the current call stack.\n* `frame [frame-number]`: Switch to a different stack frame.\n* `quit`: Exit GDB.\n\nExample Usage\n-------------\n\nSuppose you have a simple `cpp` file called `example.cpp`:\n\n #include <iostream>\n \n void my_function(int i) {\n std::cout << \"In my_function with i = \" << i << '\\n';\n }\n \n int main() {\n for (int i = 0; i < 5; ++i) {\n my_function(i);\n }\n return 0;\n }\n \n\nFirst, compile the code with debugging symbols:\n\n g++ -g example.cpp -o example\n \n\nStart GDB and load the `example` program:\n\n gdb example\n \n\nSet a breakpoint in the `my_function` function and run the program:\n\n (gdb) break my_function\n (gdb) run\n \n\nOnce stopped at the breakpoint, use `next`, `print`, and `continue` to examine the program's state:\n\n (gdb) next\n (gdb) print i\n (gdb) continue\n \n\nFinally, exit GDB with the `quit` command.\n\nThis was just a brief summary of GDB; you can find more details in the [official GDB manual](https://sourceware.org/gdb/current/onlinedocs/gdb/).",
"links": []
},
"FTMHsUiE8isD_OVZr62Xc": {
"title": "Compilers",
"description": "A compiler is a computer program that translates source code written in one programming language into a different language, usually machine code or assembly code, that can be executed directly by a computer's processor. In the context of C++, compilers take your written C++ source code and convert it into an executable program.\n\nPopular C++ Compilers\n---------------------\n\nThere are several popular C++ compilers available, here's a short list of some common ones:\n\n* **GNU Compiler Collection (GCC)**: Developed by the GNU Project, GCC is an open-source compiler that supports multiple programming languages, including C++.\n \n* **Clang**: As part of the LLVM project, Clang is another open-source compiler that supports C++ and is known for its fast compilation times and extensive diagnostics.\n \n* **Microsoft Visual C++ (MSVC)**: MSVC is a commercial compiler provided by Microsoft as part of Visual Studio, and it's widely used on Windows platforms.\n \n* **Intel C++ Compiler (ICC)**: ICC is a commercial compiler provided by Intel and is known for its ability to optimize code for the latest Intel processors.\n \n\nExample of a Simple C++ Compilation\n-----------------------------------\n\nLet's say you have a simple C++ program saved in a file called `hello.cpp`:\n\n #include <iostream>\n \n int main() {\n std::cout << \"Hello, World!\\n\";\n return 0;\n }\n \n\nYou can compile this program using the GCC compiler by executing the following command in a command-line/terminal:\n\n g++ hello.cpp -o hello\n \n\nThis will generate an executable file called `hello` (or `hello.exe` on Windows) which you can run to see the output \"Hello, World!\".\n\nNote\n----\n\nWhen learning about compilers, it's essential to know that they work closely with the linker and the standard library. The linker takes care of combining compiled object files and libraries into a single executable, while the standard library provides implementations for common functionalities used in your code.",
"links": []
},
"DVckzBUMgk_lWThVkLyAT": {
"title": "Compiler Stages",
"description": "The process of compilation in C++ can be divided into four primary stages: Preprocessing, Compilation, Assembly, and Linking. Each stage performs a specific task, ultimately converting the source code into an executable program.\n\nPreprocessing\n-------------\n\nThe first stage is the preprocessing of the source code. Preprocessors modify the source code before the actual compilation process. They handle directives that start with a `#` (hash) symbol, like `#include`, `#define`, and `#if`. In this stage, included header files are expanded, macros are replaced, and conditional compilation statements are processed.\n\n**Code Example:**\n\n #include <iostream>\n #define PI 3.14\n \n int main() {\n std::cout << \"The value of PI is: \" << PI << '\\n';\n return 0;\n }\n \n\nCompilation\n-----------\n\nThe second stage is the actual compilation of the preprocessed source code. The compiler translates the modified source code into an intermediate representation, usually specific to the target processor architecture. This step also involves performing syntax checking, semantic analysis, and producing error messages for any issues encountered in the source code.\n\n**Code Example:**\n\n int main() {\n int a = 10;\n int b = 20;\n int sum = a + b;\n return 0;\n }\n \n\nAssembly\n--------\n\nThe third stage is converting the compiler's intermediate representation into assembly language. This stage generates assembly code using mnemonics and syntax that is specific to the target processor architecture. Assemblers then convert this assembly code into object code (machine code).\n\n**Code Example (x86 Assembly):**\n\n mov eax, 10\n mov ebx, 20\n add eax, ebx\n \n\nLinking\n-------\n\nThe final stage is the linking of the object code with the necessary libraries and other object files. In this stage, the linker merges multiple object files and libraries, resolves external references from other modules or libraries, allocates memory addresses for functions and variables, and generates an executable file that can be run on the target platform.\n\n**Code Example (linking objects and libraries):**\n\n $ g++ main.o -o main -lm\n \n\nIn summary, the compilation process in C++ involves four primary stages: preprocessing, compilation, assembly, and linking. Each stage plays a crucial role in transforming the source code into an executable program.",
"links": []
},
"hSG6Aux39X0cXi6ADy2al": {
"title": "Compilers and Features",
"description": "Different C++ compilers have different features. Some of the most common features of C++ compilers are:\n\n* **Optimization:** Compilers can optimize the code to improve the performance of the program. For example, they can remove redundant code, inline functions, and perform loop unrolling.\n* **Debugging:** Compilers can generate debugging information that can be used to debug the program.\n* **Warnings:** Compilers can generate warnings for suspicious code that may cause errors.\n\nSome of the most popular C++ compilers are:\n\n* **GNU Compiler Collection (GCC):** GCC is a free and open-source compiler that supports many programming languages, including C++.\n* **Clang:** Clang is a C++ compiler that is part of the LLVM project. It is designed to be compatible with GCC.\n* **Microsoft Visual C++:** Microsoft Visual C++ is a C++ compiler that is part of the Microsoft Visual Studio IDE.\n* **Intel C++ Compiler:** Intel C++ Compiler is a C++ compiler that is part of the Intel Parallel Studio XE suite.\n\nYou should go through the documentation of your compiler to learn more about its features.",
"links": []
},
"jVXFCo6puMxJ_ifn_uwim": {
"title": "Build Systems",
"description": "A build system is a collection of tools and utilities that automate the process of compiling, linking, and executing source code files in a project. The primary goal of build systems is to manage the complexity of the compilation process and produce a build (executable or binary files) in the end. In C++ (cpp), some common build systems are:\n\n* **GNU Make**: It is a popular build system that uses `Makefile` to define the build process. It checks the dependencies and timestamps of source files to determine which files need to be compiled and linked.\n \n Code example:\n \n # Makefile\n CXX = g++\n CPPFLAGS = -Wall -std=c++11\n TARGET = HelloWorld\n \n all: $(TARGET)\n \n $(TARGET): main.cpp\n $(CXX) $(CPPFLAGS)main.cpp -o $(TARGET)\n \n clean:\n rm $(TARGET)\n \n \n* **CMake**: It is a cross-platform build system that focuses on defining project dependencies and managing build environments. CMake generates build files (like Makefiles) for different platforms and allows developers to write source code once and then compile it for different target platforms.\n \n Code example:\n \n # CMakeLists.txt\n cmake_minimum_required(VERSION 3.10)\n project(HelloWorld)\n \n set(CMAKE_CXX_STANDARD 11)\n \n add_executable(HelloWorld main.cpp)\n \n \n* **Autotools**: Also known as GNU Build System, consists of the GNU Autoconf, Automake, and Libtool tools that enable developers to create portable software across different Unix-based systems. For a C++ project, you will need to create `configure.ac`, `Makefile.am` files with specific rules, and then run the following commands in the terminal to build the project:\n \n autoreconf --install\n ./configure\n make\n make install\n \n \n* **SCons**: This build system uses Python for build scripts, making it more expressive than GNU Make. It can also build for multiple platforms and configurations simultaneously.\n \n Code example:\n \n # SConstruct\n env = Environment()\n env.Program(target=\"HelloWorld\", source=[\"main.cpp\"])\n \n \n* **Ninja**: A small and focused build system that takes a list of build targets specified in a human-readable text file and builds them as fast as possible.\n \n Code example:\n \n # build.ninja\n rule cc\n command = g++ -c $in -o $out\n \n rule link\n command = g++ $in -o $out\n \n build main.o: cc main.cpp\n build HelloWorld: link main.o\n default HelloWorld\n \n \n\nThese are some of the popular build systems in C++, each with their own syntax and capabilities. While Make is widely used, CMake is a cross-platform build system that generates build files for other build systems like Make or Ninja. Autotools is suitable for creating portable software, SCons leverages Python for its build scripts, and Ninja focuses on fast build times.",
"links": []
},
"ysnXvSHGBMMozBJyXpHl5": {
"title": "CMAKE",
"description": "CMake is a powerful cross-platform build system that generates build files, Makefiles, or workspaces for various platforms and compilers. Unlike the others build systems, CMake does not actually build the project, it only generates the files needed by build tools. CMake is widely used, particularly in C++ projects, for its ease of use and flexibility.\n\nCMakeLists.txt\n--------------\n\nCMake uses a file called `CMakeLists.txt` to define settings, source files, libraries, and other configurations. A typical `CMakeLists.txt` for a simple project would look like:\n\n cmake_minimum_required(VERSION 3.0)\n \n project(MyProject)\n \n set(SRC_DIR \"${CMAKE_CURRENT_LIST_DIR}/src\")\n set(SOURCES \"${SRC_DIR}/main.cpp\" \"${SRC_DIR}/file1.cpp\" \"${SRC_DIR}/file2.cpp\")\n \n add_executable(${PROJECT_NAME} ${SOURCES})\n \n target_include_directories(${PROJECT_NAME} PRIVATE \"${CMAKE_CURRENT_LIST_DIR}/include\")\n \n set_target_properties(${PROJECT_NAME} PROPERTIES\n CXX_STANDARD 14\n CXX_STANDARD_REQUIRED ON\n CXX_EXTENSIONS OFF\n )\n \n\nBuilding with CMake\n-------------------\n\nHere is an example of a simple build process using CMake:\n\n* Create a new directory for the build.\n\n mkdir build\n cd build\n \n\n* Generate build files using CMake.\n\n cmake ..\n \n\nIn this example, `..` indicates the parent directory where `CMakeLists.txt` is located. The build files will be generated in the `build` directory.\n\n* Build the project using the generated build files.\n\n make\n \n\nOr, on Windows with Visual Studio, you may use:\n\n msbuild MyProject.sln\n \n\nCMake makes it easy to manage large projects, define custom build configurations, and work with many different compilers and operating systems. Making it a widely chosen tool for managing build systems in C++ projects.",
"links": []
},
"t6rZLH7l8JQm99ax_fEJ9": {
"title": "Makefile",
"description": "A Makefile is a configuration file used by the `make` utility to automate the process of compiling and linking code in a C++ project. It consists of a set of rules and dependencies that help in building the target executable or library from source code files.\n\nMakefiles help developers save time, reduce errors, and ensure consistency in the build process. They achieve this by specifying the dependencies between different source files, and providing commands that generate output files (such as object files and executables) from input files (such as source code and headers).\n\nStructure of a Makefile\n-----------------------\n\nA typical Makefile has the following structure:\n\n* **Variables**: Define variables to store commonly used values, such as compiler flags, directories, or target names.\n* **Rules**: Define how to generate output files from input files using a set of commands. Each rule has a _target_, a set of _prerequisites_, and a _recipe_.\n* **Phony targets**: Targets that do not represent actual files in the project but serve as a way to group related rules and invoke them using a single command.\n\nExample\n-------\n\nConsider a basic C++ project with the following directory structure:\n\n project/\n |-- include/\n | |-- header.h\n |-- src/\n | |-- main.cpp\n |-- Makefile\n \n\nA simple Makefile for this project could be as follows:\n\n # Variables\n CXX = g++\n CXXFLAGS = -Wall -Iinclude\n SRC = src/main.cpp\n OBJ = main.o\n EXE = my_program\n \n # Rules\n $(EXE): $(OBJ)\n \t$(CXX) $(CXXFLAGS) -o $(EXE) $(OBJ)\n \n $(OBJ): $(SRC)\n \t$(CXX) $(CXXFLAGS) -c $(SRC)\n \n # Phony targets\n .PHONY: clean\n clean:\n \trm -f $(OBJ) $(EXE)\n \n\nWith this Makefile, you can simply run `make` in the terminal to build the project, and `make clean` to remove the output files. The Makefile specifies the dependencies between the source code, object files, and the final executable, as well as the commands to compile and link them.\n\nSummary\n-------\n\nMakefiles provide a powerful way to automate building C++ projects using the `make` utility. They describe the dependencies and commands required to generate output files from source code, saving time and ensuring consistency in the build process.",
"links": []
},
"HkUCD5A_M9bJxJRElkK0x": {
"title": "Ninja",
"description": "Ninja is a small build system with a focus on speed. It is designed to handle large projects by generating build files that implement the minimal amount of work necessary to build the code. This results in faster build times, especially for large codebases. Ninja is often used in conjunction with other build systems like CMake, which can generate Ninja build files for you.\n\nNinja build files are typically named `build.ninja` and contain rules, build statements, and variable declarations. Here's a simple example of a Ninja build file for a C++ project:\n\n # Variable declarations\n cxx = g++\n cflags = -Wall -Wextra -std=c++17\n \n # Rule for compiling the C++ files\n rule cxx_compile\n command = $cxx $cflags -c $in -o $out\n \n # Build statements for the source files\n build main.o: cxx_compile main.cpp\n build foo.o: cxx_compile foo.cpp\n \n # Rule for linking the object files\n rule link\n command = $cxx $in -o $out\n \n # Build statement for the final executable\n build my_program: link main.o foo.o\n \n\nTo build the project using this `build.ninja` file, simply run `ninja` in the terminal:\n\n $ ninja\n \n\nThis will build the `my_program` executable by first compiling the `main.cpp` and `foo.cpp` files into object files, and then linking them together.",
"links": []
},
"h29eJG1hWHa7vMhSqtfV2": {
"title": "Package Managers",
"description": "Package managers are tools that automate the process of installing, upgrading, and managing software (libraries, frameworks, and other dependencies) for a programming language, such as C++.\n\nSome popular package managers used in the C++ ecosystem include:\n\n* **Conan**\n* **vcpkg**\n* **C++ Archive Network (cppan)**\n\nConan\n-----\n\n[Conan](https://conan.io/) is an open-source, decentralized, cross-platform package manager for C and C++ developers. It simplifies managing dependencies and reusing code, which benefits multi-platform development projects.\n\nFor example, installing a library using Conan:\n\n conan install poco/1.9.4@\n \n\nvcpkg\n-----\n\n[vcpkg](https://github.com/microsoft/vcpkg) is a cross-platform package manager created by Microsoft. It is an open-source library management system for C++ developers to build and manage their projects.\n\nFor example, installing a package using vcpkg:\n\n ./vcpkg install boost:x64-windows\n \n\nC++ Archive Network (cppan)\n---------------------------\n\n[cppan](https://cppan.org/) is a package manager and software repository for C++ developers, simplifying the process of managing and distributing C++ libraries and tools. It's now part of [build2](https://build2.org/), a build toolchain that provides a package manager.\n\nAn example of a `cppan.yml` file:\n\n #\n # cppan.yml\n #\n \n project:\n api_version: 1\n \n depend:\n - pvt.cppan.demo.sqlite3\n - pvt.cppan.demo.xz_utils.lzma\n \n\nWith these package managers, you can streamline your development process and easily manage dependencies in your C++ projects. In addition, you can easily reuse the code in your projects to improve code quality and accelerate development.",
"links": []
},
"PKG5pACLfRS2ogfzBX47_": {
"title": "vcpkg",
"description": "`vcpkg` is a cross-platform, open-source package manager for C and C++ libraries. Developed by Microsoft, it simplifies the process of acquiring and building open-source libraries for your projects. `vcpkg` supports various platforms including Windows, Linux, and macOS, enabling you to easily manage and integrate external libraries into your projects.\n\nInstallation\n------------\n\nTo install `vcpkg`, follow these steps:\n\n* Clone the repository:\n \n git clone https://github.com/Microsoft/vcpkg.git\n \n \n* Change to the `vcpkg` directory and run the bootstrap script:\n \n * On Windows:\n \n .\\bootstrap-vcpkg.bat\n \n \n * On Linux/macOS:\n \n ./bootstrap-vcpkg.sh\n \n \n* (Optional) Add the `vcpkg` executable to your `PATH` environment variable for easy access.\n \n\nBasic usage\n-----------\n\nHere are some basic examples of using `vcpkg`:\n\n* Search for a package:\n \n vcpkg search <package_name>\n \n \n* Install a package:\n \n vcpkg install <package_name>\n \n \n* Remove a package:\n \n vcpkg remove <package_name>\n \n \n* List installed packages:\n \n vcpkg list\n \n \n* Integrate `vcpkg` with Visual Studio (Windows only):\n \n vcpkg integrate install\n \n \n\nFor additional documentation and advanced usage, you can refer to the [official GitHub repository](https://github.com/microsoft/vcpkg).",
"links": []
},
"g0s0F4mLV16eNvMBflN2e": {
"title": "NuGet",
"description": "[NuGet](https://www.nuget.org/) is a Microsoft-supported package manager for the .NET framework, mainly used in C# and other .NET languages, but also supports C++ projects with `PackageReference`. It allows you to easily add, update, and manage dependencies in your projects.\n\n### Installation\n\nYou can use NuGet either as a command-line tool or integrated in your preferred IDE like Visual Studio or Visual Studio Code. If you're using Visual Studio, it comes pre-installed. For other editors, you may need to download the command-line tool `nuget.exe`.\n\n### Usage\n\nYou can use NuGet to manage your C++ dependencies using the PackageReference format in vcxproj files:\n\n* Tools > NuGet Package Manager > Manage NuGet Packages for Solution…\n* Package source should be set to \"[nuget.org](http://nuget.org)\"\n* Select the Projects tab\n* Use the search box to find packages\n\nFor example, to install a package called \"PackageName\" for all configurations:\n\n <Project>\n <ItemGroup>\n <PackageReference Include=\"PackageName\" Version=\"1.0.0\" />\n </ItemGroup>\n ...\n </Project>\n \n\n### NuGet Command-Line\n\nYou can also use the command-line tool `nuget.exe` for more advanced scenarios or for specific needs.\n\nHere's an example of installing a package using the command line:\n\n nuget install PackageName\n \n\nAnd updating a package:\n\n nuget update PackageName\n \n\nFor more information and detailed examples on using NuGet in your projects, please refer to the [official documentation](https://docs.microsoft.com/en-us/nuget/guides/native-packages).",
"links": []
},
"ky_UqizToTZHC_b77qFi2": {
"title": "Conan",
"description": "[Conan](https://conan.io/) is a popular package manager for C and C++ languages and is designed to be cross-platform, extensible, and easy to use. It allows developers to declare, manage, and fetch dependencies while automating the build process. Conan supports various build systems, such as CMake, Visual Studio, MSBuild, and more.\n\nInstallation\n------------\n\nTo install Conan, you can use pip, the Python package manager:\n\n pip install conan\n \n\nBasic Usage\n-----------\n\n* Create a `conanfile.txt` file in your project root directory, specifying dependencies you need for your project:\n\n [requires]\n boost/1.75.0\n \n [generators]\n cmake\n \n\n* Run the `conan install` command to fetch and build required dependencies:\n\n mkdir build && cd build\n conan install ..\n \n\n* Now build your project using your build system, for example CMake:\n\n cmake .. -DCMAKE_BUILD_TYPE=Release\n cmake --build .\n \n\nCreating Packages\n-----------------\n\nTo create a package in Conan, you need to write a `conanfile.py` file with package information and build instructions.\n\nHere's an example:\n\n from conans import ConanFile, CMake\n \n \n class MyLibraryConan(ConanFile):\n name = \"MyLibrary\"\n version = \"0.1\"\n license = \"MIT\"\n url = \"https://github.com/username/mylibrary\"\n description = \"A simple example library\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n generators = \"cmake\"\n \n def build(self):\n cmake = CMake(self)\n cmake.configure(source_folder=\"src\")\n cmake.build()\n \n def package(self):\n self.copy(\"*.hpp\", dst=\"include\", src=\"src/include\")\n self.copy(\"*.lib\", dst=\"lib\", keep_path=False)\n self.copy(\"*.dll\", dst=\"bin\", keep_path=False)\n self.copy(\"*.so\", dst=\"lib\", keep_path=False)\n self.copy(\"*.a\", dst=\"lib\", keep_path=False)\n \n def package_info(self):\n self.cpp_info.libs = [\"MyLibrary\"]\n \n\nWith that setup, you can create a package by running:\n\n conan create . username/channel\n \n\nThis will compile the package and store it in your Conan cache. You can now use this package as a dependency in other projects.",
"links": []
},
"3ehBc2sKVlPj7dn4RVZCH": {
"title": "Spack",
"description": "[Spack](https://spack.io/) is a flexible package manager designed to support multiple versions, configurations, platforms, and compilers. It is particularly useful in High Performance Computing (HPC) environments and for those who require fine control over their software stack. Spack is a popular choice in scientific computing due to its support for various platforms such as Linux, macOS, and many supercomputers. It is designed to automatically search for and install dependencies, making it easy to build complex software.\n\nKey Features\n------------\n\n* **Multi-Version Support**: Spack allows for the installation of multiple versions of packages, enabling users to work with different configurations depending on their needs.\n* **Compiler Support**: Spack supports multiple compilers, including GCC, Clang, Intel, PGI, and others, allowing users to choose the best toolchain for their application.\n* **Platform Support**: Spack can run on Linux, macOS, and various supercomputers, and it can even target multiple architectures within a single package.\n* **Dependencies**: Spack takes care of dependencies, providing automatic installation and management of required packages.\n\nBasic Usage\n-----------\n\n* To install Spack, clone its Git repository and set up your environment:\n \n git clone https://github.com/spack/spack.git\n cd spack\n . share/spack/setup-env.sh\n \n \n* Install a package using Spack:\n \n spack install <package-name>\n \n \n For example, to install `hdf5`:\n \n spack install hdf5\n \n \n* Load a package in your environment:\n \n spack load <package-name>\n \n \n For example, to load `hdf5`:\n \n spack load hdf5\n \n \n* List installed packages:\n \n spack find\n \n \n* Uninstall a package:\n \n spack uninstall <package-name>\n \n \n\nFor more advanced usage, like installing specific versions or using different compilers, consult the [Spack documentation](https://spack.readthedocs.io/).",
"links": []
},
"4kkX5g_-plX9zVqr0ZoiR": {
"title": "Working with Libraries",
"description": "When working with C++, you may need to use external libraries to assist in various tasks. Libraries are precompiled pieces of code that can be reused in your program to perform a specific task or provide a certain functionality. In C++, libraries can be either static libraries (.lib) or dynamic libraries (.dll in Windows, .so in Unix/Linux).\n\n**1\\. Static Libraries**\n\nStatic libraries are incorporated into your program during compile time. They are linked with your code, creating a larger executable file, but it does not require any external files during runtime.\n\nTo create a static library, you'll need to compile your source files into object files, then bundle them into an archive. You can use the following commands:\n\n g++ -c sourcefile.cpp -o objectfile.o\n ar rcs libmystaticlibrary.a objectfile.o\n \n\nTo use a static library, you need to include the header files in your source code and then link the library during the compilation process:\n\n g++ main.cpp -o myprogram -L/path/to/your/library/ -lmystaticlibrary\n \n\nReplace `/path/to/your/library/` with the path where your `libmystaticlibrary.a` file is located.\n\n**2\\. Dynamic Libraries**\n\nDynamic libraries are loaded during runtime, which means that your executable file only contains references to these libraries. The libraries need to be available on the system where your program is running.\n\nTo create a dynamic library, you'll need to compile your source files into object files, then create a shared library:\n\n g++ -c -fPIC sourcefile.cpp -o objectfile.o\n g++ -shared -o libmydynamiclibrary.so objectfile.o\n \n\nTo use a dynamic library, include the library's header files in your source code and then link the library during the compilation process:\n\n g++ main.cpp -o myprogram -L/path/to/your/library/ -lmydynamiclibrary\n \n\nReplace `/path/to/your/library/` with the path where your `libmydynamiclibrary.so` file is located.\n\n**NOTE:** When using dynamic libraries, make sure the library is in the system's search path for shared libraries. You may need to update the `LD_LIBRARY_PATH` environment variable on Unix/Linux systems or the `PATH` variable on Windows.\n\nIn conclusion, using libraries in C++ involves creating or obtaining a library (static or dynamic), including the library's header files in your source code, and linking the library during the compilation process. Be aware of the differences between static and dynamic libraries, and choose the right approach to suit your needs.",
"links": []
},
"5mNqH_AEiLxUmgurNW1Fq": {
"title": "Library Inclusion",
"description": "In C++ programming, inclusion refers to incorporating external libraries, header files, or other code files into your program. This process allows developers to access pre-built functions, classes, and variable declarations that can be used in their own code. There are two types of inclusion in C++:\n\n* Header Inclusion\n* Source Inclusion\n\n### Header Inclusion\n\nHeader inclusion involves including header files using the preprocessor directive `#include`. Header files are typically used to provide function prototypes, class declarations, and constant definitions that can be shared across multiple source files. There are two ways to include header files in your program:\n\n* Angle brackets `<>`: Used for including standard library headers, like `iostream`, `vector`, or `algorithm`.\n\nExample:\n\n #include <iostream>\n #include <vector>\n \n\n* Double quotes `\"\"`: Used for including user-defined headers or headers provided by third-party libraries.\n\nExample:\n\n #include \"myHeader.h\"\n #include \"thirdPartyLibrary.h\"\n \n\n### Source Inclusion\n\nSource inclusion refers to including the content of a source file directly in another source file. This approach is generally not recommended as it can lead to multiple definitions and increased compile times but it can occasionally be useful for certain tasks (e.g., templates or simple small programs). To include a source file, you can use the `#include` directive with double quotes, just like with header files:\n\nExample:\n\n #include \"mySourceFile.cpp\"\n \n\nRemember, using source inclusion for large projects or in situations where it's not necessary can lead to unexpected issues and should be avoided.",
"links": []
},
"sLVs95EOeHZldoKY0L_dH": {
"title": "Licensing",
"description": "Licensing is a crucial aspect of working with libraries in C++ because it determines the rights and limitations on how you can use, modify, and distribute a given library. There are various types of licenses applied to open-source libraries. Below is a brief overview of three common licenses:\n\nMIT License\n-----------\n\nThe MIT License is a permissive license that allows users to do whatever they want with the software code. They only need to include the original copyright, license notice, and a disclaimer of warranty in their copies.\n\nExample: Including the MIT License into your project can be done by simply adding the license file and a notice at the top of your source code files like:\n\n /* Copyright (C) [year] [author]\n * SPDX-License-Identifier: MIT\n */\n \n\nGNU General Public License (GPL)\n--------------------------------\n\nThe GPL is a copyleft license that grants users the rights to use, study, share, and modify the software code. However, any changes made to the code or any software that uses GPL licensed code must also be distributed under the GPL license.\n\nExample: To include a GPL license in your project, include a `COPYING` file with the full text of the license and place a notice in your source code files like:\n\n /* Copyright (C) [year] [author]\n * SPDX-License-Identifier: GPL-3.0-or-later\n */\n \n\nApache License 2.0\n------------------\n\nThe Apache License is a permissive license similar to the MIT license and allows users to do virtually anything with the software code. The primary difference is that it requires that any changes to the code are documented, and it provides specific terms for patent protection.\n\nExample: To include the Apache License in your project, add a `LICENSE` file with the full text of the license. Add a notice to your source code files like:\n\n /* Copyright (C) [year] [author]\n * SPDX-License-Identifier: Apache-2.0\n */\n \n\nPlease note that these are brief summaries of the licenses, and there are many other licenses available for use in software projects. When using third-party libraries, it is crucial to understand and adhere to the terms of their respective licenses to avoid legal complications.",
"links": []
},
"1d7h5P1Q0RVHryKPVogQy": {
"title": "Boost",
"description": "",
"links": []
},
"Eq3TKSFJ2F2mrTHAaU2J4": {
"title": "OpenCV",
"description": "",
"links": []
},
"nOkniNXfXwPPlOEJHJoGl": {
"title": "POCO",
"description": "",
"links": []
},
"jpMCIWQko7p3ndezYHL4D": {
"title": "protobuf",
"description": "",
"links": []
},
"621J9W4xCofumNZGo4TZT": {
"title": "gRPC",
"description": "",
"links": []
},
"j_eNHhs0J08Dt7HVbo4Q2": {
"title": "Tensorflow",
"description": "",
"links": []
},
"tEkvlJPAkD5fji-MMODL7": {
"title": "pybind11",
"description": "",
"links": []
},
"q64qFxoCrR38RPsN2lC8x": {
"title": "spdlog",
"description": "",
"links": []
},
"GGZJaYpRENaqloJzt0VtY": {
"title": "opencl",
"description": "",
"links": []
},
"1CqQgmHDeo1HlPdpUJS7H": {
"title": "fmt",
"description": "",
"links": []
},
"et-dXKPYuyVW6eV2K3CM8": {
"title": "ranges_v3",
"description": "",
"links": []
},
"MrAM-viRaF8DSxB6sVdD9": {
"title": "gtest / gmock",
"description": "",
"links": []
},
"gAZ9Dqgj1_UkaLzVgzx1t": {
"title": "Qt",
"description": "",
"links": []
},
"s13jQuaC6gw0Lab3Cbyy6": {
"title": "Catch2",
"description": "",
"links": []
},
"O0lVEMTAV1pq9sYCKQvh_": {
"title": "Orbit Profiler",
"description": "",
"links": []
},
"88pr5aN7cctZfDVVo-2ns": {
"title": "PyTorch C++",
"description": "",
"links": []
}
}

@ -521,11 +521,6 @@
"title": "Operating Systems",
"description": "**Operating systems (OS)** are software that manage computer hardware and provide a platform for applications to run. They handle essential functions such as managing memory, processing tasks, controlling input and output devices, and facilitating file management. Key examples include **Windows**, **macOS**, **Linux**, and **Unix**. Each operating system offers different features and interfaces, tailored to specific user needs or system requirements, from desktop computing to server management and embedded systems.\n\nLearn more from the following resources:",
"links": [
{
"title": "What is an operating system?",
"url": "https://www.geeksforgeeks.org/what-is-an-operating-system/",
"type": "article"
},
{
"title": "What is an operating system as fast as possible",
"url": "https://www.youtube.com/watch?v=pVzRTmdd9j0",
@ -708,11 +703,6 @@
"title": "What are Network Protocols?",
"url": "https://www.solarwinds.com/resources/it-glossary/network-protocols",
"type": "article"
},
{
"title": "Types of Network Topology",
"url": "https://www.geeksforgeeks.org/types-of-network-topology/",
"type": "article"
}
]
},
@ -853,11 +843,6 @@
"title": "loopback",
"description": "**Loopback** refers to a special network interface used to send traffic back to the same device for testing and diagnostic purposes. The loopback address for IPv4 is `127.0.0.1`, while for IPv6 it is `::1`. When a device sends a request to the loopback address, the network data does not leave the local machine; instead, it is processed internally, allowing developers to test applications or network services without requiring external network access. Loopback is commonly used to simulate network traffic, check local services, or debug issues locally.\n\nLearn more from the following resources:",
"links": [
{
"title": "What is a loopback address?",
"url": "https://www.geeksforgeeks.org/what-is-a-loopback-address/",
"type": "article"
},
{
"title": "Understanding the loopback address and loopback interfaces",
"url": "https://study-ccna.com/loopback-interface-loopback-address/",
@ -1256,11 +1241,6 @@
"title": "Star",
"description": "A star network topology is a configuration where all devices (nodes) are connected directly to a central hub or switch. In this arrangement, each node has a dedicated point-to-point link to the central device, forming a star-like structure. This topology offers advantages such as easy installation and reconfiguration, centralized management, and fault isolation. If one connection fails, it doesn't affect others. However, the central hub is a single point of failure for the entire network. Star topologies are commonly used in local area networks (LANs) due to their reliability, scalability, and ease of maintenance, making them a popular choice in both small office and large enterprise environments.\n\nLearn more from the following resources:",
"links": [
{
"title": "Advantages and Disadvantages of Star Topology",
"url": "https://www.geeksforgeeks.org/advantages-and-disadvantages-of-star-topology/",
"type": "article"
},
{
"title": "Star Topology",
"url": "https://www.youtube.com/watch?v=EQ3rW22-Py0",
@ -1698,11 +1678,6 @@
"title": "Protocol Analyzers",
"description": "**Protocol analyzers**, also known as network analyzers or packet sniffers, are tools used to capture, inspect, and analyze network traffic. They help diagnose network issues, troubleshoot performance problems, and ensure security by providing detailed insights into the data packets transmitted across a network. Protocol analyzers decode and display various network protocols, such as TCP/IP, HTTP, and DNS, allowing users to understand communication patterns, detect anomalies, and identify potential vulnerabilities. Popular examples include Wireshark and tcpdump.\n\nLearn more from the following resources:",
"links": [
{
"title": "What is a protocol analyzer?",
"url": "https://www.geeksforgeeks.org/what-is-protocol-analyzer/",
"type": "article"
},
{
"title": "Protocol Analyzers",
"url": "https://www.youtube.com/watch?v=hTMhlB-o0Ow",
@ -1733,14 +1708,8 @@
},
"xFuWk7M-Vctk_xb7bHbWs": {
"title": "route",
"description": "The `route` command is a network utility used to view and manipulate the IP routing table on Unix-like and Windows systems. It allows users to display the current routes that data packets take, as well as add, modify, or delete routes for network traffic. This command is often used in network troubleshooting and configuration to control how data flows between different networks and subnets. By specifying routes manually, administrators can define specific paths for network traffic, bypassing default routes and optimizing performance or security.\n\nLearn more from the following resources:",
"links": [
{
"title": "How to check the routing table in Linux",
"url": "https://www.geeksforgeeks.org/route-command-in-linux-with-examples/",
"type": "article"
}
]
"description": "The `route` command is a network utility used to view and manipulate the IP routing table on Unix-like and Windows systems. It allows users to display the current routes that data packets take, as well as add, modify, or delete routes for network traffic. This command is often used in network troubleshooting and configuration to control how data flows between different networks and subnets. By specifying routes manually, administrators can define specific paths for network traffic, bypassing default routes and optimizing performance or security.",
"links": []
},
"y8GaUNpaCT1Ai88wPOk6d": {
"title": "tcpdump",
@ -2308,11 +2277,6 @@
"title": "Understand Handshakes",
"description": "In networking and cybersecurity, a handshake is a process of establishing a secure connection between two parties before data exchange begins. It typically involves a series of predefined messages exchanged to verify identities, agree on communication parameters, and sometimes establish encryption keys. The most common example is the TCP three-way handshake used to initiate a connection. In cryptographic protocols like TLS/SSL, handshakes are more complex, involving certificate verification and key exchange. Handshakes are crucial for ensuring secure, authenticated communications, preventing unauthorized access, and setting up the parameters for efficient data transfer in various network protocols and security systems.\n\nLearn more from the following resources:",
"links": [
{
"title": "TCP 3-Way Handshake Process",
"url": "https://www.geeksforgeeks.org/tcp-3-way-handshake-process/",
"type": "article"
},
{
"title": "TLS Handshake Explained",
"url": "https://www.youtube.com/watch?v=86cQJ0MMses",
@ -3110,14 +3074,8 @@
},
"W7bcydXdwlubXF2PHKOuq": {
"title": "Port Blocking",
"description": "Port blocking is an essential practice in hardening the security of your network and devices. It involves restricting, filtering, or entirely denying access to specific network ports to minimize exposure to potential cyber threats. By limiting access to certain ports, you can effectively safeguard your systems against unauthorized access and reduce the likelihood of security breaches.\n\nLearn more from the following resources:",
"links": [
{
"title": "What is port blocking with LAN?",
"url": "https://www.geeksforgeeks.org/what-is-port-blocking-within-lan/",
"type": "article"
}
]
"description": "Port blocking is an essential practice in hardening the security of your network and devices. It involves restricting, filtering, or entirely denying access to specific network ports to minimize exposure to potential cyber threats. By limiting access to certain ports, you can effectively safeguard your systems against unauthorized access and reduce the likelihood of security breaches.",
"links": []
},
"FxuMJmDoDkIsPFp2iocFg": {
"title": "Group Policy",
@ -4035,7 +3993,7 @@
"type": "article"
},
{
"title": "What is password praying?",
"title": "What is password spraying?",
"url": "https://www.techtarget.com/whatis/definition/password-spraying",
"type": "article"
},

@ -19,11 +19,6 @@
"title": "Types of Data Analytics",
"description": "Data Analytics has proven to be a critical part of decision-making in modern business ventures. It is responsible for discovering, interpreting, and transforming data into valuable information. Different types of data analytics look at past, present, or predictive views of business operations.\n\nData Analysts, as ambassadors of this domain, employ these types, to answer various questions:\n\n* Descriptive Analytics _(what happened in the past?)_\n* Diagnostic Analytics _(why did it happened in the past?)_\n* Predictive Analytics _(what will happen in the future?)_\n* Prescriptive Analytics _(how can we make it happen?)_\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Data Analytics and its type",
"url": "https://www.geeksforgeeks.org/data-analytics-and-its-type/",
"type": "article"
},
{
"title": "The 4 Types of Data Analysis: Ultimate Guide",
"url": "https://careerfoundry.com/en/blog/data-analytics/different-types-of-data-analysis/",

@ -204,11 +204,6 @@
"url": "https://en.wikipedia.org/wiki/Operating_system",
"type": "article"
},
{
"title": "All you need to know about OS.",
"url": "https://www.javatpoint.com/operating-system",
"type": "article"
},
{
"title": "Learn Operating Systems",
"url": "https://www.tutorialspoint.com/operating_system/os_overview.htm",
@ -532,11 +527,6 @@
"url": "https://www.learnshell.org/en/Welcome",
"type": "article"
},
{
"title": "Bash Scripting Tutorial",
"url": "https://www.javatpoint.com/bash",
"type": "article"
},
{
"title": "Explore top posts about Bash",
"url": "https://app.daily.dev/tags/bash?ref=roadmapsh",

@ -7,6 +7,11 @@
"title": "Engineering Management Resources",
"url": "https://github.com/engineering-management/awesome-engineering-management",
"type": "article"
},
{
"title": "Software Engineering at Google: The Engineering Manager",
"url": "https://abseil.io/resources/swe-book/html/ch05.html#the_engineering_manager",
"type": "article"
}
]
},
@ -223,8 +228,14 @@
},
"n9gvPHn4c1U-l6v-W9v6r": {
"title": "Agile methodologies",
"description": "An Engineering Manager ensures smooth implementation of Agile methodologies within the team. The manager oversees sprint planning, backlog refinement, and retrospectives for consistent development flow. They have the key role in facilitating communication, fostering a high-performing environment, and encouraging adaptive planning.\n\nThe Engineering Manager faces the challenge of maintaining an Agile mindset even when facing pressures to deliver. They have to ensure team members are motivated, engaged, and productive. This can be handled by adopting feedback-friendly culture and regular knowledge-sharing sessions.\n\nSkills required for an Engineering Manager in handling Agile methodologies include strong leadership, excellent communication, and proficiency in risk management. The manager has to balance the opposing needs of flexibility and stability, always keeping customer satisfaction in perspective.",
"links": []
"description": "An Engineering Manager ensures smooth implementation of Agile methodologies within the team. The manager oversees sprint planning, backlog refinement, and retrospectives for consistent development flow. They have the key role in facilitating communication, fostering a high-performing environment, and encouraging adaptive planning.\n\nThe Engineering Manager faces the challenge of maintaining an Agile mindset even when facing pressures to deliver. They have to ensure team members are motivated, engaged, and productive. This can be handled by adopting feedback-friendly culture and regular knowledge-sharing sessions.\n\nSkills required for an Engineering Manager in handling Agile methodologies include strong leadership, excellent communication, and proficiency in risk management. The manager has to balance the opposing needs of flexibility and stability, always keeping customer satisfaction in perspective.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Scrum Guide",
"url": "https://scrumguides.org/",
"type": "article"
}
]
},
"SuT6q5lMMSyVkadlQp7iU": {
"title": "Project Tracking",

@ -163,8 +163,8 @@
"type": "article"
},
{
"title": "Git & GitHub Crash Course For Beginners",
"url": "https://www.youtube.com/watch?v=SWYqp7iY_Tc",
"title": "Git & GitHub Crash Course For Beginners 2025",
"url": "https://youtu.be/vA5TTz6BXhY?si=GvKMbLL4UBtOq6fh",
"type": "video"
},
{
@ -504,7 +504,7 @@
},
"cUOfvOlQ_0Uu1VX3i67kJ": {
"title": "Basic AWS Services",
"description": "AWS has several services but you don't need to know all of them. Some common ones that you can start with are EC2, VPN, S3, Route 53, and SES.\n\nHere are some of the resources to get you started:",
"description": "AWS has several services but you don't need to know all of them. Some common ones that you can start with are EC2, VPC, S3, Route 53, and SES.\n\nHere are some of the resources to get you started:",
"links": [
{
"title": "Up and Running with AWS VPC",

@ -986,11 +986,6 @@
"title": "Computer Graphics",
"description": "Computer Graphics is a subfield of computer science that studies methods for digitally synthesizing and manipulating visual content. It involves creating and manipulating visual content using specialized computer software and hardware. This field is primarily used in the creation of digital and video games, CGI in films, and also in visual effects for commercials. The field is divided into two major categories: **Raster graphics** and **Vector graphics**. Raster graphics, also known as bitmap, involve the representation of images through a dot matrix data structure, while Vector graphics involve the use of polygons to represent images in computer graphics. Both of these methods have their unique usage scenarios. Other concepts integral to the study of computer graphics include rendering (including both real-time rendering and offline rendering), animation, and 3D modeling. Generally, computer graphics skills are essential for game developers and animation experts.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "What is Computer Graphics?",
"url": "https://www.geeksforgeeks.org/introduction-to-computer-graphics/",
"type": "article"
},
{
"title": "Introduction to Computer Graphics",
"url": "https://open.umn.edu/opentextbooks/textbooks/420",
@ -1412,8 +1407,19 @@
},
"sC3omOmL2DOyTSvET5cDa": {
"title": "Infinite",
"description": "",
"links": []
"description": "Infinite refers to concept that deals with rendering scenes or objects that extend beyond the visible boundaries of the screen. This is crucial for creating immersive environments, as it allows developers to simulate vast landscapes or endless spaces without the need to render every detail at once. Techniques such as level of detail (LOD), culling, and procedural generation are often employed to manage performance while maintaining the illusion of infinity.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Unlocking Infinite Worlds In Gaming",
"url": "https://sdlccorp.com/post/procedural-generation-unlocking-infinite-worlds-in-gaming/",
"type": "article"
},
{
"title": "Creating Infinite Game Worlds",
"url": "https://medium.com/@lemapp09/beginning-game-development-creating-infinite-game-worlds-56f8a2ad5ae5",
"type": "article"
}
]
},
"OcxesFnB5wO6VXrHYnhz-": {
"title": "Visibility and Occlusion",
@ -1896,11 +1902,6 @@
"title": "MCTS Algorithm",
"url": "https://en.wikipedia.org/wiki/Monte_Carlo_tree_search/",
"type": "article"
},
{
"title": "Monte Carlo Tree Search",
"url": "https://www.geeksforgeeks.org/ml-monte-carlo-tree-search-mcts/",
"type": "article"
}
]
},
@ -1998,11 +1999,6 @@
"title": "Artificial Neural Network",
"description": "Artificial Neural Networks (ANN) are a branch of machine learning that draw inspiration from biological neural networks. ANNs are capable of 'learning' from observational data, thereby enhancing game development in numerous ways. They consist of interconnected layers of nodes, or artificial neurons, that process information through their interconnected network. Each node's connection has numerical weight that gets adjusted during learning, which helps in optimizing problem solving. ANNs are utilized in various aspects of game development, such as improving AI behavior, procedural content generation, and game testing. They can also be used for image recognition tasks, such as identifying objects or actions in a game environment.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Artificial Neural Networks (ANN)",
"url": "https://www.geeksforgeeks.org/artificial-neural-networks-and-its-applications/",
"type": "article"
},
{
"title": "What is ANN?",
"url": "https://www.coursera.org/articles/artificial-neural-network",

@ -670,11 +670,6 @@
"url": "https://docs.github.com/en/organizations/managing-user-access-to-your-organizations-repositories/managing-outside-collaborators/adding-outside-collaborators-to-repositories-in-your-organization",
"type": "article"
},
{
"title": "What are github collaborators",
"url": "https://www.geeksforgeeks.org/what-are-github-collaborators/",
"type": "article"
},
{
"title": "How to Add Collaborators to Your GitHub Repository",
"url": "https://www.blinkops.com/blog/how-to-add-collaborators-to-your-github-repository",

@ -89,11 +89,6 @@
"title": "What are Data Types & Variables?",
"url": "https://jenkov.com/tutorials/java/data-types.html",
"type": "article"
},
{
"title": "Java Variables",
"url": "https://www.javatpoint.com/java-variables",
"type": "article"
}
]
},
@ -106,11 +101,6 @@
"url": "https://www.educative.io/answers/what-are-conditional-statements-in-programming",
"type": "article"
},
{
"title": "Conditionals in Java",
"url": "https://www.javatpoint.com/java-if-else",
"type": "article"
},
{
"title": "Conditionals and Loops in Java",
"url": "https://youtu.be/ldYLYRNaucM",
@ -143,11 +133,6 @@
"title": "Loops",
"description": "In Java and other programming languages, loops are used to iterate a part of the program several times. There are four types of loops in Java, `for`, `forEach`, `while`, and `do...while`.\n\n* Syntax of `for` loop is `for(initialization;condition;increment/decrement){}`\n* Syntax of `forEach` loop is `for(data_type variable:array_name){}`\n\nVisit the following resources to learn more:",
"links": [
{
"title": "What are loops in Java?",
"url": "https://www.javatpoint.com/java-for-loop",
"type": "article"
},
{
"title": "Loops in Java.",
"url": "https://www.programiz.com/java-programming/for-loop",
@ -371,14 +356,8 @@
},
"3qowgj1pas1X7oRric9eU": {
"title": "Object Lifecycle",
"description": "The object lifecycle refers to the series of stages an object goes through from its creation (allocation of memory) to its destruction (reclaiming of memory). These stages typically include object creation, initialization, usage, and eventual garbage collection when the object is no longer needed. Understanding this lifecycle is crucial for efficient memory management and preventing resource leaks.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Object Life Cycle in Java",
"url": "https://www.tpointtech.com/object-life-cycle-in-java",
"type": "article"
}
]
"description": "The object lifecycle refers to the series of stages an object goes through from its creation (allocation of memory) to its destruction (reclaiming of memory). These stages typically include object creation, initialization, usage, and eventual garbage collection when the object is no longer needed. Understanding this lifecycle is crucial for efficient memory management and preventing resource leaks.",
"links": []
},
"qdA6bK9ZkP8p0_NH_wMuj": {
"title": "Abstraction",
@ -495,11 +474,6 @@
"title": "Packages in Java",
"url": "https://docs.oracle.com/javase/8/docs/api/java/lang/Package.html",
"type": "article"
},
{
"title": "Java Package",
"url": "https://www.javatpoint.com/package",
"type": "article"
}
]
},
@ -704,11 +678,6 @@
"url": "https://www.tutorialspoint.com/java/java_generics.htm",
"type": "article"
},
{
"title": "Generics in Java",
"url": "https://www.javatpoint.com/generics-in-java",
"type": "article"
},
{
"title": "Generics in Java",
"url": "https://www.youtube.com/watch?v=XMvznsY02Mk",
@ -736,11 +705,6 @@
"title": "Exception Handling",
"description": "Exception Handling in Java is one of the effective means to handle the runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.\n\nThere are three types of exceptions -\n\n1. Checked Exception - exceptions checked at compile time. Example - IOException\n2. Unchecked Exception - exceptions checked at run time. Example - NullPointerException\n3. Error - It is irrecoverable. Example - OutOfMemoryError\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Exception Handling in Java",
"url": "https://www.javatpoint.com/exception-handling-in-java",
"type": "article"
},
{
"title": "Understanding Java Exceptions",
"url": "https://www.youtube.com/watch?v=W-N2ltgU-X4",
@ -876,11 +840,6 @@
"url": "https://gradle.org/",
"type": "article"
},
{
"title": "Gradle",
"url": "https://www.javatpoint.com/gradle",
"type": "article"
},
{
"title": "Building Spring Boot Projects with Gradle",
"url": "https://www.baeldung.com/spring-boot-gradle-plugin",
@ -960,11 +919,6 @@
"url": "https://www.marcobehler.com/guides/java-files",
"type": "article"
},
{
"title": "Java File Class",
"url": "https://www.javatpoint.com/java-file-class",
"type": "article"
},
{
"title": "(old) Java HttpURLConnection Example - Java HTTP Request GET, POST",
"url": "https://www.digitalocean.com/community/tutorials/java-httpurlconnection-example-java-http-request-get-post",
@ -1151,11 +1105,6 @@
"title": "Stream API",
"description": "Java provides a new additional package in Java 8 called java.util.stream. This package consists of classes, interfaces and enum to allows functional-style operations on the elements. You can use stream by importing java.util.stream package.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Java 8 Stream",
"url": "https://www.javatpoint.com/java-8-stream",
"type": "article"
},
{
"title": "The Java 8 Stream API Tutorial",
"url": "https://www.baeldung.com/java-8-streams",
@ -1245,11 +1194,6 @@
"url": "https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa",
"type": "article"
},
{
"title": "Spring Data JPA Tutorial",
"url": "https://www.javatpoint.com/spring-and-jpa-integration",
"type": "article"
},
{
"title": "Explore top posts about Spring Framework",
"url": "https://app.daily.dev/tags/spring?ref=roadmapsh",
@ -1276,11 +1220,6 @@
"url": "https://hibernate.org/",
"type": "article"
},
{
"title": "Hibernate Tutorial",
"url": "https://www.javatpoint.com/hibernate-tutorial",
"type": "article"
},
{
"title": "Second-level caching explained",
"url": "https://hazelcast.com/glossary/hibernate-second-level-cache/",
@ -1318,11 +1257,6 @@
"url": "https://www.baeldung.com/java-logging-intro",
"type": "article"
},
{
"title": "Java Logger",
"url": "https://www.javatpoint.com/java-logger",
"type": "article"
},
{
"title": "Java Logging Frameworks",
"url": "https://en.wikipedia.org/wiki/Java_logging_framework",

@ -334,11 +334,6 @@
"title": "JavaScript Scope",
"url": "https://www.w3schools.com/js/js_scope.asp",
"type": "article"
},
{
"title": "Block Scoping in JavaScript",
"url": "https://www.geeksforgeeks.org/javascript-es2015-block-scoping",
"type": "article"
}
]
},
@ -1573,7 +1568,7 @@
},
"s8wUJivWmetysJ8bt9FBC": {
"title": "Built-in Functions",
"description": "* A JavaScript **method** is a property containing a **function definition** . In other words, when the data stored on an object is a function we call that a method.\n* To differentiate between properties and methods, we can think of it this way: **A property is what an object has, while a method is what an object does.**\n* Since JavaScript methods are actions that can be performed on objects, we first need to have objects to start with. There are several objects built into JavaScript which we can use.\n\nVisit the following resources to learn more:",
"description": "JavaScript offers a variety of built-in functions that simplify common tasks, available globally or within specific objects without requiring explicit definition. Functions like parseInt(), setTimeout(), and Math.random() can be used directly, while objects like Array, String, and Date include built-in methods for efficient data manipulation. Understanding these functions enhances development by leveraging JavaScript’s core features without reinventing the wheel.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "JavaScript Built-in Functions",

@ -9,12 +9,12 @@
"description": "Python is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its significant use of indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects. Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming. Python is often described as a \"batteries included\" language due to its comprehensive standard library.\n\nLearn more from the following resources:",
"links": [
{
"title": "Python Roadmap",
"title": "Visit Dedicated Python Roadmap",
"url": "https://roadmap.sh/python",
"type": "article"
},
{
"title": "Python.org",
"title": "Python",
"url": "https://www.python.org/",
"type": "article"
},
@ -37,7 +37,7 @@
},
"vdVq3RQvQF3mF8PQc6DMg": {
"title": "Go",
"description": "Go, also known as Golang, is an open-source programming language developed by Google that emphasizes simplicity, efficiency, and strong concurrency support. Designed for modern software development, Go features a clean syntax, garbage collection, and built-in support for concurrent programming through goroutines and channels, making it well-suited for building scalable, high-performance applications, especially in cloud computing and microservices architectures. Go's robust standard library and tooling ecosystem, including a powerful package manager and testing framework, further streamline development processes, promoting rapid application development and deployment. Visit the following resources to learn more:",
"description": "Go, also known as Golang, is an open-source programming language developed by Google that emphasizes simplicity, efficiency, and strong concurrency support. Designed for modern software development, Go features a clean syntax, garbage collection, and built-in support for concurrent programming through goroutines and channels, making it well-suited for building scalable, high-performance applications, especially in cloud computing and microservices architectures. Go's robust standard library and tooling ecosystem, including a powerful package manager and testing framework, further streamline development processes, promoting rapid application development and deployment.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Visit Dedicated Go Roadmap",
@ -85,6 +85,11 @@
"url": "https://github.com/Idnan/bash-guide",
"type": "opensource"
},
{
"title": "Bash Reference Manual",
"url": "https://www.gnu.org/software/bash/manual/bashref.html",
"type": "article"
},
{
"title": "Bash Scripting Course",
"url": "https://www.youtube.com/watch?v=tK9Oc6AEnR4",
@ -105,6 +110,11 @@
"title": "What is Version Control?",
"url": "https://www.atlassian.com/git/tutorials/what-is-version-control",
"type": "article"
},
{
"title": "Explore top posts about Version Control",
"url": "https://app.daily.dev/tags/version-control?ref=roadmapsh",
"type": "article"
}
]
},
@ -113,7 +123,7 @@
"description": "Git is a distributed version control system used to track changes in source code during software development. It enables multiple developers to collaborate on a project by managing versions of code, allowing for branching, merging, and tracking of revisions. Git ensures that changes are recorded with a complete history, enabling rollback to previous versions if necessary. It supports distributed workflows, meaning each developer has a complete local copy of the project’s history, facilitating seamless collaboration, conflict resolution, and efficient management of code across different teams or environments.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Learn Git & GitHub",
"title": "Visit Dedicated Git & GitHub Roadmap",
"url": "https://roadmap.sh/git-github",
"type": "article"
},
@ -144,12 +154,12 @@
"description": "GitHub is a web-based platform built on top of Git that provides version control, collaboration tools, and project management features for software development. It enables developers to host Git repositories, collaborate on code through pull requests, and review and track changes. GitHub also offers additional features like issue tracking, continuous integration, automated workflows, and documentation hosting. With its social coding environment, GitHub fosters open-source contributions and team collaboration, making it a central hub for many software development projects.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Learn Git & GitHub",
"title": "Visit Dedicated Git & GitHub Roadmap",
"url": "https://roadmap.sh/git-github",
"type": "article"
},
{
"title": "GitHub Website",
"title": "GitHub",
"url": "https://github.com",
"type": "article"
},
@ -175,12 +185,17 @@
"description": "**Cloud Computing** refers to the delivery of computing services over the internet rather than using local servers or personal devices. These services include servers, storage, databases, networking, software, analytics, and intelligence. Cloud Computing enables faster innovation, flexible resources, and economies of scale. There are various types of cloud computing such as public clouds, private clouds, and hybrids clouds. Furthermore, it's divided into different services like Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS). These services differ mainly in the level of control an organization has over their data and infrastructures.\n\nLearn more from the following resources:",
"links": [
{
"title": "What is cloud computing?",
"title": "Cloud Computing - IBM",
"url": "https://www.ibm.com/think/topics/cloud-computing",
"type": "article"
},
{
"title": "What is Cloud Computing? - Azure",
"url": "https://azure.microsoft.com/en-gb/resources/cloud-computing-dictionary/what-is-cloud-computing",
"type": "article"
},
{
"title": "What is Cloud Computing? | Amazon Web Services",
"title": "What is Cloud Computing? - Amazon Web Services",
"url": "https://www.youtube.com/watch?v=mxT233EdY5c",
"type": "video"
}
@ -188,18 +203,23 @@
},
"u3E7FGW4Iwdsu61KYFxCX": {
"title": "AWS / Azure / GCP",
"description": "AWS (Amazon Web Services) Azure and GCP (Google Cloud Platform) are three leading providers of cloud computing services. AWS by Amazon is the oldest and the most established among the three, providing a breadth and depth of solutions ranging from infrastructure services like compute, storage, and databases to the machine and deep learning. Azure, by Microsoft, has integrated tools for DevOps, supports a large number of programming languages, and offers seamless integration with on-prem servers and Microsoft’s software. Google's GCP has strength in cost-effectiveness, live migration of virtual machines, and flexible computing options. All three have introduced various MLOps tools and services to boost capabilities for machine learning development and operations.\n\nVisit the following resources to learn more about AWS, Azure, and GCP:",
"description": "AWS (Amazon Web Services), Azure and GCP (Google Cloud Platform) are three leading providers of cloud computing services. AWS by Amazon is the oldest and the most established among the three, providing a breadth and depth of solutions ranging from infrastructure services like compute, storage, and databases to the machine and deep learning. Azure, by Microsoft, has integrated tools for DevOps, supports a large number of programming languages, and offers seamless integration with on-prem servers and Microsoft’s software. Google's GCP has strength in cost-effectiveness, live migration of virtual machines, and flexible computing options. All three have introduced various MLOps tools and services to boost capabilities for machine learning development and operations.\n\nVisit the following resources to learn more about AWS, Azure, and GCP:",
"links": [
{
"title": "AWS Roadmap",
"title": "Visit Dedicated AWS Roadmap",
"url": "https://roadmap.sh/aws",
"type": "article"
},
{
"title": "Azure Tutorials",
"title": "Microsoft Azure",
"url": "https://docs.microsoft.com/en-us/learn/azure/",
"type": "article"
},
{
"title": "Google Cloud Platform",
"url": "https://cloud.google.com/",
"type": "article"
},
{
"title": "GCP Learning Resources",
"url": "https://cloud.google.com/training",
@ -238,12 +258,12 @@
"description": "Containers are a construct in which cgroups, namespaces, and chroot are used to fully encapsulate and isolate a process. This encapsulated process, called a container image, shares the kernel of the host with other containers, allowing containers to be significantly smaller and faster than virtual machines.\n\nThese images are designed for portability, allowing for full local testing of a static image, and easy deployment to a container management platform.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "What are Containers?",
"title": "What are Containers? - Google Cloud",
"url": "https://cloud.google.com/learn/what-are-containers",
"type": "article"
},
{
"title": "What is a Container?",
"title": "What is a Container? - Docker",
"url": "https://www.docker.com/resources/what-container/",
"type": "article"
},
@ -268,6 +288,11 @@
"title": "Docker",
"description": "Docker is a platform for working with containerized applications. Among its features are a daemon and client for managing and interacting with containers, registries for storing images, and a desktop application to package all these features together.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Visit Dedicated Docker Roadmap",
"url": "https://roadmap.sh/docker",
"type": "article"
},
{
"title": "Docker Documentation",
"url": "https://docs.docker.com/",
@ -284,7 +309,7 @@
"type": "video"
},
{
"title": "Docker simplified in 55 seconds",
"title": "Docker Simplified in 55 Seconds",
"url": "https://youtu.be/vP_4DlOH1G4",
"type": "video"
}
@ -295,12 +320,12 @@
"description": "Kubernetes is an open source container management platform, and the dominant product in this space. Using Kubernetes, teams can deploy images across multiple underlying hosts, defining their desired availability, deployment logic, and scaling logic in YAML. Kubernetes evolved from Borg, an internal Google platform used to provision and allocate compute resources (similar to the Autopilot and Aquaman systems of Microsoft Azure). The popularity of Kubernetes has made it an increasingly important skill for the DevOps Engineer and has triggered the creation of Platform teams across the industry. These Platform engineering teams often exist with the sole purpose of making Kubernetes approachable and usable for their product development colleagues.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Kubernetes Roadmap",
"title": "Visit Dedicated Kubernetes Roadmap",
"url": "https://roadmap.sh/kubernetes",
"type": "article"
},
{
"title": "Kubernetes Website",
"title": "Kubernetes",
"url": "https://kubernetes.io/",
"type": "article"
},
@ -328,7 +353,7 @@
},
"ulka7VEVjz6ls5SnI6a6z": {
"title": "Machine Learning Fundamentals",
"description": "Machine learning fundamentals encompass the key concepts and techniques that enable systems to learn from data and make predictions or decisions without being explicitly programmed. At its core, machine learning involves algorithms that can identify patterns in data and improve over time with experience. Key areas include supervised learning (where models are trained on labeled data), unsupervised learning (where models identify patterns in unlabeled data), and reinforcement learning (where agents learn to make decisions based on feedback from their actions). Essential components also include data preprocessing, feature selection, model training, evaluation metrics, and the importance of avoiding overfitting. Understanding these fundamentals is crucial for developing effective machine learning applications across various domains. Learn more from the following resources:",
"description": "Machine learning fundamentals encompass the key concepts and techniques that enable systems to learn from data and make predictions or decisions without being explicitly programmed. At its core, machine learning involves algorithms that can identify patterns in data and improve over time with experience. Key areas include supervised learning (where models are trained on labeled data), unsupervised learning (where models identify patterns in unlabeled data), and reinforcement learning (where agents learn to make decisions based on feedback from their actions). Essential components also include data preprocessing, feature selection, model training, evaluation metrics, and the importance of avoiding overfitting. Understanding these fundamentals is crucial for developing effective machine learning applications across various domains.\n\nLearn more from the following resources:",
"links": [
{
"title": "Fundamentals of Machine Learning - Microsoft",
@ -368,12 +393,12 @@
"description": "Data pipelines are a series of automated processes that transport and transform data from various sources to a destination for analysis or storage. They typically involve steps like data extraction, cleaning, transformation, and loading (ETL) into databases, data lakes, or warehouses. Pipelines can handle batch or real-time data, ensuring that large-scale datasets are processed efficiently and consistently. They play a crucial role in ensuring data integrity and enabling businesses to derive insights from raw data for reporting, analytics, or machine learning.\n\nLearn more from the following resources:",
"links": [
{
"title": "What is a data pipeline?",
"title": "What is a Data Pipeline? - IBM",
"url": "https://www.ibm.com/topics/data-pipeline",
"type": "article"
},
{
"title": "What are data pipelines?",
"title": "What are Data Pipelines?",
"url": "https://www.youtube.com/watch?v=oKixNpz6jNo",
"type": "video"
}
@ -381,20 +406,20 @@
},
"wOogVDV4FIDLXVPwFqJ8C": {
"title": "Data Lakes & Warehouses",
"description": "\"**Data Lakes** are large-scale data repository systems that store raw, untransformed data, in various formats, from multiple sources. They're often used for big data and real-time analytics requirements. Data lakes preserve the original data format and schema which can be modified as necessary. On the other hand, **Data Warehouses** are data storage systems which are designed for analyzing, reporting and integrating with transactional systems. The data in a warehouse is clean, consistent, and often transformed to meet wide-range of business requirements. Hence, data warehouses provide structured data but require more processing and management compared to data lakes.\"\n\nLearn more from the following resources:",
"description": "**Data Lakes** are large-scale data repository systems that store raw, untransformed data, in various formats, from multiple sources. They're often used for big data and real-time analytics requirements. Data lakes preserve the original data format and schema which can be modified as necessary. On the other hand, **Data Warehouses** are data storage systems which are designed for analyzing, reporting and integrating with transactional systems. The data in a warehouse is clean, consistent, and often transformed to meet wide-range of business requirements. Hence, data warehouses provide structured data but require more processing and management compared to data lakes.\n\nLearn more from the following resources:",
"links": [
{
"title": "Data lake definition",
"title": "Data Lake Definition",
"url": "https://azure.microsoft.com/en-gb/resources/cloud-computing-dictionary/what-is-a-data-lake",
"type": "article"
},
{
"title": "What is a data lake?",
"title": "What is a Data Lake?",
"url": "https://www.youtube.com/watch?v=LxcH6z8TFpI",
"type": "video"
},
{
"title": "@hat is a data warehouse?",
"title": "@hat is a Data Warehouse?",
"url": "https://www.youtube.com/watch?v=k4tK2ttdSDg",
"type": "video"
}
@ -421,10 +446,15 @@
"description": "Airflow is a platform to programmatically author, schedule and monitor workflows. Use airflow to author workflows as directed acyclic graphs (DAGs) of tasks. The airflow scheduler executes your tasks on an array of workers while following the specified dependencies. Rich command line utilities make performing complex surgeries on DAGs a snap. The rich user interface makes it easy to visualize pipelines running in production, monitor progress, and troubleshoot issues when needed. When workflows are defined as code, they become more maintainable, versionable, testable, and collaborative.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Airflow website",
"title": "Airflow",
"url": "https://airflow.apache.org/",
"type": "article"
},
{
"title": "Airflow Documentation",
"url": "https://airflow.apache.org/docs",
"type": "article"
},
{
"title": "Explore top posts about Apache Airflow",
"url": "https://app.daily.dev/tags/apache-airflow?ref=roadmapsh",
@ -458,7 +488,7 @@
"description": "Apache Kafka is an open-source distributed event streaming platform used by thousands of companies for high-performance data pipelines, streaming analytics, data integration, and mission-critical applications.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Apache Kafka quickstart",
"title": "Apache Kafka Quickstart",
"url": "https://kafka.apache.org/quickstart",
"type": "article"
},
@ -484,26 +514,43 @@
"type": "article"
},
{
"title": "Explore top posts about Apache Flink",
"url": "https://app.daily.dev/tags/apache-flink?ref=roadmapsh",
"title": "Apache Flink",
"url": "https://www.tutorialspoint.com/apache_flink/apache_flink_introduction.htm",
"type": "article"
},
{
"title": "Apache Flink Tutorialpoint",
"url": "https://www.tutorialspoint.com/apache_flink/apache_flink_introduction.htm",
"title": "Explore top posts about Apache Flink",
"url": "https://app.daily.dev/tags/apache-flink?ref=roadmapsh",
"type": "article"
}
]
},
"iTsEHVCo6KGq7H2HMgy5S": {
"title": "MLOps Principles",
"description": "MLOps (Machine Learning Operations) principles focus on streamlining the deployment, monitoring, and management of machine learning models in production environments. Key principles include:\n\n1. **Collaboration**: Foster collaboration between data scientists, developers, and operations teams to ensure alignment on model goals, performance, and lifecycle management.\n \n2. **Automation**: Automate workflows for model training, testing, deployment, and monitoring to enhance efficiency, reduce errors, and speed up the development lifecycle.\n \n3. **Version Control**: Implement version control for both code and data to track changes, reproduce experiments, and maintain model lineage.\n \n4. **Continuous Integration and Deployment (CI/CD)**: Establish CI/CD pipelines tailored for machine learning to facilitate rapid model iteration and deployment.\n \n5. **Monitoring and Governance**: Continuously monitor model performance and data drift in production to ensure models remain effective and compliant with regulatory requirements.\n \n6. **Scalability**: Design systems that can scale to handle varying workloads and accommodate changes in data volume and complexity.\n \n7. **Reproducibility**: Ensure that experiments can be reliably reproduced by standardizing environments and workflows, making it easier to validate and iterate on models.\n \n\nThese principles help organizations efficiently manage the lifecycle of machine learning models, from development to deployment and beyond.",
"links": []
"description": "MLOps (Machine Learning Operations) principles focus on streamlining the deployment, monitoring, and management of machine learning models in production environments. Key principles include:\n\n1. **Collaboration**: Foster collaboration between data scientists, developers, and operations teams to ensure alignment on model goals, performance, and lifecycle management.\n \n2. **Automation**: Automate workflows for model training, testing, deployment, and monitoring to enhance efficiency, reduce errors, and speed up the development lifecycle.\n \n3. **Version Control**: Implement version control for both code and data to track changes, reproduce experiments, and maintain model lineage.\n \n4. **Continuous Integration and Deployment (CI/CD)**: Establish CI/CD pipelines tailored for machine learning to facilitate rapid model iteration and deployment.\n \n5. **Monitoring and Governance**: Continuously monitor model performance and data drift in production to ensure models remain effective and compliant with regulatory requirements.\n \n6. **Scalability**: Design systems that can scale to handle varying workloads and accommodate changes in data volume and complexity.\n \n7. **Reproducibility**: Ensure that experiments can be reliably reproduced by standardizing environments and workflows, making it easier to validate and iterate on models.\n \n\nThese principles help organizations efficiently manage the lifecycle of machine learning models, from development to deployment and beyond.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "MLOps Principles",
"url": "https://ml-ops.org/content/mlops-principles",
"type": "article"
}
]
},
"l1xasxQy2vAY34NWaqKEe": {
"title": "MLOps Components",
"description": "MLOps components can be broadly classified into three major categories: Development, Operations and Governance. The **Development** components include everything involved in the creation of machine learning models, such as data extraction, data analysis, feature engineering, and machine learning model training. The **Operations** category includes components involved in deploying, monitoring, and maintaining machine learning models in production. This may include release management, model serving, and performance monitoring. Lastly, the **Governance** category encompasses the policies and regulations related to machine learning models. This includes model audit and tracking, model explainability, and security & compliance regulations.",
"links": []
"description": "MLOps components can be broadly classified into three major categories: Development, Operations and Governance. The **Development** components include everything involved in the creation of machine learning models, such as data extraction, data analysis, feature engineering, and machine learning model training. The **Operations** category includes components involved in deploying, monitoring, and maintaining machine learning models in production. This may include release management, model serving, and performance monitoring. Lastly, the **Governance** category encompasses the policies and regulations related to machine learning models. This includes model audit and tracking, model explainability, and security & compliance regulations.\n\nLearn more from the following resources:",
"links": [
{
"title": "MLOps Workflow, Components, and Key Practices",
"url": "https://mlops.tv/p/understanding-ml-pipelines-through",
"type": "article"
},
{
"title": "MLOps Lifecycle",
"url": "https://www.moontechnolabs.com/blog/mlops-lifecycle/",
"type": "article"
}
]
},
"kHDSwlSq8WkLey4EJIQSR": {
"title": "Version Control",
@ -514,6 +561,11 @@
"url": "https://git-scm.com/",
"type": "article"
},
{
"title": "Git Documentation",
"url": "https://git-scm.com/docs",
"type": "article"
},
{
"title": "What is Version Control?",
"url": "https://www.atlassian.com/git/tutorials/what-is-version-control",
@ -531,7 +583,12 @@
"description": "CI/CD (Continuous Integration and Continuous Deployment/Delivery) is a software development practice that automates the process of integrating code changes, running tests, and deploying updates. Continuous Integration focuses on regularly merging code changes into a shared repository, followed by automated testing to ensure code quality. Continuous Deployment extends this by automatically releasing every validated change to production, while Continuous Delivery ensures code is always in a deployable state, but requires manual approval for production releases. CI/CD pipelines improve code reliability, reduce integration risks, and speed up the development lifecycle.\n\nLearn more from the following resources:",
"links": [
{
"title": "What is CI/CD?",
"title": "What is CI/CD? - Gitlab",
"url": "https://about.gitlab.com/topics/ci-cd/",
"type": "article"
},
{
"title": "What is CI/CD? - Redhat",
"url": "https://www.redhat.com/en/topics/devops/what-is-ci-cd",
"type": "article"
},
@ -579,7 +636,7 @@
"type": "article"
},
{
"title": "What is a feature store",
"title": "What is a Feature Store",
"url": "https://www.snowflake.com/guides/what-feature-store-machine-learning/",
"type": "article"
}
@ -587,8 +644,29 @@
},
"zsW1NRb0dMgS-KzWsI0QU": {
"title": "Model Training & Serving",
"description": "\"Model Training\" refers to the phase in the Machine Learning (ML) pipeline where we teach a machine learning model how to make predictions by providing it with data. This process begins with feeding the model a training dataset, which it uses to learn and understand patterns or perform computations. The model's performance is then evaluated by comparing its prediction outputs with the actual results. Various algorithms can be used in the model training process. The choice of algorithm usually depends on the task, the data available, and the requirements of the project. It is worth noting that the model training stage can be computationally expensive particularly when dealing with large datasets or complex models.\n\nDecisions depend on the organization's infrastructure.\n\n* **Repository Suggestion:** [ML Deployment k8s Fast API](https://github.com/sayakpaul/ml-deployment-k8s-fastapi/tree/main)\n* **Tutorial Suggestions:** [ML deployment with k8s FastAPI, Building an ML app with FastAPI](https://dev.to/bravinsimiyu/beginner-guide-on-how-to-build-a-machine-learning-app-with-fastapi-part-ii-deploying-the-fastapi-application-to-kubernetes-4j6g), [Basic Kubeflow pipeline](https://towardsdatascience.com/tutorial-basic-kubeflow-pipeline-from-scratch-5f0350dc1905), [Building and deploying ML pipelines](https://www.datacamp.com/tutorial/kubeflow-tutorial-building-and-deploying-machine-learning-pipelines?utm_source=google&utm_medium=paid_search&utm_campaignid=19589720818&utm_adgroupid=157156373991&utm_device=c&utm_keyword=&utm_matchtype=&utm_network=g&utm_adpostion=&utm_creative=683184494153&utm_targetid=dsa-2218886984380&utm_loc_interest_ms=&utm_loc_physical_ms=9064564&utm_content=&utm_campaign=230119_1-sea~dsa~tofu_2-b2c_3-eu_4-prc_5-na_6-na_7-le_8-pdsh-go_9-na_10-na_11-na-dec23&gad_source=1&gclid=Cj0KCQiA4Y-sBhC6ARIsAGXF1g7iSih9h2RGL27LwWY6dlPLhEss-e5Af8pnaBvdDynRh7IHIKi8sGgaApD-EALw_wcB), [KServe tutorial](https://towardsdatascience.com/kserve-highly-scalable-machine-learning-deployment-with-kubernetes-aa7af0b71202)",
"links": []
"description": "Model Training refers to the phase in the Machine Learning (ML) pipeline where we teach a machine learning model how to make predictions by providing it with data. This process begins with feeding the model a training dataset, which it uses to learn and understand patterns or perform computations. The model's performance is then evaluated by comparing its prediction outputs with the actual results. Various algorithms can be used in the model training process. The choice of algorithm usually depends on the task, the data available, and the requirements of the project. It is worth noting that the model training stage can be computationally expensive particularly when dealing with large datasets or complex models.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "ML Deployment k8s Fast API",
"url": "https://github.com/sayakpaul/ml-deployment-k8s-fastapi/",
"type": "opensource"
},
{
"title": "MLOps Principles",
"url": "https://ml-ops.org/content/mlops-principles",
"type": "article"
},
{
"title": "ML deployment with k8s FastAPI, Building an ML app with FastAPI",
"url": "https://dev.to/bravinsimiyu/beginner-guide-on-how-to-build-a-machine-learning-app-with-fastapi-part-ii-deploying-the-fastapi-application-to-kubernetes-4j6g",
"type": "article"
},
{
"title": "KServe Tutorial",
"url": "https://towardsdatascience.com/kserve-highly-scalable-machine-learning-deployment-with-kubernetes-aa7af0b71202",
"type": "article"
}
]
},
"r4fbUwD83uYumEO1X8f09": {
"title": "Monitoring & Observability",
@ -608,20 +686,25 @@
},
"sf67bSL7HAx6iN7S6MYKs": {
"title": "Infrastructure as Code",
"description": "Infrastructure as Code (IaC) is a modern approach to managing and provisioning IT infrastructure through machine-readable configuration files, rather than manual processes. It enables developers and operations teams to define and manage infrastructure resources—such as servers, networks, and databases—using code, which can be versioned, tested, and deployed like application code. IaC tools, like Terraform and AWS CloudFormation, allow for automated, repeatable deployments, reducing human error and increasing consistency across environments. This practice facilitates agile development, enhances collaboration between teams, and supports scalable and efficient infrastructure management.",
"description": "Infrastructure as Code (IaC) is a modern approach to managing and provisioning IT infrastructure through machine-readable configuration files, rather than manual processes. It enables developers and operations teams to define and manage infrastructure resources—such as servers, networks, and databases—using code, which can be versioned, tested, and deployed like application code. IaC tools, like Terraform and AWS CloudFormation, allow for automated, repeatable deployments, reducing human error and increasing consistency across environments. This practice facilitates agile development, enhances collaboration between teams, and supports scalable and efficient infrastructure management.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Visit Dedicated Terraform Roadmap",
"url": "https://roadmap.sh/terraform",
"type": "article"
},
{
"title": "What is Infrastructure as Code?",
"url": "https://www.redhat.com/en/topics/automation/what-is-infrastructure-as-code-iac",
"type": "article"
},
{
"title": "Terraform course for beginners",
"title": "Terraform Course for Beginners",
"url": "https://www.youtube.com/watch?v=SLB_c_ayRMo",
"type": "video"
},
{
"title": "8 Terraform best practices",
"title": "8 Terraform Best Practices",
"url": "https://www.youtube.com/watch?v=gxPykhPxRW0",
"type": "video"
}

@ -4,12 +4,12 @@
"description": "Node.js is an open source, cross-platform runtime environment and library that is used for running web applications outside the client’s browser.\n\nIt is used for server-side programming, and primarily deployed for non-blocking, event-driven servers, such as traditional web sites and back-end API services, but was originally designed with real-time, push-based architectures in mind. Every browser has its own version of a JS engine, and node.js is built on Google Chrome’s V8 JavaScript engine.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Website",
"title": "Node.js",
"url": "https://nodejs.org/en/",
"type": "article"
},
{
"title": "Official Documentation",
"title": "Node.js Documentation",
"url": "https://nodejs.org/en/docs/",
"type": "article"
},
@ -25,7 +25,7 @@
"description": "Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project! Node.js runs the V8 JavaScript engine, Google Chrome's core, outside the browser. This allows Node.js to be very performant. A Node.js app runs in a single process, without creating a new thread for every request.\n\nNode.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Website",
"title": "Node.js",
"url": "https://nodejs.org/en/about/",
"type": "article"
},
@ -102,7 +102,7 @@
"type": "article"
},
{
"title": "Node.js: The Documentary | An origin story",
"title": "Node.js: The Documentary | An Origin Story",
"url": "https://youtu.be/LB8KwiiUGy0",
"type": "video"
}
@ -150,7 +150,7 @@
"type": "article"
},
{
"title": "CommonJS vs. ES modules in Node.js",
"title": "CommonJS vs. ES Modules in Node.js",
"url": "https://blog.logrocket.com/commonjs-vs-es-modules-node-js/",
"type": "article"
},
@ -207,7 +207,7 @@
"description": "ESM (ECMAScript Modules) is a standardized module system in JavaScript that allows for the organized, maintainable, and reusable structuring of code. It uses import and export statements for including and sharing functions, objects, or primitives between files. ESM supports static analysis, enabling better optimization and tooling, and is always in strict mode to reduce common JavaScript issues. Node.js fully supports ESM, which can be used with .mjs file extensions or configured in the package.json for .js files, making it easier to write modular and efficient JavaScript applications.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "esm documentation on nodejs org",
"title": "ESM Documentation",
"url": "https://nodejs.org/api/esm.html",
"type": "article"
}
@ -265,23 +265,18 @@
"description": "npm is the standard package manager for Node.js.\n\nIt is two things: first and foremost, it is an online repository for the publishing of open-source Node.js projects; second, it is a command-line utility for interacting with said repository that aids in package installation, version management, and dependency management. A plethora of Node.js libraries and applications are published on npm, and many more are added every day\n\nVisit the following resources to learn more:",
"links": [
{
"title": "What is npm?",
"url": "https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager",
"title": "NPM Documentation",
"url": "https://docs.npmjs.com/",
"type": "article"
},
{
"title": "An introduction to the npm package manager",
"title": "What is npm?",
"url": "https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager",
"type": "article"
},
{
"title": "Official Website",
"url": "https://www.npmjs.com/",
"type": "article"
},
{
"title": "Official Documentation",
"url": "https://docs.npmjs.com/",
"title": "An introduction to the npm package manager",
"url": "https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager",
"type": "article"
},
{
@ -342,6 +337,11 @@
"url": "https://docs.npmjs.com/updating-packages-downloaded-from-the-registry",
"type": "article"
},
{
"title": "How to Update Npm Packages Safely With Npm Check Updates",
"url": "https://chrispennington.blog/blog/how-to-update-npm-packages-safely-with-npm-check-updates/",
"type": "article"
},
{
"title": "How to Update All NPM Dependencies At Once",
"url": "https://www.youtube.com/watch?v=Ghdfdq17JAY",
@ -375,7 +375,7 @@
"type": "article"
},
{
"title": "Getting Started with Npm Workspaces ",
"title": "Getting Started with Npm Workspaces",
"url": "https://ruanmartinelli.com/posts/npm-7-workspaces-1",
"type": "article"
},
@ -462,10 +462,10 @@
},
"05YY-AhLKzn4Ypr4eow5E": {
"title": "System Errors",
"description": "Node.js generates system errors when exceptions occur within its runtime environment. These usually occur when an application violates an operating system constraint. For example, a system error will occur if an application attempts to read a file that does not exist.\n\nBelow are the system errors commonly encountered when writing a Node.js program\n\n1. EACCES - Permission denied\n2. EADDRINUSE - Address already in use\n3. ECONNRESET - Connection reset by peer\n4. EEXIST - File exists\n5. EISDIR - Is a directory\n6. EMFILE - Too many open files in system\n7. ENOENT - No such file or directory\n8. ENOTDIR - Not a directory\n9. ENOTEMPTY - Directory not empty\n10. ENOTFOUND - DNS lookup failed\n11. EPERM - Operation not permitted\n12. EPIPE - Broken Pipe\n13. ETIMEDOUT - Operation timed out\n\nVisit the following resources to learn more:",
"description": "Node.js generates system errors when exceptions occur within its runtime environment. These usually occur when an application violates an operating system constraint. For example, a system error will occur if an application attempts to read a file that does not exist.\n\nBelow are the system errors commonly encountered when writing a Node.js program:\n\n1. EACCES - Permission denied\n2. EADDRINUSE - Address already in use\n3. ECONNRESET - Connection reset by peer\n4. EEXIST - File exists\n5. EISDIR - Is a directory\n6. EMFILE - Too many open files in system\n7. ENOENT - No such file or directory\n8. ENOTDIR - Not a directory\n9. ENOTEMPTY - Directory not empty\n10. ENOTFOUND - DNS lookup failed\n11. EPERM - Operation not permitted\n12. EPIPE - Broken Pipe\n13. ETIMEDOUT - Operation timed out\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Node.js Errors - Official Docs",
"title": "Node.js Errors",
"url": "https://nodejs.org/api/errors.html#errors_class_systemerror",
"type": "article"
},
@ -556,10 +556,15 @@
"description": "Node.js includes a command-line debugging utility. The Node.js debugger client is not a full-featured debugger, but simple stepping and inspection are possible. To use it, start Node.js with the inspect argument followed by the path to the script to debug.\n\nExample - `$ node inspect myscript.js`\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Docs",
"title": "Debugger",
"url": "https://nodejs.org/api/debugger.html",
"type": "article"
},
{
"title": "Inspect Docs",
"url": "https://nodejs.org/en/learn/getting-started/debugging",
"type": "article"
},
{
"title": "Freecodecamp.org - Debugging",
"url": "https://www.freecodecamp.org/news/how-to-debug-node-js-applications/",
@ -572,13 +577,13 @@
"description": "npx is a very powerful command that's been available in npm starting version 5.2, released in July 2017. If you don't want to install npm, you can install npx as a standalone package. npx lets you run code built with Node.js and published through the npm registry, without needing to install the package itself. This is particularly useful for trying out new tools, running one-time commands, or using packages in shared environments where global installations are undesirable. npx takes care of downloading the package on-the-fly, running the desired command, and then cleaning up the temporary installation. This keeps your project's dependencies lean and avoids version conflicts.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Introduction to the npx Node.js Package Runner",
"url": "https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b",
"title": "npx",
"url": "https://docs.npmjs.com/cli/commands/npx/",
"type": "article"
},
{
"title": "Official Documentation",
"url": "https://docs.npmjs.com/cli/commands/npx/",
"title": "Introduction to the npx Node.js Package Runner",
"url": "https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b",
"type": "article"
}
]
@ -606,7 +611,7 @@
},
"QcOqhuKWOUUUBSiu5Oelv": {
"title": "Promises",
"description": "A promise is commonly defined as a proxy for a value that will eventually become available. Asynchronous functions use promise behind the scenes, so understanding how promises work is fundamental to understanding how \"async\" and \"await\" works. Once a promise has been called, it will start in a pending state. This means that the calling function continues executing, while the promise is pending until it resolves, giving the calling function whatever data was being requested.\n\nCreating a Promise: The Promise API exposes a Promise constructor, which you initialize using new Promise().\n\nUsing resolve() and reject(), we can communicate back to the caller what the resulting Promise state was, and what to do with it.\n\nVisit the following resources to learn more:",
"description": "A promise is commonly defined as a proxy for a value that will eventually become available.\n\nAsynchronous functions use promise behind the scenes, so understanding how promises work is fundamental to understanding how \"async\" and \"await\" works.\n\nOnce a promise has been called, it will start in a pending state. This means that the calling function continues executing, while the promise is pending until it resolves, giving the calling function whatever data was being requested.\n\nCreating a Promise:\n\nThe Promise API exposes a Promise constructor, which you initialize using new Promise().\n\nUsing resolve() and reject(), we can communicate back to the caller what the resulting Promise state was, and what to do with it.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Promise Methods",
@ -656,13 +661,13 @@
"description": "Node.js, being an asynchronous platform, doesn't wait around for things like file I/O to finish - Node.js uses callbacks. A callback is a function called at the completion of a given task; this prevents any blocking, and allows other code to be run in the meantime.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "What are callbacks?",
"url": "https://developer.mozilla.org/en-US/docs/Glossary/Callback_function",
"title": "Asynchronicity in Programming Languages",
"url": "https://nodejs.org/en/learn/asynchronous-work/javascript-asynchronous-programming-and-callbacks",
"type": "article"
},
{
"title": "Asynchronicity in Programming Languages",
"url": "https://nodejs.org/en/learn/asynchronous-work/javascript-asynchronous-programming-and-callbacks",
"title": "What are Callbacks?",
"url": "https://developer.mozilla.org/en-US/docs/Glossary/Callback_function",
"type": "article"
}
]
@ -710,12 +715,12 @@
"links": [
{
"title": "Understanding setImmediate",
"url": "https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate",
"url": "https://nodejs.org/en/learn/asynchronous-work/understanding-setimmediate",
"type": "article"
},
{
"title": "Understanding setImmediate",
"url": "https://nodejs.org/en/learn/asynchronous-work/understanding-setimmediate",
"url": "https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate",
"type": "article"
}
]
@ -802,6 +807,11 @@
"url": "https://www.digitalocean.com/community/tutorials/how-to-work-with-files-using-the-fs-module-in-node-js",
"type": "article"
},
{
"title": "File system",
"url": "https://nodejs.org/docs/latest/api/fs.html",
"type": "article"
},
{
"title": "Explore top posts about Node.js",
"url": "https://app.daily.dev/tags/nodejs?ref=roadmapsh",
@ -814,7 +824,7 @@
"description": "The `process.cwd()` method returns the current working directory of the Node.js process.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Website",
"title": "process.cwd()",
"url": "https://nodejs.org/api/process.html#processcwd",
"type": "article"
},
@ -830,7 +840,7 @@
"description": "The `path` module provides utilities for working with file and directory paths. It's built-in to Node.js core and can simply be used by requiring it.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Path Documentations",
"title": "Path Documentation",
"url": "https://nodejs.org/api/path.html",
"type": "article"
},
@ -851,7 +861,7 @@
"description": "File System or `fs` module is a built in module in Node that enables interacting with the file system using JavaScript. All file system operations have synchronous, callback, and promise-based forms, and are accessible using both CommonJS syntax and ES6 Modules.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Documentation",
"title": "fs",
"url": "https://nodejs.org/api/fs.html",
"type": "article"
},
@ -872,7 +882,7 @@
"description": "The `__dirname` in a node script returns the path of the folder where the current JavaScript file resides. `__filename` and `__dirname` are used to get the filename and directory name of the currently executing file.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Website",
"title": "__dirname",
"url": "https://nodejs.org/docs/latest/api/modules.html#__dirname",
"type": "article"
},
@ -888,7 +898,7 @@
"description": "The `__filename` in Node.js returns the filename of the executed code. It gives the absolute path of the code file. The following approach covers implementing `__filename` in the Node.js project.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Docs",
"title": "__filename",
"url": "https://nodejs.org/docs/latest/api/modules.html#__filename",
"type": "article"
}
@ -926,7 +936,7 @@
"description": "fs-extra adds file system methods that aren't included in the native fs module and adds promise support to the fs methods. It also uses graceful-fs to prevent EMFILE errors. It should be a drop in replacement for fs.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Website",
"title": "fs-extra package",
"url": "https://www.npmjs.com/package/fs-extra",
"type": "article"
},
@ -942,7 +952,7 @@
"description": "Chokidar is a fast open-source file watcher for node. js. You give it a bunch of files, it watches them for changes and notifies you every time an old file is edited; or a new file is created.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "NPM Docs",
"title": "chokidar package",
"url": "https://www.npmjs.com/package/chokidar",
"type": "article"
}
@ -1010,7 +1020,7 @@
"description": "In Node. js, process. env is a global variable that is injected during runtime. It is a view of the state of the system environment variables. When we set an environment variable, it is loaded into process.env during runtime and can later be accessed.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Node.js Learn environment variables",
"title": "Node.js Learn Environment Variables",
"url": "https://nodejs.org/en/learn/command-line/how-to-read-environment-variables-from-nodejs",
"type": "article"
},
@ -1042,7 +1052,7 @@
"description": "The `process.stdin` is a standard Readable stream which listens for user input and is accessible via the process module. It uses `on()` function to listen for input events.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Documentation",
"title": "process.stdin",
"url": "https://nodejs.org/api/process.html#processstdin",
"type": "article"
},
@ -1058,7 +1068,7 @@
"description": "Prompts is a higher level and user friendly interface built on top of Node.js's inbuilt `Readline` module. It supports different type of prompts such as text, password, autocomplete, date, etc. It is an interactive module and comes with inbuilt validation support.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Documentation",
"title": "Prompts",
"url": "https://www.npmjs.com/package/prompts",
"type": "article"
}
@ -1069,7 +1079,7 @@
"description": "Inquirer.js is a collection of common interactive command line interfaces for taking inputs from user. It is promise based and supports chaining series of prompt questions together, receiving text input, checkboxes, lists of choices and much more.\n\nYou can use it to empower your terminal applications that need user input or to build your own CLI.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Docs",
"title": "Inquirer",
"url": "https://github.com/SBoudrias/Inquirer.js#readme",
"type": "opensource"
},
@ -1122,7 +1132,7 @@
"description": "This package aims to fully implement the FIGfont spec in JavaScript, which represents the graphical arrangement of characters representing larger characters. It works in the browser and with Node.js.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "GitHub Repository",
"title": "figlet",
"url": "https://github.com/patorjk/figlet.js",
"type": "opensource"
}
@ -1165,7 +1175,7 @@
"description": "Commander is a light-weight, expressive, and powerful command-line framework for node.js. with Commander.js you can create your own command-line interface (CLI).\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Documentation",
"title": "commander package",
"url": "https://www.npmjs.com/package/commander",
"type": "article"
},
@ -1202,12 +1212,12 @@
"description": "Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multi-page, and hybrid web application.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Express.js Official Website",
"title": "Express.js",
"url": "https://expressjs.com/",
"type": "article"
},
{
"title": "Official Getting Started Guide",
"title": "Getting Started Guide",
"url": "https://expressjs.com/en/starter/installing.html",
"type": "article"
},
@ -1233,12 +1243,12 @@
"description": "Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture, inspired by Hapi and Express.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Fastify Website",
"title": "Fastify",
"url": "https://www.fastify.io/",
"type": "article"
},
{
"title": "Fastify Official Documentations",
"title": "Fastify Documentations",
"url": "https://www.fastify.io/docs/latest/",
"type": "article"
},
@ -1259,12 +1269,12 @@
"description": "NestJS is a progressive Node.js framework for creating efficient and scalable server-side applications.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "NestJS Website",
"title": "NestJS",
"url": "https://nestjs.com",
"type": "article"
},
{
"title": "NestJS Official Documentations",
"title": "NestJS Documentations",
"url": "https://docs.nestjs.com",
"type": "article"
},
@ -1285,7 +1295,7 @@
"description": "Hono is a lightweight, simple, and fast web framework for Cloudflare Workers, Deno, Bun, and other applications. It is a modern web application that is both fast and flexible. It offers inbuilt support for TypeScript, and easy development in a local environment. Using Hono, It is easy to create publishable web applications with Deno, Bun, and Cloudflare Workers.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Hono Official Documentations",
"title": "Hono Documentation",
"url": "https://hono.dev/docs/",
"type": "article"
},
@ -1306,7 +1316,7 @@
"type": "article"
},
{
"title": "Node http.request() documentation",
"title": "Node.js http.request() documentation",
"url": "https://nodejs.org/docs/latest-v16.x/api/http.html#httprequesturl-options-callback",
"type": "article"
},
@ -1322,7 +1332,7 @@
"description": "Axios is a promise-based HTTP Client for node.js and the browser. Used for making requests to web servers. On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Axios Official Documentation",
"title": "Axios Documentation",
"url": "https://axios-http.com/docs/intro",
"type": "article"
},
@ -1343,7 +1353,7 @@
"description": "Ky is a tiny and elegant HTTP client based on the browser Fetch API. Ky targets modern browsers and Deno.For older browsers, you will need to transpile and use a fetch polyfill.For Node.js, check out Got.. 1 KB (minified & gzipped), one file, and no dependencies.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Ky Official Docs",
"title": "Ky Docs",
"url": "https://github.com/sindresorhus/ky",
"type": "opensource"
},
@ -1385,7 +1395,7 @@
"description": "Got is a lighter, human-friendly, and powerful HTTP request library explicitly designed to work with Node.js. It supports pagination, RFC compliant caching, makes an API request again if it fails, supports cookies out of the box, etc.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Documentation",
"title": "Got Documentation",
"url": "https://www.npmjs.com/package/got",
"type": "article"
},
@ -1401,7 +1411,7 @@
"description": "JWT, or JSON-Web-Token, is an open standard for sharing security information between two parties — a client and a server. Each JWT contains encoded JSON objects, including a set of claims. JWTs are signed using a cryptographic algorithm to ensure that the claims cannot be altered after the token is issued.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Package Documentation",
"title": "JSON Package Documentation",
"url": "https://www.npmjs.com/package/jsonwebtoken",
"type": "article"
},
@ -1422,12 +1432,12 @@
"description": "Passport.js is authentication middleware for Node.js. It makes implementing authentication in express apps really easy and fast. It is extremely flexible and modular. It uses \"strategies\" to support authentication using a username and password, Facebook, Twitter, and a lot of other sites.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "PassportJS Website",
"title": "PassportJS",
"url": "https://www.passportjs.org/",
"type": "article"
},
{
"title": "PassportJS Official Documentation",
"title": "PassportJS Documentation",
"url": "https://www.passportjs.org/docs/",
"type": "article"
},
@ -1445,20 +1455,20 @@
},
"swp4wBgA7z-sd64VDkMrw": {
"title": "Monitor Changes (Dev)",
"description": "In Node.js, you need to restart the process to make changes take effect. This adds an extra step to your workflow. You can eliminate this extra step by using `nodemon` to restart the process automatically.\n\nSince Node.js 18.11.0, you can run Node with the `--watch` flag to reload your app everytime a file is changed. So you don't need to use `nodemon` anymore. [Node.js 18.11.0 Changelog](https://github.com/nodejs/node/blob/main/doc/changelogs/CHANGELOG_V18.md#18.11.0).",
"description": "In Node.js, you need to restart the process to make changes take effect. This adds an extra step to your workflow. You can eliminate this extra step by using `nodemon` to restart the process automatically.\n\nSince Node.js 18.11.0, you can run Node with the `--watch` flag to reload your app every time a file is changed. So you don't need to use `nodemon` anymore.\n\nVisit the following resources to learn more:",
"links": []
},
"812bVEzxwTsYzLG_PmLqN": {
"title": "--watch",
"description": "The `--watch` flag in Node.js is a powerful feature introduced in Node.js version 19 that enables automatic reloading of your Node.js application whenever changes are detected in the specified files.\n\nHow it works\n------------\n\n* You run your Node.js script with the `--watch` flag: `$ node --watch your_script.js`\n* Node.js starts watching the specified file (or directory) for changes.\n* Whenever a change is detected, Node.js automatically restarts the script\n\nVisit the following resources to learn more:",
"description": "The `--watch` flag in Node.js is a powerful feature introduced in Node.js version 19 that enables automatic reloading of your Node.js application whenever changes are detected in the specified files.\n\nHere's How it works:\n\n* You run your Node.js script with the `--watch` flag: `$ node --watch your_script.js`\n* Node.js starts watching the specified file (or directory) for changes.\n* Whenever a change is detected, Node.js automatically restarts the script\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Docs",
"title": "Node.js CLI",
"url": "https://nodejs.org/api/cli.html",
"type": "article"
},
{
"title": "Node.js API Docs",
"title": "Node.js --watch Docs",
"url": "https://nodejs.org/api/cli.html#--watch",
"type": "article"
},
@ -1471,8 +1481,18 @@
},
"2Ym2jMvov0lZ79aJFaw29": {
"title": "nodemon",
"description": "In Node.js, you need to restart the process to make changes take effect. This adds an extra step to your workflow. You can eliminate this extra step by using [nodemon](https://nodemon.io/) or [PM2](https://pm2.keymetrics.io/docs/usage/quick-start/) to restart the process automatically.\n\n`nodemon` is a command-line interface (CLI) utility developed by [@rem](https://twitter.com/rem) that wraps your Node app, watches the file system, and automatically restarts the process.\n\nVisit the following resources to learn more:",
"description": "In Node.js, you need to restart the process to make changes take effect. This adds an extra step to your workflow. You can eliminate this extra step by using nodemon or PM2 to restart the process automatically.\n\n`nodemon` is a command-line interface (CLI) utility developed by rem that wraps your Node app, watches the file system, and automatically restarts the process.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Nodemon",
"url": "https://nodemon.io/",
"type": "article"
},
{
"title": "PM2",
"url": "https://pm2.keymetrics.io/docs/usage/quick-start/",
"type": "article"
},
{
"title": "How To Restart Your Node.js Apps Automatically with nodemon",
"url": "https://www.digitalocean.com/community/tutorials/workflow-nodemon",
@ -1487,25 +1507,41 @@
},
"J0ErCAZT5B97ZMogU2JHd": {
"title": "Template Engines",
"description": "Template engine helps us to create an HTML template with minimal code. Also, it can inject data into HTML template at client side and produce the final HTML.\n\nSome examples of template engines in Node.js are:\n\n* Nunjucks\n* Jade\n* Vash\n* EJS\n* Handlebars\n* HAML",
"links": []
"description": "Template engine helps us to create an HTML template with minimal code. Also, it can inject data into HTML template at client side and produce the final HTML.\n\nSome examples of template engines in Node.js are:\n\n* Nunjucks\n* Jade\n* Vash\n* EJS\n* Handlebars\n* HAML\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Getting Started with Pug",
"url": "https://pugjs.org/api/getting-started.html",
"type": "article"
},
{
"title": "Handlebars Package",
"url": "https://www.npmjs.com/package/handlebars",
"type": "article"
},
{
"title": "EJS Package",
"url": "https://www.npmjs.com/package/ejs",
"type": "article"
}
]
},
"L-_N7OxxuHCXsdWYBgZGu": {
"title": "ejs",
"description": "EJS is a template language or engine that allows you to generate HTML markup with pure JavaScript. And this is what makes it perfect for Nodejs applications. In simple words, the EJS template engine helps to easily embed JavaScript into your HTML template.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "EJS Website",
"title": "EJS",
"url": "https://ejs.co/",
"type": "article"
},
{
"title": "EJS Official Documentation",
"title": "EJS Documentation",
"url": "https://ejs.co/#docs",
"type": "article"
},
{
"title": "EJS Official Package",
"title": "EJS Package",
"url": "https://www.npmjs.com/package/ejs",
"type": "article"
},
@ -1568,7 +1604,7 @@
"description": "A database is an organized collection of structured information, or data, typically stored electronically in a computer system. A database is usually controlled by a database management system (DBMS).\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Wikipedia - What is Database?",
"title": "What is Database?",
"url": "https://en.wikipedia.org/wiki/Database",
"type": "article"
}
@ -1579,7 +1615,7 @@
"description": "Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Mongoose Website",
"title": "Mongoose",
"url": "https://mongoosejs.com",
"type": "article"
},
@ -1600,7 +1636,7 @@
"description": "Prisma provides an open source next-generation ORM in the TypeScript ecosystem. It offers a dedicated API for relation filters. It provides an abstraction layer that makes you more productive compared to writing SQL. Prisma currently supports `PostgreSQL`, `MySQL`, `SQL Server`, `SQLite`, `MongoDB` and `CockroachDB`.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Prisma Website",
"title": "Prisma",
"url": "https://www.prisma.io/",
"type": "article"
},
@ -1618,7 +1654,7 @@
},
"5WqLm53CHDT5uBoMH-iPl": {
"title": "Native Drivers",
"description": "Another way to connect to different databases in Node.js is to use the official native drivers provided by the database. For example, here is the [list of drivers by MongoDB](https://www.mongodb.com/docs/drivers/)",
"description": "Another way to connect to different databases in Node.js is to use the official native drivers provided by the database.\n\nVisit the following resources to learn more:\n\n[@official@MongoDB Drivers](https://www.mongodb.com/docs/drivers/)",
"links": []
},
"HDDnt79_PCB5JU-KnHKUh": {
@ -1626,7 +1662,7 @@
"description": "Knex.js is a \"batteries included\" SQL query builder for PostgreSQL, CockroachDB, MSSQL, MySQL, MariaDB, SQLite3, Better-SQLite3, Oracle, and Amazon Redshift designed to be flexible, portable, and fun to use.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Knex.js Docs",
"title": "Knex.js",
"url": "https://knexjs.org",
"type": "article"
},
@ -1647,7 +1683,7 @@
"type": "opensource"
},
{
"title": "Drizzle Website",
"title": "Drizzle",
"url": "https://orm.drizzle.team/",
"type": "article"
},
@ -1665,7 +1701,7 @@
},
"rk5FtAPDi1TpvWd0yBbtl": {
"title": "TypeORM",
"description": "TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript (ES5, ES6, ES7, ES8). Its goal is to always support the latest JavaScript features and provide additional features that help you to develop any kind of application that uses databases - from small applications with a few tables to large scale enterprise applications with multiple databases.\n\nTypeORM supports both [Active Record](https://typeorm.io/active-record-data-mapper#what-is-the-active-record-pattern) and [Data Mapper](https://typeorm.io/active-record-data-mapper#what-is-the-data-mapper-pattern) patterns, unlike all other JavaScript ORMs currently in existence, which means you can write high quality, loosely coupled, scalable, maintainable applications the most productive way.\n\nVisit the following resources to learn more:",
"description": "TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript (ES5, ES6, ES7, ES8). Its goal is to always support the latest JavaScript features and provide additional features that help you to develop any kind of application that uses databases - from small applications with a few tables to large scale enterprise applications with multiple databases.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "TypeORM Docs",
@ -1681,10 +1717,10 @@
},
"fOm-ktIaLqrmA0zln0Bga": {
"title": "Sequelize",
"description": "Sequelize is an easy-to-use and promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite, DB2, Microsoft SQL Server, and Snowflake. It features solid transaction support, relations, eager and lazy loading, read replication and more.\n\nWhat is an ORM ?\n----------------\n\nAn ORM is known as Object Relational Mapper. This is a tool or a level of abstraction which maps(converts) data in a relational database into programmatic objects that can be manipulated by a programmer using a programming language(usually an OOP language). ORMs solely exist to map the details between two data sources which due to a mismatch cannot coexist together.\n\nVisit the following resources to learn more:",
"description": "Sequelize is an easy-to-use and promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite, DB2, Microsoft SQL Server, and Snowflake. It features solid transaction support, relations, eager and lazy loading, read replication and more.\n\nWhat is an ORM ?\n\nAn ORM is known as Object Relational Mapper. This is a tool or a level of abstraction which maps(converts) data in a relational database into programmatic objects that can be manipulated by a programmer using a programming language (usually an OOP language). ORMs solely exist to map the details between two data sources which due to a mismatch cannot coexist together.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Sequelize Website",
"title": "Sequelize",
"url": "https://sequelize.org/",
"type": "article"
},
@ -1694,7 +1730,7 @@
"type": "article"
},
{
"title": "Official Sequelize Docs",
"title": "Sequelize Docs",
"url": "https://sequelize.org/docs/v6/getting-started/",
"type": "article"
},
@ -1715,12 +1751,12 @@
"description": "Prisma is an ORM that helps app developers build faster and make fewer errors. Combined with its Data Platform developers gain reliability and visibility when working with databases.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Prisma Website",
"title": "Prisma",
"url": "https://www.prisma.io/",
"type": "article"
},
{
"title": "Prisma Official Documentations",
"title": "Prisma Documentation",
"url": "https://www.prisma.io/docs/",
"type": "article"
},
@ -1733,21 +1769,15 @@
},
"KpC-QYKalUp7VUvnMKBoW": {
"title": "Native Drivers",
"description": "NativeDriver is an implementation of the WebDriver API which drives the UI of a native application rather than a web application. It extends the WebDriver API in a few key places, and re-interprets the existing API for native applications.\n\n* MySQL:\n * [mysql](https://www.npmjs.com/package/mysql)\n * [mysql2](https://www.npmjs.com/package/mysql2)\n* MariaDB:\n * [mariadb](https://www.npmjs.com/package/mariadb)\n* PostgreSQL:\n * [pg](https://www.npmjs.com/package/pg)\n* Microsoft SQL Server:\n * [tedious](https://www.npmjs.com/package/tedious)\n * [mssql](https://www.npmjs.com/package/mssql)\n* Oracle:",
"links": [
{
"title": "oracledb",
"url": "https://www.npmjs.com/package/oracledb",
"type": "article"
}
]
"description": "NativeDriver is an implementation of the WebDriver API which drives the UI of a native application rather than a web application. It extends the WebDriver API in a few key places, and re-interprets the existing API for native applications.",
"links": []
},
"90NIFfbWjTbyKZKwyJlfI": {
"title": "Testing",
"description": "Software testing is the process of verifying that what we create is doing exactly what we expect it to do. The tests are created to prevent bugs and improve code quality.\n\nThe two most common testing approaches are unit testing and end-to-end testing. In the first, we examine small snippets of code, in the second, we test an entire user flow.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Wikipedia - Software Testing",
"title": "Software Testing",
"url": "https://en.wikipedia.org/wiki/Software_testing",
"type": "article"
},
@ -1768,7 +1798,7 @@
"description": "Vitest is a Vite-native unit testing framework that's Jest-compatible. Vitest is a powerful testing library built on top of Vite that is growing in popularity. You can use Vitest for a range of testing needs, such as unit, integration, end-to-end (E2E), snapshot, and performance testing of functions and components. ESM, TypeScript, JSX. Out-of-box ESM, TypeScript and JSX support powered by esbuild. Vitest is free and open source.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Website",
"title": "Vitest",
"url": "https://vitest.dev/",
"type": "article"
},
@ -1781,7 +1811,7 @@
},
"oSLpy31XEcA2nRq9ks_LJ": {
"title": "node:test",
"description": "`node:test` is a built-in module in Node.js that provides a simple, asynchronous test runner. It's designed to make writing tests as straightforward as writing any other code.\n\nKey Features\n------------\n\n* Simplicity: Easy to use and understand.\n* Asynchronous Support: Handles asynchronous code gracefully.\n* Subtests: Allows for organizing tests into hierarchical structures.\n* Hooks: Provides beforeEach and afterEach hooks for setup and teardown.\n\nVisit the following resources to learn more:",
"description": "`node:test` is a built-in module in Node.js that provides a simple, asynchronous test runner. It's designed to make writing tests as straightforward as writing any other code.\n\nKey Features\n\n* Simplicity: Easy to use and understand.\n* Asynchronous Support: Handles asynchronous code gracefully.\n* Subtests: Allows for organizing tests into hierarchical structures.\n* Hooks: Provides beforeEach and afterEach hooks for setup and teardown.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Test Runner API Docs",
@ -1800,7 +1830,7 @@
"description": "Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Jest Website",
"title": "Jest",
"url": "https://jestjs.io",
"type": "article"
},
@ -1821,7 +1851,7 @@
"description": "Playwright is an open-source automation library developed by Microsoft for testing and automating web applications. 1 It offers a unified API to control Chromium, Firefox, and WebKit browsers, making it a versatile choice for cross-browser testing.\n\nPlaywright provides a high-level API to interact with web pages. You can write scripts to simulate user actions, such as clicking buttons, filling forms, and navigating through different pages. Playwright handles the underlying browser interactions, making it easy to write and maintain tests.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Playwright Website",
"title": "Playwright",
"url": "https://playwright.dev/",
"type": "article"
},
@ -1842,7 +1872,7 @@
"description": "Cypress is a new front end testing tool built for the modern web. It enables you to write faster, easier and more reliable tests.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Cypress Website",
"title": "Cypress",
"url": "https://www.cypress.io/",
"type": "article"
},
@ -1889,8 +1919,8 @@
"description": "winston is designed to be a simple and universal logging library with support for multiple transports. A transport is essentially a storage device for your logs. Each winston logger can have multiple transports configured at different levels. For example, one may want error logs to be stored in a persistent remote location (like a database), but all logs output to the console or a local file.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "winston Website",
"url": "https://github.com/winstonjs/winston",
"title": "winston",
"url": "https://github.com/winstonjs/winston?tab=readme-ov-file#readme",
"type": "opensource"
},
{
@ -1905,12 +1935,12 @@
"description": "Morgan is a NodeJS and express.js middleware to log the HTTP request and error, simplifying the debugging process. It provides flexibility in defining the format of log messages and helps override the output destination for your logs.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Official Website",
"title": "morgan package",
"url": "https://www.npmjs.com/package/morgan",
"type": "article"
},
{
"title": "How to use Morgan|DigitalOcean",
"title": "How to Use Morgan | DigitalOcean",
"url": "https://www.digitalocean.com/community/tutorials/nodejs-getting-started-morgan",
"type": "article"
}
@ -1921,7 +1951,7 @@
"description": "PM2 lets you run your nodejs scripts forever. In the event that your application crashes, PM2 will also restart it for you.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Keep a node application constantly running",
"title": "Keep a Node Application Constantly Running",
"url": "https://devtut.github.io/nodejs/keep-a-node-application-constantly-running.html#use-pm2-as-a-process-manager",
"type": "article"
},
@ -1937,12 +1967,12 @@
"description": "PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Pm2 Website",
"title": "Pm2",
"url": "https://pm2.keymetrics.io/",
"type": "article"
},
{
"title": "Pm2 Official Documentations",
"title": "Pm2 Documentations",
"url": "https://pm2.keymetrics.io/docs/usage/quick-start/",
"type": "article"
}
@ -1996,7 +2026,7 @@
"description": "Worker thread is a continuous parallel thread that runs and accepts messages until it is explicitly closed or terminated. With worker threads, we can achieve a much efficient application without creating a deadlock situation. Workers, unlike children's processes, can exchange memory.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Worker Threads Docs",
"title": "Worker Threads",
"url": "https://nodejs.org/api/worker_threads.html#worker-threads",
"type": "article"
}
@ -2007,7 +2037,7 @@
"description": "Streams are a type of data handling methods and are used to read, write or transform chunks of data piece by piece without keeping it in memory all at once. There are four types of streams in Node.js.\n\n* **Readable**: streams from which data can be read.\n* **Writable**: streams to which we can write data.\n* **Duplex**: streams that are both Readable and Writable.\n* **Transform**: streams that can modify or transform the data as it is written and read.\n\nMultiple streams can be chained together using `pipe()` method.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Stream API Official Documentation",
"title": "Stream API Documentation",
"url": "https://nodejs.org/api/stream.html",
"type": "article"
},
@ -2030,7 +2060,7 @@
},
"ZLNUuDKhJ03Kw7xMVc7IR": {
"title": "Debugging",
"description": "Debugging is a concept to identify and remove errors from software applications. Here, we will learn about the technique to debug a Node.js application.\n\nWhy not to use console.log() for debugging?\n-------------------------------------------\n\nUsing `console.log` to debug the code generally dives into an infinite loop of “stopping the app and adding a console.log, and start the app again” operations. Besides slowing down the development of the app, it also makes the writing dirty and creates unnecessary code. Finally, trying to log out variables alongside with the noise of other potential logging operations, may make the process of debugging difficult when attempting to find the values you are debugging.\n\nVisit the following resources to learn more:",
"description": "Debugging is a concept to identify and remove errors from software applications. Here, we will learn about the technique to debug a Node.js application.\n\nWhy not to use `console.log()` for debugging?\n\nUsing `console.log` to debug the code generally dives into an infinite loop of “stopping the app and adding a console.log, and start the app again” operations. Besides slowing down the development of the app, it also makes the writing dirty and creates unnecessary code. Finally, trying to log out variables alongside with the noise of other potential logging operations, may make the process of debugging difficult when attempting to find the values you are debugging.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Wikipedia - What is Debugging?",
@ -2049,17 +2079,17 @@
"description": "Memory leaks are caused when your Node.js app’s CPU and memory usage increases over time for no apparent reason. In simple terms, a Node.js memory leak is an orphan block of memory on the Heap that is no longer used by your app because it has not been released by the garbage collector. It’s a useless block of memory. These blocks can grow over time and lead to your app crashing because it runs out of memory.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Memory leaks in Node.js",
"title": "Memory Leaks in Node.js",
"url": "https://sematext.com/blog/nodejs-memory-leaks/",
"type": "article"
},
{
"title": "Memory leaks causes",
"title": "Memory Leaks Causes",
"url": "https://sematext.com/blog/nodejs-memory-leaks/#what-causes-them-common-node-js-memory-leaks",
"type": "article"
},
{
"title": "Memory leaks detectors",
"title": "Memory Leaks Detectors",
"url": "https://sematext.com/blog/nodejs-memory-leaks/#node-js-memory-leak-detectors",
"type": "article"
},
@ -2118,52 +2148,52 @@
"description": "These are the core modules that come with `Node.js` out of the box. This module provides tools or APIs for performing out certain standard `Node.js` operations. like interacting with the file system, url parsing, or logging information to the console.\n\nLearn more from the following resources:",
"links": [
{
"title": "Nodejs fs module",
"title": "fs module",
"url": "https://nodejs.org/api/fs.html",
"type": "article"
},
{
"title": "Nodejs url module",
"title": "url module",
"url": "https://nodejs.org/api/url.html",
"type": "article"
},
{
"title": "Nodejs console module",
"title": "console module",
"url": "https://nodejs.org/api/console.html",
"type": "article"
},
{
"title": "Nodejs util module",
"title": "util module",
"url": "https://nodejs.org/api/util.html",
"type": "article"
},
{
"title": "Nodejs events module",
"title": "events module",
"url": "https://nodejs.org/api/events.html",
"type": "article"
},
{
"title": "Nodejs os module",
"title": "os module",
"url": "https://nodejs.org/api/os.html",
"type": "article"
},
{
"title": "Nodejs worker threads module",
"title": "worker threads module",
"url": "https://nodejs.org/api/worker_threads.html",
"type": "article"
},
{
"title": "Nodejs child process module",
"title": "child process module",
"url": "https://nodejs.org/api/child_process.html",
"type": "article"
},
{
"title": "Nodejs process object",
"title": "process object",
"url": "https://nodejs.org/api/process.html",
"type": "article"
},
{
"title": "Nodejs crypto module",
"title": "crypto module",
"url": "https://nodejs.org/api/crypto.html",
"type": "article"
}

@ -780,8 +780,8 @@
"description": "Object-Relational Mapping (ORM) is a popular technique used with PHP to convert data between incompatible type systems using an object-oriented programming language. Essentially, it saves PHP developers time by enabling them to work with databases using OOP standards and avoid writing long SQL queries. One commonly used ORM in PHP is Doctrine. For instance, to save data into a products table, you don't use SQL but OOP-style code:\n\n $product = new Product();\n $product->setName('New Product');\n $entityManager->persist($product);\n $entityManager->flush();\n \n\nVisit the following resources to learn more:",
"links": [
{
"title": "Object Relational Mapping (ORM)",
"url": "https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/tutorials/getting-started.html",
"title": "What is an Object Relational Mapping (ORM)",
"url": "https://stackoverflow.com/questions/1279613/what-is-an-orm-how-does-it-work-and-how-should-i-use-one#answer-1279678",
"type": "article"
}
]

@ -251,11 +251,6 @@
"title": "What is the Relational Model?",
"url": "https://www.postgresql.org/docs/7.1/relmodel-oper.html",
"type": "article"
},
{
"title": "The Relational Model",
"url": "https://www.geeksforgeeks.org/relational-model-in-dbms/",
"type": "article"
}
]
},
@ -456,7 +451,7 @@
},
{
"title": "Query Processing in PostgreSQL",
"url": "https://medium.com/agedb/query-processing-in-postgresql-1309fa93f69f",
"url": "https://www.interdb.jp/pg/pgsql03.html",
"type": "article"
}
]
@ -2631,7 +2626,7 @@
]
},
"xEu5n6U9-WKVxjlT5YUgx": {
"title": "Tenser",
"title": "Tensor",
"description": "Tensor Query Language (TQL) is a specialized SQL-like language designed for querying and managing datasets stored as tensors, primarily used within the Deep Lake platform. TQL extends traditional SQL capabilities to support multidimensional array operations, making it particularly useful for data science and machine learning workflows. Key features include array arithmetic, user-defined functions, and integration with deep learning frameworks like PyTorch and TensorFlow, allowing for efficient data manipulation and analysis directly within these environments.\n\nTQL enables users to perform complex queries on datasets, including operations like embedding search, array slicing, and custom numeric computations. This flexibility supports a wide range of applications, from simple data retrieval to sophisticated data preprocessing steps needed for training machine learning models. The language also integrates with version control, allowing users to manage and query different versions of their datasets seamlessly.\n\nLearn more from the following resources:",
"links": [
{

@ -126,7 +126,7 @@
},
"-DJgS6l2qngfwurExlmmT": {
"title": "Functions, Builtin Functions",
"description": "In programming, a function is a reusable block of code that executes a certain functionality when it is called. Functions are integral parts of every programming language because they help make your code more modular and reusable. In Python, we define a function with the `def` keyword, then write the function identifier (name) followed by parentheses and a colon.\n\nExample\n-------\n\n def greet(name):\n print(f\"Hello, {name}!\")\n \n greet(\"Roadmap.sh\") \n \n\nVisit the following resources to learn more:",
"description": "In programming, a function is a reusable block of code that executes a certain functionality when it is called. Functions are integral parts of every programming language because they help make your code more modular and reusable. In Python, we define a function with the `def` keyword, then write the function identifier (name) followed by parentheses and a colon.\n\nExample\n-------\n\n def greet(name):\n print(f\"Hello, {name}!\")\n \n \n greet(\"Roadmap.sh\")\n \n\nVisit the following resources to learn more:",
"links": [
{
"title": "Built-in Functions in Python",
@ -243,11 +243,6 @@
"title": "Loops",
"description": "Loops are used to execute a block of code repeatedly.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Loops in Python",
"url": "https://www.geeksforgeeks.org/loops-in-python/",
"type": "article"
},
{
"title": "Python \"while\" Loops (Indefinite Iteration)",
"url": "https://realpython.com/python-while-loop/",
@ -705,11 +700,6 @@
"title": "Python Inheritance",
"url": "https://www.w3schools.com/python/python_inheritance.asp",
"type": "article"
},
{
"title": "Inheritance in Python",
"url": "https://www.javatpoint.com/inheritance-in-python",
"type": "article"
}
]
},

@ -97,11 +97,6 @@
"title": "TestLink",
"url": "https://testlink.org/",
"type": "article"
},
{
"title": "TestLink Tutorial: A Complete Guide",
"url": "https://www.guru99.com/testlink-tutorial-complete-guide.html",
"type": "article"
}
]
},
@ -550,24 +545,8 @@
},
"XCeXiKvBblmDArfbWjDvw": {
"title": "Regression Testing",
"description": "Regression Testing is a type of software testing to confirm that a recent program or code change has not adversely affected existing features. Regression testing is a black box testing technique. Test cases are re-executed to check the previous functionality of the application is working fine and that the new changes have not produced any bugs.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Regression Testing",
"url": "https://www.javatpoint.com/regression-testing",
"type": "article"
},
{
"title": "What is Regression Testing with Test Cases",
"url": "https://www.guru99.com/regression-testing.html",
"type": "article"
},
{
"title": "Explore top posts about Testing",
"url": "https://app.daily.dev/tags/testing?ref=roadmapsh",
"type": "article"
}
]
"description": "Regression Testing is a type of software testing to confirm that a recent program or code change has not adversely affected existing features. Regression testing is a black box testing technique. Test cases are re-executed to check the previous functionality of the application is working fine and that the new changes have not produced any bugs.",
"links": []
},
"MVShii4LZiWW_gPTJzkty": {
"title": "Smoke Testing",
@ -674,11 +653,6 @@
"url": "https://www.guru99.com/agile-scrum-extreme-testing.html",
"type": "article"
},
{
"title": "Agile Model",
"url": "https://www.javatpoint.com/software-engineering-agile-model",
"type": "article"
},
{
"title": "Manifesto for Agile Software Development",
"url": "https://agilemanifesto.org/",
@ -759,11 +733,6 @@
"url": "https://www.guru99.com/manual-testing.html",
"type": "article"
},
{
"title": "Manual Testing",
"url": "https://www.javatpoint.com/manual-testing",
"type": "article"
},
{
"title": "Explore top posts about QA",
"url": "https://app.daily.dev/tags/qa?ref=roadmapsh",
@ -1562,11 +1531,6 @@
"title": "Accessibility Tests",
"description": "In software QA, accessibility testing is the practice of confirming that an application is usable for as many people as possible, including people with disabilities such as vision impairment, hearing problems and cognitive conditions.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Accessibility Testing - Javatpoint",
"url": "https://www.javatpoint.com/accessibility-testing",
"type": "article"
},
{
"title": "Explore top posts about Accessibility",
"url": "https://app.daily.dev/tags/accessibility?ref=roadmapsh",

@ -732,11 +732,6 @@
"title": "Redis Lists",
"url": "https://redis.io/docs/latest/develop/data-types/lists/",
"type": "article"
},
{
"title": "Complete Guide to Redis Lists",
"url": "https://www.geeksforgeeks.org/complete-guide-to-redis-lists/",
"type": "article"
}
]
},
@ -976,11 +971,6 @@
"title": "Redis Pipelining",
"url": "https://redis.io/docs/latest/develop/use/pipelining/",
"type": "article"
},
{
"title": "Complete Guide to Redis Pipelining",
"url": "https://www.geeksforgeeks.org/complete-guide-to-redis-pipelining/",
"type": "article"
}
]
},

@ -61,28 +61,88 @@
},
"1GML0Jsfdb1Fn-0PNryiQ": {
"title": "Congestion Control",
"description": "",
"links": []
"description": "**Congestion control** is a fundamental mechanism in `TCP` that prevents excessive data transmission from overwhelming the network, ensuring stable and efficient communication. In server-side game development, congestion control helps maintain smooth gameplay by dynamically adjusting the data flow based on network conditions. `TCP` employs various congestion control algorithms, such as `Reno`, `CUBIC`, and `BBR`, to detect congestion and reduce packet loss. These algorithms regulate the senders transmission rate using strategies like slow start, congestion avoidance, and fast recovery. Proper tuning of congestion control mechanisms is critical for minimizing lag, preventing packet drops, and optimizing multiplayer game performance, especially in high-traffic scenarios.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Congestion Control in Linux TCP",
"url": "https://www.usenix.org/conference/2002-usenix-annual-technical-conference/congestion-control-linux-tcp",
"type": "article"
}
]
},
"X2KHWgQZDHSVDsTRMUwSj": {
"title": "Reliable Transmission",
"description": "",
"links": []
"description": "**Reliable transmission** ensures that data sent over a network reaches its destination accurately and in the correct order, a critical requirement for server-side game development. `TCP` achieves this through mechanisms like acknowledgments (ACKs), sequence numbers, and retransmission strategies. When a packet is lost or corrupted, `TCP` retransmits it using algorithms such as automatic repeat request (ARQ) and fast retransmit. Additionally, flow control and congestion control work together to prevent data loss due to network congestion. Reliable transmission is essential for maintaining synchronization in multiplayer games, preventing desynchronization issues, and ensuring a smooth gaming experience.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Reliable Transmission",
"url": "https://book.systemsapproach.org/direct/reliable.html",
"type": "article"
},
{
"title": "TCP Reliable Transmission (IETF RFC 793)",
"url": "https://datatracker.ietf.org/doc/html/rfc793",
"type": "article"
}
]
},
"lDVD-3i64Mk7-KPJrXmFH": {
"title": "Flow Control",
"description": "",
"links": []
"description": "**Flow control** is a crucial mechanism in `TCP` that regulates data transmission between a sender and a receiver to prevent network congestion and packet loss. In server-side game development, effective flow control ensures smooth data transfer, reducing latency and improving real-time responsiveness for multiplayer games. `TCP` uses techniques like sliding window protocols, where the receiver dictates how much data it can handle at a time, preventing buffer overflows. Additionally, congestion control algorithms like `TCP Reno` and `CUBIC` help dynamically adjust transmission rates based on network conditions. Proper flow control tuning is essential for maintaining stable connections, minimizing lag, and optimizing server performance in high-traffic gaming environments.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "How Flow Control is Achieved in TCP?",
"url": "https://datatracker.ietf.org/doc/html/rfc5681",
"type": "article"
},
{
"title": "Flow Control vs. Congestion Control in TCP",
"url": "https://www.baeldung.com/cs/tcp-flow-control-vs-congestion-control",
"type": "article"
},
{
"title": "TCP Flow Control",
"url": "https://www.sanfoundry.com/computer-network-tcp-flow-control/",
"type": "article"
}
]
},
"vFM311xSa5OqNVove2f6j": {
"title": "Error Detection",
"description": "",
"links": []
"description": "**Error detection** ensures data integrity in `TCP-based` communication, preventing corrupted or altered packets from disrupting server-side game interactions. `TCP` uses checksums to verify data integrity, detecting bit errors during transmission. If an error is found, the corrupted packet is discarded, and retransmission is requested via acknowledgments (ACKs). Additional mechanisms such as cyclic redundancy check (CRC) and parity checks may be used in lower network layers to enhance reliability. Effective error detection minimizes data corruption in multiplayer games, ensuring smooth gameplay and synchronization across players.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Error Detection Code – Checksum",
"url": "https://www.geeksforgeeks.org/error-detection-code-checksum/",
"type": "article"
},
{
"title": "Error Control in TCP",
"url": "https://www.cisco.com/c/en/us/support/docs/ip/tcp/13733-40.html",
"type": "article"
}
]
},
"w6ysmcsBn9jJ8xMvg7hcD": {
"title": "Max Segment Size",
"description": "",
"links": []
"description": "**Max Segment Size (MSS)** is a crucial concept in `TCP` networking, representing the largest amount of data that can be sent in a single `TCP` segment, excluding the `TCP` header. `MSS` is vital for optimizing performance in server-side game development, as it helps to avoid fragmentation and ensures that data is transmitted efficiently over the network. By adjusting the `MSS`, game servers can minimize packet fragmentation, which can lead to increased latency and reduced throughput. Typically, `MSS` is determined during the `TCP` handshake based on the maximum transmission unit (MTU) of the network, and it can be configured to suit the needs of specific applications or networks. Optimizing `MSS` can improve the overall reliability and performance of data transfers, especially in multiplayer games where real-time communication and high throughput are essential.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "RFC 879 - Maximum Segment Size",
"url": "https://tools.ietf.org/html/rfc879",
"type": "article"
},
{
"title": "What is MSS (maximum segment size)?",
"url": "https://www.cloudflare.com/learning/network-layer/what-is-mss/",
"type": "article"
},
{
"title": "TCP Maximum Segment Size tuning",
"url": "https://www.ibm.com/docs/en/aix/7.2?topic=tuning-tcp-maximum-segment-size",
"type": "article"
}
]
},
"MwLWDlciJOq_0n5S3GoF-": {
"title": "Vulnerability",
@ -387,8 +447,14 @@
},
"DYvzGc_r0SlOArPPc1gNI": {
"title": "Semaphore",
"description": "",
"links": []
"description": "**Semaphores** are crucial synchronization mechanisms in server-side game development, ensuring controlled access to shared resources and preventing race conditions. They are widely used for managing concurrent processes, such as limiting the number of active players in a session, regulating access to database connections, and synchronizing threads in physics or AI computations. By using semaphores, developers can optimize performance by preventing resource starvation and contention. Implementing them correctly requires careful handling to avoid deadlocks and ensure efficient thread scheduling. Commonly used in conjunction with mutexes and condition variables, semaphores help maintain stability in high-performance multiplayer environments.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Semaphores in Process Synchronization",
"url": "https://www.geeksforgeeks.org/semaphores-in-process-synchronization/",
"type": "article"
}
]
},
"zbIbPlqTNSbJUkqH9iLQv": {
"title": "Future & Promises",
@ -397,13 +463,40 @@
},
"o0Y_hM0KXUApfsXG4PvOY": {
"title": "Coroutine",
"description": "",
"links": []
"description": "**Coroutines** are lightweight, cooperative multitasking constructs that enable efficient asynchronous programming in server-side game development. Unlike traditional threads, coroutines allow functions to be paused and resumed without blocking the entire execution thread, making them ideal for handling game logic, networking, and AI behavior with minimal overhead. They work seamlessly with future & promise mechanisms, simplifying concurrency management by avoiding callback hell and reducing synchronization complexity. Coroutines are widely supported in modern languages like C++ (via `std::coroutine`), Python (`asyncio`), and Kotlin, offering game developers an efficient way to write non-blocking code while maintaining readability and performance.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "C++ Coroutines (cppreference)",
"url": "https://en.cppreference.com/w/cpp/language/coroutines",
"type": "article"
},
{
"title": "Python Coroutines and Tasks",
"url": "https://docs.python.org/3/library/asyncio-task.html",
"type": "article"
}
]
},
"SXOEMkcVYBsRza6BPmmwy": {
"title": "Channel",
"description": "",
"links": []
"description": "A **channel** is a synchronization primitive used to communicate between concurrent tasks or threads, particularly in asynchronous programming. In server-side game development, channels are frequently used to manage data flow between different components, such as game logic, network communication, and I/O operations. `Channels` provide a thread-safe way to pass messages or data between coroutines or threads without the need for complex locks, reducing the chances of race conditions. This makes them ideal for handling tasks like event propagation, message passing, or coordinating actions in multiplayer game servers. `Channels` often work in conjunction with futures and promises to efficiently manage concurrency and improve overall game performance.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Go Channel Documentation",
"url": "https://golang.org/doc/effective_go.html#channels",
"type": "article"
},
{
"title": "Rust Channels for Concurrency",
"url": "https://doc.rust-lang.org/book/ch16-02-message-passing.html",
"type": "article"
},
{
"title": "Comprehensive Guide to Channel",
"url": "https://elixir-lang.org/getting-started/processes.html#using-processes-and-messages",
"type": "article"
}
]
},
"xR6pERldq4wPl9GVLHAhT": {
"title": "Condition Variable",
@ -597,23 +690,67 @@
},
"5-5toy2CblZPCV9d5QPEo": {
"title": "select",
"description": "",
"links": []
"description": "**select** is a multiplexing system call in Linux used for monitoring multiple file descriptors to check if they are ready for I/O operations. It is commonly used in server-side game development for handling multiple connections asynchronously. However, `select` has limitations, as it scans all file descriptors linearly, making it inefficient for handling a large number of concurrent connections. Despite its drawbacks, it remains useful for simpler applications or legacy systems. Modern alternatives like `epoll` or `kqueue` offer better performance and scalability.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Linux select API",
"url": "https://man7.org/linux/man-pages/man2/select.2.html",
"type": "article"
},
{
"title": "select vs epoll vs poll",
"url": "https://devarea.com/linux-io-multiplexing-select-vs-poll-vs-epoll/",
"type": "article"
}
]
},
"D9Yeyn8phDhB1ohMWccgr": {
"title": "WSA Poll",
"description": "",
"links": []
"description": "**WSA-Poll** is a Windows-specific alternative to `poll`, used for monitoring multiple sockets for readiness in non-blocking network applications. It is commonly utilized in server-side game development to handle multiple client connections efficiently. Unlike `select`, `WSA-Poll` eliminates the limitation of FD\\_SETSIZE, allowing it to scale better for a larger number of connections. However, it is generally less efficient than `epoll` on Linux due to its linear scanning mechanism. For high-performance game servers on Windows, IOCP (I/O Completion Ports) is often preferred over `WSA-Poll`.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Microsoft WSA-Poll Documentation",
"url": "https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsapoll",
"type": "article"
}
]
},
"qaWv4gxnnj3uX8lEm9KQ4": {
"title": "epoll",
"description": "",
"links": []
"description": "**epoll** is a high-performance I/O event notification system in Linux, essential for handling large-scale asynchronous network operations in server-side game development. Unlike `select` or `poll`, it uses an event-driven model, reducing CPU overhead and improving scalability. Game servers leverage `epoll` to efficiently manage thousands of concurrent connections, responding only when events occur, minimizing system calls, and optimizing resource usage—making it ideal for multiplayer games and real-time applications.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Linux epoll API",
"url": "https://man7.org/linux/man-pages/man7/epoll.7.html",
"type": "article"
},
{
"title": "Understanding epoll for Scalable Network Servers",
"url": "https://medium.com/@copyconstruct/the-method-to-epolls-madness-d9d2d6378642",
"type": "article"
},
{
"title": "epoll vs select vs poll",
"url": "https://devarea.com/linux-io-multiplexing-select-vs-poll-vs-epoll/",
"type": "article"
}
]
},
"caK32NMMrn-3BGAXZoPPr": {
"title": "kqueue",
"description": "",
"links": []
"description": "**kqueue** is an efficient event notification system available on BSD-based operating systems, including macOS and FreeBSD. It is designed to handle large numbers of concurrent connections with minimal CPU overhead, making it well-suited for server-side game development. Similar to `epoll` on Linux, `kqueue` operates in an event-driven manner, allowing game servers to efficiently manage network events, timers, and file system changes. By reducing unnecessary polling and system calls, `kqueue` helps improve the scalability and responsiveness of multiplayer game servers, ensuring low-latency interactions and optimized resource usage.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "FreeBSD kqueue Documentation",
"url": "https://man.freebsd.org/cgi/man.cgi?query=kqueue",
"type": "article"
},
{
"title": "macOS kqueue API Reference",
"url": "https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/kqueue.2.html",
"type": "article"
}
]
},
"Tvxe2NemcH21y-eB4bosv": {
"title": "Proactor",
@ -622,18 +759,41 @@
},
"7pgdOZomhGilBTwfJLMbm": {
"title": "IOCP",
"description": "",
"links": []
"description": "**I/O Completion Ports (IOCP)** is a high-performance asynchronous I/O mechanism in Windows, designed to efficiently handle large numbers of concurrent network connections. It is widely used in server-side game development to optimize networking performance, making it ideal for MMORPGs and real-time multiplayer games. Unlike `select` or `WSA-Poll`, IOCP uses a thread pool and a queue-based event system to process completed I/O operations asynchronously, minimizing CPU overhead and improving scalability. By leveraging IOCP, game servers can efficiently handle thousands of connections with minimal latency, making it the preferred choice for high-performance Windows-based game networking.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Microsoft IOCP Documentation",
"url": "https://learn.microsoft.com/en-us/windows/win32/fileio/i-o-completion-ports",
"type": "article"
}
]
},
"YH7u1FKh85wz78J0stuzS": {
"title": "io_uring",
"description": "",
"links": []
"description": "**io\\_uring** is a modern asynchronous I/O framework introduced in Linux 5.1, designed to provide high-performance, low-latency I/O operations. It is widely used in server-side game development to efficiently handle network and disk operations, making it ideal for real-time multiplayer games. Unlike `epoll` or traditional polling mechanisms, `io_uring` minimizes system calls by using a shared memory ring buffer between the kernel and user space, reducing context switching overhead. This results in improved scalability and responsiveness, allowing game servers to handle thousands of concurrent connections with minimal CPU usage.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Linux io_uring_enter",
"url": "https://man7.org/linux/man-pages/man2/io_uring_enter.2.html",
"type": "article"
},
{
"title": "Efficient Networking with io_uring",
"url": "https://lwn.net/Articles/776703/",
"type": "article"
}
]
},
"94hJX1iGifDzIuaU3zU5j": {
"title": "Registered IO",
"description": "",
"links": []
"description": "**Registered I/O** is an optimization technique that enhances the performance of asynchronous I/O operations by pre-registering resources such as file descriptors, memory buffers, or network sockets with the operating system. This reduces the overhead of repeated system calls and resource management, making it highly beneficial for server-side game development, where low-latency and high-throughput are critical. Technologies like `io_uring` and Windows `RIO (Registered I/O)` API leverage this approach to minimize kernel interactions, improving efficiency for handling large-scale multiplayer game servers. By reducing context switching and memory allocation overhead, Registered I/O helps game servers achieve smoother performance and lower latency.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Microsoft Registered I/O (RIO)",
"url": "https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/hh997032(v=ws.11)",
"type": "article"
}
]
},
"LKPcEeqBOPhQOztD3cM3T": {
"title": "Task-Based",

@ -38,14 +38,8 @@
},
"2sR4KULvAUUoOtopvsEBs": {
"title": "Levels of Architecture",
"description": "Architecture can be done on several “levels” of abstractions. The level influences the importance of necessary skills. As there are many categorizations possible my favorite segmentation includes these 3 levels:\n\n* **Application Level:** The lowest level of architecture. Focus on one single application. Very detailed, low level design. Communication is usually within one development team.\n* **Solution Level:** The mid-level of architecture. Focus on one or more applications which fulfill a business need (business solution). Some high, but mainly low-level design. Communication is between multiple development teams.\n* **Enterprise Level:** The highest level of architecture. Focus on multiple solutions. High level, abstract design, which needs to be detailed out by solution or application architects. Communication is across the organization.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Software Engineering Architecture",
"url": "https://www.geeksforgeeks.org/software-engineering-architectural-design/",
"type": "article"
}
]
"description": "Architecture can be done on several “levels” of abstractions. The level influences the importance of necessary skills. As there are many categorizations possible my favorite segmentation includes these 3 levels:\n\n* **Application Level:** The lowest level of architecture. Focus on one single application. Very detailed, low level design. Communication is usually within one development team.\n* **Solution Level:** The mid-level of architecture. Focus on one or more applications which fulfill a business need (business solution). Some high, but mainly low-level design. Communication is between multiple development teams.\n* **Enterprise Level:** The highest level of architecture. Focus on multiple solutions. High level, abstract design, which needs to be detailed out by solution or application architects. Communication is across the organization.",
"links": []
},
"Lqe47l4j-C4OwkbkwPYry": {
"title": "Application Architecture",
@ -103,14 +97,8 @@
},
"lBtlDFPEQvQ_xtLtehU0S": {
"title": "Important Skills to Learn",
"description": "To support the laid-out activities specific skills are required. From my experience, read books and discussions we can boil this down to these ten skills every software architect should have:\n\n* Design\n* Decide\n* Simplify\n* Code\n* Document\n* Communicate\n* Estimate\n* Balance\n* Consult\n* Market\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Software Architect Skills",
"url": "https://www.geeksforgeeks.org/software-architects-skills/",
"type": "article"
}
]
"description": "To support the laid-out activities specific skills are required. From my experience, read books and discussions we can boil this down to these ten skills every software architect should have:\n\n* Design\n* Decide\n* Simplify\n* Code\n* Document\n* Communicate\n* Estimate\n* Balance\n* Consult\n* Market",
"links": []
},
"fBd2m8tMJmhuNSaakrpg4": {
"title": "Design & Architecture",
@ -854,14 +842,8 @@
},
"SuMhTyaBS9vwASxAt39DH": {
"title": "Tools",
"description": "Architect tools are software tools that help architects to design, document, and manage software architectures. These tools can be used to create architecture diagrams, generate code, and automate the software development process.\n\nVisit the following resources to learn more:",
"links": [
{
"title": "Top 10 Software Architecture Tools in 2024",
"url": "https://www.geeksforgeeks.org/software-architecture-tools/",
"type": "article"
}
]
"description": "Architect tools are software tools that help architects to design, document, and manage software architectures. These tools can be used to create architecture diagrams, generate code, and automate the software development process.",
"links": []
},
"OaLmlfkZid7hKqJ9G8oNV": {
"title": "Architecture",
@ -1856,11 +1838,6 @@
"url": "https://www.fortinet.com/resources/cyberglossary/tcp-ip#:~:text=The%20TCP%2FIP%20model%20defines,exchanged%20and%20organized%20over%20networks.",
"type": "article"
},
{
"title": "TCP/IP Model",
"url": "https://www.geeksforgeeks.org/tcp-ip-model/",
"type": "article"
},
{
"title": "What is TCP/IP and How Does it Work?",
"url": "https://www.techtarget.com/searchnetworking/definition/TCP-IP",

@ -21,12 +21,7 @@
"links": [
{
"title": "Advantages and Disadvantages of DBMS",
"url": "https://www.javatpoint.com/advantages-and-disadvantages-of-dbms",
"type": "article"
},
{
"title": "ACID Transactions in Databases",
"url": "https://www.databricks.com/glossary/acid-transactions",
"url": "https://cloud.google.com/learn/what-is-a-relational-database",
"type": "article"
}
]
@ -947,11 +942,6 @@
"title": "CEILING",
"description": "The `CEILING()` function in SQL returns the smallest integer greater than or equal to a given numeric value. It's useful when you need to round up a number to the nearest whole number, regardless of whether the number is already an integer or a decimal. For example, `CEILING(4.2)` would return `5`, and `CEILING(-4.7)` would return `-4`. This function is commonly used in scenarios where rounding up is necessary, such as calculating the number of pages needed to display a certain number of items when each page has a fixed capacity.\n\nLearn more from the following resources:",
"links": [
{
"title": "CEILING Function in SQL",
"url": "https://www.javatpoint.com/ceiling-function-in-sql",
"type": "article"
},
{
"title": "SQL CEILING",
"url": "https://www.w3schools.com/sql/func_sqlserver_ceiling.asp",

@ -670,7 +670,7 @@
},
"RNITLR1FUQWkRbSBXTD_z": {
"title": "Write-through",
"description": "The application uses the cache as the main data store, reading and writing data to it, while the cache is responsible for reading and writing to the database:\n\n* Application adds/updates entry in cache\n* Cache synchronously writes entry to data store\n* Return\n\nApplication code:\n\n set_user(12345, {\"foo\":\"bar\"})\n \n\nCache code:\n\n def set_user(user_id, values):\n user = db.query(\"UPDATE Users WHERE id = {0}\", user_id, values)\n cache.set(user_id, user)\n \n\nWrite-through is a slow overall operation due to the write operation, but subsequent reads of just written data are fast. Users are generally more tolerant of latency when updating data than reading data. Data in the cache is not stale.\n\nDisadvantages\n-------------\n\n* When a new node is created due to failure or scaling, the new node will not cache entries until the entry is updated in the database. Cache-aside in conjunction with write through can mitigate this issue.\n* Most data written might never be read, which can be minimized with a TTL.\n\n![Write through](https://i.imgur.com/Ujf0awN.png)\n\nHave a look at the following resources to learn more:",
"description": "The application uses the cache as the main data store, reading and writing data to it, while the cache is responsible for reading and writing to the database:\n\n* Application adds/updates entry in cache\n* Cache synchronously writes entry to data store\n* Return\n\nApplication code:\n\n set_user(12345, {\"foo\": \"bar\"})\n \n\nCache code:\n\n def set_user(user_id, values):\n user = db.query(\"UPDATE Users WHERE id = {0}\", user_id, values)\n cache.set(user_id, user)\n \n\nWrite-through is a slow overall operation due to the write operation, but subsequent reads of just written data are fast. Users are generally more tolerant of latency when updating data than reading data. Data in the cache is not stale.\n\nDisadvantages\n-------------\n\n* When a new node is created due to failure or scaling, the new node will not cache entries until the entry is updated in the database. Cache-aside in conjunction with write through can mitigate this issue.\n* Most data written might never be read, which can be minimized with a TTL.\n\n![Write through](https://i.imgur.com/Ujf0awN.png)\n\nHave a look at the following resources to learn more:",
"links": [
{
"title": "Scalability, availability, stability, patterns",
@ -1839,11 +1839,6 @@
"title": "Geode pattern",
"url": "https://learn.microsoft.com/en-us/azure/architecture/patterns/geodes",
"type": "article"
},
{
"title": "Geode Formation, Types & Appearance | What is a Geode?",
"url": "https://study.com/academy/lesson/geode-formation-types-appearance.html",
"type": "article"
}
]
},

@ -652,14 +652,8 @@
},
"lvtTSHH9yBTCiLng8btnI": {
"title": "Hybrid Types",
"description": "In TypeScript, a hybrid type is a type that combines multiple types into a single type. The resulting type is considered a union of those types. This allows you to specify that a value can have multiple types, rather than just one.\n\nFor example, you can create a hybrid type that can accept either a string or a number:\n\n type StringOrNumber = string | number;\n \n\nYou can also use hybrid types to create more complex types that can represent a combination of several different types of values. For example:\n\n type Education = {\n degree: string;\n school: string;\n year: number;\n };\n \n type User = {\n name: string;\n age: number;\n email: string;\n education: Education;\n };\n \n\nLearn more from the following links:",
"links": [
{
"title": "Geeksforgeeks.org - Hybrid Types",
"url": "https://www.geeksforgeeks.org/what-are-hybrid-types-in-typescript/#:~:text=Hybrid%20types%20are%20a%20combination,properties%20like%20a%20regular%20object.",
"type": "article"
}
]
"description": "In TypeScript, a hybrid type is a type that combines multiple types into a single type. The resulting type is considered a union of those types. This allows you to specify that a value can have multiple types, rather than just one.\n\nFor example, you can create a hybrid type that can accept either a string or a number:\n\n type StringOrNumber = string | number;\n \n\nYou can also use hybrid types to create more complex types that can represent a combination of several different types of values. For example:\n\n type Education = {\n degree: string;\n school: string;\n year: number;\n };\n \n type User = {\n name: string;\n age: number;\n email: string;\n education: Education;\n };",
"links": []
},
"ib0jfZzukYOZ42AdJqt_W": {
"title": "Classes",
@ -1033,11 +1027,6 @@
"title": "External Modules",
"description": "In TypeScript, external modules allow you to organize and share code across multiple files. External modules in TypeScript follow the CommonJS or ES modules standards.\n\nHere's an example of how you can use external modules in TypeScript:\n\n // myModule.ts\n export function doSomething() {\n console.log('Doing something...');\n }\n \n // main.ts\n import { doSomething } from './myModule';\n doSomething(); // Output: \"Doing something...\"\n \n\nIn this example, we use the \"export\" keyword in the \"myModule.ts\" file to export the \"doSomething\" function, making it available for other files to use.\n\nLearn more from the following links:",
"links": [
{
"title": "External Module",
"url": "https://www.javatpoint.com/typescript-module",
"type": "article"
},
{
"title": "TypeScript - External Module",
"url": "https://learncodeweb.com/typescript/modules-in-typescript-explain-with-an-example/",

@ -573,11 +573,6 @@
"title": "Binding Events",
"url": "https://vuejs.org/guide/essentials/event-handling",
"type": "article"
},
{
"title": "Vue.js Event Handling",
"url": "https://www.geeksforgeeks.org/vue-js-event-handling/",
"type": "article"
}
]
},

Binary file not shown.

Before

Width:  |  Height:  |  Size: 257 KiB

After

Width:  |  Height:  |  Size: 786 KiB

@ -18,3 +18,16 @@ export function aiRoadmapApi(context: APIContext) {
},
};
}
export interface AICourseDocument {
_id: string;
userId: string;
title: string;
slug?: string;
keyword: string;
difficulty: string;
data: string;
viewCount: number;
createdAt: Date;
updatedAt: Date;
}

@ -27,7 +27,7 @@ const sidebarLinks = [
href: '/account/update-profile',
title: 'Profile',
id: 'profile',
isNew: true,
isNew: false,
icon: {
glyph: 'user',
classes: 'h-4 w-4',
@ -56,7 +56,7 @@ const sidebarLinks = [
},
{
href: '/account/road-card',
title: 'Card',
title: 'Road Card',
id: 'road-card',
isNew: false,
icon: {
@ -64,6 +64,16 @@ const sidebarLinks = [
classes: 'h-4 w-4',
},
},
{
href: '/account/billing',
title: 'Billing',
id: 'billing',
isNew: true,
icon: {
glyph: 'credit-card',
classes: 'h-4 w-4',
},
},
{
href: '/account/settings',
title: 'Settings',
@ -97,7 +107,7 @@ const sidebarLinks = [
}`}
>
<AstroIcon icon={'users'} class={`h-4 w-4 mr-2`} />
Teams
Teams
</a>
</li>
{

@ -1,5 +1,4 @@
import { getUser } from '../../lib/jwt';
import { getPercentage } from '../../helper/number';
import { ProjectProgressActions } from './ProjectProgressActions';
import { cn } from '../../lib/classname';
import type { ProjectStatusDocument } from '../Projects/ListProjectSolutions';

@ -1,7 +1,7 @@
import { getUser } from '../../lib/jwt';
import { getPercentage } from '../../helper/number';
import { ResourceProgressActions } from './ResourceProgressActions';
import { cn } from '../../lib/classname';
import { getPercentage } from '../../lib/number';
type ResourceProgressType = {
resourceType: 'roadmap' | 'best-practice';

@ -0,0 +1,109 @@
<script async src='https://securepubads.g.doubleclick.net/tag/js/gpt.js'
></script>
<script async>
const ignoredPages = [
'login',
'signup',
'best-practices',
'guides',
'videos',
'roadmaps',
'community',
'start-here',
'ai-roadmaps',
'ai',
'teams',
'about',
'account',
'projects',
'questions',
'guides',
'advertise',
];
function sanitizeSettingValue(value) {
return (
String(value)
.trim()
// Remove characters forbidden at https://support.google.com/admanager/answer/10020177.
.replace(/'|\\|'|=|!|#|\*|~|;|\^|\(|\)|<|>|\[|\]|,|&/g, '')
// Extra spaces aren't forbidden, but rarely desired.
.replace(/\s+/, ' ')
// The + sign is also forbidden, but is being replaced with 'and' instead.
.replace('+', 'and')
// Maximum length of 40 for values.
.substring(0, 40)
);
}
const page = window.location.pathname;
const pageParts = page.split('/').filter(Boolean);
const isRoadmapPage =
pageParts.length === 1 && !ignoredPages.includes(pageParts[0]);
const isBestPracticesPage =
pageParts.length === 2 && pageParts[0] === 'best-practices';
let adSettings = {};
if (isRoadmapPage) {
adSettings = {
post_id: sanitizeSettingValue(pageParts[0]),
page_type: 'roadmap',
category: ['roadmap', sanitizeSettingValue(pageParts[0])],
};
} else if (isBestPracticesPage) {
adSettings = {
post_id: sanitizeSettingValue(pageParts[1]),
page_type: 'best-practice',
category: ['best-practice', sanitizeSettingValue(pageParts[1])],
};
}
// @ts-nocheck
window.googletag = window.googletag || { cmd: [] };
googletag.cmd.push(function () {
// Always use non-personalized ads
googletag.pubads().setPrivacySettings({
restrictDataProcessing: true,
nonPersonalizedAds: true,
});
// Define ad slot and enable services
googletag
.defineSlot(
'/22873384501/roadmap',
['fluid'],
'div-gpt-ad-1742391132948-0',
)
.addService(googletag.pubads());
// Set targeting for all ad slots on the page.
for (let key in adSettings) {
if (adSettings.hasOwnProperty(key)) {
googletag.pubads().setTargeting(key, adSettings[key]);
}
}
googletag.pubads().enableSingleRequest();
googletag.enableServices();
googletag.pubads().addEventListener('slotRenderEnded', function (e) {
if (!e.isEmpty) {
return;
}
const slotId = e.slot.getSlotElementId();
if (!slotId) {
return;
}
// If empty, hide the ad slot after a small delay.
setTimeout(() => {
const adContainer = document.getElementById(slotId);
if (adContainer) {
adContainer.style.display = 'none';
}
}, 1800);
});
});
</script>

@ -0,0 +1,59 @@
<div
id='div-gpt-ad-1742391132948-0'
class='gam-slot fixed bottom-4 right-4 z-50 h-[160px] w-[350px] cursor-pointer max-md:bottom-0 max-md:right-0 max-md:h-[106px] max-md:w-full'
>
<script>
// @ts-nocheck
googletag.cmd.push(function () {
if (!googletag.pubads) {
console.log('googletag.pubads not found');
return;
}
// Configure all ad slots on the page to be expanded by default, but
// collapse slots that are unable to be filled with an ad.
googletag.pubads().collapseEmptyDivs();
// Set non-personalized ads
googletag.pubads().setPrivacySettings({
restrictDataProcessing: true,
nonPersonalizedAds: true,
});
googletag.display('div-gpt-ad-1742391132948-0');
});
</script>
</div>
<script>
const nativeAds: Window[] = [];
function sendSize(iframe: Window) {
const breakpoint = window.innerWidth < 768 ? 'sm' : 'lg';
iframe.postMessage(`breakpoint:${breakpoint}`, '*');
}
window.addEventListener(
'resize',
() => {
nativeAds.forEach((ad) => {
sendSize(ad);
});
},
{
passive: true,
},
);
window.addEventListener('message', function (e: MessageEvent<any>) {
if (e.data === 'initdfp') {
nativeAds.push(e.source as Window);
sendSize(e.source as Window);
} else if (e.data === 'close-ad') {
const ad = document.getElementById('div-gpt-ad-1742391132948-0');
if (ad) {
ad.remove();
}
}
});
</script>

@ -0,0 +1,19 @@
<script>
// @ts-nocheck
!(function (w, d) {
if (!w.rdt) {
var p = (w.rdt = function () {
p.sendEvent
? p.sendEvent.apply(p, arguments)
: p.callQueue.push(arguments);
});
p.callQueue = [];
var t = d.createElement('script');
(t.src = 'https://www.redditstatic.com/ads/pixel.js'), (t.async = !0);
var s = d.getElementsByTagName('script')[0];
s.parentNode.insertBefore(t, s);
}
})(window, document);
rdt('init', 'a2_ghq8846qpphp');
rdt('track', 'PageVisit');
</script>

@ -18,7 +18,7 @@ async function getSVG(name: string) {
throw new Error(`${filepath} not found`);
}
const root = parse(files[filepath].default as string);
const root = parse((files[filepath] as any).default as string);
const svg = root.querySelector('svg');

@ -81,7 +81,7 @@ export function CourseLoginPopup(props: CourseLoginPopupProps) {
<Modal onClose={onClose} bodyClassName="p-5 h-auto">
<div className="mb-7 text-center">
<p className="mb-3.5 pt-2 text-2xl font-semibold leading-5 text-slate-900">
Create or login to your account
Create or login to Enroll
</p>
<p className="mt-2 text-sm leading-4 text-slate-600">
Login or sign up for an account to start learning

@ -1,6 +1,11 @@
import { type FormEvent, useEffect, useState } from 'react';
import { httpPost } from '../../lib/http';
import { deleteUrlParam, getUrlParams } from '../../lib/browser';
import {
deleteUrlParam,
getLastPath,
getUrlParams,
urlToId,
} from '../../lib/browser';
import { isLoggedIn, setAIReferralCode } from '../../lib/jwt';
type EmailSignupFormProps = {
@ -34,6 +39,7 @@ export function EmailSignupForm(props: EmailSignupFormProps) {
email,
password,
name,
src: urlToId(getLastPath() || window.location.pathname),
},
);

@ -9,7 +9,7 @@ import { cn } from '../../lib/classname.ts';
import { httpGet } from '../../lib/http';
import { Spinner } from '../ReactIcons/Spinner.tsx';
import { CHECKOUT_AFTER_LOGIN_KEY } from './CourseLoginPopup.tsx';
import { triggerUtmRegistration } from '../../lib/browser.ts';
import { getLastPath, triggerUtmRegistration, urlToId } from '../../lib/browser.ts';
type GitHubButtonProps = {
isDisabled?: boolean;
@ -38,10 +38,12 @@ export function GitHubButton(props: GitHubButtonProps) {
setIsLoading(true);
setIsDisabled?.(true);
const lastPageBeforeGithub = localStorage.getItem(GITHUB_LAST_PAGE);
httpGet<{ token: string; isNewUser: boolean }>(
`${import.meta.env.PUBLIC_API_URL}/v1-github-callback${
window.location.search
}`,
}&src=${urlToId(lastPageBeforeGithub || getLastPath() || window.location.pathname)}`,
)
.then(({ response, error }) => {
if (!response?.token) {
@ -57,7 +59,6 @@ export function GitHubButton(props: GitHubButtonProps) {
let redirectUrl = new URL('/', window.location.origin);
const gitHubRedirectAt = localStorage.getItem(GITHUB_REDIRECT_AT);
const lastPageBeforeGithub = localStorage.getItem(GITHUB_LAST_PAGE);
// If the social redirect is there and less than 30 seconds old
// redirect to the page that user was on before they clicked the github login button
@ -127,9 +128,12 @@ export function GitHubButton(props: GitHubButtonProps) {
// For non authentication pages, we want to redirect back to the page
// the user was on before they clicked the social login button
if (!['/login', '/signup'].includes(window.location.pathname)) {
const pagePath = ['/respond-invite', '/befriend', '/r', '/ai'].includes(
window.location.pathname,
)
const pagePath = [
'/respond-invite',
'/befriend',
'/r',
'/ai-roadmaps',
].includes(window.location.pathname)
? window.location.pathname + window.location.search
: window.location.pathname;

@ -1,19 +1,11 @@
import { useEffect, useState } from 'react';
import Cookies from 'js-cookie';
import {
FIRST_LOGIN_PARAM,
TOKEN_COOKIE_NAME,
setAuthToken,
} from '../../lib/jwt';
import { FIRST_LOGIN_PARAM, setAuthToken } from '../../lib/jwt';
import { httpGet } from '../../lib/http';
import { COURSE_PURCHASE_PARAM } from '../../lib/jwt';
import { GoogleIcon } from '../ReactIcons/GoogleIcon.tsx';
import { Spinner } from '../ReactIcons/Spinner.tsx';
import { CHECKOUT_AFTER_LOGIN_KEY } from './CourseLoginPopup.tsx';
import {
getStoredUtmParams,
triggerUtmRegistration,
} from '../../lib/browser.ts';
import { triggerUtmRegistration, urlToId, getLastPath } from '../../lib/browser.ts';
import { cn } from '../../lib/classname.ts';
type GoogleButtonProps = {
@ -43,10 +35,12 @@ export function GoogleButton(props: GoogleButtonProps) {
setIsLoading(true);
setIsDisabled?.(true);
const lastPageBeforeGoogle = localStorage.getItem(GOOGLE_LAST_PAGE);
httpGet<{ token: string; isNewUser: boolean }>(
`${import.meta.env.PUBLIC_API_URL}/v1-google-callback${
window.location.search
}`,
}&src=${urlToId(lastPageBeforeGoogle || getLastPath() || window.location.pathname)}`,
)
.then(({ response, error }) => {
if (!response?.token) {
@ -61,7 +55,6 @@ export function GoogleButton(props: GoogleButtonProps) {
let redirectUrl = new URL('/', window.location.origin);
const googleRedirectAt = localStorage.getItem(GOOGLE_REDIRECT_AT);
const lastPageBeforeGoogle = localStorage.getItem(GOOGLE_LAST_PAGE);
// If the social redirect is there and less than 30 seconds old
// redirect to the page that user was on before they clicked the github login button
@ -132,7 +125,7 @@ export function GoogleButton(props: GoogleButtonProps) {
'/respond-invite',
'/befriend',
'/r',
'/ai',
'/ai-roadmaps',
].includes(window.location.pathname)
? window.location.pathname + window.location.search
: window.location.pathname;

@ -1,9 +1,7 @@
import { useEffect, useState } from 'react';
import Cookies from 'js-cookie';
import {
FIRST_LOGIN_PARAM,
COURSE_PURCHASE_PARAM,
TOKEN_COOKIE_NAME,
setAuthToken,
} from '../../lib/jwt';
import { cn } from '../../lib/classname.ts';
@ -11,7 +9,7 @@ import { httpGet } from '../../lib/http';
import { LinkedInIcon } from '../ReactIcons/LinkedInIcon.tsx';
import { Spinner } from '../ReactIcons/Spinner.tsx';
import { CHECKOUT_AFTER_LOGIN_KEY } from './CourseLoginPopup.tsx';
import { triggerUtmRegistration } from '../../lib/browser.ts';
import { getLastPath, triggerUtmRegistration, urlToId } from '../../lib/browser.ts';
type LinkedInButtonProps = {
isDisabled?: boolean;
@ -40,10 +38,12 @@ export function LinkedInButton(props: LinkedInButtonProps) {
setIsLoading(true);
setIsDisabled?.(true);
const lastPageBeforeLinkedIn = localStorage.getItem(LINKEDIN_LAST_PAGE);
httpGet<{ token: string; isNewUser: boolean }>(
`${import.meta.env.PUBLIC_API_URL}/v1-linkedin-callback${
window.location.search
}`,
}&src=${urlToId(lastPageBeforeLinkedIn || getLastPath() || window.location.pathname)}`,
)
.then(({ response, error }) => {
if (!response?.token) {
@ -58,7 +58,6 @@ export function LinkedInButton(props: LinkedInButtonProps) {
let redirectUrl = new URL('/', window.location.origin);
const linkedInRedirectAt = localStorage.getItem(LINKEDIN_REDIRECT_AT);
const lastPageBeforeLinkedIn = localStorage.getItem(LINKEDIN_LAST_PAGE);
// If the social redirect is there and less than 30 seconds old
// redirect to the page that user was on before they clicked the github login button
@ -131,7 +130,7 @@ export function LinkedInButton(props: LinkedInButtonProps) {
'/respond-invite',
'/befriend',
'/r',
'/ai',
'/ai-roadmaps',
].includes(window.location.pathname)
? window.location.pathname + window.location.search
: window.location.pathname;

@ -7,7 +7,7 @@ import { AuthenticationForm } from './AuthenticationForm';
<Popup id='login-popup' title='' subtitle=''>
<div class='mb-7 text-center'>
<p class='mb-3 text-2xl font-semibold leading-5 text-slate-900'>
Login to your account
Login or Signup
</p>
<p class='mt-2 text-sm leading-4 text-slate-600'>
You must be logged in to perform this action.

@ -0,0 +1,226 @@
import { useEffect, useState } from 'react';
import { pageProgressMessage } from '../../stores/page';
import { useToast } from '../../hooks/use-toast';
import { useMutation, useQuery } from '@tanstack/react-query';
import {
billingDetailsOptions,
USER_SUBSCRIPTION_PLAN_PRICES,
} from '../../queries/billing';
import { queryClient } from '../../stores/query-client';
import { httpPost } from '../../lib/query-http';
import { UpgradeAccountModal } from './UpgradeAccountModal';
import { getUrlParams } from '../../lib/browser';
import { VerifyUpgrade } from './VerifyUpgrade';
import { EmptyBillingScreen } from './EmptyBillingScreen';
import {
Calendar,
RefreshCw,
Loader2,
CreditCard,
ArrowRightLeft,
CircleX,
} from 'lucide-react';
import { BillingWarning } from './BillingWarning';
export type CreateCustomerPortalBody = {};
export type CreateCustomerPortalResponse = {
url: string;
};
export function BillingPage() {
const toast = useToast();
const [showUpgradeModal, setShowUpgradeModal] = useState(false);
const [showVerifyUpgradeModal, setShowVerifyUpgradeModal] = useState(false);
const { data: billingDetails, isPending: isLoadingBillingDetails } = useQuery(
billingDetailsOptions(),
queryClient,
);
const isCanceled =
billingDetails?.status === 'canceled' || billingDetails?.cancelAtPeriodEnd;
const isPastDue = billingDetails?.status === 'past_due';
const {
mutate: createCustomerPortal,
isSuccess: isCreatingCustomerPortalSuccess,
isPending: isCreatingCustomerPortal,
} = useMutation(
{
mutationFn: (body: CreateCustomerPortalBody) => {
return httpPost<CreateCustomerPortalResponse>(
'/v1-create-customer-portal',
body,
);
},
onSuccess: (data) => {
window.location.href = data.url;
},
onError: (error) => {
console.error(error);
toast.error(error?.message || 'Failed to Create Customer Portal');
},
},
queryClient,
);
useEffect(() => {
if (isLoadingBillingDetails) {
return;
}
pageProgressMessage.set('');
const shouldVerifyUpgrade = getUrlParams()?.s === '1';
if (shouldVerifyUpgrade) {
setShowVerifyUpgradeModal(true);
}
}, [isLoadingBillingDetails]);
if (isLoadingBillingDetails || !billingDetails) {
return null;
}
const selectedPlanDetails = USER_SUBSCRIPTION_PLAN_PRICES.find(
(plan) => plan.priceId === billingDetails?.priceId,
);
const priceDetails = selectedPlanDetails;
const formattedNextBillDate = new Date(
billingDetails?.currentPeriodEnd || '',
).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
return (
<>
{showUpgradeModal && (
<UpgradeAccountModal
onClose={() => {
setShowUpgradeModal(false);
}}
success="/account/billing?s=1"
cancel="/account/billing"
/>
)}
{showVerifyUpgradeModal && <VerifyUpgrade />}
{billingDetails?.status === 'none' && !isLoadingBillingDetails && (
<EmptyBillingScreen onUpgrade={() => setShowUpgradeModal(true)} />
)}
{billingDetails?.status !== 'none' &&
!isLoadingBillingDetails &&
priceDetails && (
<div className="mt-1">
{isCanceled && (
<BillingWarning
icon={CircleX}
message="Your subscription has been canceled."
buttonText="Reactivate?"
onButtonClick={() => {
createCustomerPortal({});
}}
isLoading={
isCreatingCustomerPortal || isCreatingCustomerPortalSuccess
}
/>
)}
{isPastDue && (
<BillingWarning
message="We were not able to charge your card."
buttonText="Update payment information."
onButtonClick={() => {
createCustomerPortal({});
}}
isLoading={
isCreatingCustomerPortal || isCreatingCustomerPortalSuccess
}
/>
)}
<h2 className="mb-2 text-xl font-semibold text-black">
Current Subscription
</h2>
<p className="text-sm text-gray-500">
Thank you for being a pro member. Your plan details are below.
</p>
<div className="mt-8 flex flex-col gap-6 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-center gap-4">
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-gray-100">
<RefreshCw className="size-5 text-gray-600" />
</div>
<div>
<span className="text-xs uppercase tracking-wider text-gray-400">
Payment
</span>
<h3 className="flex items-baseline text-lg font-semibold text-black">
${priceDetails.amount}
<span className="ml-1 text-sm font-normal text-gray-500">
/ {priceDetails.interval}
</span>
</h3>
</div>
</div>
</div>
<div className="mt-6 border-t border-gray-100 pt-6">
<div className="flex items-start gap-4">
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-gray-100">
<Calendar className="size-5 text-gray-600" />
</div>
<div>
<span className="text-xs uppercase tracking-wider text-gray-400">
{billingDetails?.cancelAtPeriodEnd
? 'Expires On'
: 'Renews On'}
</span>
<h3 className="text-lg font-semibold text-black">
{formattedNextBillDate}
</h3>
</div>
</div>
<div className="mt-8 flex gap-3 max-sm:flex-col">
{!isCanceled && (
<button
className="inline-flex items-center justify-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm transition-colors hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2 max-sm:flex-grow"
onClick={() => {
setShowUpgradeModal(true);
}}
>
<ArrowRightLeft className="mr-2 h-4 w-4" />
Switch Plan
</button>
)}
<button
className="inline-flex items-center justify-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm transition-colors hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
onClick={() => {
createCustomerPortal({});
}}
disabled={
isCreatingCustomerPortal || isCreatingCustomerPortalSuccess
}
>
{isCreatingCustomerPortal ||
isCreatingCustomerPortalSuccess ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<CreditCard className="mr-2 h-4 w-4" />
)}
Manage Subscription
</button>
</div>
</div>
</div>
)}
</>
);
}

@ -0,0 +1,39 @@
import { AlertTriangle, type LucideIcon } from 'lucide-react';
export type BillingWarningProps = {
icon?: LucideIcon;
message: string;
onButtonClick?: () => void;
buttonText?: string;
isLoading?: boolean;
};
export function BillingWarning(props: BillingWarningProps) {
const {
message,
onButtonClick,
buttonText,
isLoading,
icon: Icon = AlertTriangle,
} = props;
return (
<div className="mb-6 flex items-center gap-2 rounded-lg border border-red-300 bg-red-50 p-4 text-sm text-red-600">
<Icon className="h-5 w-5" />
<span>
{message}
{buttonText && (
<button
disabled={isLoading}
onClick={() => {
onButtonClick?.();
}}
className="font-semibold underline underline-offset-4 disabled:cursor-not-allowed disabled:opacity-50 ml-0.5"
>
{buttonText}
</button>
)}
</span>
</div>
);
}

@ -0,0 +1,22 @@
import { useEffect, useState } from 'react';
import { getUrlParams } from '../../lib/browser';
import { VerifyUpgrade } from "./VerifyUpgrade";
export function CheckSubscriptionVerification() {
const [shouldVerifyUpgrade, setShouldVerifyUpgrade] = useState(false);
useEffect(() => {
const params = getUrlParams();
if (params.s !== '1') {
return;
}
setShouldVerifyUpgrade(true);
}, []);
if (!shouldVerifyUpgrade) {
return null;
}
return <VerifyUpgrade />;
}

@ -0,0 +1,68 @@
import {
CreditCard,
Ellipsis,
HeartHandshake,
MessageCircleIcon,
SparklesIcon,
Zap,
} from 'lucide-react';
type EmptyBillingScreenProps = {
onUpgrade: () => void;
};
const perks = [
{
icon: Zap,
text: 'Unlimited AI course generations',
},
{
icon: MessageCircleIcon,
text: 'Unlimited AI Chat feature usage',
},
{
icon: SparklesIcon,
text: 'Early access to new features',
},
{
icon: HeartHandshake,
text: 'Support the development of platform',
},
{
icon: Ellipsis,
text: 'more perks coming soon!',
},
];
export function EmptyBillingScreen(props: EmptyBillingScreenProps) {
const { onUpgrade } = props;
return (
<div className="mt-12 flex h-full w-full flex-col items-center">
<CreditCard className="mb-3 h-12 w-12 text-gray-300" />
<h3 className="mb-3 text-xl font-semibold text-black">
No Active Subscription
</h3>
<p className="text-balance text-gray-700">
Unlock pro benefits by upgrading to a subscription
</p>
<div className="my-8 flex flex-col gap-2">
{perks.map((perk) => (
<p className="textsm flex items-center text-gray-600" key={perk.text}>
<perk.icon className="mr-2 h-4 w-4 text-gray-500" />
{perk.text}
</p>
))}
</div>
<button
onClick={onUpgrade}
className="inline-flex items-center justify-center rounded-lg bg-black px-6 py-2.5 text-sm font-medium text-white transition-colors hover:opacity-80 focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2"
>
Upgrade Account
</button>
</div>
);
}

@ -0,0 +1,96 @@
import { useMutation } from '@tanstack/react-query';
import type { USER_SUBSCRIPTION_PLAN_PRICES } from '../../queries/billing';
import { Modal } from '../Modal';
import { queryClient } from '../../stores/query-client';
import { useToast } from '../../hooks/use-toast';
import { VerifyUpgrade } from './VerifyUpgrade';
import { Loader2Icon } from 'lucide-react';
import { httpPost } from '../../lib/query-http';
type UpdatePlanBody = {
priceId: string;
};
type UpdatePlanResponse = {
status: 'ok';
};
type UpdatePlanConfirmationProps = {
planDetails: (typeof USER_SUBSCRIPTION_PLAN_PRICES)[number];
onClose: () => void;
onCancel: () => void;
};
export function UpdatePlanConfirmation(props: UpdatePlanConfirmationProps) {
const { planDetails, onClose, onCancel } = props;
const toast = useToast();
const {
mutate: updatePlan,
isPending,
status,
} = useMutation(
{
mutationFn: (body: UpdatePlanBody) => {
return httpPost<UpdatePlanResponse>(
'/v1-update-subscription-plan',
body,
);
},
onError: (error) => {
console.error(error);
toast.error(error?.message || 'Failed to Create Customer Portal');
},
},
queryClient,
);
if (!planDetails) {
return null;
}
const selectedPrice = planDetails;
if (status === 'success') {
return <VerifyUpgrade newPriceId={selectedPrice.priceId} />;
}
return (
<Modal
onClose={isPending ? () => {} : onClose}
bodyClassName="rounded-xl bg-white p-6"
>
<h3 className="text-xl font-bold text-black">Subscription Update</h3>
<p className="mt-2 text-balance text-gray-600">
Your plan will be updated to the{' '}
<b className="text-black">{planDetails.interval}</b> plan, and will
be charged{' '}
<b className="text-black">
${selectedPrice.amount}/{selectedPrice.interval}
</b>
.
</p>
<div className="mt-6 grid grid-cols-2 gap-3">
<button
className="rounded-md border border-gray-200 py-2 text-sm font-semibold hover:bg-gray-50 transition-colors disabled:opacity-50"
onClick={onCancel}
disabled={isPending}
>
Cancel
</button>
<button
className="flex items-center justify-center rounded-md bg-purple-600 py-2 text-sm font-semibold text-white hover:bg-purple-500 transition-colors disabled:opacity-50"
disabled={isPending}
onClick={() => {
updatePlan({ priceId: selectedPrice.priceId });
}}
>
{isPending && (
<Loader2Icon className="size-4 animate-spin stroke-[2.5] mr-2" />
)}
{!isPending && 'Confirm'}
</button>
</div>
</Modal>
);
}

@ -0,0 +1,306 @@
import {
Loader2,
Zap,
Infinity,
MessageSquare,
Sparkles,
Heart,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { getUser } from '../../lib/jwt';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Modal } from '../Modal';
import {
billingDetailsOptions,
USER_SUBSCRIPTION_PLAN_PRICES,
type AllowedSubscriptionInterval,
} from '../../queries/billing';
import { cn } from '../../lib/classname';
import { queryClient } from '../../stores/query-client';
import { httpPost } from '../../lib/query-http';
import { useToast } from '../../hooks/use-toast';
import { UpdatePlanConfirmation } from './UpdatePlanConfirmation';
// Define the perk type
type Perk = {
icon: LucideIcon;
title: string;
description: string;
};
// Define the perks array
const PREMIUM_PERKS: Perk[] = [
{
icon: Zap,
title: 'Unlimited AI Course Generations',
description: 'Generate as many custom courses as you need',
},
{
icon: Infinity,
title: 'No Daily Limits on course features',
description: 'Use all features without restrictions',
},
{
icon: MessageSquare,
title: 'Unlimited Course Follow-ups',
description: 'Ask as many questions as you need',
},
{
icon: Sparkles,
title: 'Early Access to Features',
description: 'Be the first to try new tools and features',
},
{
icon: Heart,
title: 'Support Development',
description: 'Help us continue building roadmap.sh',
},
];
type CreateSubscriptionCheckoutSessionBody = {
priceId: string;
success?: string;
cancel?: string;
};
type CreateSubscriptionCheckoutSessionResponse = {
checkoutUrl: string;
};
type UpgradeAccountModalProps = {
onClose: () => void;
success?: string;
cancel?: string;
};
export function UpgradeAccountModal(props: UpgradeAccountModalProps) {
const { onClose, success, cancel } = props;
const [selectedPlan, setSelectedPlan] =
useState<AllowedSubscriptionInterval>('month');
const [isUpdatingPlan, setIsUpdatingPlan] = useState(false);
const user = getUser();
const {
data: userBillingDetails,
isLoading,
error: billingError,
} = useQuery(billingDetailsOptions(), queryClient);
const toast = useToast();
const {
mutate: createCheckoutSession,
isPending: isCreatingCheckoutSession,
} = useMutation(
{
mutationFn: (body: CreateSubscriptionCheckoutSessionBody) => {
return httpPost<CreateSubscriptionCheckoutSessionResponse>(
'/v1-create-subscription-checkout-session',
body,
);
},
onSuccess: (data) => {
window.location.href = data.checkoutUrl;
},
onError: (error) => {
console.error(error);
toast.error(error?.message || 'Failed to create checkout session');
},
},
queryClient,
);
const selectedPlanDetails = USER_SUBSCRIPTION_PLAN_PRICES.find(
(plan) => plan.interval === selectedPlan,
);
const currentPlanPriceId = userBillingDetails?.priceId;
const currentPlan = USER_SUBSCRIPTION_PLAN_PRICES.find(
(plan) => plan.priceId === currentPlanPriceId,
);
useEffect(() => {
if (!currentPlan) {
return;
}
setSelectedPlan(currentPlan.interval);
}, [currentPlan]);
if (!user) {
return null;
}
const loader = isLoading ? (
<div className="absolute inset-0 flex h-[540px] w-full items-center justify-center bg-white">
<Loader2 className="h-6 w-6 animate-spin stroke-[3px] text-green-600" />
</div>
) : null;
const error = billingError;
const errorContent = error ? (
<div className="flex h-full w-full flex-col">
<p className="text-center text-red-400">
{error?.message ||
'An error occurred while loading the billing details.'}
</p>
</div>
) : null;
const calculateYearlyPrice = (monthlyPrice: number) => {
return (monthlyPrice * 12).toFixed(2);
};
if (isUpdatingPlan && selectedPlanDetails) {
return (
<UpdatePlanConfirmation
planDetails={selectedPlanDetails}
onClose={() => setIsUpdatingPlan(false)}
onCancel={() => setIsUpdatingPlan(false)}
/>
);
}
return (
<Modal
onClose={onClose}
bodyClassName="p-4 sm:p-6 bg-white"
wrapperClassName="h-auto rounded-xl max-w-3xl w-full min-h-[540px] mx-2 sm:mx-4"
overlayClassName="items-start md:items-center"
>
<div onClick={(e) => e.stopPropagation()}>
{errorContent}
{loader}
{!isLoading && !error && (
<div className="flex flex-col">
<div className="mb-6 text-left sm:mb-8">
<h2 className="text-xl font-bold text-black sm:text-2xl">
Unlock Premium Features
</h2>
<p className="mt-1 text-sm text-gray-600 sm:mt-2 sm:text-base">
Supercharge your learning experience with premium benefits
</p>
</div>
<div className="mb-6 grid grid-cols-1 gap-4 sm:mb-8 sm:gap-6 md:grid-cols-2">
{USER_SUBSCRIPTION_PLAN_PRICES.map((plan) => {
const isCurrentPlanSelected =
currentPlan?.priceId === plan.priceId;
const isYearly = plan.interval === 'year';
return (
<div
key={plan.interval}
className={cn(
'flex flex-col space-y-3 rounded-lg bg-white p-4 sm:space-y-4 sm:p-6',
isYearly
? 'border-2 border-yellow-400'
: 'border border-gray-200',
)}
>
<div className="flex items-start justify-between">
<div>
<h4 className="text-sm font-semibold text-black sm:text-base">
{isYearly ? 'Yearly Payment' : 'Monthly Payment'}
</h4>
{isYearly && (
<span className="text-xs font-medium text-green-500 sm:text-sm">
(2 months free)
</span>
)}
</div>
{isYearly && (
<span className="rounded-full bg-yellow-400 px-1.5 py-0.5 text-xs font-semibold text-black sm:px-2 sm:py-1">
Most Popular
</span>
)}
</div>
<div className="flex items-baseline">
{isYearly && (
<p className="mr-2 text-xs text-gray-400 line-through sm:text-sm">
$
{calculateYearlyPrice(
USER_SUBSCRIPTION_PLAN_PRICES[0].amount,
)}
</p>
)}
<p className="text-2xl font-bold text-black sm:text-3xl">
${plan.amount}{' '}
<span className="text-xs font-normal text-gray-500 sm:text-sm">
/ {isYearly ? 'year' : 'month'}
</span>
</p>
</div>
<div className="flex-grow"></div>
<div>
<button
className={cn(
'flex min-h-9 w-full items-center justify-center rounded-md py-2 text-sm font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-yellow-400 disabled:cursor-not-allowed disabled:opacity-60 sm:min-h-11 sm:py-2.5 sm:text-base',
'bg-yellow-400 text-black hover:bg-yellow-500',
)}
disabled={
isCurrentPlanSelected || isCreatingCheckoutSession
}
onClick={() => {
setSelectedPlan(plan.interval);
if (!currentPlanPriceId) {
const currentUrlPath = window.location.pathname;
createCheckoutSession({
priceId: plan.priceId,
success: success || `${currentUrlPath}?s=1`,
cancel: cancel || `${currentUrlPath}?s=0`,
});
return;
}
setIsUpdatingPlan(true);
}}
data-1p-ignore=""
data-form-type="other"
data-lpignore="true"
>
{isCreatingCheckoutSession &&
selectedPlan === plan.interval ? (
<Loader2 className="h-3.5 w-3.5 animate-spin sm:h-4 sm:w-4" />
) : isCurrentPlanSelected ? (
'Current Plan'
) : (
'Select Plan'
)}
</button>
</div>
</div>
);
})}
</div>
{/* Benefits Section */}
<div className="grid grid-cols-1 gap-3 sm:gap-4 md:grid-cols-2">
{PREMIUM_PERKS.map((perk, index) => {
const Icon = perk.icon;
return (
<div key={index} className="flex items-start space-x-2 sm:space-x-3">
<Icon className="mt-0.5 h-4 w-4 text-yellow-500 sm:h-5 sm:w-5" />
<div>
<h4 className="text-sm font-medium text-black sm:text-base">
{perk.title}
</h4>
<p className="text-xs text-gray-600 sm:text-sm">
{perk.description}
</p>
</div>
</div>
);
})}
</div>
</div>
)}
</div>
</Modal>
);
}

@ -0,0 +1,76 @@
import { useEffect } from 'react';
import { Loader2, CheckCircle } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { billingDetailsOptions } from '../../queries/billing';
import { queryClient } from '../../stores/query-client';
import { Modal } from '../Modal';
import { deleteUrlParam } from '../../lib/browser';
type VerifyUpgradeProps = {
newPriceId?: string;
};
export function VerifyUpgrade(props: VerifyUpgradeProps) {
const { newPriceId } = props;
const { data: userBillingDetails } = useQuery(
{
...billingDetailsOptions(),
refetchInterval: 1000,
},
queryClient,
);
useEffect(() => {
if (!userBillingDetails) {
return;
}
if (
userBillingDetails.status === 'active' &&
(newPriceId ? userBillingDetails.priceId === newPriceId : true)
) {
deleteUrlParam('s');
window.location.reload();
}
}, [userBillingDetails]);
return (
<Modal
// it's an unique modal, so we don't need to close it
// user can close it by refreshing the page
onClose={() => {}}
bodyClassName="rounded-xl bg-white p-6"
>
<div className="mb-4 flex flex-col items-center text-center">
<CheckCircle className="mb-3 h-12 w-12 text-green-600" />
<h3 className="text-xl font-bold text-black">Subscription Activated</h3>
</div>
<p className="mt-2 text-balance text-center text-gray-600">
Your subscription has been activated successfully.
</p>
<p className="mt-4 text-balance text-center text-gray-600">
It might take a minute for the changes to reflect. We will{' '}
<b className="text-black">reload</b> the page for you.
</p>
<div className="my-6 flex animate-pulse items-center justify-center gap-2">
<Loader2 className="size-4 animate-spin stroke-[2.5px] text-green-600" />
<span className="text-gray-600">Please wait...</span>
</div>
<p className="text-center text-sm text-gray-500">
If it takes longer than expected, please email us at{' '}
<a
href="mailto:info@roadmap.sh"
className="text-blue-600 underline underline-offset-2 hover:text-blue-700"
>
info@roadmap.sh
</a>
.
</p>
</Modal>
);
}

@ -196,7 +196,6 @@ export function RoadmapHeader(props: RoadmapHeaderProps) {
<RoadmapHint
roadmapTitle={title!}
hasTNSBanner={false}
roadmapId={roadmapId!}
/>
</div>

@ -4,42 +4,19 @@ import { ResourceProgressStats } from './ResourceProgressStats';
type RoadmapHintProps = {
roadmapId: string;
roadmapTitle: string;
hasTNSBanner?: boolean;
tnsBannerLink?: string;
};
export function RoadmapHint(props: RoadmapHintProps) {
const {
roadmapTitle,
roadmapId,
hasTNSBanner = false,
tnsBannerLink = '',
} = props;
const { roadmapTitle, roadmapId } = props;
return (
<div
className={cn('mb-0 mt-4 rounded-md border-0 sm:mt-7 sm:border', {
'sm:-mb-[82px]': hasTNSBanner,
'sm:-mb-[65px]': !hasTNSBanner,
})}
>
{hasTNSBanner && (
<div className="hidden border-b bg-gray-100 px-2 py-1.5 sm:block">
<p className="text-sm">
Get the latest {roadmapTitle} news from our sister site{' '}
<a
href={tnsBannerLink}
target="_blank"
className="font-semibold underline"
>
TheNewStack.io
</a>
</p>
</div>
className={cn(
'mb-0 mt-4 rounded-md border-0 sm:-mb-[65px] sm:mt-7 sm:border',
)}
>
<ResourceProgressStats
isSecondaryBanner={hasTNSBanner}
isSecondaryBanner={false}
resourceId={roadmapId}
resourceType="roadmap"
/>

@ -1,15 +1,6 @@
import type { UserProgress } from '../TeamProgress/TeamProgressPage';
import { DashboardCustomProgressCard } from './DashboardCustomProgressCard';
import { DashboardCardLink } from './DashboardCardLink';
import { useState } from 'react';
import { CreateRoadmapModal } from '../CustomRoadmap/CreateRoadmap/CreateRoadmapModal';
import { Simulate } from 'react-dom/test-utils';
import {
ArrowUpRight,
Bot,
BrainCircuit,
Map,
PencilRuler,
BrainCircuit
} from 'lucide-react';
type DashboardAiRoadmapsProps = {
@ -30,7 +21,7 @@ export function DashboardAiRoadmaps(props: DashboardAiRoadmapsProps) {
<h2 className="text-xs uppercase text-gray-400">My AI Roadmaps</h2>
<a
href="/ai/explore"
href="/ai-roadmaps/explore"
className="rounded-full bg-gray-200 px-2.5 py-0.5 text-xs font-medium text-gray-700 hover:bg-gray-300 hover:text-black"
>
AI Generated Roadmaps
@ -41,7 +32,7 @@ export function DashboardAiRoadmaps(props: DashboardAiRoadmapsProps) {
<DashboardCardLink
className="mt-0"
icon={BrainCircuit}
href="/ai"
href="/ai-roadmaps"
title="Generate Roadmaps with AI"
description="You can generate your own roadmap with AI"
/>
@ -61,7 +52,7 @@ export function DashboardAiRoadmaps(props: DashboardAiRoadmapsProps) {
{roadmaps.map((roadmap) => (
<a
key={roadmap.id}
href={`/ai/${roadmap.slug}`}
href={`/ai-roadmaps/${roadmap.slug}`}
className="relative truncate rounded-md border bg-white p-2.5 text-left text-sm shadow-sm hover:border-gray-400 hover:bg-gray-50"
>
{roadmap.title}
@ -70,7 +61,7 @@ export function DashboardAiRoadmaps(props: DashboardAiRoadmapsProps) {
<a
className="flex items-center justify-center rounded-lg border border-dashed border-gray-300 bg-white p-2.5 text-sm font-medium text-gray-500 hover:bg-gray-50 hover:text-gray-600"
href={'/ai'}
href={'/ai-roadmaps'}
>
+ Generate New
</a>

@ -1,5 +1,5 @@
import { getPercentage } from '../../helper/number';
import { getRelativeTimeString } from '../../lib/date';
import { getPercentage } from '../../lib/number';
import type { UserProgress } from '../TeamProgress/TeamProgressPage';
type DashboardCustomProgressCardProps = {

@ -1,6 +1,5 @@
import { getPercentage } from '../../helper/number';
import { getPercentage } from '../../lib/number';
import type { UserProgress } from '../TeamProgress/TeamProgressPage';
import { ArrowUpRight, ExternalLink } from 'lucide-react';
type DashboardProgressCardProps = {
progress: UserProgress;

@ -3,13 +3,8 @@ import { DashboardCustomProgressCard } from './DashboardCustomProgressCard';
import { DashboardCardLink } from './DashboardCardLink';
import { useState } from 'react';
import { CreateRoadmapModal } from '../CustomRoadmap/CreateRoadmap/CreateRoadmapModal';
import { Simulate } from 'react-dom/test-utils';
import {
ArrowUpRight,
Bot,
BrainCircuit,
Map,
PencilRuler,
BrainCircuit, PencilRuler
} from 'lucide-react';
type ListDashboardCustomProgressProps = {
@ -63,7 +58,7 @@ export function ListDashboardCustomProgress(
<DashboardCardLink
className="mt-0"
icon={BrainCircuit}
href="/ai"
href="/ai-roadmaps"
title="Generate Roadmaps with AI"
description="You can generate your own roadmap with AI"
/>
@ -99,7 +94,7 @@ export function ListDashboardCustomProgress(
<a
className="flex min-h-[80px] items-center justify-center rounded-lg border border-dashed border-gray-300 bg-white p-4 text-sm font-medium text-gray-500 hover:bg-gray-50 hover:text-gray-600"
href={'/ai'}
href={'/ai-roadmaps'}
onClick={(e) => {
if (!isAIGeneratedRoadmaps) {
e.preventDefault();

@ -26,7 +26,7 @@ export function AIRoadmapsList(props: AIRoadmapsListProps) {
return (
<ul className="mb-4 grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
{roadmaps.map((roadmap) => {
const roadmapLink = `/ai/${roadmap.slug}`;
const roadmapLink = `/ai-roadmaps/${roadmap.slug}`;
return (
<a

@ -12,7 +12,7 @@ export function EmptyRoadmaps() {
</p>
<div className="flex flex-col items-center gap-1 sm:flex-row sm:gap-1.5">
<a
href="/ai"
href="/ai-roadmaps"
className="flex w-full items-center gap-1.5 rounded-md bg-gray-900 px-3 py-1.5 text-xs text-white sm:w-auto sm:text-sm"
>
<Wand2 className="h-4 w-4" />

@ -0,0 +1,172 @@
import { SearchIcon, WandIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { cn } from '../../lib/classname';
import { isLoggedIn } from '../../lib/jwt';
import { showLoginPopup } from '../../lib/popup';
import { UserCoursesList } from './UserCoursesList';
import { FineTuneCourse } from './FineTuneCourse';
import {
clearFineTuneData,
getCourseFineTuneData,
getLastSessionId,
storeFineTuneData,
} from '../../lib/ai';
export const difficultyLevels = [
'beginner',
'intermediate',
'advanced',
] as const;
export type DifficultyLevel = (typeof difficultyLevels)[number];
type AICourseProps = {};
export function AICourse(props: AICourseProps) {
const [keyword, setKeyword] = useState('');
const [difficulty, setDifficulty] = useState<DifficultyLevel>('beginner');
const [hasFineTuneData, setHasFineTuneData] = useState(false);
const [about, setAbout] = useState('');
const [goal, setGoal] = useState('');
const [customInstructions, setCustomInstructions] = useState('');
useEffect(() => {
const lastSessionId = getLastSessionId();
if (!lastSessionId) {
return;
}
const fineTuneData = getCourseFineTuneData(lastSessionId);
if (!fineTuneData) {
return;
}
setAbout(fineTuneData.about);
setGoal(fineTuneData.goal);
setCustomInstructions(fineTuneData.customInstructions);
}, []);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && keyword.trim()) {
onSubmit();
}
};
function onSubmit() {
if (!isLoggedIn()) {
showLoginPopup();
return;
}
let sessionId = '';
if (hasFineTuneData) {
clearFineTuneData();
sessionId = storeFineTuneData({
about,
goal,
customInstructions,
});
}
window.location.href = `/ai/search?term=${encodeURIComponent(keyword)}&difficulty=${difficulty}&id=${sessionId}`;
}
return (
<section className="flex flex-grow flex-col bg-gray-100">
<div className="container mx-auto flex max-w-3xl flex-col py-24 max-sm:py-4">
<h1 className="mb-2.5 text-center text-4xl font-bold max-sm:mb-2 max-sm:text-left max-sm:text-xl">
Learn anything with AI
</h1>
<p className="mb-6 text-center text-lg text-gray-600 max-sm:hidden max-sm:text-left max-sm:text-sm">
Enter a topic below to generate a personalized course for it
</p>
<div className="rounded-lg border border-gray-200 bg-white p-6 max-sm:p-4">
<form
className="flex flex-col gap-5"
onSubmit={(e) => {
e.preventDefault();
onSubmit();
}}
>
<div className="flex flex-col">
<label
htmlFor="keyword"
className="mb-2.5 text-sm font-medium text-gray-700"
>
Course Topic
</label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
<SearchIcon size={18} />
</div>
<input
id="keyword"
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="e.g., Algebra, JavaScript, Photography"
className="w-full rounded-md border border-gray-300 bg-white p-3 pl-10 text-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-500 max-sm:placeholder:text-base"
maxLength={50}
/>
</div>
</div>
<div className="flex flex-col">
<label className="mb-2.5 text-sm font-medium text-gray-700">
Difficulty Level
</label>
<div className="flex gap-2 max-sm:flex-col max-sm:gap-1">
{difficultyLevels.map((level) => (
<button
key={level}
type="button"
onClick={() => setDifficulty(level)}
className={cn(
'rounded-md border px-4 py-2 capitalize max-sm:text-sm',
difficulty === level
? 'border-gray-800 bg-gray-800 text-white'
: 'border-gray-200 bg-gray-100 text-gray-700 hover:bg-gray-200',
)}
>
{level}
</button>
))}
</div>
</div>
<FineTuneCourse
hasFineTuneData={hasFineTuneData}
setHasFineTuneData={setHasFineTuneData}
about={about}
goal={goal}
customInstructions={customInstructions}
setAbout={setAbout}
setGoal={setGoal}
setCustomInstructions={setCustomInstructions}
/>
<button
type="submit"
disabled={!keyword.trim()}
className={cn(
'mt-2 flex items-center justify-center rounded-md px-4 py-2 font-medium text-white transition-colors max-sm:text-sm',
!keyword.trim()
? 'cursor-not-allowed bg-gray-400'
: 'bg-black hover:bg-gray-800',
)}
>
<WandIcon size={18} className="mr-2" />
Generate Course
</button>
</form>
</div>
<div className="mt-8 min-h-[200px]">
<UserCoursesList />
</div>
</div>
</section>
);
}

@ -0,0 +1,116 @@
import { MoreVertical, Play, Trash2 } from 'lucide-react';
import { useRef, useState } from 'react';
import { useOutsideClick } from '../../hooks/use-outside-click';
import { useKeydown } from '../../hooks/use-keydown';
import { useToast } from '../../hooks/use-toast';
import { useMutation } from '@tanstack/react-query';
import { queryClient } from '../../stores/query-client';
import { httpDelete } from '../../lib/query-http';
type AICourseActionsType = {
courseSlug: string;
onDeleted?: () => void;
};
export function AICourseActions(props: AICourseActionsType) {
const { courseSlug, onDeleted } = props;
const toast = useToast();
const dropdownRef = useRef<HTMLDivElement>(null);
const [isOpen, setIsOpen] = useState(false);
const [isConfirming, setIsConfirming] = useState(false);
const { mutate: deleteCourse, isPending: isDeleting } = useMutation(
{
mutationFn: async () => {
return httpDelete(`/v1-delete-ai-course/${courseSlug}`);
},
onSuccess: () => {
toast.success('Course deleted');
queryClient.invalidateQueries({
predicate: (query) => query.queryKey?.[0] === 'user-ai-courses',
});
onDeleted?.();
},
onError: (error) => {
toast.error(error?.message || 'Failed to delete course');
},
},
queryClient,
);
useOutsideClick(dropdownRef, () => {
setIsOpen(false);
});
useKeydown('Escape', () => {
setIsOpen(false);
});
return (
<div className="relative h-full" ref={dropdownRef}>
<button
className="h-full text-gray-400 hover:text-gray-700"
onClick={(e) => {
e.stopPropagation();
setIsOpen(!isOpen);
}}
>
<MoreVertical size={16} />
</button>
{isOpen && (
<div className="absolute right-0 top-8 z-10 w-48 overflow-hidden rounded-md border border-gray-200 bg-white shadow-lg">
<a
href={`/ai/${courseSlug}`}
className="flex w-full items-center gap-1.5 p-2 text-sm font-medium text-gray-500 hover:bg-gray-100 hover:text-black disabled:cursor-not-allowed disabled:opacity-70"
>
<Play className="h-3.5 w-3.5" />
Start Course
</a>
{!isConfirming && (
<button
className="flex w-full items-center gap-1.5 p-2 text-sm font-medium text-gray-500 hover:bg-gray-100 hover:text-black disabled:cursor-not-allowed disabled:opacity-70"
onClick={() => setIsConfirming(true)}
disabled={isDeleting}
>
{!isDeleting ? (
<>
<Trash2 className="h-3.5 w-3.5" />
Delete Course
</>
) : (
'Deleting...'
)}
</button>
)}
{isConfirming && (
<span className="flex w-full items-center justify-between gap-1.5 p-2 text-sm font-medium text-gray-500 hover:bg-gray-100 hover:text-black disabled:cursor-not-allowed disabled:opacity-70">
Are you sure?
<div className="flex items-center gap-2">
<button
onClick={() => {
setIsConfirming(false);
deleteCourse();
}}
disabled={isDeleting}
className="text-red-500 underline hover:text-red-800"
>
Yes
</button>
<button
onClick={() => setIsConfirming(false)}
className="text-red-500 underline hover:text-red-800"
>
No
</button>
</div>
</span>
)}
</div>
)}
</div>
);
}

@ -0,0 +1,82 @@
import type { AICourseWithLessonCount } from '../../queries/ai-course';
import type { DifficultyLevel } from './AICourse';
import { BookOpen } from 'lucide-react';
import { AICourseActions } from './AICourseActions';
type AICourseCardProps = {
course: AICourseWithLessonCount;
};
export function AICourseCard(props: AICourseCardProps) {
const { course } = props;
// Format date if available
const formattedDate = course.createdAt
? new Date(course.createdAt).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
})
: null;
// Map difficulty to color
const difficultyColor =
{
beginner: 'text-green-700',
intermediate: 'text-blue-700',
advanced: 'text-purple-700',
}[course.difficulty as DifficultyLevel] || 'text-gray-700';
// Calculate progress percentage
const totalTopics = course.lessonCount || 0;
const completedTopics = course.done?.length || 0;
const progressPercentage =
totalTopics > 0 ? Math.round((completedTopics / totalTopics) * 100) : 0;
return (
<div className="relative">
<a
href={`/ai/${course.slug}`}
className="hover:border-gray-3 00 group relative flex w-full flex-col overflow-hidden rounded-lg border border-gray-200 bg-white p-4 text-left transition-all hover:bg-gray-50"
>
<div className="flex items-center justify-between">
<span
className={`rounded-full text-xs font-medium capitalize opacity-80 ${difficultyColor}`}
>
{course.difficulty}
</span>
</div>
<h3 className="my-2 text-base font-semibold text-gray-900">
{course.title}
</h3>
<div className="mt-auto flex items-center justify-between pt-2">
<div className="flex items-center text-xs text-gray-600">
<BookOpen className="mr-1 h-3.5 w-3.5" />
<span>{totalTopics} lessons</span>
</div>
{totalTopics > 0 && (
<div className="flex items-center">
<div className="mr-2 h-1.5 w-16 overflow-hidden rounded-full bg-gray-200">
<div
className="h-full rounded-full bg-blue-600"
style={{ width: `${progressPercentage}%` }}
/>
</div>
<span className="text-xs font-medium text-gray-700">
{progressPercentage}%
</span>
</div>
)}
</div>
</a>
{course.slug && (
<div className="absolute right-2 top-2">
<AICourseActions courseSlug={course.slug} />
</div>
)}
</div>
);
}

@ -0,0 +1,484 @@
import {
BookOpenCheck,
ChevronLeft,
CircleAlert,
CircleOff,
Menu,
X,
Map, MessageCircleOffIcon,
MessageCircleIcon
} from 'lucide-react';
import { useEffect, useState } from 'react';
import { type AiCourse } from '../../lib/ai';
import { cn } from '../../lib/classname';
import { useIsPaidUser } from '../../queries/billing';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
import { ErrorIcon } from '../ReactIcons/ErrorIcon';
import { AICourseLesson } from './AICourseLesson';
import { AICourseLimit } from './AICourseLimit';
import { AICourseSidebarModuleList } from './AICourseSidebarModuleList';
import { AILimitsPopup } from './AILimitsPopup';
import { AICourseOutlineView } from './AICourseOutlineView';
import { AICourseRoadmapView } from './AICourseRoadmapView';
import { AICourseFooter } from './AICourseFooter';
type AICourseContentProps = {
courseSlug?: string;
course: AiCourse;
isLoading: boolean;
error?: string;
onRegenerateOutline: (prompt?: string) => void;
};
export type AICourseViewMode = 'module' | 'outline' | 'roadmap';
export function AICourseContent(props: AICourseContentProps) {
const { course, courseSlug, isLoading, error, onRegenerateOutline } = props;
const [showUpgradeModal, setShowUpgradeModal] = useState(false);
const [showAILimitsPopup, setShowAILimitsPopup] = useState(false);
const [isAIChatsOpen, setIsAIChatsOpen] = useState(true);
const [activeModuleIndex, setActiveModuleIndex] = useState(0);
const [activeLessonIndex, setActiveLessonIndex] = useState(0);
const [sidebarOpen, setSidebarOpen] = useState(false);
const [viewMode, setViewMode] = useState<AICourseViewMode>('outline');
const { isPaidUser } = useIsPaidUser();
const aiCourseProgress = course.done || [];
const [expandedModules, setExpandedModules] = useState<
Record<number, boolean>
>({});
const goToNextModule = () => {
if (activeModuleIndex >= course.modules.length) {
return;
}
const nextModuleIndex = activeModuleIndex + 1;
setActiveModuleIndex(nextModuleIndex);
setActiveLessonIndex(0);
setExpandedModules((prev) => {
const newState: Record<number, boolean> = {};
course.modules.forEach((_, idx) => {
newState[idx] = false;
});
newState[nextModuleIndex] = true;
return newState;
});
};
const goToNextLesson = () => {
const currentModule = course.modules[activeModuleIndex];
if (currentModule && activeLessonIndex < currentModule.lessons.length - 1) {
setActiveLessonIndex(activeLessonIndex + 1);
} else {
goToNextModule();
}
};
const goToPrevLesson = () => {
if (activeLessonIndex > 0) {
setActiveLessonIndex(activeLessonIndex - 1);
return;
}
const prevModule = course.modules[activeModuleIndex - 1];
if (!prevModule) {
return;
}
const prevModuleIndex = activeModuleIndex - 1;
setActiveModuleIndex(prevModuleIndex);
setActiveLessonIndex(prevModule.lessons.length - 1);
// Expand the previous module in the sidebar
setExpandedModules((prev) => {
const newState: Record<number, boolean> = {};
// Set all modules to collapsed
course.modules.forEach((_, idx) => {
newState[idx] = false;
});
// Expand only the previous module
newState[prevModuleIndex] = true;
return newState;
});
};
const currentModule = course.modules[activeModuleIndex];
const currentLesson = currentModule?.lessons[activeLessonIndex];
const totalModules = course.modules.length;
const totalLessons = currentModule?.lessons.length || 0;
const totalCourseLessons = course.modules.reduce(
(total, module) => total + module.lessons.length,
0,
);
const totalDoneLessons = (course?.done || []).length;
const finishedPercentage = Math.round(
(totalDoneLessons / totalCourseLessons) * 100,
);
const modals = (
<>
{showUpgradeModal && (
<UpgradeAccountModal onClose={() => setShowUpgradeModal(false)} />
)}
{showAILimitsPopup && (
<AILimitsPopup
onClose={() => setShowAILimitsPopup(false)}
onUpgrade={() => {
setShowAILimitsPopup(false);
setShowUpgradeModal(true);
}}
/>
)}
</>
);
useEffect(() => {
if (window && window?.innerWidth < 1024 && isAIChatsOpen) {
setIsAIChatsOpen(false);
}
}, []);
if (error && !isLoading) {
const isLimitReached = error.includes('limit');
const isNotFound = error.includes('not exist');
let icon = <ErrorIcon additionalClasses="mb-4 size-16" />;
let title = 'Error occurred';
let message = error;
if (isLimitReached) {
icon = <CircleAlert className="mb-4 size-16 text-yellow-500" />;
title = 'Limit Reached';
message =
'You have reached the daily AI usage limit. Please upgrade your account to continue.';
} else if (isNotFound) {
icon = <CircleOff className="mb-4 size-16 text-gray-300" />;
title = 'Course Not Found';
message =
'The course you are looking for does not exist. Why not create your own course?';
}
const showUpgradeButton = isLimitReached && !isPaidUser;
return (
<>
{modals}
<div className="flex h-screen flex-col items-center justify-center px-4 text-center">
{icon}
<h1 className="mb-2 text-2xl font-bold">{title}</h1>
<p className="max-w-sm text-balance text-gray-500">{message}</p>
{showUpgradeButton && (
<div className="my-5">
<button
onClick={() => setShowUpgradeModal(true)}
className="rounded-md bg-yellow-400 px-6 py-2 text-sm font-medium text-black hover:bg-yellow-500"
>
Upgrade to remove Limits
</button>
<p className="mt-5 text-sm text-black">
<a
href="/ai"
className="font-medium underline underline-offset-2"
>
Back to AI Tutor
</a>
</p>
</div>
)}
{(isNotFound || !showUpgradeButton) && (
<div className="my-5">
<a
href="/ai"
className="rounded-md bg-black px-6 py-2 text-sm font-medium text-white hover:bg-opacity-80"
>
Create a course with AI
</a>
</div>
)}
</div>
</>
);
}
const isViewingLesson = viewMode === 'module';
return (
<section className="flex h-screen flex-grow flex-col overflow-hidden bg-gray-50">
{modals}
<div className="border-b border-gray-200 bg-gray-100">
<div className="flex items-center justify-between px-4 py-2">
<a
href="/ai"
onClick={(e) => {
if (isViewingLesson) {
e.preventDefault();
setViewMode('outline');
}
}}
className="flex flex-row items-center gap-1.5 text-sm font-medium text-gray-700 hover:text-gray-900"
aria-label="Back to generator"
>
<ChevronLeft className="size-4" strokeWidth={2.5} />
Back {isViewingLesson ? 'to Outline' : 'to AI Tutor'}
</a>
<div className="flex items-center gap-2">
<div className="flex flex-row lg:hidden">
<AICourseLimit
onUpgrade={() => setShowUpgradeModal(true)}
onShowLimits={() => setShowAILimitsPopup(true)}
/>
</div>
{viewMode === 'module' && (
<button
onClick={() => setIsAIChatsOpen(!isAIChatsOpen)}
className="flex items-center justify-center text-gray-400 shadow-sm transition-colors hover:bg-gray-50 hover:text-gray-900 lg:hidden"
>
{isAIChatsOpen ? (
<MessageCircleOffIcon size={17} strokeWidth={3} />
) : (
<MessageCircleIcon size={17} strokeWidth={3} />
)}
</button>
)}
<button
onClick={() => setSidebarOpen(!sidebarOpen)}
className="flex items-center justify-center text-gray-400 shadow-sm transition-colors hover:bg-gray-50 hover:text-gray-900 lg:hidden"
>
{sidebarOpen ? (
<X size={17} strokeWidth={3} />
) : (
<Menu size={17} strokeWidth={3} />
)}
</button>
</div>
</div>
</div>
<header className="flex items-center justify-between border-b border-gray-200 bg-white px-6 max-lg:py-4 lg:h-[80px]">
<div className="flex items-center">
<div className="flex flex-col">
<h1 className="text-balance text-xl font-bold !leading-tight text-gray-900 max-lg:mb-0.5 max-lg:text-lg">
{course.title || 'Loading Course...'}
</h1>
<div className="mt-1 flex flex-row items-center gap-2 text-sm text-gray-600 max-lg:text-xs">
<span className="font-medium">{totalModules} modules</span>
<span className="text-gray-400"></span>
<span className="font-medium">{totalCourseLessons} lessons</span>
{viewMode === 'module' && (
<span className="flex flex-row items-center gap-1 lg:hidden">
<span className="text-gray-400"></span>
<button
className="underline underline-offset-2"
onClick={() => {
setExpandedModules({});
setViewMode('outline');
}}
>
View outline
</button>
</span>
)}
{finishedPercentage > 0 && (
<>
<span className="text-gray-400"></span>
<span className="font-medium text-green-600">
{finishedPercentage}% complete
</span>
</>
)}
</div>
</div>
</div>
<div className="flex gap-2">
<div className="hidden gap-2 lg:flex">
<AICourseLimit
onUpgrade={() => setShowUpgradeModal(true)}
onShowLimits={() => setShowAILimitsPopup(true)}
/>
</div>
</div>
</header>
<div className="flex flex-1 overflow-hidden">
<aside
className={cn(
'fixed inset-y-0 left-0 z-20 w-80 transform overflow-y-auto border-r border-gray-200 bg-white transition-transform duration-200 ease-in-out lg:relative lg:mt-0 lg:translate-x-0',
sidebarOpen ? 'translate-x-0' : '-translate-x-full',
)}
>
<div
className={cn(
'relative flex min-h-[40px] items-center justify-between border-b border-gray-200 px-3',
isLoading && 'striped-loader bg-gray-50',
)}
>
{!isLoading && (
<div className="flex w-full items-center justify-between text-xs text-black">
<span>
<span className="relative z-10 rounded-full bg-yellow-400 px-1.5 py-0.5">
{finishedPercentage}%
</span>{' '}
<span className="relative z-10">Completed</span>
</span>
<span
style={{
width: `${finishedPercentage}%`,
}}
className={cn(
'absolute bottom-0 left-0 top-0',
'bg-gray-200/50',
)}
></span>
<div className="flex gap-0 rounded-md bg-white p-0.5">
<button
onClick={() => {
setExpandedModules({});
setViewMode('outline');
}}
className={cn(
'flex items-center gap-1 rounded px-2 py-1 text-xs transition-colors',
viewMode === 'outline'
? 'bg-gray-200 text-gray-900'
: 'text-gray-600 hover:bg-gray-50',
)}
>
<BookOpenCheck size={14} />
Outline
</button>
<button
onClick={() => {
setExpandedModules({});
setViewMode('roadmap');
}}
className={cn(
'flex items-center gap-1 rounded px-2 py-1 text-xs transition-colors',
viewMode === 'roadmap'
? 'bg-gray-200 text-gray-900'
: 'text-gray-600 hover:bg-gray-50',
)}
>
<Map size={14} />
Map
</button>
</div>
</div>
)}
<button
onClick={() => setSidebarOpen(false)}
className="rounded-md p-1 hover:bg-gray-100 lg:hidden"
>
<X size={18} />
</button>
</div>
<AICourseSidebarModuleList
course={course}
courseSlug={courseSlug}
activeModuleIndex={
viewMode === 'module' ? activeModuleIndex : undefined
}
setActiveModuleIndex={setActiveModuleIndex}
activeLessonIndex={
viewMode === 'module' ? activeLessonIndex : undefined
}
setActiveLessonIndex={setActiveLessonIndex}
setSidebarOpen={setSidebarOpen}
viewMode={viewMode}
setViewMode={setViewMode}
expandedModules={expandedModules}
setExpandedModules={setExpandedModules}
isLoading={isLoading}
/>
</aside>
<main
className={cn(
'flex-1 overflow-y-scroll p-6 transition-all duration-200 ease-in-out max-lg:p-3',
sidebarOpen ? 'lg:ml-0' : '',
viewMode === 'module'
? 'flex flex-col overflow-hidden p-0 max-lg:p-0'
: '',
)}
key={`${courseSlug}-${viewMode}`}
>
{viewMode === 'module' && (
<AICourseLesson
courseSlug={courseSlug!}
progress={aiCourseProgress}
activeModuleIndex={activeModuleIndex}
totalModules={totalModules}
currentModuleTitle={currentModule?.title || ''}
activeLessonIndex={activeLessonIndex}
totalLessons={totalLessons}
currentLessonTitle={currentLesson || ''}
onGoToPrevLesson={goToPrevLesson}
onGoToNextLesson={goToNextLesson}
key={`${courseSlug}-${activeModuleIndex}-${activeLessonIndex}`}
onUpgrade={() => setShowUpgradeModal(true)}
isAIChatsOpen={isAIChatsOpen}
setIsAIChatsOpen={setIsAIChatsOpen}
/>
)}
{viewMode === 'outline' && (
<AICourseOutlineView
course={course}
isLoading={isLoading}
onRegenerateOutline={onRegenerateOutline}
setActiveModuleIndex={setActiveModuleIndex}
setActiveLessonIndex={setActiveLessonIndex}
setSidebarOpen={setSidebarOpen}
setViewMode={setViewMode}
setExpandedModules={setExpandedModules}
viewMode={viewMode}
/>
)}
{viewMode === 'roadmap' && !isLoading && (
<AICourseRoadmapView
done={course.done}
courseSlug={courseSlug!}
course={course}
isLoading={isLoading}
onRegenerateOutline={onRegenerateOutline}
setActiveModuleIndex={setActiveModuleIndex}
setActiveLessonIndex={setActiveLessonIndex}
setViewMode={setViewMode}
setExpandedModules={setExpandedModules}
onUpgradeClick={() => setShowUpgradeModal(true)}
viewMode={viewMode}
/>
)}
<AICourseFooter className={viewMode === 'module' ? 'hidden' : ''} />
</main>
</div>
{sidebarOpen && (
<div
className="fixed inset-0 z-10 bg-gray-900 bg-opacity-50 lg:hidden"
onClick={() => setSidebarOpen(false)}
></div>
)}
</section>
);
}

@ -0,0 +1,19 @@
import { cn } from '../../lib/classname';
type AICourseFooterProps = {
className?: string;
};
export function AICourseFooter(props: AICourseFooterProps) {
const { className } = props;
return (
<div
className={cn(
'mx-auto mb-10 mt-5 text-center text-sm text-gray-400',
className,
)}
>
AI can make mistakes, check important info.
</div>
);
}

@ -0,0 +1,503 @@
import { useMutation } from '@tanstack/react-query';
import {
CheckIcon,
ChevronLeft,
ChevronRight,
Loader2Icon,
LockIcon,
MessageCircleIcon,
MessageCircleOffIcon,
XIcon,
} from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import type { AICourseDocument } from '../../api/ai-roadmap';
import { readStream } from '../../lib/ai';
import { cn } from '../../lib/classname';
import { isLoggedIn, removeAuthToken } from '../../lib/jwt';
import {
markdownToHtml,
markdownToHtmlWithHighlighting,
} from '../../lib/markdown';
import { httpPatch } from '../../lib/query-http';
import { slugify } from '../../lib/slugger';
import {
getAiCourseLimitOptions,
getAiCourseOptions,
} from '../../queries/ai-course';
import { useIsPaidUser } from '../../queries/billing';
import { queryClient } from '../../stores/query-client';
import './AICourseLessonChat.css';
import { RegenerateLesson } from './RegenerateLesson';
import { TestMyKnowledgeAction } from './TestMyKnowledgeAction';
import {
AICourseLessonChat,
type AIChatHistoryType,
} from './AICourseLessonChat';
import { AICourseFooter } from './AICourseFooter';
import {
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
} from './Resizeable';
function getQuestionsFromResult(result: string) {
const matchedQuestions = result.match(
/=START_QUESTIONS=(.*?)=END_QUESTIONS=/,
);
if (matchedQuestions) {
return matchedQuestions[1].split('@@');
}
return [];
}
type AICourseLessonProps = {
courseSlug: string;
progress: string[];
activeModuleIndex: number;
totalModules: number;
currentModuleTitle: string;
activeLessonIndex: number;
totalLessons: number;
currentLessonTitle: string;
onGoToPrevLesson: () => void;
onGoToNextLesson: () => void;
onUpgrade: () => void;
isAIChatsOpen: boolean;
setIsAIChatsOpen: (isOpen: boolean) => void;
};
export function AICourseLesson(props: AICourseLessonProps) {
const {
courseSlug,
progress = [],
activeModuleIndex,
totalModules,
currentModuleTitle,
activeLessonIndex,
totalLessons,
currentLessonTitle,
onGoToPrevLesson,
onGoToNextLesson,
onUpgrade,
isAIChatsOpen,
setIsAIChatsOpen,
} = props;
const [isLoading, setIsLoading] = useState(true);
const [isGenerating, setIsGenerating] = useState(false);
const [error, setError] = useState('');
const [defaultQuestions, setDefaultQuestions] = useState<string[]>([]);
const [lessonHtml, setLessonHtml] = useState('');
const lessonId = `${slugify(String(activeModuleIndex))}-${slugify(String(activeLessonIndex))}`;
const isLessonDone = progress?.includes(lessonId);
const [courseAIChatHistory, setCourseAIChatHistory] = useState<
AIChatHistoryType[]
>([
{
role: 'assistant',
content:
'Hey, I am your AI instructor. How can I help you today? 🤖',
isDefault: true,
},
]);
const { isPaidUser } = useIsPaidUser();
const abortController = useMemo(
() => new AbortController(),
[activeModuleIndex, activeLessonIndex],
);
const generateAiCourseContent = async (
isForce?: boolean,
customPrompt?: string,
) => {
setIsLoading(true);
setError('');
setLessonHtml('');
if (!isLoggedIn()) {
setIsLoading(false);
setError('Please login to generate course content');
return;
}
if (!currentModuleTitle || !currentLessonTitle) {
setIsLoading(false);
setError('Invalid module title or lesson title');
return;
}
const response = await fetch(
`${import.meta.env.PUBLIC_API_URL}/v1-generate-ai-course-lesson/${courseSlug}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
signal: abortController.signal,
credentials: 'include',
body: JSON.stringify({
moduleIndex: activeModuleIndex,
lessonIndex: activeLessonIndex,
isForce,
customPrompt,
}),
},
);
if (!response.ok) {
const data = await response.json();
setError(data?.message || 'Something went wrong');
setIsLoading(false);
// Logout user if token is invalid
if (data.status === 401) {
removeAuthToken();
window.location.reload();
}
return;
}
if (!response.body) {
setIsLoading(false);
setError('No response body received');
return;
}
try {
const reader = response.body.getReader();
setIsLoading(false);
setIsGenerating(true);
await readStream(reader, {
onStream: async (result) => {
if (abortController.signal.aborted) {
return;
}
const questions = getQuestionsFromResult(result);
setDefaultQuestions(questions);
const newResult = result.replace(
/=START_QUESTIONS=.*?=END_QUESTIONS=/,
'',
);
setLessonHtml(markdownToHtml(newResult, false));
},
onStreamEnd: async (result) => {
if (abortController.signal.aborted) {
return;
}
const questions = getQuestionsFromResult(result);
setDefaultQuestions(questions);
const newResult = result.replace(
/=START_QUESTIONS=.*?=END_QUESTIONS=/,
'',
);
const markdownHtml = await markdownToHtmlWithHighlighting(
newResult,
).catch((e) => {
console.error(e);
return newResult;
});
setLessonHtml(markdownHtml);
queryClient.invalidateQueries(getAiCourseLimitOptions());
setIsGenerating(false);
},
});
} catch (e) {
setError(e instanceof Error ? e.message : 'Something went wrong');
setIsLoading(false);
}
};
const { mutate: toggleDone, isPending: isTogglingDone } = useMutation(
{
mutationFn: () => {
return httpPatch<AICourseDocument>(
`/v1-toggle-done-ai-lesson/${courseSlug}`,
{
moduleIndex: activeModuleIndex,
lessonIndex: activeLessonIndex,
},
);
},
onSuccess: (data) => {
queryClient.setQueryData(
getAiCourseOptions({ aiCourseSlug: courseSlug }).queryKey,
data,
);
},
},
queryClient,
);
useEffect(() => {
generateAiCourseContent();
}, [currentModuleTitle, currentLessonTitle]);
useEffect(() => {
return () => {
abortController.abort();
};
}, [abortController]);
const cantGoForward =
(activeModuleIndex === totalModules - 1 &&
activeLessonIndex === totalLessons - 1) ||
isGenerating ||
isLoading;
const cantGoBack =
(activeModuleIndex === 0 && activeLessonIndex === 0) ||
isGenerating ||
isLoading;
return (
<div className="h-full">
<ResizablePanelGroup direction="horizontal">
<ResizablePanel
defaultSize={isAIChatsOpen ? 70 : 100}
minSize={40}
id="course-text-content"
className="h-full !overflow-y-scroll bg-white"
order={1}
>
<div className="relative mx-auto max-w-5xl">
<div className="bg-white p-8 pb-0 max-lg:px-4 max-lg:pt-3">
{(isGenerating || isLoading) && (
<div className="absolute right-6 top-6 flex items-center justify-center">
<Loader2Icon
size={18}
strokeWidth={3}
className="animate-spin text-gray-400/70"
/>
</div>
)}
<div className="mb-4 flex items-center justify-between">
<div className="text-sm text-gray-500">
Lesson {activeLessonIndex + 1} of {totalLessons}
</div>
{!isGenerating && !isLoading && (
<div className="absolute top-2 right-2 lg:right-6 lg:top-6 flex items-center justify-between gap-2">
<button
onClick={() => setIsAIChatsOpen(!isAIChatsOpen)}
className="rounded-full p-1 text-gray-400 hover:text-black max-lg:hidden"
>
{!isAIChatsOpen ? (
<MessageCircleIcon className="size-4 stroke-[2.5]" />
) : (
<MessageCircleOffIcon className="size-4 stroke-[2.5]" />
)}
</button>
<RegenerateLesson
onRegenerateLesson={(prompt) => {
generateAiCourseContent(true, prompt);
}}
/>
<button
disabled={isLoading || isTogglingDone}
className={cn(
'flex items-center gap-1.5 rounded-full bg-black py-1 pl-2 pr-3 text-sm text-white hover:bg-gray-800 disabled:opacity-50 max-lg:text-xs',
isLessonDone
? 'bg-red-500 hover:bg-red-600'
: 'bg-green-500 hover:bg-green-600',
)}
onClick={() => toggleDone()}
>
{isTogglingDone ? (
<>
<Loader2Icon
size={16}
strokeWidth={3}
className="animate-spin text-white"
/>
Please wait ...
</>
) : (
<>
{isLessonDone ? (
<>
<XIcon size={16} />
Mark as Undone
</>
) : (
<>
<CheckIcon size={16} />
Mark as Done
</>
)}
</>
)}
</button>
</div>
)}
</div>
<h1 className="mb-6 text-balance text-3xl font-semibold max-lg:mb-3 max-lg:text-xl">
{currentLessonTitle?.replace(/^Lesson\s*?\d+[\.:]\s*/, '')}
</h1>
{!error && isLoggedIn() && (
<div
className="course-content prose prose-lg mt-8 max-w-full text-black prose-headings:mb-3 prose-headings:mt-8 prose-blockquote:font-normal prose-pre:rounded-2xl prose-pre:text-lg prose-li:my-1 prose-thead:border-zinc-800 prose-tr:border-zinc-800 max-lg:mt-4 max-lg:text-base max-lg:prose-h2:mt-3 max-lg:prose-h2:text-lg max-lg:prose-h3:text-base max-lg:prose-pre:px-3 max-lg:prose-pre:text-sm"
dangerouslySetInnerHTML={{ __html: lessonHtml }}
/>
)}
{error && isLoggedIn() && (
<div className="mt-8 flex min-h-[300px] items-center justify-center rounded-xl bg-red-50/80">
{error.includes('reached the limit') ? (
<div className="flex max-w-sm flex-col items-center text-center">
<h2 className="text-xl font-semibold text-red-600">
Limit reached
</h2>
<p className="my-3 text-red-600">
You have reached the AI usage limit for today.
{!isPaidUser && (
<>Please upgrade your account to continue.</>
)}
{isPaidUser && (
<>&nbsp;Please wait until tomorrow to continue.</>
)}
</p>
{!isPaidUser && (
<button
onClick={() => {
onUpgrade();
}}
className="rounded-full bg-red-600 px-4 py-1 text-white hover:bg-red-700"
>
Upgrade Account
</button>
)}
</div>
) : (
<p className="text-red-600">{error}</p>
)}
</div>
)}
{!isLoggedIn() && (
<div className="mt-8 flex min-h-[152px] flex-col items-center justify-center gap-3 rounded-lg border border-gray-200 p-8">
<LockIcon className="size-7 stroke-[2] text-gray-400/90" />
<p className="text-sm text-gray-500">
Please login to generate course content
</p>
</div>
)}
{!isLoading && !isGenerating && !error && (
<TestMyKnowledgeAction
courseSlug={courseSlug}
activeModuleIndex={activeModuleIndex}
activeLessonIndex={activeLessonIndex}
/>
)}
<div className="mt-8 flex items-center justify-between">
<button
onClick={onGoToPrevLesson}
disabled={cantGoBack}
className={cn(
'flex items-center rounded-full px-4 py-2 disabled:opacity-50 max-lg:px-3 max-lg:py-1.5 max-lg:text-sm',
cantGoBack
? 'cursor-not-allowed text-gray-400'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200',
)}
>
<ChevronLeft size={16} className="mr-2" />
Previous{' '}
<span className="hidden lg:inline">&nbsp;Lesson</span>
</button>
<div>
<button
onClick={() => {
if (!isLessonDone) {
toggleDone(undefined, {
onSuccess: () => {
onGoToNextLesson();
},
});
} else {
onGoToNextLesson();
}
}}
disabled={cantGoForward || isTogglingDone}
className={cn(
'flex items-center rounded-full px-4 py-2 disabled:opacity-50 max-lg:px-3 max-lg:py-1.5 max-lg:text-sm',
cantGoForward
? 'cursor-not-allowed text-gray-400'
: 'bg-gray-800 text-white hover:bg-gray-700',
)}
>
{isTogglingDone ? (
<>
<Loader2Icon
size={16}
strokeWidth={3}
className="animate-spin text-white"
/>
Please wait ...
</>
) : (
<>
Next{' '}
<span className="hidden lg:inline">&nbsp;Lesson</span>
<ChevronRight size={16} className="ml-2" />
</>
)}
</button>
</div>
</div>
<AICourseFooter />
</div>
</div>
</ResizablePanel>
{isAIChatsOpen && (
<>
<ResizableHandle withHandle={false} className="max-lg:hidden" />
<AICourseLessonChat
courseSlug={courseSlug}
moduleTitle={currentModuleTitle}
lessonTitle={currentLessonTitle}
onUpgradeClick={onUpgrade}
courseAIChatHistory={courseAIChatHistory}
setCourseAIChatHistory={setCourseAIChatHistory}
isDisabled={isGenerating || isLoading || isTogglingDone}
isGeneratingLesson={isGenerating || isLoading}
defaultQuestions={defaultQuestions}
onClose={() => setIsAIChatsOpen(false)}
isAIChatsOpen={isAIChatsOpen}
setIsAIChatsOpen={setIsAIChatsOpen}
/>
</>
)}
</ResizablePanelGroup>
</div>
);
}

@ -0,0 +1,131 @@
.prose ul li > code,
.prose ol li > code,
p code,
a > code,
strong > code,
em > code,
h1 > code,
h2 > code,
h3 > code {
background: #ebebeb !important;
color: currentColor !important;
font-size: 14px;
font-weight: normal !important;
}
.course-ai-content.course-content.prose ul li > code,
.course-ai-content.course-content.prose ol li > code,
.course-ai-content.course-content.prose p code,
.course-ai-content.course-content.prose a > code,
.course-ai-content.course-content.prose strong > code,
.course-ai-content.course-content.prose em > code,
.course-ai-content.course-content.prose h1 > code,
.course-ai-content.course-content.prose h2 > code,
.course-ai-content.course-content.prose h3 > code,
.course-notes-content.prose ul li > code,
.course-notes-content.prose ol li > code,
.course-notes-content.prose p code,
.course-notes-content.prose a > code,
.course-notes-content.prose strong > code,
.course-notes-content.prose em > code,
.course-notes-content.prose h1 > code,
.course-notes-content.prose h2 > code,
.course-notes-content.prose h3 > code {
font-size: 12px !important;
}
.course-ai-content pre {
-ms-overflow-style: none;
scrollbar-width: none;
}
.course-ai-content pre::-webkit-scrollbar {
display: none;
}
.course-ai-content pre,
.course-notes-content pre {
overflow: scroll;
font-size: 15px;
margin: 10px 0;
}
.prose ul li > code:before,
p > code:before,
.prose ul li > code:after,
.prose ol li > code:before,
p > code:before,
.prose ol li > code:after,
.course-content h1 > code:after,
.course-content h1 > code:before,
.course-content h2 > code:after,
.course-content h2 > code:before,
.course-content h3 > code:after,
.course-content h3 > code:before,
.course-content h4 > code:after,
.course-content h4 > code:before,
p > code:after,
a > code:after,
a > code:before {
content: '' !important;
}
.course-content.prose ul li > code,
.course-content.prose ol li > code,
.course-content p code,
.course-content a > code,
.course-content strong > code,
.course-content em > code,
.course-content h1 > code,
.course-content h2 > code,
.course-content h3 > code,
.course-content table code {
background: #f4f4f5 !important;
border: 1px solid #282a36 !important;
color: #282a36 !important;
padding: 2px 4px;
border-radius: 5px;
font-size: 16px !important;
white-space: pre;
font-weight: normal;
}
.course-content blockquote {
font-style: normal;
}
.course-content.prose blockquote h1,
.course-content.prose blockquote h2,
.course-content.prose blockquote h3,
.course-content.prose blockquote h4 {
font-style: normal;
margin-bottom: 8px;
}
.course-content.prose ul li > code:before,
.course-content p > code:before,
.course-content.prose ul li > code:after,
.course-content p > code:after,
.course-content h2 > code:after,
.course-content h2 > code:before,
.course-content table code:before,
.course-content table code:after,
.course-content a > code:after,
.course-content a > code:before,
.course-content h2 code:after,
.course-content h2 code:before,
.course-content h2 code:after,
.course-content h2 code:before {
content: '' !important;
}
.course-content table {
border-collapse: collapse;
border: 1px solid black;
border-radius: 5px;
}
.course-content table td,
.course-content table th {
padding: 5px 10px;
}

@ -0,0 +1,484 @@
import { useQuery } from '@tanstack/react-query';
import {
BookOpen,
Bot,
Hammer,
HelpCircle,
LockIcon,
Send,
User2,
X,
XIcon,
} from 'lucide-react';
import {
Fragment,
useCallback,
useEffect,
useMemo,
useRef,
useState,
type FormEvent,
} from 'react';
import { flushSync } from 'react-dom';
import TextareaAutosize from 'react-textarea-autosize';
import { useToast } from '../../hooks/use-toast';
import { readStream } from '../../lib/ai';
import { cn } from '../../lib/classname';
import { isLoggedIn, removeAuthToken } from '../../lib/jwt';
import {
markdownToHtml,
markdownToHtmlWithHighlighting,
} from '../../lib/markdown';
import { getAiCourseLimitOptions } from '../../queries/ai-course';
import { queryClient } from '../../stores/query-client';
import { billingDetailsOptions } from '../../queries/billing';
import { ResizablePanel } from './Resizeable';
import { Spinner } from '../ReactIcons/Spinner';
export type AllowedAIChatRole = 'user' | 'assistant';
export type AIChatHistoryType = {
role: AllowedAIChatRole;
content: string;
isDefault?: boolean;
html?: string;
};
type AICourseLessonChatProps = {
courseSlug: string;
moduleTitle: string;
lessonTitle: string;
onUpgradeClick: () => void;
isDisabled?: boolean;
isGeneratingLesson?: boolean;
defaultQuestions?: string[];
courseAIChatHistory: AIChatHistoryType[];
setCourseAIChatHistory: (history: AIChatHistoryType[]) => void;
onClose: () => void;
isAIChatsOpen: boolean;
setIsAIChatsOpen: (isOpen: boolean) => void;
};
export function AICourseLessonChat(props: AICourseLessonChatProps) {
const {
courseSlug,
moduleTitle,
lessonTitle,
onUpgradeClick,
isDisabled,
defaultQuestions = [],
courseAIChatHistory,
setCourseAIChatHistory,
onClose,
isAIChatsOpen,
setIsAIChatsOpen,
isGeneratingLesson,
} = props;
const toast = useToast();
const scrollareaRef = useRef<HTMLDivElement | null>(null);
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const [isStreamingMessage, setIsStreamingMessage] = useState(false);
const [message, setMessage] = useState('');
const [streamedMessage, setStreamedMessage] = useState('');
const { data: tokenUsage, isLoading } = useQuery(
getAiCourseLimitOptions(),
queryClient,
);
const { data: userBillingDetails, isLoading: isBillingDetailsLoading } =
useQuery(billingDetailsOptions(), queryClient);
const isLimitExceeded = (tokenUsage?.used || 0) >= (tokenUsage?.limit || 0);
const isPaidUser = userBillingDetails?.status === 'active';
const handleChatSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const trimmedMessage = message.trim();
if (
!trimmedMessage ||
isStreamingMessage ||
!isLoggedIn() ||
isLimitExceeded ||
isLoading
) {
return;
}
const newMessages: AIChatHistoryType[] = [
...courseAIChatHistory,
{
role: 'user',
content: trimmedMessage,
},
];
flushSync(() => {
setCourseAIChatHistory(newMessages);
setMessage('');
});
scrollToBottom();
completeCourseAIChat(newMessages);
};
const scrollToBottom = useCallback(() => {
scrollareaRef.current?.scrollTo({
top: scrollareaRef.current.scrollHeight,
behavior: 'smooth',
});
}, [scrollareaRef]);
const completeCourseAIChat = async (messages: AIChatHistoryType[]) => {
setIsStreamingMessage(true);
const response = await fetch(
`${import.meta.env.PUBLIC_API_URL}/v1-follow-up-ai-course/${courseSlug}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({
moduleTitle,
lessonTitle,
messages: messages.slice(-10),
}),
},
);
if (!response.ok) {
const data = await response.json();
toast.error(data?.message || 'Something went wrong');
setCourseAIChatHistory([...messages].slice(0, messages.length - 1));
setIsStreamingMessage(false);
if (data.status === 401) {
removeAuthToken();
window.location.reload();
}
}
const reader = response.body?.getReader();
if (!reader) {
setIsStreamingMessage(false);
toast.error('Something went wrong');
return;
}
await readStream(reader, {
onStream: async (content) => {
flushSync(() => {
setStreamedMessage(content);
});
scrollToBottom();
},
onStreamEnd: async (content) => {
const newMessages: AIChatHistoryType[] = [
...messages,
{
role: 'assistant',
content,
html: await markdownToHtmlWithHighlighting(content),
},
];
flushSync(() => {
setStreamedMessage('');
setIsStreamingMessage(false);
setCourseAIChatHistory(newMessages);
});
queryClient.invalidateQueries(getAiCourseLimitOptions());
scrollToBottom();
},
});
setIsStreamingMessage(false);
};
useEffect(() => {
scrollToBottom();
}, []);
return (
<ResizablePanel
defaultSize={isAIChatsOpen ? 30 : 0}
minSize={20}
id="course-chat-content"
order={2}
className="relative h-full max-lg:fixed max-lg:inset-0 max-lg:data-[chat-state=open]:flex max-lg:data-[chat-state=closed]:hidden"
data-chat-state={isAIChatsOpen ? 'open' : 'closed'}
>
<div
className="absolute inset-y-0 right-0 z-20 flex w-full flex-col overflow-hidden bg-white data-[state=open]:flex data-[state=closed]:hidden"
data-state={isAIChatsOpen ? 'open' : 'closed'}
>
<button
onClick={onClose}
className="absolute right-2 top-2 z-20 hidden rounded-full p-1 text-gray-400 hover:text-black max-lg:block"
>
<XIcon className="size-4 stroke-[2.5]" />
</button>
<div className="flex items-center justify-between gap-2 border-b border-gray-200 px-4 py-2 text-sm">
<h4 className="flex items-center gap-2 text-base font-medium">
<Bot className="size-5 shrink-0 text-black relative -top-[1px]" strokeWidth={2.5} />
AI Instructor
</h4>
<button
onClick={onClose}
className="hidden rounded-md px-2 py-2 text-xs font-medium text-gray-500 hover:bg-gray-100 hover:text-black lg:block"
>
<X className="size-4 stroke-[2.5]" />
</button>
</div>
<div
className="scrollbar-thumb-gray-300 scrollbar-track-transparent scrollbar-thin relative grow overflow-y-auto"
ref={scrollareaRef}
>
<div className="absolute inset-0 flex flex-col">
<div className="relative flex grow flex-col justify-end">
{isGeneratingLesson && (
<div className="absolute inset-0 flex items-center justify-center gap-1.5 bg-gray-100">
<div className="flex items-center gap-1.5 rounded-md border border-gray-200 bg-white px-3 py-1.5">
<Spinner
className="size-4 text-gray-400"
outerFill="transparent"
/>
<p className="text-sm text-gray-500">
Generating lesson...
</p>
</div>
</div>
)}
<div className="flex flex-col justify-end gap-2 px-3 py-2">
{courseAIChatHistory.map((chat, index) => {
return (
<Fragment key={`chat-${index}`}>
<AIChatCard
role={chat.role}
content={chat.content}
html={chat.html}
/>
{chat.isDefault && defaultQuestions?.length > 1 && (
<div className="mb-1 mt-0.5">
<p className="mb-2 text-xs font-normal text-gray-500">
Some questions you might have about this lesson.
</p>
<div className="flex flex-col justify-end gap-1">
{defaultQuestions.map((question, index) => (
<button
key={`default-question-${index}`}
className="flex h-full self-start rounded-md bg-yellow-500/10 px-3 py-2 text-left text-sm text-black hover:bg-yellow-500/20"
onClick={() => {
flushSync(() => {
setMessage(question);
});
textareaRef.current?.focus();
}}
>
{question}
</button>
))}
</div>
</div>
)}
</Fragment>
);
})}
{isStreamingMessage && !streamedMessage && (
<AIChatCard role="assistant" content="Thinking..." />
)}
{streamedMessage && (
<AIChatCard role="assistant" content={streamedMessage} />
)}
</div>
</div>
</div>
</div>
<form
className="relative flex items-start border-t border-gray-200 text-sm"
onSubmit={handleChatSubmit}
>
{isLimitExceeded && (
<div className="absolute inset-0 flex items-center justify-center gap-2 bg-black text-white">
<LockIcon
className="size-4 cursor-not-allowed"
strokeWidth={2.5}
/>
<p className="cursor-not-allowed">
Limit reached for today
{isPaidUser ? '. Please wait until tomorrow.' : ''}
</p>
{!isPaidUser && (
<button
onClick={() => {
onUpgradeClick();
}}
className="rounded-md bg-white px-2 py-1 text-xs font-medium text-black hover:bg-gray-300"
>
Upgrade for more
</button>
)}
</div>
)}
<TextareaAutosize
className={cn(
'h-full min-h-[41px] grow resize-none bg-transparent px-4 py-2 focus:outline-none',
isDisabled ? 'cursor-not-allowed opacity-50' : 'cursor-auto',
)}
placeholder="Ask AI anything about the lesson..."
value={message}
onChange={(e) => setMessage(e.target.value)}
autoFocus={true}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
handleChatSubmit(e as unknown as FormEvent<HTMLFormElement>);
}
}}
ref={textareaRef}
/>
<button
type="submit"
disabled={isDisabled || isStreamingMessage || isLimitExceeded}
className="flex aspect-square size-[41px] items-center justify-center text-zinc-500 hover:text-black disabled:cursor-not-allowed disabled:opacity-50"
>
<Send className="size-4 stroke-[2.5]" />
</button>
</form>
</div>
</ResizablePanel>
);
}
type AIChatCardProps = {
role: AllowedAIChatRole;
content: string;
html?: string;
};
function AIChatCard(props: AIChatCardProps) {
const { role, content, html: defaultHtml } = props;
const html = useMemo(() => {
if (defaultHtml) {
return defaultHtml;
}
return markdownToHtml(content, false);
}, [content, defaultHtml]);
return (
<div
className={cn(
'flex flex-col rounded-lg',
role === 'user' ? 'bg-gray-300/30' : 'bg-yellow-500/30',
)}
>
<div className="flex items-start gap-2.5 p-3">
<div
className={cn(
'flex size-6 shrink-0 items-center justify-center rounded-full',
role === 'user'
? 'bg-gray-200 text-black'
: 'bg-yellow-400 text-black',
)}
>
{role === 'user' ? (
<User2 className="size-4 stroke-[2.5]" />
) : (
<Bot className="size-4 stroke-[2.5]" />
)}
</div>
<div
className="course-content course-ai-content prose prose-sm mt-0.5 max-w-full overflow-hidden text-sm"
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
</div>
);
}
type CapabilityCardProps = {
icon: React.ReactNode;
title: string;
description: string;
className?: string;
};
function CapabilityCard({
icon,
title,
description,
className,
}: CapabilityCardProps) {
return (
<div
className={cn(
'flex flex-col gap-2 rounded-lg bg-yellow-500/10 p-3',
className,
)}
>
<div className="flex items-center gap-2">
{icon}
<span className="text-[13px] font-medium leading-none text-black">
{title}
</span>
</div>
<p className="text-[12px] leading-normal text-gray-600">{description}</p>
</div>
);
}
const capabilities = [
{
icon: (
<HelpCircle
className="size-4 shrink-0 text-yellow-600"
strokeWidth={2.5}
/>
),
title: 'Clarify Concepts',
description: "If you don't understand a concept, ask me to clarify it",
},
{
icon: (
<BookOpen className="size-4 shrink-0 text-yellow-600" strokeWidth={2.5} />
),
title: 'More Details',
description: 'Get deeper insights about topics covered in the lesson',
},
{
icon: (
<Hammer className="size-4 shrink-0 text-yellow-600" strokeWidth={2.5} />
),
title: 'Real-world Examples',
description: 'Ask for real-world examples to understand better',
},
{
icon: <Bot className="size-4 shrink-0 text-yellow-600" strokeWidth={2.5} />,
title: 'Best Practices',
description: 'Learn about best practices and common pitfalls',
},
] as const;

@ -0,0 +1,79 @@
import { useQuery } from '@tanstack/react-query';
import { Gift, Info } from 'lucide-react';
import { getPercentage } from '../../lib/number';
import { getAiCourseLimitOptions } from '../../queries/ai-course';
import { billingDetailsOptions } from '../../queries/billing';
import { queryClient } from '../../stores/query-client';
type AICourseLimitProps = {
onUpgrade: () => void;
onShowLimits: () => void;
};
export function AICourseLimit(props: AICourseLimitProps) {
const { onUpgrade, onShowLimits } = props;
const { data: limits, isLoading } = useQuery(
getAiCourseLimitOptions(),
queryClient,
);
const { data: userBillingDetails, isLoading: isBillingDetailsLoading } =
useQuery(billingDetailsOptions(), queryClient);
if (isLoading || !limits || isBillingDetailsLoading || !userBillingDetails) {
return (
<div className="hidden h-[38px] w-[208.09px] animate-pulse rounded-lg border border-gray-200 bg-gray-200 lg:block"></div>
);
}
const { used, limit } = limits;
const totalPercentage = getPercentage(used, limit);
// has consumed 85% of the limit
const isPaidUser = userBillingDetails.status === 'active';
return (
<>
{!isPaidUser && (
<button
className="mr-1 flex items-center gap-1 text-sm font-medium underline underline-offset-2 lg:hidden"
onClick={() => onShowLimits()}
>
<Info className="size-4" />
{totalPercentage}% limit used
</button>
)}
{!isPaidUser && (
<button
onClick={() => {
onShowLimits();
}}
className="relative hidden h-full min-h-[38px] cursor-pointer items-center overflow-hidden rounded-lg border border-gray-300 px-3 py-1.5 text-sm hover:bg-gray-50 lg:flex"
>
<span className="relative z-10">
{totalPercentage}% of the daily limit used
</span>
<div
className="absolute inset-0 h-full bg-gray-200/80"
style={{
width: `${totalPercentage}%`,
}}
></div>
</button>
)}
{!isPaidUser && (
<button
className="hidden items-center justify-center gap-1 rounded-md bg-yellow-400 px-4 py-1 text-sm font-medium underline-offset-2 hover:bg-yellow-500 lg:flex"
onClick={() => onUpgrade()}
>
<Gift className="size-4" />
Upgrade
</button>
)}
</>
);
}

@ -0,0 +1,80 @@
import { cn } from '../../lib/classname';
import type { AiCourse } from '../../lib/ai';
import { RegenerateOutline } from './RegenerateOutline';
import type { AICourseViewMode } from './AICourseContent';
import { BookOpenCheck, Signpost } from 'lucide-react';
type AICourseOutlineHeaderProps = {
course: AiCourse;
isLoading: boolean;
onRegenerateOutline: (prompt?: string) => void;
viewMode: AICourseViewMode;
setViewMode: (mode: AICourseViewMode) => void;
};
export function AICourseOutlineHeader(props: AICourseOutlineHeaderProps) {
const { course, isLoading, onRegenerateOutline, viewMode, setViewMode } =
props;
return (
<div
className={cn(
'relative mb-1 flex items-start justify-between border-b border-gray-100 p-6 max-lg:p-3',
isLoading && 'striped-loader',
)}
>
<div className="max-lg:hidden">
<h2 className="mb-1 text-balance text-2xl font-bold max-lg:text-lg max-lg:leading-tight">
{course.title || 'Loading course ..'}
</h2>
<p className="text-sm capitalize text-gray-500">
{course.title ? course.difficulty : 'Please wait ..'}
</p>
</div>
<div className="absolute right-3 top-3 flex gap-2 max-lg:relative max-lg:right-0 max-lg:top-0 max-lg:w-full max-lg:flex-row-reverse max-lg:justify-between">
{!isLoading && (
<>
<RegenerateOutline onRegenerateOutline={onRegenerateOutline} />
<div className="mr-1 flex rounded-lg border border-gray-200 bg-white p-0.5">
<button
onClick={() => setViewMode('outline')}
className={cn(
'flex items-center gap-1 rounded-md px-2 py-1 text-sm transition-colors',
viewMode === 'outline'
? 'bg-gray-200 text-gray-900'
: 'text-gray-500 hover:text-gray-900',
)}
>
<BookOpenCheck
className={cn(
'size-4',
viewMode === 'outline' && 'text-gray-900',
)}
/>
<span>Outline</span>
</button>
<button
onClick={() => setViewMode('roadmap')}
className={cn(
'flex items-center gap-1 rounded-md px-2 py-1 text-sm transition-colors',
viewMode === 'roadmap'
? 'bg-gray-200 text-gray-900'
: 'text-gray-500 hover:text-gray-900',
)}
>
<Signpost
className={cn(
'size-4',
viewMode === 'roadmap' && 'text-gray-900',
)}
/>
<span>Map</span>
</button>
</div>
</>
)}
</div>
</div>
);
}

@ -0,0 +1,117 @@
import { cn } from '../../lib/classname';
import type { AiCourse } from '../../lib/ai';
import { slugify } from '../../lib/slugger';
import { CheckIcon } from '../ReactIcons/CheckIcon';
import type { Dispatch, SetStateAction } from 'react';
import { Loader2Icon } from 'lucide-react';
import type { AICourseViewMode } from './AICourseContent';
import { AICourseOutlineHeader } from './AICourseOutlineHeader';
type AICourseOutlineViewProps = {
course: AiCourse;
isLoading: boolean;
onRegenerateOutline: (prompt?: string) => void;
setActiveModuleIndex: (index: number) => void;
setActiveLessonIndex: (index: number) => void;
setSidebarOpen: (open: boolean) => void;
setViewMode: (mode: AICourseViewMode) => void;
setExpandedModules: Dispatch<SetStateAction<Record<number, boolean>>>;
viewMode: AICourseViewMode;
};
export function AICourseOutlineView(props: AICourseOutlineViewProps) {
const {
course,
isLoading,
onRegenerateOutline,
setActiveModuleIndex,
setActiveLessonIndex,
setSidebarOpen,
setViewMode,
setExpandedModules,
viewMode,
} = props;
const aiCourseProgress = course.done || [];
return (
<div className="mx-auto rounded-xl border border-gray-200 bg-white shadow-sm lg:max-w-5xl">
<AICourseOutlineHeader
course={course}
isLoading={isLoading}
onRegenerateOutline={onRegenerateOutline}
viewMode={viewMode}
setViewMode={setViewMode}
/>
{course.title ? (
<div className="flex flex-col p-6 max-lg:mt-0.5 max-lg:p-4">
{course.modules.map((courseModule, moduleIdx) => {
return (
<div
key={moduleIdx}
className="mb-5 pb-4 last:border-0 last:pb-0 max-lg:mb-2"
>
<h2 className="mb-4 text-xl font-bold text-gray-800 max-lg:mb-2 max-lg:text-lg max-lg:leading-tight">
{courseModule.title}
</h2>
<div className="divide-y divide-gray-100">
{courseModule.lessons.map((lesson, lessonIdx) => {
const key = `${slugify(String(moduleIdx))}-${slugify(String(lessonIdx))}`;
const isCompleted = aiCourseProgress.includes(key);
return (
<div
key={key}
className="flex cursor-pointer items-center gap-2 px-2 py-2.5 transition-colors hover:bg-gray-100 max-lg:px-0 max-lg:py-1.5"
onClick={() => {
setActiveModuleIndex(moduleIdx);
setActiveLessonIndex(lessonIdx);
setExpandedModules((prev) => {
const newState: Record<number, boolean> = {};
course.modules.forEach((_, idx) => {
newState[idx] = false;
});
newState[moduleIdx] = true;
return newState;
});
setSidebarOpen(false);
setViewMode('module');
}}
>
{!isCompleted && (
<span
className={cn(
'flex size-6 flex-shrink-0 items-center justify-center rounded-full bg-gray-200 text-sm font-medium text-gray-800 max-lg:size-5 max-lg:text-xs',
)}
>
{lessonIdx + 1}
</span>
)}
{isCompleted && (
<CheckIcon additionalClasses="size-6 flex-shrink-0 text-green-500" />
)}
<p className="flex-1 truncate text-base text-gray-800 max-lg:text-sm">
{lesson.replace(/^Lesson\s*?\d+[\.:]\s*/, '')}
</p>
<span className="text-sm font-medium text-gray-700 max-lg:hidden">
{isCompleted ? 'View' : 'Start'}
</span>
</div>
);
})}
</div>
</div>
);
})}
</div>
) : (
<div className="flex h-64 items-center justify-center">
<Loader2Icon size={36} className="animate-spin text-gray-300" />
</div>
)}
</div>
);
}

@ -0,0 +1,252 @@
import '../GenerateRoadmap/GenerateRoadmap.css';
import { renderFlowJSON } from '../../../editor/renderer/renderer';
import { generateAIRoadmapFromText } from '../../../editor/utils/roadmap-generator';
import {
generateAICourseRoadmapStructure,
readAIRoadmapStream,
type ResultItem,
} from '../../lib/ai';
import {
useCallback,
useEffect,
useRef,
useState,
type Dispatch,
type SetStateAction,
type MouseEvent,
} from 'react';
import type { AICourseViewMode } from './AICourseContent';
import { replaceChildren } from '../../lib/dom';
import { Frown, Loader2Icon } from 'lucide-react';
import { renderTopicProgress } from '../../lib/resource-progress';
import { queryClient } from '../../stores/query-client';
import { useQuery } from '@tanstack/react-query';
import { billingDetailsOptions } from '../../queries/billing';
import { AICourseOutlineHeader } from './AICourseOutlineHeader';
import type { AiCourse } from '../../lib/ai';
export type AICourseRoadmapViewProps = {
done: string[];
courseSlug: string;
course: AiCourse;
isLoading: boolean;
onRegenerateOutline: (prompt?: string) => void;
setActiveModuleIndex: (index: number) => void;
setActiveLessonIndex: (index: number) => void;
setViewMode: (mode: AICourseViewMode) => void;
onUpgradeClick: () => void;
setExpandedModules: Dispatch<SetStateAction<Record<number, boolean>>>;
viewMode: AICourseViewMode;
};
export function AICourseRoadmapView(props: AICourseRoadmapViewProps) {
const {
done = [],
courseSlug,
course,
isLoading,
onRegenerateOutline,
setActiveModuleIndex,
setActiveLessonIndex,
setViewMode,
setExpandedModules,
onUpgradeClick,
viewMode,
} = props;
const containerEl = useRef<HTMLDivElement>(null);
const [roadmapStructure, setRoadmapStructure] = useState<ResultItem[]>([]);
const [isGenerating, setIsGenerating] = useState(false);
const [error, setError] = useState<string | null>(null);
const { data: userBillingDetails, isLoading: isBillingDetailsLoading } =
useQuery(billingDetailsOptions(), queryClient);
const isPaidUser = userBillingDetails?.status === 'active';
const generateAICourseRoadmap = async (courseSlug: string) => {
try {
const response = await fetch(
`${import.meta.env.PUBLIC_API_URL}/v1-generate-ai-course-roadmap/${courseSlug}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
},
);
if (!response.ok) {
const data = await response.json();
console.error(
'Error generating course roadmap:',
data?.message || 'Something went wrong',
);
setError(data?.message || 'Something went wrong');
setIsGenerating(false);
return;
}
const reader = response.body?.getReader();
if (!reader) {
console.error('Failed to get reader from response');
setError('Something went wrong');
setIsGenerating(false);
return;
}
setIsGenerating(true);
await readAIRoadmapStream(reader, {
onStream: async (result) => {
const roadmap = generateAICourseRoadmapStructure(result, true);
const { nodes, edges } = generateAIRoadmapFromText(roadmap);
const svg = await renderFlowJSON({ nodes, edges });
replaceChildren(containerEl.current!, svg);
},
onStreamEnd: async (result) => {
const roadmap = generateAICourseRoadmapStructure(result, true);
const { nodes, edges } = generateAIRoadmapFromText(roadmap);
const svg = await renderFlowJSON({ nodes, edges });
replaceChildren(containerEl.current!, svg);
setRoadmapStructure(roadmap);
setIsGenerating(false);
done.forEach((id) => {
renderTopicProgress(id, 'done');
});
const modules = roadmap.filter((item) => item.type === 'topic');
for (const module of modules) {
const moduleId = module.id;
const isAllLessonsDone =
module?.children?.every((child) => done.includes(child.id)) ??
false;
if (isAllLessonsDone) {
renderTopicProgress(moduleId, 'done');
}
}
},
});
} catch (error) {
console.error('Error generating course roadmap:', error);
setError('Something went wrong');
setIsGenerating(false);
}
};
useEffect(() => {
if (!courseSlug) {
return;
}
generateAICourseRoadmap(courseSlug);
}, []);
const handleNodeClick = useCallback(
(e: MouseEvent<HTMLDivElement, unknown>) => {
if (isGenerating) {
return;
}
const target = e.target as SVGElement;
const targetGroup = (target?.closest('g') as SVGElement) || {};
const nodeId = targetGroup?.dataset?.nodeId;
const nodeType = targetGroup?.dataset?.type;
if (!nodeId || !nodeType) {
return null;
}
if (nodeType === 'topic') {
const topicIndex = roadmapStructure
.filter((item) => item.type === 'topic')
.findIndex((item) => item.id === nodeId);
setExpandedModules((prev) => {
const newState: Record<number, boolean> = {};
roadmapStructure.forEach((_, idx) => {
newState[idx] = false;
});
newState[topicIndex] = true;
return newState;
});
setActiveModuleIndex(topicIndex);
setActiveLessonIndex(0);
setViewMode('module');
return;
}
if (nodeType !== 'subtopic') {
return null;
}
const [moduleIndex, topicIndex] = nodeId.split('-').map(Number);
setExpandedModules((prev) => {
const newState: Record<number, boolean> = {};
roadmapStructure.forEach((_, idx) => {
newState[idx] = false;
});
newState[moduleIndex] = true;
return newState;
});
setActiveModuleIndex(moduleIndex);
setActiveLessonIndex(topicIndex);
setViewMode('module');
},
[
roadmapStructure,
setExpandedModules,
setActiveModuleIndex,
setActiveLessonIndex,
setViewMode,
],
);
return (
<div className="relative mx-auto min-h-[500px] rounded-xl border border-gray-200 bg-white shadow-sm lg:max-w-5xl">
<AICourseOutlineHeader
course={course}
isLoading={isLoading}
onRegenerateOutline={(prompt) => {
setViewMode('outline');
onRegenerateOutline(prompt);
}}
viewMode={viewMode}
setViewMode={setViewMode}
/>
{isLoading && (
<div className="absolute inset-0 flex h-full w-full items-center justify-center">
<Loader2Icon className="h-10 w-10 animate-spin stroke-[3px]" />
</div>
)}
{error && !isGenerating && (
<div className="absolute inset-0 flex h-full w-full flex-col items-center justify-center">
<Frown className="size-20 text-red-500" />
<p className="mx-auto mt-5 max-w-[250px] text-balance text-center text-base text-red-500">
{error || 'Something went wrong'}
</p>
{!isPaidUser && (error || '')?.includes('limit') && (
<button
onClick={onUpgradeClick}
className="mt-5 rounded-full bg-red-600 px-4 py-1 text-white hover:bg-red-700"
>
Upgrade Account
</button>
)}
</div>
)}
<div
id={'resource-svg-wrap'}
ref={containerEl}
onClick={handleNodeClick}
className="px-4 pb-2"
></div>
</div>
);
}

@ -0,0 +1,46 @@
import { SearchIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useDebounceValue } from '../../hooks/use-debounce';
type AICourseSearchProps = {
value: string;
onChange: (value: string) => void;
};
export function AICourseSearch(props: AICourseSearchProps) {
const { value: defaultValue, onChange } = props;
const [searchTerm, setSearchTerm] = useState(defaultValue);
const debouncedSearchTerm = useDebounceValue(searchTerm, 500);
useEffect(() => {
setSearchTerm(defaultValue);
}, [defaultValue]);
useEffect(() => {
if (debouncedSearchTerm && debouncedSearchTerm.length < 3) {
return;
}
if (debouncedSearchTerm === defaultValue) {
return;
}
onChange(debouncedSearchTerm);
}, [debouncedSearchTerm]);
return (
<div className="relative w-64 max-sm:hidden">
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
<SearchIcon className="h-4 w-4 text-gray-400" />
</div>
<input
type="text"
className="block w-full rounded-md border border-gray-200 bg-white py-1.5 pl-10 pr-3 leading-5 placeholder-gray-500 focus:border-gray-300 focus:outline-none focus:ring-blue-500 disabled:opacity-70 sm:text-sm"
placeholder="Search your courses..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
);
}

@ -0,0 +1,205 @@
import { type Dispatch, type SetStateAction } from 'react';
import type { AiCourse } from '../../lib/ai';
import { Check, ChevronDownIcon, ChevronRightIcon } from 'lucide-react';
import { cn } from '../../lib/classname';
import { slugify } from '../../lib/slugger';
import { CheckIcon } from '../ReactIcons/CheckIcon';
import { CircularProgress } from './CircularProgress';
import type { AICourseViewMode } from './AICourseContent';
type AICourseModuleListProps = {
course: AiCourse;
courseSlug?: string;
activeModuleIndex: number | undefined;
setActiveModuleIndex: (index: number) => void;
activeLessonIndex: number | undefined;
setActiveLessonIndex: (index: number) => void;
setSidebarOpen: (open: boolean) => void;
viewMode: AICourseViewMode;
setViewMode: (mode: AICourseViewMode) => void;
expandedModules: Record<number, boolean>;
setExpandedModules: Dispatch<SetStateAction<Record<number, boolean>>>;
isLoading: boolean;
};
export function AICourseSidebarModuleList(props: AICourseModuleListProps) {
const {
course,
courseSlug,
activeModuleIndex,
setActiveModuleIndex,
activeLessonIndex,
setActiveLessonIndex,
setSidebarOpen,
setViewMode,
expandedModules,
setExpandedModules,
isLoading,
} = props;
const aiCourseProgress = course.done || [];
const toggleModule = (index: number) => {
setExpandedModules((prev) => {
// If this module is already expanded, collapse it
if (prev[index]) {
return {
...prev,
[index]: false,
};
}
// Otherwise, collapse all modules and expand only this one
const newState: Record<number, boolean> = {};
// Set all modules to collapsed
course.modules.forEach((_, idx) => {
newState[idx] = false;
});
// Expand only the clicked module
newState[index] = true;
return newState;
});
};
const done = aiCourseProgress || [];
return (
<nav className="bg-gray-100">
{course.modules.map((courseModule, moduleIdx) => {
const totalLessons = courseModule.lessons.length;
const completedLessons = courseModule.lessons.filter(
(lesson, lessonIdx) => {
const key = `${slugify(String(moduleIdx))}-${slugify(String(lessonIdx))}`;
return done.includes(key);
},
).length;
const percentage = Math.round((completedLessons / totalLessons) * 100);
const isActive = expandedModules[moduleIdx];
const isModuleCompleted = completedLessons === totalLessons;
return (
<div key={moduleIdx} className="rounded-md">
<button
onClick={() => toggleModule(moduleIdx)}
className={cn(
'relative z-10 flex w-full cursor-pointer flex-row items-center gap-2 border-b border-b-gray-200 bg-white px-2 py-3 text-base text-gray-600 hover:bg-gray-100',
activeModuleIndex === moduleIdx
? 'text-gray-900'
: 'text-gray-700',
moduleIdx === 0 && 'pt-4',
)}
>
<div className="flex min-w-0 flex-1 items-center gap-2">
<div className="flex-shrink-0">
<CircularProgress
percentage={percentage}
isVisible={!isModuleCompleted}
isActive={isActive}
isLoading={isLoading}
>
<span
className={cn(
'flex size-[21px] flex-shrink-0 items-center justify-center rounded-full bg-gray-400/70 text-xs font-semibold text-white',
{
'bg-black': isActive,
'bg-green-600': isModuleCompleted,
},
)}
>
{!isModuleCompleted && moduleIdx + 1}
{isModuleCompleted && (
<Check className="size-3 stroke-[3] text-white" />
)}
</span>
</CircularProgress>
</div>
<span className="flex flex-1 items-center break-words text-left text-sm leading-relaxed">
{courseModule.title?.replace(/^Module\s*?\d+[\.:]\s*/, '')}
</span>
</div>
<div className="ml-auto self-center">
{expandedModules[moduleIdx] ? (
<ChevronDownIcon size={16} className="flex-shrink-0" />
) : (
<ChevronRightIcon size={16} className="flex-shrink-0" />
)}
</div>
</button>
{/* Lessons */}
{expandedModules[moduleIdx] && (
<div className="flex flex-col border-b border-b-gray-200 bg-gray-100">
{courseModule.lessons.map((lesson, lessonIdx) => {
const key = `${slugify(String(moduleIdx))}-${slugify(String(lessonIdx))}`;
const isCompleted = done.includes(key);
return (
<button
key={key}
onClick={() => {
setActiveModuleIndex(moduleIdx);
setActiveLessonIndex(lessonIdx);
setExpandedModules((prev) => {
const newState: Record<number, boolean> = {};
course.modules.forEach((_, idx) => {
newState[idx] = false;
});
newState[moduleIdx] = true;
return newState;
});
setSidebarOpen(false);
setViewMode('module');
}}
className={cn(
'flex w-full cursor-pointer items-center gap-2.5 py-3 pl-3.5 pr-2 text-left text-sm leading-normal',
activeModuleIndex === moduleIdx &&
activeLessonIndex === lessonIdx
? 'bg-gray-200 text-black'
: 'text-gray-600 hover:bg-gray-200/70',
)}
>
{isCompleted ? (
<CheckIcon
additionalClasses={cn(
'size-[18px] relative bg-white rounded-full top-[2px] flex-shrink-0 text-green-600',
{
'text-black':
activeModuleIndex === moduleIdx &&
activeLessonIndex === lessonIdx,
},
)}
/>
) : (
<span
className={cn(
'flex size-[18px] flex-shrink-0 items-center justify-center rounded-full bg-gray-400/70 text-xs font-semibold text-white',
{
'bg-black':
activeModuleIndex === moduleIdx &&
activeLessonIndex === lessonIdx,
},
)}
>
{lessonIdx + 1}
</span>
)}
<span className="break-words">
{lesson?.replace(/^Lesson\s*?\d+[\.:]\s*/, '')}
</span>
</button>
);
})}
</div>
)}
</div>
);
})}
</nav>
);
}

@ -0,0 +1,103 @@
import { Gift } from 'lucide-react';
import { Modal } from '../Modal';
import { formatCommaNumber } from '../../lib/number';
import { billingDetailsOptions } from '../../queries/billing';
import { queryClient } from '../../stores/query-client';
import { useQuery } from '@tanstack/react-query';
import { getAiCourseLimitOptions } from '../../queries/ai-course';
type AILimitsPopupProps = {
onClose: () => void;
onUpgrade: () => void;
};
export function AILimitsPopup(props: AILimitsPopupProps) {
const { onClose, onUpgrade } = props;
const { data: limits, isLoading } = useQuery(
getAiCourseLimitOptions(),
queryClient,
);
const { used, limit } = limits ?? { used: 0, limit: 0 };
const { data: userBillingDetails, isLoading: isBillingDetailsLoading } =
useQuery(billingDetailsOptions(), queryClient);
const isPaidUser = userBillingDetails?.status === 'active';
return (
<Modal
onClose={onClose}
wrapperClassName="rounded-xl max-w-xl w-full h-auto"
bodyClassName="p-6"
overlayClassName="items-start md:items-center"
>
<h2 className="mb-8 text-center text-xl font-semibold">
Daily AI Limits
</h2>
{/* Usage Progress Bar */}
<div className="mb-6">
<div className="mb-2 flex justify-between">
<span className="text-sm font-medium">
Usage: {formatCommaNumber(used)}&nbsp;/&nbsp;
{formatCommaNumber(limit)} tokens
</span>
<span className="text-sm font-medium">
{Math.round((used / limit) * 100)}%
</span>
</div>
<div className="h-2.5 w-full rounded-full bg-gray-200">
<div
className="h-2.5 rounded-full bg-yellow-500"
style={{ width: `${Math.min(100, (used / limit) * 100)}%` }}
></div>
</div>
</div>
{/* Usage Stats */}
<div className="rounded-lg bg-gray-50 p-4">
<div className="grid grid-cols-2 gap-4">
<div>
<p className="text-sm text-gray-500">Used Today</p>
<p className="text-2xl font-bold">{formatCommaNumber(used)}</p>
</div>
<div>
<p className="text-sm text-gray-500">Daily Limit</p>
<p className="text-2xl font-bold">{formatCommaNumber(limit)}</p>
</div>
</div>
</div>
{/* Explanation */}
<div className="mt-2">
<div className="space-y-3 text-gray-600">
<p className="text-sm">
Limit resets every 24 hours.{' '}
{!isPaidUser && 'Consider upgrading for more tokens.'}
</p>
</div>
</div>
{/* Action Button */}
<div className="mt-auto flex flex-col gap-2 pt-4">
{!isPaidUser && (
<button
onClick={onUpgrade}
className="flex w-full items-center justify-center gap-2 rounded-lg bg-yellow-400 px-4 py-2.5 text-sm font-medium text-black transition-colors hover:bg-yellow-500"
>
<Gift className="size-4" />
Upgrade to Unlimited
</button>
)}
<button
onClick={onClose}
className="w-full rounded-lg bg-gray-200 px-4 py-2.5 text-sm text-gray-600 transition-colors hover:bg-gray-300"
>
Close
</button>
</div>
</Modal>
);
}

@ -0,0 +1,81 @@
import { BookOpenCheckIcon, SignpostIcon, type LucideIcon } from 'lucide-react';
import { cn } from '../../lib/classname';
import type { AICourseViewMode } from './AICourseContent';
type AIRoadmapViewSwitchProps = {
viewMode: AICourseViewMode;
setViewMode: (mode: AICourseViewMode) => void;
isLoading: boolean;
variant?: 'icon' | 'text';
};
export function AIRoadmapViewSwitch(props: AIRoadmapViewSwitchProps) {
const { viewMode, setViewMode, isLoading, variant = 'icon' } = props;
return (
<div
className={cn(
'grid shrink-0 grid-cols-2 gap-0.5 rounded-md border border-gray-300 bg-white p-0.5 shadow-sm',
)}
>
<SwitchButton
onClick={() => setViewMode('outline')}
isActive={viewMode === 'outline'}
disabled={isLoading}
variant={variant}
icon={BookOpenCheckIcon}
label="Outline"
/>
<SwitchButton
onClick={() => setViewMode('roadmap')}
isActive={viewMode === 'roadmap'}
disabled={isLoading}
variant={variant}
icon={SignpostIcon}
label="Roadmap"
/>
</div>
);
}
type SwitchButtonProps = {
onClick: () => void;
isActive: boolean;
disabled: boolean;
variant?: 'icon' | 'text';
icon: LucideIcon;
label: string;
};
export function SwitchButton(props: SwitchButtonProps) {
const {
onClick,
isActive,
disabled,
variant = 'icon',
icon: Icon,
label,
} = props;
return (
<button
className={cn(
'flex items-center justify-center gap-1.5 rounded text-sm hover:bg-gray-100 disabled:cursor-not-allowed',
isActive && 'bg-gray-100 text-gray-800',
variant === 'text' ? 'px-2 py-1.5' : 'p-[5px]',
)}
onClick={onClick}
disabled={disabled}
>
<Icon
className={cn(
'size-4',
variant === 'icon' && 'h-3 w-3',
isActive && 'text-gray-800',
)}
/>
{variant === 'text' && label}
</button>
);
}

@ -0,0 +1,57 @@
import { cn } from '../../lib/classname';
export function ChapterNumberSkeleton() {
return (
<div className="h-[28px] w-[28px] animate-pulse rounded-full bg-gray-200" />
);
}
type CircularProgressProps = {
percentage: number;
children: React.ReactNode;
isVisible?: boolean;
isActive?: boolean;
isLoading?: boolean;
};
export function CircularProgress(props: CircularProgressProps) {
const {
percentage,
children,
isVisible = true,
isActive = false,
isLoading = false,
} = props;
const circumference = 2 * Math.PI * 13;
const strokeDasharray = `${circumference}`;
const strokeDashoffset = circumference - (percentage / 100) * circumference;
return (
<div className="relative flex h-[28px] w-[28px] flex-shrink-0 items-center justify-center">
{isVisible && !isLoading && (
<svg className="absolute h-full w-full -rotate-90">
<circle
cx="14"
cy="14"
r="13"
stroke="currentColor"
strokeWidth="1.75"
fill="none"
className={cn('text-gray-400/70', {
'text-black': isActive,
})}
style={{
strokeDasharray,
strokeDashoffset,
transition: 'stroke-dashoffset 0.3s ease',
}}
/>
</svg>
)}
{!isLoading && children}
{isLoading && <ChapterNumberSkeleton />}
</div>
);
}

@ -0,0 +1,103 @@
import { useState } from 'react';
import { cn } from '../../lib/classname';
type QuestionProps = {
label: string;
placeholder: string;
autoFocus?: boolean;
value: string;
onChange: (value: string) => void;
};
function Question(props: QuestionProps) {
const { label, placeholder, value, onChange, autoFocus = false } = props;
return (
<div className="flex flex-col">
<label className="border-y bg-gray-100 px-4 py-2.5 text-sm font-medium text-gray-700">
{label}
</label>
<textarea
placeholder={placeholder}
className="min-h-[80px] w-full resize-none px-4 py-3 text-gray-700 placeholder:text-gray-400 focus:outline-none"
value={value}
onChange={(e) => onChange(e.target.value)}
autoFocus={autoFocus}
/>
</div>
);
}
type FineTuneCourseProps = {
hasFineTuneData: boolean;
about: string;
goal: string;
customInstructions: string;
setHasFineTuneData: (hasMetadata: boolean) => void;
setAbout: (about: string) => void;
setGoal: (goal: string) => void;
setCustomInstructions: (customInstructions: string) => void;
};
export function FineTuneCourse(props: FineTuneCourseProps) {
const {
about,
goal,
customInstructions,
hasFineTuneData,
setAbout,
setGoal,
setCustomInstructions,
setHasFineTuneData,
} = props;
return (
<div className="flex flex-col overflow-hidden rounded-lg border border-gray-200 transition-all">
<label
className={cn(
'group flex cursor-pointer select-none flex-row items-center gap-2.5 px-4 py-3 text-left text-gray-500 transition-colors hover:bg-gray-100 focus:outline-none',
hasFineTuneData && 'bg-gray-100',
)}
>
<input
id="fine-tune-checkbox"
type="checkbox"
className="h-4 w-4 group-hover:fill-current"
checked={hasFineTuneData}
onChange={() => {
setHasFineTuneData(!hasFineTuneData);
}}
/>
Tell us more to tailor the course (optional){' '}
<span className="ml-auto rounded-md bg-gray-400 px-2 py-0.5 text-xs text-white">
recommended
</span>
</label>
{hasFineTuneData && (
<div className="mt-0 flex flex-col">
<Question
label="Tell us about your self"
placeholder="e.g. I am a frontend developer and have good knowledge of HTML, CSS, and JavaScript."
value={about}
onChange={setAbout}
autoFocus={true}
/>
<Question
label="What is your goal with this course?"
placeholder="e.g. I want to be able to build Node.js APIs with Express.js and MongoDB."
value={goal}
onChange={setGoal}
/>
<Question
label="Custom Instructions (Optional)"
placeholder="Give additional instructions to the AI as if you were giving them to a friend."
value={customInstructions}
onChange={setCustomInstructions}
/>
</div>
)}
</div>
);
}

@ -0,0 +1,166 @@
import { useEffect, useState } from 'react';
import { getUrlParams } from '../../lib/browser';
import { isLoggedIn } from '../../lib/jwt';
import { getCourseFineTuneData, type AiCourse } from '../../lib/ai';
import { AICourseContent } from './AICourseContent';
import { generateCourse } from '../../helper/generate-ai-course';
import { useQuery } from '@tanstack/react-query';
import { getAiCourseOptions } from '../../queries/ai-course';
import { queryClient } from '../../stores/query-client';
type GenerateAICourseProps = {};
export function GenerateAICourse(props: GenerateAICourseProps) {
const [term, setTerm] = useState('');
const [difficulty, setDifficulty] = useState('');
const [sessionId, setSessionId] = useState('');
const [goal, setGoal] = useState('');
const [about, setAbout] = useState('');
const [customInstructions, setCustomInstructions] = useState('');
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState('');
const [courseId, setCourseId] = useState('');
const [courseSlug, setCourseSlug] = useState('');
const [course, setCourse] = useState<AiCourse>({
title: '',
modules: [],
difficulty: '',
done: [],
});
// Once the course is generated, we fetch the course from the database
// so that we get the up-to-date course data and also so that we
// can reload the changes (e.g. progress) etc using queryClient.setQueryData
const { data: aiCourse } = useQuery(
getAiCourseOptions({ aiCourseSlug: courseSlug }),
queryClient,
);
useEffect(() => {
if (aiCourse) {
setCourse(aiCourse);
}
}, [aiCourse]);
useEffect(() => {
if (term || difficulty) {
return;
}
const params = getUrlParams();
const paramsTerm = params?.term;
const paramsDifficulty = params?.difficulty;
if (!paramsTerm || !paramsDifficulty) {
return;
}
setTerm(paramsTerm);
setDifficulty(paramsDifficulty);
const sessionId = params?.id;
setSessionId(sessionId);
let paramsGoal = '';
let paramsAbout = '';
let paramsCustomInstructions = '';
if (sessionId) {
const fineTuneData = getCourseFineTuneData(sessionId);
if (fineTuneData) {
paramsGoal = fineTuneData.goal;
paramsAbout = fineTuneData.about;
paramsCustomInstructions = fineTuneData.customInstructions;
setGoal(paramsGoal);
setAbout(paramsAbout);
setCustomInstructions(paramsCustomInstructions);
}
}
handleGenerateCourse({
term: paramsTerm,
difficulty: paramsDifficulty,
instructions: paramsCustomInstructions,
goal: paramsGoal,
about: paramsAbout,
});
}, [term, difficulty]);
const handleGenerateCourse = async (options: {
term: string;
difficulty: string;
instructions?: string;
goal?: string;
about?: string;
isForce?: boolean;
prompt?: string;
}) => {
const { term, difficulty, isForce, prompt, instructions, goal, about } =
options;
if (!isLoggedIn()) {
window.location.href = '/ai';
return;
}
await generateCourse({
term,
difficulty,
slug: courseSlug,
onCourseIdChange: setCourseId,
onCourseSlugChange: setCourseSlug,
onCourseChange: setCourse,
onLoadingChange: setIsLoading,
onError: setError,
instructions,
goal,
about,
isForce,
prompt,
});
};
useEffect(() => {
const handlePopState = (e: PopStateEvent) => {
const { courseId, courseSlug, term, difficulty } = e.state || {};
if (!courseId || !courseSlug) {
window.location.reload();
return;
}
setCourseId(courseId);
setCourseSlug(courseSlug);
setTerm(term);
setDifficulty(difficulty);
setIsLoading(true);
handleGenerateCourse({ term, difficulty }).finally(() => {
setIsLoading(false);
});
};
window.addEventListener('popstate', handlePopState);
return () => {
window.removeEventListener('popstate', handlePopState);
};
}, []);
return (
<AICourseContent
courseSlug={courseSlug}
course={course}
isLoading={isLoading}
error={error}
onRegenerateOutline={(prompt) => {
handleGenerateCourse({
term,
difficulty,
isForce: true,
prompt,
});
}}
/>
);
}

@ -0,0 +1,107 @@
import { useQuery } from '@tanstack/react-query';
import { getAiCourseOptions } from '../../queries/ai-course';
import { queryClient } from '../../stores/query-client';
import { useEffect, useState } from 'react';
import { AICourseContent } from './AICourseContent';
import { isLoggedIn } from '../../lib/jwt';
import { generateCourse } from '../../helper/generate-ai-course';
type GetAICourseProps = {
courseSlug: string;
};
export function GetAICourse(props: GetAICourseProps) {
const { courseSlug } = props;
const [isLoading, setIsLoading] = useState(true);
const [isRegenerating, setIsRegenerating] = useState(false);
const [error, setError] = useState('');
const { data: aiCourse, error: queryError } = useQuery(
{
...getAiCourseOptions({ aiCourseSlug: courseSlug }),
enabled: !!courseSlug && !!isLoggedIn(),
},
queryClient,
);
useEffect(() => {
if (!isLoggedIn()) {
window.location.href = '/ai';
}
}, [isLoggedIn]);
useEffect(() => {
if (!aiCourse) {
return;
}
setIsLoading(false);
}, [aiCourse]);
useEffect(() => {
if (!queryError) {
return;
}
setIsLoading(false);
setError(queryError.message);
}, [queryError]);
const handleRegenerateCourse = async (prompt?: string) => {
if (!aiCourse) {
return;
}
queryClient.setQueryData(
getAiCourseOptions({ aiCourseSlug: courseSlug }).queryKey,
{
...aiCourse,
title: '',
difficulty: '',
modules: [],
},
);
await generateCourse({
term: aiCourse.keyword,
difficulty: aiCourse.difficulty,
slug: courseSlug,
prompt,
onCourseChange: (course, rawData) => {
queryClient.setQueryData(
getAiCourseOptions({ aiCourseSlug: courseSlug }).queryKey,
{
...aiCourse,
title: course.title,
difficulty: course.difficulty,
modules: course.modules,
},
);
},
onLoadingChange: (isNewLoading) => {
setIsRegenerating(isNewLoading);
if (!isNewLoading) {
// TODO: Update progress
}
},
onError: setError,
isForce: true,
});
};
return (
<AICourseContent
course={{
title: aiCourse?.title || '',
modules: aiCourse?.modules || [],
difficulty: aiCourse?.difficulty || 'Easy',
done: aiCourse?.done || [],
}}
isLoading={isLoading || isRegenerating}
courseSlug={courseSlug}
error={error}
onRegenerateOutline={handleRegenerateCourse}
/>
);
}

@ -0,0 +1,69 @@
import { useState } from 'react';
import { Modal } from '../Modal';
export type ModifyCoursePromptProps = {
onClose: () => void;
onSubmit: (prompt: string) => void;
};
export function ModifyCoursePrompt(props: ModifyCoursePromptProps) {
const { onClose, onSubmit } = props;
const [prompt, setPrompt] = useState('');
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
onSubmit(prompt);
};
return (
<Modal
onClose={onClose}
wrapperClassName="rounded-xl max-w-xl w-full h-auto"
bodyClassName="p-6"
overlayClassName="items-start md:items-center"
>
<div className="flex flex-col gap-4">
<div>
<h2 className="mb-2 text-left text-xl font-semibold">
Give AI more context
</h2>
<p className="text-sm text-gray-500">
Pass additional information to the AI to generate a course outline.
</p>
</div>
<form className="flex flex-col gap-2" onSubmit={handleSubmit}>
<textarea
id="prompt"
autoFocus
rows={3}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
className="w-full rounded-md border border-gray-200 p-2 placeholder:text-sm focus:outline-black"
placeholder="e.g. make sure to add a section on React hooks"
/>
<p className="text-sm text-gray-500">
Complete the sentence: "I want AI to..."
</p>
<div className="flex justify-end gap-2">
<button
className="rounded-md bg-gray-200 px-4 py-2.5 text-sm text-black hover:opacity-80"
onClick={onClose}
>
Cancel
</button>
<button
type="submit"
disabled={!prompt.trim()}
className="rounded-md bg-black px-4 py-2.5 text-sm text-white hover:opacity-80 disabled:opacity-50"
>
Modify Prompt
</button>
</div>
</form>
</div>
</Modal>
);
}

@ -0,0 +1,88 @@
import { PenSquare, RefreshCcw } from 'lucide-react';
import { useRef, useState } from 'react';
import { useOutsideClick } from '../../hooks/use-outside-click';
import { cn } from '../../lib/classname';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
import { ModifyCoursePrompt } from './ModifyCoursePrompt';
type RegenerateLessonProps = {
onRegenerateLesson: (prompt?: string) => void;
};
export function RegenerateLesson(props: RegenerateLessonProps) {
const { onRegenerateLesson } = props;
const [isDropdownVisible, setIsDropdownVisible] = useState(false);
const [showUpgradeModal, setShowUpgradeModal] = useState(false);
const [showPromptModal, setShowPromptModal] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useOutsideClick(ref, () => setIsDropdownVisible(false));
return (
<>
{showUpgradeModal && (
<UpgradeAccountModal
onClose={() => {
setShowUpgradeModal(false);
}}
/>
)}
{showPromptModal && (
<ModifyCoursePrompt
title="Give AI more context"
description="Pass additional information to the AI to generate a lesson."
onClose={() => setShowPromptModal(false)}
onSubmit={(prompt) => {
setShowPromptModal(false);
onRegenerateLesson(prompt);
}}
/>
)}
<div className="relative mr-2 flex items-center" ref={ref}>
<button
className={cn('rounded-full p-1 text-gray-400 hover:text-black', {
'text-black': isDropdownVisible,
})}
onClick={() => setIsDropdownVisible(!isDropdownVisible)}
>
<PenSquare className="text-current" size={16} strokeWidth={2.5} />
</button>
{isDropdownVisible && (
<div className="absolute right-0 top-full min-w-[170px] overflow-hidden rounded-md border border-gray-200 bg-white">
<button
onClick={() => {
onRegenerateLesson();
}}
className="flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm text-gray-600 hover:bg-gray-100"
>
<RefreshCcw
size={16}
className="text-gray-400"
strokeWidth={2.5}
/>
Regenerate
</button>
<button
onClick={() => {
setIsDropdownVisible(false);
setShowPromptModal(true);
}}
className="flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm text-gray-600 hover:bg-gray-100"
>
<PenSquare
size={16}
className="text-gray-400"
strokeWidth={2.5}
/>
Modify Prompt
</button>
</div>
)}
</div>
</>
);
}

@ -0,0 +1,89 @@
import { PenSquare, RefreshCcw } from 'lucide-react';
import { useRef, useState } from 'react';
import { useOutsideClick } from '../../hooks/use-outside-click';
import { cn } from '../../lib/classname';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
import { ModifyCoursePrompt } from './ModifyCoursePrompt';
type RegenerateOutlineProps = {
onRegenerateOutline: (prompt?: string) => void;
};
export function RegenerateOutline(props: RegenerateOutlineProps) {
const { onRegenerateOutline } = props;
const [isDropdownVisible, setIsDropdownVisible] = useState(false);
const [showUpgradeModal, setShowUpgradeModal] = useState(false);
const [showPromptModal, setShowPromptModal] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useOutsideClick(ref, () => setIsDropdownVisible(false));
return (
<>
{showUpgradeModal && (
<UpgradeAccountModal
onClose={() => {
setShowUpgradeModal(false);
}}
/>
)}
{showPromptModal && (
<ModifyCoursePrompt
onClose={() => setShowPromptModal(false)}
onSubmit={(prompt) => {
setShowPromptModal(false);
onRegenerateOutline(prompt);
}}
/>
)}
<div ref={ref} className="flex relative items-stretch">
<button
className={cn(
'rounded-md px-2.5 text-gray-400 hover:text-black',
{
'text-black': isDropdownVisible,
},
)}
onClick={() => setIsDropdownVisible(!isDropdownVisible)}
>
<PenSquare className="text-current" size={16} strokeWidth={2.5} />
</button>
{isDropdownVisible && (
<div className="absolute right-0 top-full translate-y-1 min-w-[170px] overflow-hidden rounded-md border border-gray-200 bg-white shadow-md">
<button
onClick={() => {
onRegenerateOutline();
}}
className="flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm text-gray-600 hover:bg-gray-100"
>
<RefreshCcw
size={16}
className="text-gray-400"
strokeWidth={2.5}
/>
Regenerate
</button>
<button
onClick={() => {
setIsDropdownVisible(false);
setShowPromptModal(true);
}}
className="flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm text-gray-600 hover:bg-gray-100"
>
<PenSquare
size={16}
className="text-gray-400"
strokeWidth={2.5}
/>
Modify Prompt
</button>
</div>
)}
</div>
</>
);
}

@ -0,0 +1,42 @@
import { GripVertical } from 'lucide-react';
import * as ResizablePrimitive from 'react-resizable-panels';
import { cn } from '../../lib/classname';
const ResizablePanelGroup = ({
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (
<ResizablePrimitive.PanelGroup
className={cn(
'flex h-full w-full data-[panel-group-direction=vertical]:flex-col',
className,
)}
{...props}
/>
);
const ResizablePanel = ResizablePrimitive.Panel;
const ResizableHandle = ({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean;
}) => (
<ResizablePrimitive.PanelResizeHandle
className={cn(
'relative flex w-px items-center justify-center bg-gray-200 after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90',
className,
)}
{...props}
>
{withHandle && (
<div className="z-10 flex h-[30px] w-3 items-center justify-center rounded-sm bg-gray-200 text-black hover:bg-gray-300">
<GripVertical className="size-5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
);
export { ResizablePanelGroup, ResizablePanel, ResizableHandle };

@ -0,0 +1,473 @@
import {
ChevronLeftIcon,
ChevronRightIcon,
CircleCheckIcon,
CircleIcon,
CircleXIcon,
FlaskConicalIcon,
FrownIcon,
Loader2Icon,
} from 'lucide-react';
import { cn } from '../../lib/classname';
import {
generateAiCourseLessonQuestions,
readStream,
type Question,
} from '../../lib/ai';
import { useCallback, useMemo, useState } from 'react';
import { isLoggedIn, removeAuthToken } from '../../lib/jwt';
type TestMyKnowledgeActionProps = {
courseSlug: string;
activeModuleIndex: number;
activeLessonIndex: number;
};
export function TestMyKnowledgeAction(props: TestMyKnowledgeActionProps) {
const { courseSlug, activeModuleIndex, activeLessonIndex } = props;
const [questions, setQuestions] = useState<Question[]>([]);
const [isKnowledgeTestOpen, setIsKnowledgeTestOpen] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [isGenerating, setIsGenerating] = useState(false);
const [error, setError] = useState('');
const abortController = useMemo(
() => new AbortController(),
[activeModuleIndex, activeLessonIndex],
);
const generateAiLessonQuestions = async () => {
setIsLoading(true);
setError('');
if (!isLoggedIn()) {
setIsLoading(false);
setError('Please login to generate course content');
return;
}
const response = await fetch(
`${import.meta.env.PUBLIC_API_URL}/v1-generate-ai-course-lesson-question/${courseSlug}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
signal: abortController.signal,
credentials: 'include',
body: JSON.stringify({
moduleIndex: activeModuleIndex,
lessonIndex: activeLessonIndex,
}),
},
);
if (!response.ok) {
const data = await response.json();
setError(data?.message || 'Something went wrong');
setIsLoading(false);
// Logout user if token is invalid
if (data.status === 401) {
removeAuthToken();
window.location.reload();
}
return;
}
if (!response.body) {
setIsLoading(false);
setError('No response body received');
return;
}
try {
const reader = response.body.getReader();
setIsLoading(false);
setIsGenerating(true);
await readStream(reader, {
onStream: async (result) => {
if (abortController.signal.aborted) {
return;
}
const questions = generateAiCourseLessonQuestions(result);
setQuestions(questions);
},
onStreamEnd: async (result) => {
if (abortController.signal.aborted) {
return;
}
const questions = generateAiCourseLessonQuestions(result);
setQuestions(questions);
setIsGenerating(false);
},
});
} catch (e) {
setError(e instanceof Error ? e.message : 'Something went wrong');
setIsLoading(false);
setIsGenerating(false);
}
};
return (
<div className="mt-10 flex flex-col gap-4">
{!isKnowledgeTestOpen && (
<div className="flex items-center gap-2">
<button
className={cn(
'group flex flex-shrink-0 items-center gap-2 rounded-xl border border-gray-200 bg-white px-6 py-3 text-sm font-medium text-gray-700 transition-all hover:border-black hover:bg-gray-50 hover:text-gray-900',
{
'bg-gray-100 text-gray-900': isKnowledgeTestOpen,
},
)}
onClick={() => {
if (isGenerating || isLoading) {
return;
}
if (!isKnowledgeTestOpen) {
setIsKnowledgeTestOpen(true);
generateAiLessonQuestions();
} else {
setIsKnowledgeTestOpen(false);
}
}}
>
<FlaskConicalIcon className="size-5 shrink-0 transition-transform group-hover:scale-110" />
<span>Test My Knowledge</span>
</button>
</div>
)}
{error && (
<div className="flex min-h-[200px] flex-col items-center justify-center gap-3 rounded-xl bg-red-50/80 p-6 text-red-500">
<FrownIcon className="size-12 shrink-0" />
<span className="text-center font-semibold">{error}</span>
</div>
)}
{!error && isKnowledgeTestOpen && (
<ListQuestions
isLoading={isLoading}
isGenerating={isGenerating}
questions={questions}
/>
)}
</div>
);
}
type ListQuestionsProps = {
isLoading: boolean;
isGenerating: boolean;
questions: Question[];
};
export function ListQuestions(props: ListQuestionsProps) {
const { isLoading, isGenerating, questions } = props;
const [selectedAnswers, setSelectedAnswers] = useState<
Record<string, string[]>
>({});
const [submitted, setSubmitted] = useState(false);
const [activeQuestionIndex, setActiveQuestionIndex] = useState(0);
const activeQuestion = questions[activeQuestionIndex];
const handleOptionSelectChange = function (
questionId: string,
optionId: string,
) {
setSelectedAnswers((prev) => {
const newAnswers = { ...prev };
const canMultiSelect =
activeQuestion.options.filter((option) => option.isCorrect).length > 1;
const isAlreadySelected = selectedAnswers[questionId]?.includes(optionId);
if (isAlreadySelected) {
newAnswers[questionId] = newAnswers[questionId].filter(
(id) => id !== optionId,
);
} else {
if (canMultiSelect) {
newAnswers[questionId] = [
...(newAnswers[questionId] || []),
optionId,
];
} else {
newAnswers[questionId] = [optionId];
}
}
return newAnswers;
});
};
const handleNext = useCallback(() => {
const isLastQuestion = activeQuestionIndex === questions.length - 1;
if (isLastQuestion) {
setSubmitted(true);
setActiveQuestionIndex(0);
return;
}
setActiveQuestionIndex(activeQuestionIndex + 1);
}, [activeQuestionIndex, questions, submitted]);
const handlePrevious = useCallback(() => {
setActiveQuestionIndex((prev) => Math.max(prev - 1, 0));
}, [questions]);
const handleTryAgain = useCallback(() => {
setSelectedAnswers({});
setSubmitted(false);
setActiveQuestionIndex(0);
}, []);
const correctAnswerCount = useMemo(() => {
if (!submitted) {
return 0;
}
return questions.filter((question) => {
const selectedOptionIds = selectedAnswers[question.id];
const correctAnswerIds = question.options
.filter((option) => option.isCorrect)
.map((option) => option.id);
return (
correctAnswerIds.length === selectedOptionIds?.length &&
correctAnswerIds.every((correctAnswerId) =>
selectedOptionIds?.includes(correctAnswerId),
)
);
}).length;
}, [questions, selectedAnswers, submitted]);
if (isLoading || !questions.length) {
return (
<div className="flex h-[306px] w-full items-center justify-center rounded-lg border p-5 text-black">
<Loader2Icon className="size-8 animate-spin stroke-[2.5] text-gray-400" />
</div>
);
}
return (
<QuizItem
counter={activeQuestionIndex + 1}
totalQuestions={questions.length}
correctAnswerCount={correctAnswerCount}
isLoading={isGenerating}
question={activeQuestion}
onOptionSelectChange={handleOptionSelectChange}
selectedOptionIds={selectedAnswers[activeQuestion.id]}
submitted={submitted}
onNext={handleNext}
onPrevious={handlePrevious}
onTryAgain={handleTryAgain}
/>
);
}
type QuizItemProps = {
totalQuestions: number;
correctAnswerCount: number;
counter: number;
question: Question;
onOptionSelectChange?: (id: string, optionId: string) => void;
selectedOptionIds?: string[];
submitted?: boolean;
isLoading: boolean;
onNext?: () => void;
onPrevious?: () => void;
onTryAgain?: () => void;
};
export function QuizItem(props: QuizItemProps) {
const {
totalQuestions,
correctAnswerCount,
counter,
isLoading,
question,
onOptionSelectChange,
selectedOptionIds,
submitted = false,
onNext,
onPrevious,
onTryAgain,
} = props;
const { id: questionId, title, options } = question;
const canMultiSelect =
options.filter((option) => option.isCorrect).length > 1;
const correctAnswerIds = options
.filter((option) => option.isCorrect)
.map((option) => option.id);
const isAllCorrectAnswer =
correctAnswerIds.length === selectedOptionIds?.length &&
correctAnswerIds.every((correctAnswerId) =>
selectedOptionIds?.includes(correctAnswerId),
);
const hasWrongAnswer = submitted && !isAllCorrectAnswer;
const hasCorrectAnswer = submitted && isAllCorrectAnswer;
return (
<div
className={cn(
'relative w-full overflow-hidden rounded-xl border text-black transition-all',
{
'border-red-400': hasWrongAnswer,
'border-green-500': hasCorrectAnswer,
},
)}
>
<div className="flex items-center gap-4 rounded-t-xl border-b bg-gradient-to-r from-gray-50 to-white p-5">
<span className="text-sm font-medium text-gray-700">
Question {counter} of {totalQuestions}
</span>
<div className="h-2 flex-1 rounded-full bg-gray-100">
<div
className="h-full rounded-full bg-black transition-all duration-300"
style={{ width: `${(counter / totalQuestions) * 100}%` }}
/>
</div>
{submitted && (
<span
className={cn('rounded-full px-3 py-1 text-xs font-medium', {
'bg-red-500 text-white': hasWrongAnswer,
'bg-green-500 text-white': hasCorrectAnswer,
})}
>
{hasWrongAnswer ? 'Wrong' : 'Correct'}
</span>
)}
</div>
<div className="p-6">
<h3 className="mx-2 text-balance text-xl font-medium">
{title} {canMultiSelect ? '(Select Multiple)' : ''}
</h3>
<div className="mt-6 flex flex-col gap-0.5">
{options.map((option, index) => {
let status: QuizOptionStatus = 'default';
if (submitted) {
if (option.isCorrect) {
status = 'correct';
} else if (selectedOptionIds?.includes(option.id)) {
status = 'wrong';
}
} else {
if (selectedOptionIds?.includes(option.id)) {
status = 'selected';
}
}
return (
<QuizOption
key={index}
title={option.title}
status={status}
onSelect={() => onOptionSelectChange?.(questionId, option.id)}
submitted={submitted}
/>
);
})}
</div>
<div className="mt-6 flex w-full items-center justify-between px-2">
<div className="text-gray-600">
{submitted ? (
<span className="flex items-center gap-2">
You got {correctAnswerCount} out of {totalQuestions} correct.
<button
className="relative rounded-md bg-black px-3 py-1 text-xs font-medium uppercase tracking-wider text-white transition-colors hover:bg-black/80"
onClick={onTryAgain}
>
Try again
</button>
</span>
) : (
<span>Answer all questions to submit</span>
)}
</div>
<div className="flex gap-2">
<button
className="group flex h-10 items-center justify-center gap-1 rounded-lg border border-gray-200 p-2 pr-4 text-sm text-black transition-all hover:border-black hover:bg-black hover:text-white focus:outline-none max-sm:pr-2"
onClick={onPrevious}
>
<ChevronLeftIcon className="size-5 shrink-0 transition-transform group-hover:-translate-x-0.5" />
<span className="max-sm:hidden">Previous</span>
</button>
<button
className="group flex h-10 items-center justify-center gap-1 rounded-lg border border-gray-200 p-2 pl-4 text-sm text-black transition-all hover:border-black hover:bg-black hover:text-white focus:outline-none max-sm:pl-2"
onClick={onNext}
>
<span className="max-sm:hidden">Next</span>
<ChevronRightIcon className="size-5 shrink-0 transition-transform group-hover:translate-x-0.5" />
</button>
</div>
</div>
</div>
{isLoading && (
<div className="absolute bg-white right-3 top-3 flex h-8 items-center justify-center gap-1 rounded-lg border border-gray-200 p-2 text-sm text-black hover:bg-black hover:text-white focus:outline-none">
<Loader2Icon className="size-5 animate-spin text-gray-400" />
</div>
)}
</div>
);
}
type QuizOptionStatus = 'default' | 'selected' | 'wrong' | 'correct';
type QuizOptionProps = {
title: string;
status?: QuizOptionStatus;
onSelect: () => void;
submitted?: boolean;
};
export function QuizOption(props: QuizOptionProps) {
const { title, status = 'default', onSelect, submitted = false } = props;
return (
<button
onClick={onSelect}
className={cn(
'group flex items-start gap-3 rounded-xl p-4 text-base transition-all disabled:cursor-not-allowed',
status === 'selected' && 'bg-black text-white',
status === 'wrong' && submitted && 'bg-red-100 text-red-800',
status === 'correct' && submitted && 'bg-green-100 text-green-800',
status === 'default' && 'bg-white hover:bg-gray-50',
submitted && status !== 'correct' && 'opacity-40',
)}
disabled={submitted}
>
<span className="mt-[2px]">
{status === 'wrong' && submitted && <CircleXIcon className="size-5" />}
{status === 'correct' && submitted && (
<CircleCheckIcon className="size-5" />
)}
{(status === 'selected' || status === 'default') && (
<CircleIcon className="size-5" />
)}
</span>
<p className="text-left">{title}</p>
</button>
);
}

@ -0,0 +1,195 @@
import { useQuery } from '@tanstack/react-query';
import {
getAiCourseLimitOptions,
listUserAiCoursesOptions,
type ListUserAiCoursesQuery,
} from '../../queries/ai-course';
import { queryClient } from '../../stores/query-client';
import { AICourseCard } from './AICourseCard';
import { useEffect, useState } from 'react';
import { Gift, Loader2, User2 } from 'lucide-react';
import { isLoggedIn } from '../../lib/jwt';
import { showLoginPopup } from '../../lib/popup';
import { cn } from '../../lib/classname';
import { useIsPaidUser } from '../../queries/billing';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal';
import { getUrlParams, setUrlParams, deleteUrlParam } from '../../lib/browser';
import { AICourseSearch } from './AICourseSearch';
import { Pagination } from '../Pagination/Pagination';
type UserCoursesListProps = {};
export function UserCoursesList(props: UserCoursesListProps) {
const [isInitialLoading, setIsInitialLoading] = useState(true);
const [showUpgradePopup, setShowUpgradePopup] = useState(false);
const [pageState, setPageState] = useState<ListUserAiCoursesQuery>({
perPage: '10',
currPage: '1',
query: '',
});
const { data: limits, isLoading: isLimitsLoading } = useQuery(
getAiCourseLimitOptions(),
queryClient,
);
const { used, limit } = limits ?? { used: 0, limit: 0 };
const { isPaidUser, isLoading: isPaidUserLoading } = useIsPaidUser();
const { data: userAiCourses, isFetching: isUserAiCoursesLoading } = useQuery(
listUserAiCoursesOptions(pageState),
queryClient,
);
useEffect(() => {
setIsInitialLoading(false);
}, [userAiCourses]);
const courses = userAiCourses?.data ?? [];
const isAuthenticated = isLoggedIn();
const limitUsedPercentage = Math.round((used / limit) * 100);
useEffect(() => {
const queryParams = getUrlParams();
setPageState({
...pageState,
currPage: queryParams?.p || '1',
query: queryParams?.q || '',
});
}, []);
useEffect(() => {
if (pageState?.currPage !== '1' || pageState?.query !== '') {
setUrlParams({
p: pageState?.currPage || '1',
q: pageState?.query || '',
});
} else {
deleteUrlParam('p');
deleteUrlParam('q');
}
}, [pageState]);
return (
<>
{showUpgradePopup && (
<UpgradeAccountModal onClose={() => setShowUpgradePopup(false)} />
)}
<div className="mb-3 flex min-h-[35px] items-center justify-between max-sm:mb-1">
<div className="flex items-center gap-2">
<h2 className="text-lg font-semibold">
<span className="max-md:hidden">Your </span>Courses
</h2>
</div>
<div className="flex items-center gap-2">
{used > 0 && limit > 0 && !isPaidUserLoading && (
<div
className={cn(
'pointer-events-none flex items-center gap-2 opacity-0 transition-opacity',
{
'pointer-events-auto opacity-100': !isPaidUser,
},
)}
>
<p className="flex items-center text-sm text-yellow-600">
<span className="max-md:hidden">
{limitUsedPercentage}% of daily limit used{' '}
</span>
<span className="inline md:hidden">
{limitUsedPercentage}% used
</span>
<button
onClick={() => {
setShowUpgradePopup(true);
}}
className="ml-1.5 flex items-center gap-1 rounded-full bg-yellow-600 py-0.5 pl-1.5 pr-2 text-xs text-white"
>
<Gift className="size-4" />
Upgrade
</button>
</p>
</div>
)}
<AICourseSearch
value={pageState?.query || ''}
onChange={(value) => {
setPageState({
...pageState,
query: value,
currPage: '1',
});
}}
/>
</div>
</div>
{!isInitialLoading && !isUserAiCoursesLoading && !isAuthenticated && (
<div className="flex min-h-[152px] flex-col items-center justify-center rounded-lg border border-gray-200 bg-white px-6 py-4">
<User2 className="mb-2 size-8 text-gray-300" />
<p className="max-w-sm text-balance text-center text-gray-500">
<button
onClick={() => {
showLoginPopup();
}}
className="font-medium text-black underline underline-offset-2 hover:opacity-80"
>
Sign up (free and takes 2s) or login
</button>{' '}
to generate and save courses.
</p>
</div>
)}
{!isUserAiCoursesLoading && !isInitialLoading && courses.length === 0 && isAuthenticated && (
<div className="flex min-h-[152px] items-center justify-center rounded-lg border border-gray-200 bg-white py-4">
<p className="text-sm text-gray-600">
You haven't generated any courses yet.
</p>
</div>
)}
{(isUserAiCoursesLoading || isInitialLoading) && (
<div className="flex min-h-[152px] items-center justify-center gap-2 rounded-lg border border-gray-200 bg-white py-4">
<Loader2
className="size-4 animate-spin text-gray-400"
strokeWidth={2.5}
/>
<p className="text-sm font-medium text-gray-600">Loading...</p>
</div>
)}
{!isUserAiCoursesLoading && courses && courses.length > 0 && (
<div className="flex flex-col gap-2">
{courses.map((course) => (
<AICourseCard key={course._id} course={course} />
))}
<Pagination
totalCount={userAiCourses?.totalCount || 0}
totalPages={userAiCourses?.totalPages || 0}
currPage={Number(userAiCourses?.currPage || 1)}
perPage={Number(userAiCourses?.perPage || 10)}
onPageChange={(page) => {
setPageState({ ...pageState, currPage: String(page) });
}}
className="rounded-lg border border-gray-200 bg-white p-4"
/>
</div>
)}
{!isUserAiCoursesLoading &&
(userAiCourses?.data?.length || 0 > 0) &&
courses.length === 0 && (
<div className="flex min-h-[114px] items-center justify-center rounded-lg border border-gray-200 bg-white py-4">
<p className="text-sm text-gray-600">
No courses match your search.
</p>
</div>
)}
</>
);
}

@ -128,32 +128,32 @@ export function AITermSuggestionInput(props: AITermSuggestionInputProps) {
return allRoadmaps;
};
useEffect(() => {
if (debouncedSearchValue.length === 0 || isFirstRender.current) {
setSearchResults([]);
return;
}
// useEffect(() => {
// if (debouncedSearchValue.length === 0 || isFirstRender.current) {
// setSearchResults([]);
// return;
// }
setIsActive(true);
setIsLoading(true);
loadTopAIRoadmapTerm()
.then((results) => {
const normalizedSearchText = debouncedSearchValue.trim().toLowerCase();
const matchingOfficialRoadmaps = officialRoadmaps.filter((roadmap) => {
return (
roadmap.title.toLowerCase().indexOf(normalizedSearchText) !== -1
);
});
// setIsActive(true);
// setIsLoading(true);
// loadTopAIRoadmapTerm()
// .then((results) => {
// const normalizedSearchText = debouncedSearchValue.trim().toLowerCase();
// const matchingOfficialRoadmaps = officialRoadmaps.filter((roadmap) => {
// return (
// roadmap.title.toLowerCase().indexOf(normalizedSearchText) !== -1
// );
// });
setSearchResults(
[...matchingOfficialRoadmaps, ...results]?.slice(0, 5) || [],
);
setActiveCounter(0);
})
.finally(() => {
setIsLoading(false);
});
}, [debouncedSearchValue]);
// setSearchResults(
// [...matchingOfficialRoadmaps, ...results]?.slice(0, 5) || [],
// );
// setActiveCounter(0);
// })
// .finally(() => {
// setIsLoading(false);
// });
// }, [debouncedSearchValue]);
useEffect(() => {
if (isFirstRender.current) {

@ -11,9 +11,7 @@ import {
import { useToast } from '../../hooks/use-toast';
import { generateAIRoadmapFromText, renderFlowJSON } from '@roadmapsh/editor';
import { replaceChildren } from '../../lib/dom';
import { readAIRoadmapStream } from '../../helper/read-stream';
import {
getOpenAIKey,
isLoggedIn,
removeAuthToken,
setAIReferralCode,
@ -21,7 +19,7 @@ import {
} from '../../lib/jwt';
import { RoadmapSearch } from './RoadmapSearch.tsx';
import { Spinner } from '../ReactIcons/Spinner.tsx';
import { Ban, Cog, Download, PenSquare, Save, Wand } from 'lucide-react';
import { Ban, Download, PenSquare, Save, Wand } from 'lucide-react';
import { ShareRoadmapButton } from '../ShareRoadmapButton.tsx';
import { httpGet, httpPost } from '../../lib/http.ts';
import { pageProgressMessage } from '../../stores/page.ts';
@ -31,10 +29,15 @@ import { showLoginPopup } from '../../lib/popup.ts';
import { cn } from '../../lib/classname.ts';
import { RoadmapTopicDetail } from './RoadmapTopicDetail.tsx';
import { AIRoadmapAlert } from './AIRoadmapAlert.tsx';
import { IS_KEY_ONLY_ROADMAP_GENERATION } from '../../lib/ai.ts';
import {
generateAICourseRoadmapStructure,
IS_KEY_ONLY_ROADMAP_GENERATION,
readAIRoadmapStream,
} from '../../lib/ai.ts';
import { AITermSuggestionInput } from './AITermSuggestionInput.tsx';
import { IncreaseRoadmapLimit } from './IncreaseRoadmapLimit.tsx';
import { AuthenticationForm } from '../AuthenticationFlow/AuthenticationForm.tsx';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal.tsx';
import { useIsPaidUser } from '../../queries/billing.ts';
export type GetAIRoadmapLimitResponse = {
used: number;
@ -52,6 +55,7 @@ export type RoadmapNodeDetails = {
targetGroup?: SVGElement;
nodeTitle?: string;
parentTitle?: string;
parentId?: string;
};
export function getNodeDetails(
@ -63,9 +67,10 @@ export function getNodeDetails(
const nodeType = targetGroup?.dataset?.type;
const nodeTitle = targetGroup?.dataset?.title;
const parentTitle = targetGroup?.dataset?.parentTitle;
const parentId = targetGroup?.dataset?.parentId;
if (!nodeId || !nodeType) return null;
return { nodeId, nodeType, targetGroup, nodeTitle, parentTitle };
return { nodeId, nodeType, targetGroup, nodeTitle, parentTitle, parentId };
}
export const allowedClickableNodeTypes = [
@ -97,6 +102,7 @@ export function GenerateRoadmap(props: GenerateRoadmapProps) {
const roadmapContainerRef = useRef<HTMLDivElement>(null);
const { isPaidUser, isLoading: isLoadingPaidUser } = useIsPaidUser();
const { rc: referralCode } = getUrlParams() as {
rc?: string;
};
@ -125,13 +131,11 @@ export function GenerateRoadmap(props: GenerateRoadmapProps) {
const [roadmapTopicLimitUsed, setRoadmapTopicLimitUsed] = useState(0);
const [isConfiguring, setIsConfiguring] = useState(false);
const [openAPIKey, setOpenAPIKey] = useState<string | undefined>(
getOpenAIKey(),
);
const isKeyOnly = IS_KEY_ONLY_ROADMAP_GENERATION;
const renderRoadmap = async (roadmap: string) => {
const { nodes, edges } = generateAIRoadmapFromText(roadmap);
const result = generateAICourseRoadmapStructure(roadmap);
const { nodes, edges } = generateAIRoadmapFromText(result);
const svg = await renderFlowJSON({ nodes, edges });
if (roadmapContainerRef?.current) {
replaceChildren(roadmapContainerRef?.current, svg);
@ -195,7 +199,7 @@ export function GenerateRoadmap(props: GenerateRoadmapProps) {
roadmapSlug,
},
'',
`${origin}/ai/${roadmapSlug}`,
`${origin}/ai-roadmaps/${roadmapSlug}`,
);
}
@ -473,15 +477,27 @@ export function GenerateRoadmap(props: GenerateRoadmapProps) {
);
}
const pageUrl = `https://roadmap.sh/ai/${roadmapSlug}`;
const canGenerateMore = roadmapLimitUsed < roadmapLimit;
const pageUrl = `https://roadmap.sh/ai-roadmaps/${roadmapSlug}`;
const canGenerateMore = roadmapLimitUsed < roadmapLimit || isPaidUser;
const isGenerateButtonDisabled =
isLoadingResults ||
(isAuthenticatedUser &&
// if no limit,
(!roadmapLimit ||
// no roadmap term,
!roadmapTerm ||
// if limit is reached and user is not paid user,
(roadmapLimitUsed >= roadmapLimit && !isPaidUser) ||
// if roadmap term is the same as the current roadmap term,
roadmapTerm === currentRoadmap?.term ||
// if key only,
isKeyOnly));
return (
<>
{isConfiguring && (
<IncreaseRoadmapLimit
<UpgradeAccountModal
onClose={() => {
setOpenAPIKey(getOpenAIKey());
setIsConfiguring(false);
loadAIRoadmapLimit().finally(() => null);
}}
@ -522,34 +538,21 @@ export function GenerateRoadmap(props: GenerateRoadmapProps) {
{!isLoading && (
<div className="container flex flex-grow flex-col items-start">
<AIRoadmapAlert />
{isKeyOnly && isAuthenticatedUser && (
{isKeyOnly && isAuthenticatedUser && !isPaidUser && (
<div className="flex flex-row gap-4">
{!openAPIKey && (
<p className={'text-left text-red-500'}>
We have hit the limit for AI roadmap generation. Please
try again tomorrow or{' '}
<button
onClick={() => setIsConfiguring(true)}
className="font-semibold text-purple-600 underline underline-offset-2"
>
add your own OpenAI API key
</button>
</p>
)}
{openAPIKey && (
<p className={'text-left text-gray-500'}>
You have added your own OpenAI API key.{' '}
<button
onClick={() => setIsConfiguring(true)}
className="font-semibold text-purple-600 underline underline-offset-2"
>
Configure it here if you want.
</button>
</p>
)}
<p className={'text-left text-red-500'}>
We have hit the limit for AI roadmap generation. Please try
again tomorrow or{' '}
<button
onClick={() => setIsConfiguring(true)}
className="font-semibold text-purple-600 underline underline-offset-2"
>
add more credits.
</button>
</p>
</div>
)}
{!isKeyOnly && isAuthenticatedUser && (
{!isKeyOnly && isAuthenticatedUser && !isPaidUser && (
<div className="mt-2 flex w-full flex-col items-start justify-between gap-2 text-sm sm:flex-row sm:items-center sm:gap-0">
<span>
<span
@ -565,25 +568,13 @@ export function GenerateRoadmap(props: GenerateRoadmapProps) {
</span>{' '}
roadmaps generated today.
</span>
{!openAPIKey && (
<button
onClick={() => setIsConfiguring(true)}
className="rounded-xl border border-current px-2 py-0.5 text-left text-sm text-blue-500 transition-colors hover:bg-blue-400 hover:text-white"
>
Need to generate more?{' '}
<span className="font-semibold">Click here.</span>
</button>
)}
{openAPIKey && (
<button
onClick={() => setIsConfiguring(true)}
className="flex flex-row items-center gap-1 rounded-xl border border-current px-2 py-0.5 text-sm text-blue-500 transition-colors hover:bg-blue-400 hover:text-white"
>
<Cog size={15} />
Configure OpenAI key
</button>
)}
<button
onClick={() => setIsConfiguring(true)}
className="rounded-xl border border-current px-2 py-0.5 text-left text-sm text-blue-500 transition-colors hover:bg-blue-400 hover:text-white"
>
Need to generate more?{' '}
<span className="font-semibold">Click here.</span>
</button>
</div>
)}
{!isAuthenticatedUser && (
@ -610,7 +601,7 @@ export function GenerateRoadmap(props: GenerateRoadmapProps) {
<button
type={'submit'}
className={cn(
'flex min-w-[127px] flex-shrink-0 items-center justify-center gap-2 rounded-md bg-black px-4 py-2 text-white',
'flex min-w-[127px] flex-shrink-0 items-center justify-center gap-2 rounded-md bg-black px-4 py-2.5 text-white',
'disabled:cursor-not-allowed disabled:opacity-50',
)}
onClick={(e) => {
@ -619,15 +610,7 @@ export function GenerateRoadmap(props: GenerateRoadmapProps) {
showLoginPopup();
}
}}
disabled={
isLoadingResults ||
(isAuthenticatedUser &&
(!roadmapLimit ||
!roadmapTerm ||
roadmapLimitUsed >= roadmapLimit ||
roadmapTerm === currentRoadmap?.term ||
(isKeyOnly && !openAPIKey)))
}
disabled={isGenerateButtonDisabled}
>
{isLoadingResults && (
<>

@ -1,68 +1,84 @@
import { useState } from 'react';
import { Check, Clipboard } from 'lucide-react';
import { useRef } from 'react';
import { useAuth } from '../../hooks/use-auth';
import { useCopyText } from '../../hooks/use-copy-text';
import { useToast } from '../../hooks/use-toast';
import { cn } from '../../lib/classname';
import { ChevronUp } from 'lucide-react';
import { Modal } from '../Modal';
import { ReferYourFriend } from './ReferYourFriend';
import { OpenAISettings } from './OpenAISettings';
import { PayToBypass } from './PayToBypass';
import { PickLimitOption } from './PickLimitOption';
import { getOpenAIKey } from '../../lib/jwt.ts';
export type IncreaseTab = 'api-key' | 'refer-friends' | 'payment';
export const increaseLimitTabs: {
key: IncreaseTab;
title: string;
}[] = [
{ key: 'api-key', title: 'Add your own API Key' },
{ key: 'refer-friends', title: 'Refer your Friends' },
{ key: 'payment', title: 'Pay to Bypass the limit' },
];
type IncreaseRoadmapLimitProps = {
onClose: () => void;
};
export function IncreaseRoadmapLimit(props: IncreaseRoadmapLimitProps) {
const { onClose } = props;
const openAPIKey = getOpenAIKey();
const [activeTab, setActiveTab] = useState<IncreaseTab | null>(
openAPIKey ? 'api-key' : null,
);
const user = useAuth();
const toast = useToast();
const inputRef = useRef<HTMLInputElement>(null);
const { copyText, isCopied } = useCopyText();
const referralLink = new URL(
`/ai?rc=${user?.id}`,
import.meta.env.DEV ? 'http://localhost:3000' : 'https://roadmap.sh',
).toString();
const handleCopy = () => {
inputRef.current?.select();
copyText(referralLink);
toast.success('Copied to clipboard');
};
return (
<Modal
onClose={onClose}
overlayClassName={cn(
'overscroll-contain',
activeTab === 'payment' && 'block',
)}
overlayClassName={cn('overscroll-contain')}
wrapperClassName="max-w-lg mx-auto"
bodyClassName={cn('h-auto pt-px', !activeTab && 'overflow-hidden')}
bodyClassName={cn('h-auto pt-px')}
>
{!activeTab && (
<PickLimitOption activeTab={activeTab} setActiveTab={setActiveTab} />
)}
<div className="p-4">
<h2 className="text-xl font-semibold text-gray-800">
Refer your Friends
</h2>
<p className="mt-2 text-sm text-gray-500">
Share the URL below with your friends. When they sign up with your
link, you will get extra roadmap generation credits.
</p>
<label className="mt-4 flex flex-col gap-2">
<input
ref={inputRef}
className="w-full rounded-md border bg-gray-100 p-2 px-2.5 text-gray-700 focus:outline-none"
value={referralLink}
readOnly={true}
onClick={handleCopy}
/>
{activeTab === 'api-key' && (
<OpenAISettings
onClose={() => {
onClose();
}}
onBack={() => setActiveTab(null)}
/>
)}
{activeTab === 'refer-friends' && (
<ReferYourFriend onBack={() => setActiveTab(null)} />
)}
{activeTab === 'payment' && (
<PayToBypass
onBack={() => setActiveTab(null)}
onClose={() => {
onClose();
}}
/>
)}
<button
className={cn(
'flex h-10 items-center justify-center gap-1.5 rounded-md p-2 px-2.5 text-sm',
{
'bg-green-500 text-black transition-colors': isCopied,
'rounded-md bg-black text-white': !isCopied,
},
)}
onClick={handleCopy}
disabled={isCopied}
>
{isCopied ? (
<>
<Check className="h-4 w-4" />
Copied to Clipboard
</>
) : (
<>
<Clipboard className="h-4 w-4" />
Copy URL
</>
)}
</button>
</label>
</div>
</Modal>
);
}

@ -1,171 +0,0 @@
import { useEffect, useState } from 'react';
import { deleteOpenAIKey, getOpenAIKey, saveOpenAIKey } from '../../lib/jwt.ts';
import { cn } from '../../lib/classname.ts';
import { CloseIcon } from '../ReactIcons/CloseIcon.tsx';
import { useToast } from '../../hooks/use-toast.ts';
import { httpPost } from '../../lib/http.ts';
import { ChevronLeft } from 'lucide-react';
type OpenAISettingsProps = {
onClose: () => void;
onBack: () => void;
};
export function OpenAISettings(props: OpenAISettingsProps) {
const { onClose, onBack } = props;
const [defaultOpenAIKey, setDefaultOpenAIKey] = useState('');
const [error, setError] = useState('');
const [openaiApiKey, setOpenaiApiKey] = useState('');
const [isLoading, setIsLoading] = useState(false);
const toast = useToast();
useEffect(() => {
const apiKey = getOpenAIKey();
setOpenaiApiKey(apiKey || '');
setDefaultOpenAIKey(apiKey || '');
}, []);
return (
<div className="p-4">
<button
onClick={onBack}
className="mb-5 flex items-center gap-1.5 text-sm leading-none opacity-40 transition-opacity hover:opacity-100 focus:outline-none"
>
<ChevronLeft size={16} />
Back to options
</button>
<h2 className="text-xl font-semibold text-gray-800">OpenAI Settings</h2>
<p className="mt-2 text-sm leading-normal text-gray-500">
Add your OpenAI API key below to bypass the roadmap generation limits.
You can use your existing key or{' '}
<a
className="underline underline-offset-2 hover:text-gray-900"
href={'https://platform.openai.com/signup'}
target="_blank"
>
create a new one here
</a>
.
</p>
<form
className="mt-4"
onSubmit={async (e) => {
e.preventDefault();
setError('');
const normalizedKey = openaiApiKey.trim();
if (!normalizedKey) {
deleteOpenAIKey();
toast.success('OpenAI API key removed');
onClose();
return;
}
if (!normalizedKey.startsWith('sk-')) {
setError("Invalid OpenAI API key. It should start with 'sk-'");
return;
}
setIsLoading(true);
const { response, error } = await httpPost(
`${import.meta.env.PUBLIC_API_URL}/v1-validate-openai-key`,
{
key: normalizedKey,
},
);
if (error) {
setError(error.message);
setIsLoading(false);
return;
}
// Save the API key to cookies
saveOpenAIKey(normalizedKey);
toast.success('OpenAI API key saved');
onClose();
}}
>
<div className="relative">
<input
type="text"
name="openai-api-key"
id="openai-api-key"
className={cn(
'block w-full rounded-md border border-gray-300 px-3 py-2 text-gray-800 transition-colors focus:border-black focus:outline-none',
{
'border-red-500 bg-red-100 focus:border-red-500': error,
},
)}
placeholder="Enter your OpenAI API key"
value={openaiApiKey}
onChange={(e) => {
setError('');
setOpenaiApiKey((e.target as HTMLInputElement).value);
}}
/>
{openaiApiKey && (
<button
type={'button'}
onClick={() => {
setOpenaiApiKey('');
}}
className="absolute right-2 top-1/2 flex h-[20px] w-[20px] -translate-y-1/2 items-center justify-center rounded-full bg-gray-400 text-white hover:bg-gray-600"
>
<CloseIcon className="h-[13px] w-[13px] stroke-[3.5]" />
</button>
)}
</div>
<p className={'mb-2 mt-1 text-xs text-gray-500'}>
We do not store your API key on our servers.
</p>
{error && (
<p className="mt-2 text-sm text-red-500">
{error}
</p>
)}
<button
disabled={isLoading}
type="submit"
className={
'mt-2 w-full rounded-md bg-gray-700 px-4 py-2 text-white transition-colors hover:bg-black disabled:cursor-not-allowed disabled:opacity-50'
}
>
{!isLoading && 'Save'}
{isLoading && 'Validating ..'}
</button>
{!defaultOpenAIKey && (
<button
type="button"
onClick={() => {
onClose();
}}
className="mt-1 w-full rounded-md border border-red-500 px-4 py-2 text-sm text-red-600 transition-colors hover:bg-red-700 hover:text-white"
>
Cancel
</button>
)}
{defaultOpenAIKey && (
<button
type="button"
onClick={() => {
deleteOpenAIKey();
onClose();
toast.success('OpenAI API key removed');
}}
className="mt-1 w-full rounded-md border border-red-500 px-4 py-2 text-sm text-red-600 transition-colors hover:bg-red-700 hover:text-white"
>
Remove API Key
</button>
)}
</form>
</div>
);
}

@ -1,50 +0,0 @@
import { ChevronRight, ChevronUpIcon } from 'lucide-react';
import { cn } from '../../lib/classname';
import { increaseLimitTabs, type IncreaseTab } from './IncreaseRoadmapLimit';
type PickLimitOptionProps = {
activeTab: IncreaseTab | null;
setActiveTab: (tab: IncreaseTab | null) => void;
};
export function PickLimitOption(props: PickLimitOptionProps) {
const { activeTab, setActiveTab } = props;
return (
<>
<div className="p-4">
<h2 className="text-xl font-semibold text-gray-800">
Generate more Roadmaps
</h2>
<p className="mt-2 text-sm text-gray-700">
Pick one of the options below to increase your roadmap limit.
</p>
</div>
<div className="flex w-full flex-col gap-1 px-3 pb-4">
{increaseLimitTabs.map((tab) => {
const isActive = tab.key === activeTab;
return (
<button
key={tab.key}
onClick={() => {
setActiveTab(isActive ? null : tab.key);
}}
className={cn(
'flex w-full items-center justify-between gap-2 rounded-md border-t py-2 text-sm font-medium pl-3 pr-3',
{
'bg-gray-100 text-gray-800': isActive,
'bg-gray-200 hover:bg-gray-300 transition-colors text-black': !isActive,
},
)}
>
{tab.title}
<ChevronRight size={16} />
</button>
);
})}
</div>
</>
);
}

@ -1,4 +1,4 @@
import { Check, ChevronLeft, Clipboard } from 'lucide-react';
import { Check, Clipboard } from 'lucide-react';
import { useAuth } from '../../hooks/use-auth';
import { useCopyText } from '../../hooks/use-copy-text';
import { useToast } from '../../hooks/use-toast';
@ -30,14 +30,6 @@ export function ReferYourFriend(props: ReferYourFriendProps) {
return (
<div className="p-4">
<button
onClick={onBack}
className="mb-5 flex items-center gap-1.5 text-sm leading-none opacity-40 transition-opacity hover:opacity-100 focus:outline-none"
>
<ChevronLeft size={16} />
Back to options
</button>
<h2 className="text-xl font-semibold text-gray-800">
Refer your Friends
</h2>

@ -1,12 +1,12 @@
import { ArrowUpRight, Ban, Cog, Telescope, Wand } from 'lucide-react';
import { ArrowUpRight, Ban, Telescope, Wand } from 'lucide-react';
import type { FormEvent } from 'react';
import { useEffect, useState } from 'react';
import { getOpenAIKey, isLoggedIn } from '../../lib/jwt';
import { isLoggedIn } from '../../lib/jwt';
import { showLoginPopup } from '../../lib/popup';
import { cn } from '../../lib/classname.ts';
import { OpenAISettings } from './OpenAISettings.tsx';
import { AITermSuggestionInput } from './AITermSuggestionInput.tsx';
import { IncreaseRoadmapLimit } from './IncreaseRoadmapLimit.tsx';
import { UpgradeAccountModal } from '../Billing/UpgradeAccountModal.tsx';
import { useIsPaidUser } from '../../queries/billing.ts';
type RoadmapSearchProps = {
roadmapTerm: string;
@ -31,14 +31,13 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
isKeyOnly,
} = props;
const { isPaidUser, isLoading } = useIsPaidUser();
const canGenerateMore = limitUsed < limit;
const [isConfiguring, setIsConfiguring] = useState(false);
const [openAPIKey, setOpenAPIKey] = useState('');
const [isAuthenticatedUser, setIsAuthenticatedUser] = useState(false);
const [isLoadingResults, setIsLoadingResults] = useState(false);
useEffect(() => {
setOpenAPIKey(getOpenAIKey() || '');
setIsAuthenticatedUser(isLoggedIn());
}, []);
@ -47,9 +46,8 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
return (
<div className="flex flex-grow flex-col items-center px-4 py-6 sm:px-6 md:my-24 lg:my-32">
{isConfiguring && (
<IncreaseRoadmapLimit
<UpgradeAccountModal
onClose={() => {
setOpenAPIKey(getOpenAIKey()!);
setIsConfiguring(false);
loadAIRoadmapLimit();
}}
@ -104,10 +102,7 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
disabled={
isLoadingResults ||
(isAuthenticatedUser &&
(!limit ||
!roadmapTerm ||
limitUsed >= limit ||
(isKeyOnly && !openAPIKey)))
(!limit || !roadmapTerm || limitUsed >= limit || isKeyOnly))
}
>
{isLoadingResults && (
@ -165,7 +160,7 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
</button>
))}
<a
href="/ai/explore"
href="/ai-roadmaps/explore"
className="flex items-center gap-1.5 rounded-full border border-black bg-gray-700 px-2 py-0.5 text-sm text-white transition-colors hover:border-black hover:bg-black"
>
Explore AI Roadmaps <Telescope size={17} />
@ -186,7 +181,7 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
</p>
<p className="flex flex-col gap-2 text-center text-gray-500 sm:flex-row">
<a
href="/ai/explore"
href="/ai-roadmaps/explore"
className="flex items-center gap-1.5 rounded-full border border-purple-600 px-2.5 py-0.5 text-sm text-purple-600 transition-colors hover:bg-purple-600 hover:text-white"
>
Explore AI Generated Roadmaps <Telescope size={15} />
@ -200,37 +195,22 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
</p>
</div>
)}
{isKeyOnly && isAuthenticatedUser && (
{isKeyOnly && isAuthenticatedUser && !isPaidUser && (
<div className="mx-auto mt-12 flex max-w-[450px] flex-col items-center gap-4">
{!openAPIKey && (
<>
<p className={'text-center text-red-500'}>
We have hit the limit for AI roadmap generation. Please try
again later or{' '}
<button
onClick={() => setIsConfiguring(true)}
className="font-semibold text-purple-600 underline underline-offset-2"
>
add your own OpenAI API key.
</button>
</p>
</>
)}
{openAPIKey && (
<p className={'text-center text-gray-500'}>
You have added your own OpenAI API key.{' '}
<button
onClick={() => setIsConfiguring(true)}
className="font-semibold text-purple-600 underline underline-offset-2"
>
Configure it here if you want.
</button>
</p>
)}
<p className={'text-center text-red-500'}>
We have hit the limit for AI roadmap generation. Please try again
again later or{' '}
<button
onClick={() => setIsConfiguring(true)}
className="font-semibold text-purple-600 underline underline-offset-2"
>
get more credits.
</button>
</p>
<p className="flex flex-col gap-2 text-center text-gray-500 sm:flex-row">
<a
href="/ai/explore"
href="/ai-roadmaps/explore"
className="flex items-center gap-1.5 rounded-full border border-purple-600 px-2.5 py-0.5 text-sm text-purple-600 transition-colors hover:bg-purple-600 hover:text-white"
>
Explore AI Roadmaps <Telescope size={15} />
@ -244,7 +224,7 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
</p>
</div>
)}
{!isKeyOnly && limit > 0 && isAuthenticatedUser && (
{!isKeyOnly && limit > 0 && isAuthenticatedUser && !isPaidUser && (
<div className="mt-12 flex flex-col items-center gap-4">
<p className="text-center text-gray-500">
You have generated{' '}
@ -257,29 +237,15 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
</span>{' '}
roadmaps today.
</p>
{isAuthenticatedUser && (
<p className="flex items-center text-sm">
{!openAPIKey && (
<button
onClick={() => setIsConfiguring(true)}
className="rounded-xl border border-current px-2 py-0.5 text-sm text-blue-500 transition-colors hover:bg-blue-400 hover:text-white"
>
Need to generate more?{' '}
<span className="font-semibold">Click here.</span>
</button>
)}
{openAPIKey && (
<button
onClick={() => setIsConfiguring(true)}
className="flex flex-row items-center gap-1 rounded-xl border border-current px-2 py-0.5 text-sm text-blue-500 transition-colors hover:bg-blue-400 hover:text-white"
>
<Cog size={15} />
Configure OpenAI key
</button>
)}
</p>
)}
<p className="flex items-center text-sm">
<button
onClick={() => setIsConfiguring(true)}
className="rounded-xl border border-current px-2 py-0.5 text-sm text-blue-500 transition-colors hover:bg-blue-400 hover:text-white"
>
Need to generate more?{' '}
<span className="font-semibold">Click here.</span>
</button>
</p>
</div>
)}
</div>

@ -3,13 +3,13 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { useKeydown } from '../../hooks/use-keydown';
import { useOutsideClick } from '../../hooks/use-outside-click';
import { markdownToHtml } from '../../lib/markdown';
import { Ban, Cog, Contact, FileText, User, UserRound, X } from 'lucide-react';
import { Ban, Contact, FileText, X, ArrowRight } from 'lucide-react';
import { Spinner } from '../ReactIcons/Spinner';
import type { RoadmapNodeDetails } from './GenerateRoadmap';
import { getOpenAIKey, isLoggedIn, removeAuthToken } from '../../lib/jwt';
import { readAIRoadmapContentStream } from '../../helper/read-stream';
import { isLoggedIn, removeAuthToken } from '../../lib/jwt';
import { cn } from '../../lib/classname';
import { showLoginPopup } from '../../lib/popup';
import { readAIRoadmapContentStream } from '../../lib/ai';
type RoadmapTopicDetailProps = RoadmapNodeDetails & {
onClose?: () => void;
@ -35,6 +35,7 @@ export function RoadmapTopicDetail(props: RoadmapTopicDetailProps) {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');
const [topicHtml, setTopicHtml] = useState('');
const [isStreaming, setIsStreaming] = useState(false);
const topicRef = useRef<HTMLDivElement>(null);
@ -90,10 +91,14 @@ export function RoadmapTopicDetail(props: RoadmapTopicDetailProps) {
}
setIsLoading(false);
setIsStreaming(true);
await readAIRoadmapContentStream(reader, {
onStream: async (result) => {
setTopicHtml(markdownToHtml(result, false));
},
onStreamEnd(roadmap) {
setIsStreaming(false);
},
});
onTopicContentGenerateComplete?.();
};
@ -121,7 +126,6 @@ export function RoadmapTopicDetail(props: RoadmapTopicDetailProps) {
}, []);
const hasContent = topicHtml?.length > 0;
const openAIKey = getOpenAIKey();
return (
<div className={'relative z-[92]'}>
@ -146,24 +150,12 @@ export function RoadmapTopicDetail(props: RoadmapTopicDetailProps) {
</span>{' '}
topics generated
</span>
{!openAIKey && (
<button
className="rounded-xl border border-current px-1.5 py-0.5 text-left text-sm font-medium text-blue-500 sm:text-center"
onClick={onConfigureOpenAI}
>
Need to generate more?{' '}
<span className="font-semibold">Click here.</span>
</button>
)}
{openAIKey && (
<button
className="flex items-center gap-1 rounded-xl border border-current px-1.5 py-0.5 text-left text-sm font-medium text-blue-500 sm:text-center"
onClick={onConfigureOpenAI}
>
<Cog className="-mt-0.5 inline-block h-4 w-4" />
Configure OpenAI Key
</button>
)}
<button
className="rounded-xl border border-current px-1.5 py-0.5 text-left text-sm font-medium text-blue-500 sm:text-center"
onClick={onConfigureOpenAI}
>
Need more? <span className="font-semibold">Click here.</span>
</button>
</div>
)}
@ -212,6 +204,18 @@ export function RoadmapTopicDetail(props: RoadmapTopicDetailProps) {
id="topic-content"
dangerouslySetInnerHTML={{ __html: topicHtml }}
/>
{!isStreaming && (
<div className="mt-4">
<a
href="/ai"
className="mb-1 mt-2 inline-flex items-center rounded-md bg-yellow-400 px-3 py-2 text-sm font-medium text-gray-800 no-underline hover:bg-yellow-500"
>
Dive deeper using AI Tutor
<ArrowRight className="ml-2 h-4 w-4" />
</a>
</div>
)}
</div>
) : (
<div className="flex h-[calc(100%-38px)] flex-col items-center justify-center">

@ -1,6 +1,6 @@
import { ChevronDown } from 'lucide-react';
import { useState } from 'react';
import { cn } from '../../lib/classname';
import { ChevronDown } from 'lucide-react';
type RelatedGuidesProps = {
relatedTitle?: string;
@ -27,7 +27,7 @@ export function RelatedGuides(props: RelatedGuidesProps) {
<div className={cn('relative min-w-[250px] pt-0 lg:px-5 lg:pt-10')}>
<h4 className="text-lg font-medium max-lg:hidden">{relatedTitle}</h4>
<button
className="flex border-b w-full items-center justify-between gap-2 bg-gray-300 px-3 py-2 text-sm font-medium lg:hidden"
className="flex w-full items-center justify-between gap-2 border-b bg-gray-300 px-3 py-2 text-sm font-medium lg:hidden"
onClick={() => setIsOpen(!isOpen)}
>
{relatedTitle}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save