├── LICENSE
├── README.md
├── project-1-hello-world
└── README.md
├── project-2-tictactoe-analyzer
├── README.md
└── TicTacToe.java
├── project-3-vulnerable-analysis
└── README.md
├── project-4-contactbook-JSON
└── README.md
├── project-5-runtime-analysis-tool
└── README.md
├── project-6-modernization
├── README.md
└── paychecks.cbl
├── project-7-ado-pipeline
└── README.md
└── prompt-engineering-tips.md
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Mashrur Hossain
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # GitHub Copilot Workshop - Learn GH Copilot using projects
2 |
3 | Welcome to the **GitHub Copilot Workshop Projects** repository! This repository contains seven projects designed to help you gain hands-on experience with GitHub Copilot's features, from basic coding assistance to advanced workflows.
4 |
5 | Each project is intended to showcase different uses of GitHub Copilot, and can be completed individually or as part of a guided learning experience.
6 |
7 | ## Prerequisites
8 | Individual project build prequisities are listed below the project.
9 | - Install [Visual Studio Code](https://code.visualstudio.com/download) or use [Codespaces](https://github.com/features/codespaces)
10 | - Install Copilot and sigin in with GitHub credentials
11 |
12 | ### Local Build Prerequisities
13 | #### Python
14 | - Install Python 3.x
15 | - [Brew](https://brew.sh/) is recommended for Macintosh users
16 | - Install VS Code Python language support extension pack
17 |
18 | #### Java
19 | - Install JDK 21+
20 | - [SDKMan](https://sdkman.io/) is recommended for Macintosh users
21 | - Install Maven or Gradle using SDKman
22 | - `sdk install maven` or `sdk install gradle`
23 | - Install VS Code Java language support extension pack
24 |
25 |
26 |
27 | ## Table of Contents
28 |
29 | 1. [Project 1: Hello World](#project-1-hello-world)
30 | 2. [Project 2: Tic Tac Toe Analyzer (including conversion to Browser-based)](#project-2-tic-tac-toe-analyzer-browser-based)
31 | 3. [Project 3: Vulnerable Code Analysis and Documentation - mini project](#project-3-vulnerable-code-analysis-and-documentation)
32 | 4. [Project 4: Contact Book with JSON Persistence](#project-4-contact-book-with-json-persistence)
33 | 5. [Project 5: Run-time Analysis Tool](#project-5-run-time-analysis-tool)
34 | 6. [Project 6: Translation and Modernization Project](#project-6-translation-and-modernization-project)
35 | 7. [Project 7: ADO to GitHub Actions Translation](#project-7-ado-to-github-actions-translation)
36 |
37 | ---
38 |
39 | ## Project 1: Hello World
40 |
41 | **Description:**
42 |
43 | This is a simple "Hello World!" project that introduces you to the basics of using GitHub Copilot. With this project, you will test your setup and practice using Copilot to complete simple code and get comfortable with how it suggests functions and snippets.
44 |
45 | ---
46 |
47 | ## Project 2: Tic Tac Toe Analyzer (bonus - make it Browser-based)
48 |
49 | **Description:**
50 |
51 | In this project, you will analyze a java based Tic Tac Toe game. You’ll use Copilot to analyze the code, document what the code does, look for vulnerabilities and then use GH Copilot to convert the project to run in a browser.
52 |
53 | ---
54 |
55 | ## Project 3: Vulnerable Code Analysis and Documentation
56 |
57 | **Description:**
58 |
59 | This project is focused on analyzing vulnerable code snippets using GitHub Copilot. You will analyze known security vulnerabilities and document the code. Copilot will assist you in identifying potential issues and generating proper documentation for the code.
60 |
61 | **Learning Objectives:**
62 | - Learn how Copilot can assist in code review and vulnerability analysis/detection.
63 | - Document insecure code and recommend fixes using Copilot’s suggestions.
64 |
65 | ---
66 |
67 | ## Project 4: Contact Book with JSON Persistence
68 |
69 | **Description:**
70 |
71 | This project involves building a simple contact book application where contact details are stored using a JSON persistence layer. The contact book allows adding, viewing, and removing contacts, and all data is saved in a JSON file for persistence across sessions.
72 |
73 | **Learning Objectives:**
74 | - Use Copilot to build a contact management system.
75 | - Understand how to read and write data using JSON for persistent storage.
76 |
77 | ---
78 |
79 | ## Project 5: Run-time Analysis Tool
80 |
81 | **Description:**
82 |
83 | In this project, you will build a run-time analysis tool that measures the performance of functions. The tool will track execution time for specific algorithms. You’ll use GitHub Copilot to build the tool.
84 |
85 | **Learning Objectives:**
86 | - Building tools with GitHub Copilot.
87 |
88 | ---
89 |
90 | ## Project 6: Translation and Modernization Project
91 |
92 | **Description:**
93 |
94 | This project focuses on the steps involved, at a high level, of translating legacy code (COBOL) to a modern language. GitHub Copilot will assist in all phases of this project.
95 |
96 | **Learning Objectives:**
97 | - Use GitHub Copilot for code modernization
98 |
99 | ---
100 |
101 | ## Project 7: ADO to GitHub Actions Translation
102 |
103 | **Description:**
104 |
105 | In this project, you will interpret and document what an Azure DevOps (ADO) configuration file. Then translate it into a GitHub Actions YAML file. You’ll use GitHub Copilot to confirm the translated GitHub Actions YAML file performs the same tasks.
106 |
107 | **Learning Objectives:**
108 | - Analyze an ADO pipeline configuration file.
109 | - Translate the configuration file.
110 | - Validate that the translated GitHub Actions YAML performs the same tasks as the original ADO file.
111 |
112 | ---
113 |
114 | ## How to Use This Repository
115 |
116 | Each project folder contains:
117 | - The source code for the project.
118 | - A detailed README for each project outlining the steps, expected outputs, and learning goals.
119 | - Sample input files or configurations where applicable.
120 |
121 | ### Prerequisites:
122 | - Ability to execute either Python, JavaScript (using node) or Java programs.
123 | - Access to GitHub Copilot business license.
124 |
125 | ---
126 |
127 | ## Contributions
128 |
129 | Feel free to contribute improvements to these projects by submitting a pull request or opening an issue with suggestions.
130 |
131 | ---
132 |
133 | Happy Coding with GitHub Copilot!
134 |
--------------------------------------------------------------------------------
/project-1-hello-world/README.md:
--------------------------------------------------------------------------------
1 | # Project 1: "Hello, Copilot!" — Introduction to GitHub Copilot
2 |
3 | ### Use Case: Testing setup and getting familiar with GitHub Copilot's basic functionality, exploring how Copilot assists with common coding tasks, and understanding how to work with its suggestions.
4 |
5 | ### Objective:
6 | - Introduce the basics of GitHub Copilot by creating a simple "Hello, World!" project in Python.
7 | - Audience will learn how to leverage Copilot's code complete, code suggestions, and refactoring capabilities.
8 |
9 | ### Problem to Solve:
10 | - Create a Python/JavaScript or Java program that prints "Hello, World!" but adds some personalization by dynamically greeting the user based on the time of day (morning, afternoon, or evening).
11 |
12 | Steps:
13 | 1. Create a new Python file called `greeting.py`.
14 | 2. Task: Write a script that:
15 | - Gets the current time.
16 | - Based on the time, it should greet the user with "Good Morning," "Good Afternoon," or "Good Evening."
17 | 3. Use comments in the file to dictate what you want Copilot to generate.
18 | 4. Use the completions panel to get additional results, do they satisfy your use case?
19 | 5. Use Copilot Chat:
20 | - Use GitHub Copilot Chat to prompt Copilot to solve the same problem.
21 | Question: Which method did you prefer?
22 | 6. Use Copilot Chat to create a simple unit test for the program. Does it work as expected?
23 |
24 | > [!TIP]
25 | > If using a language you are unfamiliar with, prompt Copilot chat with questions on how to "run/execute the script"
26 |
--------------------------------------------------------------------------------
/project-2-tictactoe-analyzer/README.md:
--------------------------------------------------------------------------------
1 | # Project 2: Using GitHub Copilot To modify/fix an existing Tic Tac Toe game
2 |
3 | In this workshop, we will focus on using the power of GitHub Copilot to fix issues with an existing project. There is a working Tic Tac Toe game written in Java but it has problems.
4 |
5 | As a developer, your goal is to **find and fix the problems**. We recommend the following tasks in order:
6 | - Highlight the program code using #selection to find out if there are any issues with the provided code.
7 | - Use GitHub Copilot to fix the issues.
8 | - Generate unit tests to verify the various functions in the game are working as expected.
9 | - Are you able to refactor and/or optimize the code, any methods?
10 | - Generate documentation based on the code that explains what the program does.
11 |
12 | > [!TIP]
13 | > If Copilot is blocked from using public code, it is highly recommended to read the prompt engineering guidance and prompt tips below to break prompts into smaller action items.
14 |
15 | ## Optional:
16 | In this optional section of the project, you'll use GitHub Copilot to create a browser version of the Tic Tac Toe game you completed in the first exercise. No order or task list is provided, the goal here is to prompt Copilot Chat to create the JavaScript version of this game and any other necessary files you need to run it in the browser (hint: HTML, CSS). Optionally if you have time you can modify the look of the webpage to make the game interface visually appealing.
17 |
18 | ## 🌻Optional reading:
19 | If you have extra time, you can read more about GitHub Copilot and how to use it in your projects:
20 | - [Introduction to prompt engineering with GitHub Copilot](https://learn.microsoft.com/training/modules/introduction-prompt-engineering-with-github-copilot//?WT.mc_id=academic-113596-abartolo)
21 | - [GitHub Copilot in VS Code](https://code.visualstudio.com/docs/copilot/overview)
22 | - [How to use GitHub Copilot: Prompts, tips, and use cases](https://github.blog/2023-06-20-how-to-write-better-prompts-for-github-copilot/)
23 | - [10 Unexpected Ways to Use Github Copilot](https://github.blog/2024-01-22-10-unexpected-ways-to-use-github-copilot/)
24 |
25 |
26 |
27 |
28 | Hints for Completion
29 | - Use /fix for each function to optimize and fix code logic
30 | - Use /docs for each function to complete documentation
31 | - Use /tests to quickly write unit tests
32 | - Ask Copilot chat to generate a pom.xml or how to run the tests to complete tests
33 |
34 |
--------------------------------------------------------------------------------
/project-2-tictactoe-analyzer/TicTacToe.java:
--------------------------------------------------------------------------------
1 | import java.util.Scanner;
2 |
3 | public class TicTacToe {
4 | static char[][] board = new char[3][3];
5 | static boolean gameRunning = true;
6 | static char currentPlayer = 'X';
7 |
8 | public static void main(String[] args) {
9 | initializeBoard();
10 | while (gameRunning) {
11 | printBoard();
12 | handlePlayerMove();
13 | checkGameOver();
14 | switchPlayer();
15 | }
16 | }
17 |
18 | static void initializeBoard() {
19 | for (int i = 0; i < 3; i++) {
20 | for (int j = 0; j < 3; j++) {
21 | board[i][j] = '-';
22 | }
23 | }
24 | }
25 |
26 | static void printBoard() {
27 | for (int i = 0; i < 3; i++) {
28 | for (int j = 0; j < 3; j++) {
29 | System.out.print(board[i][j] + " ");
30 | }
31 | System.out.println();
32 | }
33 | }
34 |
35 | static void handlePlayerMove() {
36 | Scanner scanner = new Scanner(System.in);
37 | System.out.println("Player " + currentPlayer + ", enter your move (row [1-3] and column [1-3]):");
38 | int row = scanner.nextInt() - 1;
39 | int col = scanner.nextInt() - 1;
40 | board[row][col] = currentPlayer;
41 | }
42 |
43 | static void checkGameOver() {
44 | for (int i = 0; i < 3; i++) {
45 | if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) {
46 | gameRunning = false;
47 | System.out.println("Player " + currentPlayer + " wins!");
48 | return;
49 | }
50 | if (board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer) {
51 | gameRunning = false;
52 | System.out.println("Player " + currentPlayer + " wins!");
53 | return;
54 | }
55 | }
56 | if (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) {
57 | gameRunning = false;
58 | System.out.println("Player " + currentPlayer + " wins!");
59 | return;
60 | }
61 | if (board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer) {
62 | gameRunning = false;
63 | System.out.println("Player " + currentPlayer + " wins!");
64 | return;
65 | }
66 | }
67 |
68 | static void switchPlayer() {
69 | if (currentPlayer == 'X') {
70 | currentPlayer = 'O';
71 | } else {
72 | currentPlayer = 'X';
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/project-3-vulnerable-analysis/README.md:
--------------------------------------------------------------------------------
1 | # Project 3 - Analyze code and look for vulnerabilities
2 |
3 | This project is focused on analyzing vulnerable code snippets using GitHub Copilot. The snippet provided below was captured by a code scanning tool without any additional context, your task will be to use GH Copilot to analyze the code for any known security vulnerabilities and document it. Copilot will assist you in identifying potential issues and generating proper documentation.
4 |
5 | ```python
6 | def get_user_data(username):
7 | conn = sqlite3.connect('example.db')
8 | cursor = conn.cursor()
9 |
10 | # Secure against SQL injection
11 | query = "SELECT * FROM users WHERE username = ?"
12 | cursor.execute(query, (username,))
13 |
14 | result = cursor.fetchall()
15 | conn.close()
16 |
17 | return result
18 |
19 |
20 |
21 | Hints for Completion
22 | - Are regular expressions for input validation secure? Ask Copilot for other ways to handle input validation.
23 | - Ask Copilot how to create a virtual environment and install a secure library
24 |
25 |
--------------------------------------------------------------------------------
/project-4-contactbook-JSON/README.md:
--------------------------------------------------------------------------------
1 | # Project 4: Contact Book with JSON Persistence
2 |
3 | This project involves building a simple contact book application where contact details are stored using a JSON persistence layer. The contact book allows adding, viewing, and removing contacts, and all data is saved in a JSON file for persistence across sessions.
4 |
5 | ### Learning Objectives:
6 | - Use GH Copilot to build a contact management system.
7 | - Understand how to read and write data using JSON for persistent storage.
8 |
9 | - Write a JavaScript/Python or Java program that allows users to:
10 | - Add a contact (name, phone number, email).
11 | - View all contacts.
12 | - Remove a contact by name (and/or other attribute).
13 | - Save the contacts to a JSON file, so that they persist across program runs.
14 |
15 | Steps:
16 | 1. Setting up the project: Create a JavaScript/Java or Python file called `contact_book.js or .py or ContactBook.java`.
17 | - For Java projects, use the command palette and "create a new java project"
18 |
19 | 2. Use GH Copilot to write a script that:
20 | - Uses a JSON file to store contact data.
21 | - Implements the ability to add, view, and remove contacts.
22 | - Handles saving and loading contacts from a JSON file.
23 |
24 | 3. GitHub Copilot Usage:
25 | - Use either GH Copilot Chat or Code Completions to structure for contact management (e.g., adding contacts), and let Copilot assist in implementing file reading and writing using the `json` module.
26 |
27 | 4. Generate Unit tests for each function - Do all the functions in the program work correctly?
28 |
29 |
30 |
31 |
32 | Completed Python implementation, for emergency reference only
33 |
34 | ```python
35 | import json
36 | import os
37 |
38 | class Contact:
39 | def __init__(self, first_name, last_name, phone, email):
40 | self.first_name = first_name
41 | self.last_name = last_name
42 | self.phone = phone
43 | self.email = email
44 |
45 | def __repr__(self):
46 | return f"Contact(first_name={self.first_name}, last_name={self.last_name}, phone={self.phone}, email={self.email})"
47 |
48 | class ContactBook:
49 | def __init__(self):
50 | self.contacts = []
51 |
52 | def add_contact(self, first_name, last_name, phone, email):
53 | new_contact = Contact(first_name, last_name, phone, email)
54 | self.contacts.append(new_contact)
55 |
56 | def view_contacts(self):
57 | for contact in self.contacts:
58 | print(f"First Name: {contact.first_name}\nLast Name: {contact.last_name}\nPhone: {contact.phone}\nEmail: {contact.email}\n")
59 |
60 | def remove_contact(self, first_name, last_name):
61 | self.contacts = [contact for contact in self.contacts if not (contact.first_name == first_name and contact.last_name == last_name)]
62 |
63 | def update_contact(self, first_name, last_name, new_last_name=None, new_phone=None, new_email=None):
64 | for contact in self.contacts:
65 | if contact.first_name == first_name and contact.last_name == last_name:
66 | if new_last_name:
67 | contact.last_name = new_last_name
68 | if new_phone:
69 | contact.phone = new_phone
70 | if new_email:
71 | contact.email = new_email
72 | return True
73 | return False
74 |
75 | def save_to_file(self, filename):
76 | with open(filename, 'w') as file:
77 | json.dump([contact.__dict__ for contact in self.contacts], file)
78 |
79 | def load_from_file(self, filename):
80 | if not os.path.exists(filename) or os.path.getsize(filename) == 0:
81 | with open(filename, 'w') as file:
82 | json.dump([], file)
83 | else:
84 | with open(filename, 'r') as file:
85 | contacts_data = json.load(file)
86 | self.contacts = [Contact(**data) for data in contacts_data]
87 |
88 | def main():
89 | contact_book = ContactBook()
90 | contact_book.load_from_file('contacts.json')
91 |
92 | while True:
93 | print("\nContact Book Menu:")
94 | print("1. Add Contact")
95 | print("2. View Contacts")
96 | print("3. Remove Contact")
97 | print("4. Update Contact")
98 | print("5. Exit")
99 | choice = input("Enter your choice: ")
100 |
101 | if choice == '1':
102 | first_name = input("Enter first name: ")
103 | last_name = input("Enter last name: ")
104 | phone = input("Enter phone number: ")
105 | email = input("Enter email: ")
106 | contact_book.add_contact(first_name, last_name, phone, email)
107 | elif choice == '2':
108 | contact_book.view_contacts()
109 | elif choice == '3':
110 | first_name = input("Enter the first name of the contact to remove: ")
111 | last_name = input("Enter the last name of the contact to remove: ")
112 | contact_book.remove_contact(first_name, last_name)
113 | elif choice == '4':
114 | first_name = input("Enter the first name of the contact to update: ")
115 | last_name = input("Enter the last name of the contact to update: ")
116 | new_last_name = input("Enter new last name (leave blank to keep current): ")
117 | new_phone = input("Enter new phone number (leave blank to keep current): ")
118 | new_email = input("Enter new email (leave blank to keep current): ")
119 | if contact_book.update_contact(first_name, last_name, new_last_name or None, new_phone or None, new_email or None):
120 | print("Contact updated successfully.")
121 | else:
122 | print("Contact not found.")
123 | elif choice == '5':
124 | contact_book.save_to_file('contacts.json')
125 | break
126 | else:
127 | print("Invalid choice. Please try again.")
128 |
129 | if __name__ == "__main__":
130 | main()
131 | ```
132 |
133 |
134 |
135 |
136 |
137 | Completed Java implementation, for emergency reference only
138 |
139 | ```Java
140 | /*
141 | * This source file was generated by the Gradle 'init' task
142 | */
143 | package contactbook;
144 |
145 | import java.util.ArrayList;
146 | import java.util.Scanner;
147 | import java.io.FileWriter;
148 | import java.io.File;
149 | import java.io.IOException;
150 |
151 | public class App {
152 | public static ArrayList contacts = new ArrayList<>();
153 |
154 | public static void main(String[] args) {
155 | Scanner scanner = new Scanner(System.in);
156 | while (true) {
157 | System.out.println("Welcome to your Contact Book!");
158 | System.out.println("1. Add a contact");
159 | System.out.println("2. View contacts");
160 | System.out.println("3. Remove a contact");
161 | System.out.println("4. Exit");
162 | System.out.print("Choose an option: ");
163 | int choice = scanner.nextInt();
164 | scanner.nextLine(); // Consume newline
165 |
166 | switch (choice) {
167 | case 1:
168 | addContact(scanner);
169 | break;
170 | case 2:
171 | viewContacts(true);
172 | break;
173 | case 3:
174 | removeContact(scanner);
175 | break;
176 | case 4:
177 | System.out.println("Goodbye!");
178 | scanner.close();
179 | return;
180 | default:
181 | System.out.println("Invalid option. Please try again.");
182 | }
183 | }
184 | }
185 |
186 | public static void addContact(Scanner scanner) {
187 | System.out.print("Enter contact name: ");
188 | String name = scanner.nextLine();
189 | System.out.print("Enter phone number: ");
190 | String phoneNumber = scanner.nextLine();
191 | System.out.print("Enter email: ");
192 | String email = scanner.nextLine();
193 | String contact = name + "," + phoneNumber + "," + email;
194 | contacts.add(contact);
195 | saveContactsToFile();
196 | System.out.println("Contact added.");
197 | }
198 |
199 | /**
200 | * Saves the list of contacts to a file named "contacts.json".
201 | * The contacts are written in JSON array format.
202 | * If the directory for the file does not exist, it will be created.
203 | *
204 | * The method handles any IOExceptions that may occur during the file writing process.
205 | * In case of an error, an error message is printed to the console.
206 | */
207 | public static void saveContactsToFile() {
208 | try {
209 | File file = new File("contacts.json");
210 | if (file.getParentFile() != null) {
211 | file.getParentFile().mkdirs(); // Ensure the directory exists
212 | }
213 | FileWriter writer = new FileWriter(file);
214 | writer.write("[\n");
215 | for (int i = 0; i < contacts.size(); i++) {
216 | writer.write(" \"" + contacts.get(i) + "\"");
217 | if (i < contacts.size() - 1) {
218 | writer.write(",");
219 | }
220 | writer.write("\n");
221 | }
222 | writer.write("]");
223 | writer.close();
224 | } catch (IOException e) {
225 | System.out.println("An error occurred while saving the contacts to a file.");
226 | }
227 | }
228 |
229 | public static void viewContacts(boolean loadFromFile) {
230 | if (loadFromFile) {
231 | loadContactsFromJson();
232 | }
233 | if (contacts.isEmpty()) {
234 | System.out.println("No contacts found.");
235 | } else {
236 | System.out.println("Your contacts:");
237 | for (int i = 0; i < contacts.size(); i++) {
238 | System.out.println((i + 1) + ". " + contacts.get(i));
239 | }
240 | }
241 | }
242 |
243 | public static void loadContactsFromJson() {
244 | contacts.clear(); // Clear existing contacts before loading from file
245 | // load the json file and parse it into a list of strings
246 | try {
247 | Scanner scanner = new Scanner(new File("contacts.json"));
248 | StringBuilder json = new StringBuilder();
249 | while (scanner.hasNextLine()) {
250 | json.append(scanner.nextLine());
251 | }
252 | scanner.close();
253 | // remove leading and trailing whitespace
254 | String jsonString = json.toString().strip();
255 | // remove leading and trailing brackets
256 | String data = jsonString.substring(1, jsonString.length() - 1);
257 | // split the data into an array of strings
258 | String[] dataArray = data.split("(?<=\\\"),\\s*(?=\\\")");
259 | // remove leading and trailing quotes from each string and add to the contacts list
260 | for (String contact : dataArray) {
261 | contacts.add(contact.replaceAll("^\\s*\"|\"\\s*$", ""));
262 | }
263 | } catch (IOException e) {
264 | System.out.println("An error occurred while loading the contacts from the file.");
265 | }
266 | }
267 |
268 |
269 | public static void removeContact(Scanner scanner) {
270 | loadContactsFromJson();
271 | System.out.print("Enter the number of the contact to remove: ");
272 | int index = scanner.nextInt() - 1;
273 | if (index >= 0 && index < contacts.size()) {
274 | contacts.remove(index);
275 | saveContactsToFile();
276 | System.out.println("Contact removed.");
277 | } else {
278 | System.out.println("Invalid contact number.");
279 | }
280 | }
281 |
282 |
283 | }
284 |
285 | ```
286 |
287 |
--------------------------------------------------------------------------------
/project-5-runtime-analysis-tool/README.md:
--------------------------------------------------------------------------------
1 | # Project 5 - Build a runtime analysis tool that analyzes performance of various functions
2 |
3 | Example ideas of functions to analyze
4 | - Language native - Built-in sort
5 | - User implemented - Quick sort, Merge sort, Selection sort, Bubble sort
6 |
7 | Steps: Use GitHub Copilot to
8 | - Build a function that generates lists of random integers according to provided input: 10 - 1 million
9 | - List size will be specified by user at run-time
10 | - Range of integer values will be specified by user at run-time
11 | - Run the functions (sorting algorithms) with generated list of integers
12 | - Calculate and display the time it took to run the function
13 | - Allow for multiple runs
14 |
15 | Method:
16 | Use GH Copilot to build each step for you
17 |
18 |
19 |
20 |
21 | Completed Python implementation, for emergency reference only
22 |
23 | **analyzer.py**
24 |
25 | ```python
26 | import time
27 | import random
28 | from demos import quicksort, mergesort, bubblesort
29 |
30 | def create_random_list(size, max_val):
31 | ran_list = []
32 | for num in range(size):
33 | ran_list.append(random.randint(1,max_val))
34 | return ran_list
35 |
36 | def analyze_func(func_name, arr):
37 | tic = time.time()
38 | func_name(arr)
39 | toc = time.time()
40 | seconds = toc-tic
41 | print(f"{func_name.__name__.capitalize()}\t-> Elapsed time: {seconds:.5f}")
42 |
43 | size = int(input("What size list do you want to create? "))
44 | max = int(input("What is the max value of the range? "))
45 | run_times = int(input("How many times do you want to run? "))
46 |
47 | for num in range(run_times):
48 | print(f"Run: {num+1}")
49 | l = create_random_list(size,max)
50 | analyze_func(bubblesort, l.copy())
51 | analyze_func(quicksort, l)
52 | analyze_func(mergesort, l)
53 | analyze_func(sorted, l)
54 | print("-" * 40)
55 |
56 | ```
57 |
58 |
59 | **demos.py**
60 | ```python
61 | print("Algorithms file loaded")
62 |
63 | def quicksort(arr):
64 | if len(arr) < 2:
65 | return arr
66 | else:
67 | pivot = arr[-1]
68 | smaller, equal, larger = [], [], []
69 | for num in arr:
70 | if num < pivot:
71 | smaller.append(num)
72 | elif num == pivot:
73 | equal.append(num)
74 | else:
75 | larger.append(num)
76 | return quicksort(smaller) + equal + quicksort(larger)
77 |
78 | def merge_sorted(arr1,arr2):
79 | sorted_arr = []
80 | i, j = 0, 0
81 | while i < len(arr1) and j < len(arr2):
82 | if arr1[i] < arr2[j]:
83 | sorted_arr.append(arr1[i])
84 | i += 1
85 | else:
86 | sorted_arr.append(arr2[j])
87 | j += 1
88 | while i < len(arr1):
89 | sorted_arr.append(arr1[i])
90 | i += 1
91 | while j < len(arr2):
92 | sorted_arr.append(arr2[j])
93 | j += 1
94 | return sorted_arr
95 |
96 | def mergesort(arr):
97 | if len(arr) < 2:
98 | return arr[:]
99 | else:
100 | middle = len(arr)//2
101 | l1 = mergesort(arr[:middle])
102 | l2 = mergesort(arr[middle:])
103 | return merge_sorted(l1, l2)
104 |
105 | def bubblesort(arr):
106 | swap_happened = True
107 | while swap_happened:
108 | swap_happened = False
109 | for num in range(len(arr)-1):
110 | if arr[num] > arr[num+1]:
111 | swap_happened = True
112 | arr[num], arr[num+1] = arr[num+1], arr[num]
113 |
114 |
115 | ```
116 |
117 |
--------------------------------------------------------------------------------
/project-6-modernization/README.md:
--------------------------------------------------------------------------------
1 | # Project 6 - Code Modernization
2 | The below projects showcase different ways of modernizing code using the assistance of Copilot.
3 | ## COBOL
4 |
5 | In this project you will use GitHub Copilot to undertake the task of modernizing a COBOL program including the intermediary steps involved.
6 | Specifically, use GitHub Copilot to:
7 | - Explain what the COBOL program is doing
8 | - Create documentation for what the program is doing in markdown format
9 | - Create a Data flow diagram using mermaid.js that can be copied to a GitHub issue and previewed
10 | - Create user stories
11 | - Create a Java/JavaScript or Python program from the user stories
12 | - Translate the COBOL code to Java/JavaScript or Python code
13 | - Create a Data Flow diagram from the converted Java/JavaScript or Python code in mermaid.js that can be copied to a GitHub issue and previewed
14 |
15 | > [!TIP]
16 | > [Mermaid Chart](https://github.com/marketplace/mermaid-chart) can be used within the IDE using [Copilot Extensions](https://docs.github.com/en/copilot/using-github-copilot/using-extensions-to-integrate-external-tools-with-copilot-chat)
17 |
18 |
19 | ## React to Angular
20 | This project requires the user to download an open source React application. Copilot is then used to understand the application and transform to Angular.
21 | - Clone https://github.com/andrewagain/emoji-search
22 | - Run the application to get an idea of what it does and use Copilot `/explain` in the terminal to assist with any errors.
23 | - Use the following chat prompt before asking Copilot how to transform the code
24 | - `@workspace /explain`
25 | - Convert the application from React to Angular
26 |
27 | > [!TIP]
28 | > Attaching a codebase to the prompt gives copilot all of the context of the entire application.
29 | > Copilot may switch between standalone components and NgModule if not given context in each prompt or with a .github/copilot-instructions.md file
--------------------------------------------------------------------------------
/project-6-modernization/paychecks.cbl:
--------------------------------------------------------------------------------
1 | IDENTIFICATION DIVISION.
2 | PROGRAM-ID. PAYCHECKS.
3 | AUTHOR. CHARLES R. MARTIN.
4 | DATE-WRITTEN. 2020-APR-15.
5 | ENVIRONMENT DIVISION.
6 | INPUT-OUTPUT SECTION.
7 | FILE-CONTROL.
8 | SELECT TIMECARDS
9 | ASSIGN TO "TIMECARDS.DAT"
10 | ORGANIZATION IS LINE SEQUENTIAL.
11 | DATA DIVISION.
12 | FILE SECTION.
13 | FD TIMECARDS.
14 | 01 TIMECARD.
15 | 02 EMPLOYEE-NAME.
16 | 03 EMP-FIRSTNAME PIC X(10).
17 | 03 EMP-SURNAME PIC X(15).
18 | 02 HOURS-WORKED PIC 99V9.
19 | 02 PAY-RATE PIC 99.
20 | WORKING-STORAGE SECTION.
21 | * temporary variables in computational usage.
22 | * intermediate values for computing paycheck with overtime
23 | 01 REGULAR-HOURS PIC 9(4)V99 USAGE COMP.
24 | 01 OVERTIME-HOURS PIC 9(4)V99 USAGE COMP.
25 | 01 OVERTIME-RATE PIC 9(4)V99 USAGE COMP.
26 | 01 REGULAR-PAY PIC 9(4)V99 USAGE COMP.
27 | 01 OVERTIME-PAY PIC 9(4)V99 USAGE COMP.
28 | * computed parts of the paycheck
29 | 01 GROSS-PAY PIC 9(4)V99 USAGE COMP.
30 | 01 FED-TAX PIC 9(4)V99 USAGE COMP.
31 | 01 STATE-TAX PIC 9(4)V99 USAGE COMP.
32 | 01 FICA-TAX PIC 9(4)V99 USAGE COMP.
33 | 01 NET-PAY PIC 9(4)V99 USAGE COMP.
34 | * print format of the check
35 | 01 PAYCHECK.
36 | 02 PRT-EMPLOYEE-NAME PIC X(25).
37 | 02 FILLER PIC X.
38 | 02 PRT-HOURS-WORKED PIC 99.9.
39 | 02 FILLER PIC X.
40 | 02 PRT-PAY-RATE PIC 99.9.
41 | 02 PRT-GROSS-PAY PIC $,$$9.99.
42 | 02 PRT-FED-TAX PIC $,$$9.99.
43 | 02 PRT-STATE-TAX PIC $,$$9.99.
44 | 02 PRT-FICA-TAX PIC $,$$9.99.
45 | 02 FILLER PIC X(5).
46 | 02 PRT-NET-PAY PIC $*,**9.99.
47 | * Tax rates -- 77 level aha!
48 | 77 Fed-tax-rate Pic V999 Value Is .164 .
49 | 77 State-tax-rate Pic V999 Value Is .070 .
50 | 77 Fica-tax-rate Pic V999 Value Is .062 .
51 | * 88 Level is for conditions.
52 | 01 END-FILE PIC X.
53 | 88 EOF VALUE "T".
54 | PROCEDURE DIVISION.
55 | BEGIN.
56 | PERFORM INITIALIZE-PROGRAM.
57 | PERFORM PROCESS-LINE WITH TEST BEFORE UNTIL EOF
58 | PERFORM CLEAN-UP.
59 | STOP RUN.
60 | INITIALIZE-PROGRAM.
61 | OPEN INPUT TIMECARDS.
62 | PROCESS-LINE.
63 | READ TIMECARDS INTO TIMECARD
64 | AT END MOVE "T" TO END-FILE.
65 | IF NOT EOF THEN
66 | PERFORM COMPUTE-GROSS-PAY
67 | PERFORM COMPUTE-FED-TAX
68 | PERFORM COMPUTE-STATE-TAX
69 | PERFORM COMPUTE-FICA
70 | PERFORM COMPUTE-NET-PAY
71 | PERFORM PRINT-CHECK
72 | END-IF.
73 | COMPUTE-GROSS-PAY.
74 | IF HOURS-WORKED > 40 THEN
75 | MULTIPLY PAY-RATE BY 1.5 GIVING OVERTIME-RATE
76 | MOVE 40 TO REGULAR-HOURS
77 | SUBTRACT 40 FROM HOURS-WORKED GIVING OVERTIME-HOURS
78 | MULTIPLY REGULAR-HOURS BY PAY-RATE GIVING REGULAR-PAY
79 | MULTIPLY OVERTIME-HOURS BY OVERTIME-RATE
80 | GIVING OVERTIME-PAY
81 | ADD REGULAR-PAY TO OVERTIME-PAY GIVING GROSS-PAY
82 | ELSE
83 | MULTIPLY HOURS-WORKED BY PAY-RATE GIVING GROSS-PAY
84 | END-IF
85 | .
86 | COMPUTE-FED-TAX.
87 | MULTIPLY GROSS-PAY BY FED-TAX-RATE GIVING FED-TAX
88 | .
89 | COMPUTE-STATE-TAX.
90 | * Compute lets us use a more familiar syntax
91 | COMPUTE STATE-TAX = GROSS-PAY * STATE-TAX-RATE
92 | .
93 | COMPUTE-FICA.
94 | MULTIPLY GROSS-PAY BY FICA-TAX-RATE GIVING FICA-TAX
95 | .
96 | COMPUTE-NET-PAY.
97 | SUBTRACT FED-TAX STATE-TAX FICA-TAX FROM GROSS-PAY
98 | GIVING NET-PAY
99 | PRINT-CHECK.
100 | MOVE EMPLOYEE-NAME TO PRT-EMPLOYEE-NAME
101 | MOVE HOURS-WORKED TO PRT-HOURS-WORKED
102 | MOVE PAY-RATE TO PRT-PAY-RATE
103 | MOVE GROSS-PAY TO PRT-GROSS-PAY
104 | MOVE FED-TAX TO PRT-FED-TAX
105 | MOVE STATE-TAX TO PRT-STATE-TAX
106 | MOVE FICA-TAX TO PRT-FICA-TAX
107 | MOVE NET-PAY TO PRT-NET-PAY
108 | DISPLAY PAYCHECK
109 | CLEAN-UP.
110 | CLOSE TIMECARDS.
111 | END PROGRAM PAYCHECKS.
112 |
--------------------------------------------------------------------------------
/project-7-ado-pipeline/README.md:
--------------------------------------------------------------------------------
1 | # Project 7: Analyze pipeline config file
2 |
3 | In this project you will identify what the pipeline config YAML file does using GH Copilot followed by documenting it.
4 |
5 | - Analyze file.
6 | - Document what it does.
7 | - Convert to GH Actions yml format.
8 | - Document what it does.
9 | - Does it still do the same thing?
10 |
11 | ```YAML
12 | trigger:
13 | - main
14 |
15 | pool:
16 | vmImage: 'ubuntu-22.04'
17 |
18 | variables:
19 | container_name: ''
20 | container_owner: ''
21 | maven_changelist: ''
22 | maven_sha1: ''
23 | github_branch_name: ''
24 | github_short_sha: ''
25 | jar_version: ''
26 | artifact_name: ''
27 | artifact_path: ''
28 |
29 | jobs:
30 | - job: DefineBuildParameters
31 | displayName: Define Build Parameters
32 | steps:
33 | - checkout: self
34 |
35 | - task: NodeTool@0
36 | inputs:
37 | versionSpec: '14.x'
38 | displayName: 'Install Node.js'
39 |
40 | - script: |
41 | npm install
42 | node ./.github/workflows/scripts/buildParameters.js
43 | displayName: 'Define Build Parameters'
44 | env:
45 | GITHUB_REF: $(Build.SourceBranch)
46 | GITHUB_SHA: $(Build.SourceVersion)
47 | GITHUB_REPOSITORY: $(Build.Repository.Name)
48 | GITHUB_ACTOR: $(Build.RequestedFor)
49 | GITHUB_RUN_ID: $(Build.BuildId)
50 | GITHUB_RUN_NUMBER: $(Build.BuildId)
51 | GITHUB_WORKFLOW: $(Build.DefinitionName)
52 | GITHUB_HEAD_REF: $(System.PullRequest.SourceBranch)
53 | GITHUB_BASE_REF: $(System.PullRequest.TargetBranch)
54 | GITHUB_EVENT_NAME: $(Build.Reason)
55 | GITHUB_EVENT_PATH: $(Build.SourceBranch)
56 | GITHUB_ACTION: $(Build.DefinitionName)
57 | GITHUB_ACTIONS: true
58 | GITHUB_TOKEN: $(System.AccessToken)
59 | displayName: 'Run buildParameters.js'
60 |
61 | - powershell: |
62 | Write-Output "##vso[task.setvariable variable=container_name]$(container_name)"
63 | Write-Output "##vso[task.setvariable variable=container_owner]$(container_owner)"
64 | Write-Output "##vso[task.setvariable variable=maven_changelist]$(maven_changelist)"
65 | Write-Output "##vso[task.setvariable variable=maven_sha1]$(maven_sha1)"
66 | Write-Output "##vso[task.setvariable variable=github_branch_name]$(github_branch_name)"
67 | Write-Output "##vso[task.setvariable variable=github_short_sha]$(github_short_sha)"
68 | displayName: 'Set Build Parameters'
69 |
70 | - job: PublishMavenDependencies
71 | displayName: Publish Maven dependencies
72 | dependsOn: DefineBuildParameters
73 | condition: eq(variables['Build.SourceBranch'], 'refs/heads/main')
74 | steps:
75 | - checkout: self
76 |
77 | - task: Maven@3
78 | inputs:
79 | mavenPomFile: 'pom.xml'
80 | goals: 'dependency:tree'
81 | displayName: 'Maven Dependency Tree Dependency Submission'
82 |
83 | - job: BuildAndTest
84 | displayName: Build and Test
85 | dependsOn: DefineBuildParameters
86 | strategy:
87 | matrix:
88 | os: [ 'ubuntu-20.04', 'ubuntu-22.04' ]
89 | java: [ '11' ]
90 | pool:
91 | vmImage: $(os)
92 | steps:
93 | - checkout: self
94 |
95 | - task: UseJavaVersion@1
96 | inputs:
97 | versionSpec: '$(java)'
98 | jdkArchitectureOption: 'x64'
99 | jdkSourceOption: 'PreInstalled'
100 | displayName: 'Set up JDK $(java)'
101 |
102 | - script: |
103 | mvn package -B \
104 | -Dsha1="$(maven_sha1)" \
105 | -Dchangelist="$(maven_changelist)" \
106 | -Dgithub.repository="$(Build.Repository.Name)"
107 | displayName: 'Build Test and Package'
108 |
109 | - script: |
110 | cat target/classes/version.properties >> $(Build.ArtifactStagingDirectory)/version.properties
111 | displayName: 'Output Version'
112 | id: maven_version
113 |
114 | - powershell: |
115 | Write-Output "##vso[task.setvariable variable=jar_version]$(jar_version)"
116 | Write-Output "##vso[task.setvariable variable=artifact_name]application-jar"
117 | Write-Output "##vso[task.setvariable variable=artifact_path]target"
118 | displayName: 'Set artifact parameters'
119 | condition: eq(variables['Agent.OS'], 'Linux')
120 |
121 | - task: PublishBuildArtifacts@1
122 | inputs:
123 | PathtoPublish: '$(Build.ArtifactStagingDirectory)'
124 | ArtifactName: 'application-jar'
125 | publishLocation: 'Container'
126 | displayName: 'Upload application jar artifact'
127 | condition: eq(variables['Agent.OS'], 'Linux')
128 |
129 | - job: BuildApplicationContainer
130 | displayName: Container Build - application
131 | dependsOn:
132 | - DefineBuildParameters
133 | - BuildAndTest
134 | condition: ne(variables['Build.RequestedFor'], 'dependabot[bot]')
135 | steps:
136 | - checkout: self
137 |
138 | - task: Docker@2
139 | inputs:
140 | containerRegistry: '$(dockerRegistryServiceConnection)'
141 | repository: '$(container_owner)/$(container_name)'
142 | command: 'buildAndPush'
143 | Dockerfile: '**/Dockerfile'
144 | tags: |
145 | $(jar_version)
146 | displayName: 'Build and Publish Container'
147 |
148 | - job: ContinuousDelivery
149 | displayName: Continuous Delivery Deployment
150 | dependsOn:
151 | - DefineBuildParameters
152 | - BuildAndTest
153 | - BuildApplicationContainer
154 | condition: eq(variables['Build.SourceBranch'], 'refs/heads/main')
155 | steps:
156 | - checkout: self
157 |
158 | - task: AzureCLI@2
159 | inputs:
160 | azureSubscription: '$(azureSubscription)'
161 | scriptType: 'ps'
162 | scriptLocation: 'inlineScript'
163 | inlineScript: |
164 | $token = az ad app credential reset --id $(application_id) --append --credential-description "temp-token" --years 1 --query password -o tsv
165 | Write-Output "##vso[task.setvariable variable=temp_token]$token"
166 | displayName: 'Get temporary token for creating deployment'
167 |
168 | - task: AzureCLI@2
169 | inputs:
170 | azureSubscription: '$(azureSubscription)'
171 | scriptType: 'ps'
172 | scriptLocation: 'inlineScript'
173 | inlineScript: |
174 | $appContainerImage = "$(container_owner)/$(container_name):$(jar_version)"
175 | node ./.github/workflows/scripts/deployEnvironment.js
176 | displayName: 'Create Deployment'
177 | env:
178 | app_container_image: $(appContainerImage)
179 | GITHUB_TOKEN: $(temp_token)
180 |
--------------------------------------------------------------------------------
/prompt-engineering-tips.md:
--------------------------------------------------------------------------------
1 | # Prompt Engineering Tips and Tricks
2 | ## Prompt Engineering
3 | - Be specific and provide context with prompts
4 | - Explore the following using https://editor.p5js.org/ and Copilot IDE Chat
5 | `draw an ice cream cone`
6 | vs
7 | `draw an ice cream cone with using p5.js`
8 | vs
9 | `draw an ice cream cone with a single scoop and a cherry on top of whip cream using p5.js`
10 | - If you can't describe it, provide examples for better output
11 | - Iterate to improve results
12 |
13 | ## [Prompt Engineering 101 with Damian Brady](https://www.linkedin.com/events/promptengineering1017236807732413022208/)
14 | Excellent video that shows the differences between autocomplete vs chat and how to provide context.
15 |
16 | ## Copilot IDE Chat
17 | ### General
18 | - Use `@workspace /new` to create a project workspace with proper scaffolding
19 | - Use `@workspace` for questions on how to build or run your application if unfamiliar
20 | - `/help` to see all the commands available in your copilot since it can be different with Copilot extensions
21 | - This command also helps you understand how to provide context with different # commands
22 | - Use `/startDebugging` to have Copilot assist with debug setup
23 | - Auto complete should be used as assistant when in deep code flow and chat/editor should used for code generation from prompt
24 | - In the terminal, highlight and have copilot explain for compile errors
25 |
26 | ### Multi File
27 | - Use the editor(preview) for working with multiple files and generating new files
28 |
29 | ### Single File
30 | - Highlight code and and use `/edit` to make updates
31 | - Use `/fix` for suggestions on how to improve code quality
32 | - Click any errors/warnings "the dreaded squiggles" and have copilot fix
33 | - Before running `/tests`, always use `/setupTests` to get VSCode ready for your project
34 | - `/fixTestFailure` for troubleshooting tests
35 |
36 | ### Useful/Popular Extensions
37 | - `@terminal` for assistance with anything in the terminal
38 | - `@vscode` for assistance with anything in VSCode
39 | - `@github` for indexed repos, knowledgbases, and anything GitHub
40 | - [Docker](https://github.com/marketplace/docker-for-github-copilot) - generate docker assets & open a pull request, find vulnerabilities with Docker Scout
41 | - [Mermaid Chart](https://github.com/marketplace/mermaid-chart) for creating diagrams
42 | - [Stack Overflow](https://github.com/marketplace/stack-overflow-extension-for-github-copilot) - for team Stack Overflow knowledgebases
43 | - [Atlassian Rovo](https://github.com/marketplace/atlassian) - JIRA & Confluence
44 |
45 |
--------------------------------------------------------------------------------