Your AI pair programmer
Push what's possible with GitHub Copilot, the world's most trusted and widely adopted AI developer tool.
#!/usr/bin/env ts-node
import { fetch } from "fetch-h2";
// Determine whether the sentiment of text is positive
// Use a web service
async function isPositive(text: string): Promise<boolean> {
const response = await fetch(`http://text-processing.com/api/sentiment/`, {
method: "POST",
body: `text=${text}`,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
const json = await response.json();
return json.label === "pos";
}
package main
type CategorySummary struct {
Title string
Tasks int
AvgValue float64
}
func createTables(db *sql.DB) {
db.Exec("CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, value INTEGER, category TEXT)")
}
func createCategorySummaries(db *sql.DB) ([]CategorySummary, error) {
var summaries []CategorySummary
rows, err := db.Query("SELECT category, COUNT(category), AVG(value) FROM tasks GROUP BY category")
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var summary CategorySummary
err := rows.Scan(&summary.Title, &summary.Tasks, &summary.AvgValue)
if err != nil {
return nil, err
}
summaries = append(summaries, summary)
}
return summaries, nil
}
import datetime
def parse_expenses(expenses_string):
"""Parse the list of expenses and return the list of triples (date, value, currency).
Ignore lines starting with #.
Parse the date using datetime.
Example expenses_string:
2016-01-02 -34.01 USD
2016-01-03 2.59 DKK
2016-01-03 -2.72 EUR
"""
expenses = []
for line in expenses_string.splitlines():
if line.startswith("#"):
continue
date, value, currency = line.split(" ")
expenses.append((datetime.datetime.strptime(date, "%Y-%m-%d"),
float(value),
currency))
return expenses
class CreateShippingAddresses < ActiveRecord::Migration
def change
create_table :shipping_addresses do |t|
t.string :name
t.string :address
t.string :city
t.string :zip
t.string :state
t.string :phone
t.string :email
t.references :shipping_method, index: true, foreign_key: true
t.references :customer, index: true, foreign_key: true
t.timestamps null: false
end
end
end
Trained on billions of lines of code, GitHub Copilot turns natural language prompts into coding suggestions across dozens of languages.
Don't fly solo
Developers all over the world use GitHub Copilot to code faster, focus on business logic over boilerplate, and do what matters most: building great software.
Copilot for Individuals
$
10
per month /
$100 per year
- Plugs right into your editor
- Turns natural language prompts into code
- Offers multi-line function suggestions
- Speeds up test generation
- Filters out common vulnerable coding patterns
- Blocks suggestions matching public code
Copilot for Business
new
$
19
per user
per month
- Everything included in Copilot for Individuals, plus...
- Simple license management
- Organization-wide policy management
- Industry-leading privacy
- Corporate proxy support
- Copilot Chat beta
Learn about GitHub Copilot Terms and Conditions
Focus on solving bigger problems
Spend less time creating boilerplate and repetitive code patterns, and more time on what matters: building great software. Write a comment describing the logic you want and GitHub Copilot will immediately suggest code to implement the solution.
package main
type Run struct {
Time int // in milliseconds
Results string
Failed bool
}
// Get average runtime of successful runs in seconds
func averageRuntimeInSeconds(runs []Run) float64 {
var totalTime int
var failedRuns int
for _, run := range runs {
if run.Failed {
failedRuns++
} else {
totalTime += run.Time
}
}
averageRuntime := float64(totalTime) / float64(len(runs) - failedRuns) / 1000
return averageRuntime
}
class Course < ApplicationRecord
has_many :enrollments, dependent: :destroy
has_many :students, through: :enrollments, source: :user
has_many :teachers, through: :enrollments, source: :user
has_many :assignments, dependent: :destroy
has_many :submissions, through: :assignments
validates :name, presence: true
validates :start_date, presence: true
validates :end_date, presence: true
validates :term, presence: true
validates :year, presence: true
def self.find_by_name(name)
Course.find_by(name: name)
end
end
const seconds = 3600
const minutes = seconds / 60
const hours = minutes / 60
const days = hours / 24
const weeks = days / 7
const months = days / 30
const years = months / 12
import static org.junit.Assert.*;
import org.junit.Test;
public class IsPrimeTest {
// Math.isPrime(int) returns whether the given number is prime or not
@Test
public void testIsPrime() {
assertTrue(Math.isPrime(2));
assertTrue(Math.isPrime(3));
assertTrue(Math.isPrime(5));
assertTrue(Math.isPrime(7));
assertTrue(Math.isPrime(11));
assertTrue(Math.isPrime(13));
assertTrue(Math.isPrime(17));
assertTrue(Math.isPrime(19));
assertTrue(Math.isPrime(23));
assertTrue(Math.isPrime(29));
}
Get AI-based suggestions, just for you
Visual Studio Code
def max_sum_slice(xs):
max_ending = max_so_far = 0
for x in xs:
max_ending = max(0, max_ending + x)
max_so_far = max(max_so_far, max_ending)
return max_so_far
Visual Studio Code
def max_sum_slice(xs):
if not xs:
return 0
max_ending = max_slice = 0
for x in xs:
max_ending = max(0, max_ending + x)
max_slice = max(max_slice, max_ending)
return max_slice
Visual Studio Code
def max_sum_slice(xs):
max_ending = max_so_far = 0
begin = end = 0
for i, x in enumerate(xs):
if max_ending + x > 0:
max_ending += x
else:
max_ending = 0
begin = i
if max_ending > max_so_far:
max_so_far = max_ending
end = i
return begin, end, max_so_far
Visual Studio Code
def max_sum_slice(xs):
if not xs:
return 0
current_max = 0
max_so_far = 0
for x in xs:
current_max = max(0, current_max + x)
max_so_far = max(max_so_far, current_max)
return max_so_far
Visual Studio Code
def max_sum_slice(xs):
max_sum = 0
max_sum_so_far = 0
start_index = 0
end_index = 0
for i in range(len(xs)):
max_sum_so_far += xs[i]
if max_sum_so_far > max_sum:
max_sum = max_sum_so_far
start_index = i
end_index = i
elif max_sum_so_far < 0:
max_sum_so_far = 0
start_index = i
else:
end_index = i
return (start_index, end_index, max_sum)
Visual Studio Code
def max_sum_slice(xs):
if len(xs) == 0:
return 0
max_sum = 0
max_sum_ending_here = 0
max_ending_here = 0
for x in xs:
max_ending_here = max(0, max_ending_here + x)
max_sum_ending_here = max(max_sum_ending_here, max_ending_here)
max_sum = max(max_sum, max_sum_ending_here)
return max_sum
Visual Studio Code
def max_sum_slice(xs):
best_sum, best_start, best_end = 0, None, None
for i, x in enumerate(xs):
if best_start is None or best_sum < x + best_sum:
best_sum = x + best_sum
best_start = i
best_end = i
elif best_sum > x + best_sum:
best_sum = x + best_sum
best_end = i
return best_sum, best_start, best_end
Visual Studio Code
def max_sum_slice(xs):
"""
Return a tuple (i,j) where i is the index of the first slice with a max value,
and j is the index of the slice whose sum is the max
"""
if len(xs) == 0:
return None
elif len(xs) == 1:
return (0,0)
elif len(xs) == 2:
return (0,1) if xs[0] >= xs[1] else (1,0)
else:
return max_sum_slice_helper(xs,0,len(xs)-1)
Keep flying with your favorite editor
The numbers speak for themselves
Code confidently in unfamiliar territory
Whether you’re working in a new language or framework, or just learning to code, GitHub Copilot can help you find your way. Tackle a bug, or learn how to use a new framework without spending most of your time spelunking through the docs or searching the web.
const token = process.env["TWITTER_BEARER_TOKEN"]
const fetchTweetsFromUser = async (screenName, count) => {
const response = await fetch(
`https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=${screenName}&count=${count}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
}
)
const json = await response.json()
return json
}
import tweepy, os # secrets in environment variables
def fetch_tweets_from_user(user_name):
# authentification
auth = tweepy.OAuthHandler(os.environ['TWITTER_KEY'], os.environ['TWITTER_SECRET'])
auth.set_access_token(os.environ['TWITTER_TOKEN'], os.environ['TWITTER_TOKEN_SECRET'])
api = tweepy.API(auth)
# fetch tweets
tweets = api.user_timeline(screen_name=user, count=200, include_rts=False)
return tweets
require 'twitter'
def fetch_tweets_from_user(handle)
twitter = Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
config.access_token = ENV['TWITTER_ACCESS_TOKEN']
config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET']
end
tweets = twitter.user_timeline(handle)
tweets
end
const token = process.env["TWITTER_BEARER_TOKEN"]
const fetchTweetsFromUser = (userName: string) => {
const url = `https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=${userName}&count=20`
return fetch(url, {
headers: {
"Authorization": `Bearer ${token}`
}
})
.then(res => res.json())
.then(tweets => tweets.map(tweet => ({
id: tweet.id,
text: tweet.text,
created_at: tweet.created_at,
user: {
id: tweet.user.id,
name: tweet.user.name,
screen_name: tweet.user.screen_name,
profile_image_url: tweet.user.profile_image_url
}
})))
}
package main
var apiKey = os.Getenv("TWITTER_BEARER_TOKEN")
type Tweet = struct{ Text string }
func fetchTweetsFromUser(user string) ([]Tweet, error) {
url := "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" + user + "&count=200"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("bad status: %d", resp.StatusCode)
}
var tweets []Tweet
if err := json.NewDecoder(resp.Body).Decode(&tweets); err != nil {
return nil, err
}
return tweets, nil
}
import d3 from "d3"
const drawScatterplot = (data, height, width) => {
const svg = d3.select("#scatterplot")
.append("svg")
.attr("height", height)
.attr("width", width)