Languages
CoderPad supports a wide variety of programming languages. Some of them have quirks and quite a few have supplementary libraries that you might want to use. Click on the language you're interested in, or scroll through the list!
- Interpreted
- Bash
- CoffeeScript
- Elixir
- JavaScript
- Perl
- PHP
- Python 2
- Python 3
- R
- Ruby
- Tcl
- TypeScript
Bash
Switch to BashWe install a variety of commonly used linux tools.
The bash environment is reset when the “Reset” button is clicked, or the pad switches to another language.
The gcc compiler is invoked with the following args:
gcc -g -fsanitize=address -std=c11 -Wall -fdiagnostics-color -pthread -lm
Which will:
- Use the C11 standard
- Turn on all warning messages
- Compile in debug mode
- Warn on memory use-after-free bugs and other memory issues
- Link the pthread and math libraries
You should define an int main()
entrypoint.
Clojure
Switch to ClojureNo extra information available. It probably just works!
CoffeeScript
Switch to CoffeeScriptCoffeeScript in CoderPad just runs on top of the JavaScript environment, the only difference being
that we do not run CoffeeScript with the --harmony
flag.
We also have an array of interesting npm packages available for your use:
underscore and lodash for many useful functional helpers. Fun fact: I managed to get _.sample added to underscore. You’re welcome.
chai, sinon, sinon-chai, and mocha testing libraries.
Here’s a quick example of how to use sinon
and chai
:
chai = require('chai')
sinon = require('sinon')
sinonChai = require('sinon-chai')
hello = (name, cb) ->
cb 'hello ' + name
return
chai.should()
chai.use sinonChai
cb = sinon.spy()
hello 'world', cb
cb.should.have.been.calledWith 'this test should fail'
as well as mocha
:
Mocha = require('mocha')
assert = require('assert')
mocha = new Mocha
# Bit of a hack, sorry!
mocha.suite.emit 'pre-require', this, 'solution', mocha
describe 'Test suite', ->
it 'should work', ->
assert true
mocha.run()
async, request, and isomorphic-fetch for making async HTTP a little more convenient.
q and bluebird are promise libraries to help make managing async in general easier.
jsdom is a library for mimicking an HTML DOM within our JS environment. Useful if you want to test how candidates can manipulate elements without using our full HTML/CSS/JS environment.
C++
Switch to C++We run your C++ code with GCC 8. You should define an int main()
entrypoint. The gcc compiler
is invoked with the following args:
g++ -Wall -fsanitize=address -std=c++17 -pthread \
-lboost_date_time -lboost_regex -lboost_system -lboost_thread -lboost_timer -lboost_filesystem \
-lssl -lcrypto -lmysqlcppconn
Which results in:
- Use the C++17 standard
- Turn on all warning messages
- Compile in debug mode
- Warn on memory use-after-free bugs and other memory issues with ASan. If you see an unusual message or segfault, it’s likely ASan picking up a use-after-free or use of uninitialized memory bug in your code.
- Link the
pthread
library - Link a few static boost libraries
We also provide a few libraries:
Boost is provided, with most of its header-only libraries working straight out of the box. Of its statically compiled components, we link to
DateTime
,Regex
,System
,Thread
, andTimer
. If you need more than those, please let us know!nlohmann/json, a convenient and simple JSON library. To use it on CoderPad, just include
"json.hpp"
and go nuts:
#include "json.hpp"
#include <iostream>
int main() {
nlohmann::json j2 = {
{"hello", "world"}
};
std::cout << j2;
}
- Catch, a C++ testing library. Catch is a single-header library and very easy to get started with. To use it on CoderPad, simply define a macro and include the header like so:
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
unsigned int Factorial( unsigned int number ) {
return number <= 1 ? 1 : Factorial(number - 1) * number;
}
TEST_CASE( "Factorials are computed", "[factorial]" ) {
REQUIRE( Factorial(0) == 1 );
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
REQUIRE( Factorial(10) == 3628800 );
}
If you do so, you should not define your own main method. You can also read more about Catch’s macros for testing.
- Eigen, a library for linear algebra. We provide all of the Eigen modules and header files to the environment. To use it on CoderPad, just include the header that you want and instantiate an object:
#include <iostream>
#include <Eigen/Dense>
using Eigen::MatrixXd;
int main()
{
MatrixXd m(2,2);
m(0,0) = 3;
m(1,0) = 2.5;
m(0,1) = -1;
m(1,1) = m(1,0) + m(0,1);
std::cout << m << std::endl;
}
C#
Switch to C#Our C# environment runs on Microsoft’s cross-platform .NET Core runtime. The System.Json
assembly
is linked.
You should define a static void Main
on a class named Solution
.
Tests can be written in NUnit. Note that if you run NUnit tests, you should only use the test runner’s main method, like so:
using NUnit.Framework;
using NUnitLite;
using System;
using System.Reflection;
public class Runner {
public static int Main(string[] args) {
return new AutoRun(Assembly.GetCallingAssembly()).Execute(new String[] {"--labels=All"});
}
[TestFixture]
public class Dog {
public String bark() {
return "bark";
}
[Test]
public void TestBarker() {
Assert.AreEqual("bark", new Dog().bark());
}
}
}
You should be able to run LINQ queries, like so:
using System;
using System.Linq;
class Solution
{
static void Main(string[] args)
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums =
from n in numbers
where n < 5
select n;
Console.WriteLine("Numbers < 5:");
foreach (var x in lowNums)
{
Console.WriteLine(x);
}
}
}
Your code is compiled and run with debug mode enabled.
Dart
Switch to DartNo extra information available. It probably just works!
Elixir
Switch to ElixirNo extra information available. It probably just works!
Erlang
Switch to ErlangYou should define the module as “solution” and define and export a method named “start” on it, like so:
-module(solution).
-export([start/0]).
start() ->
io:format("Hello, World").
If you’d like to write some tests using eunit
, you can do so as long as you remember to include_lib
and invoke your module’s test
function from your start
function:
-module(solution).
-export([start/0]).
-include_lib("eunit/include/eunit.hrl"). % attach eunit handlers to this module
f(0) -> 1;
f(1) -> 1;
f(N) when N > 1 -> f(N-1) + f(N-2).
f_test() ->
1 = f(0),
1 = f(1),
2 = f(2),
3 = f(3),
6 = f(4). % this should fail
start() ->
test(). % remember to call test from start, or we won't know that we need to run tests!
F#
Switch to F#Our F# environment runs on Microsoft’s cross-platform .NET Core runtime.
Your code is compiled and run with debug mode enabled.
You can run NUnit tests with the following code:
module Solution
open NUnitLite
open NUnit.Framework
open System
open System.Reflection
[<Test>]
let test1() = Assert.Pass()
[<Test>]
let test2() = Assert.Fail()
[<EntryPoint>]
let main argv =
printfn "Hello, World!"
(new AutoRun(Assembly.GetCallingAssembly())).Execute( [| "--labels=All" |])
Go
Switch to GoYou should declare a func main() in a package “main”, like so:
package main
import "fmt"
func main() {
fmt.Println("Hello, world")
}
Haskell
Switch to HaskellYour code is run with runghc solution.hs
. Your code runs in interpreted mode, so you don’t need a
special entrypoint or anything.
We have a couple testing options available. Simple tests using Hspec are straightforward:
import Test.Hspec
import Test.QuickCheck
import Control.Exception (evaluate)
main :: IO ()
main = hspec $ do
describe "Prelude.head" $ do
it "returns the first element of a list" $ do
head [23 ..] `shouldBe` (23 :: Int)
it "returns the first element of an *arbitrary* list" $
property $ \x xs -> head (x:xs) == (x :: Int)
it "throws an exception if used with an empty list" $ do
evaluate (head []) `shouldThrow` anyException
You can also use QuickCheck’s more powerful test generation framework directly (this test fails):
import Test.QuickCheck
prop_revapp :: [Int] -> [Int] -> Bool
prop_revapp xs ys = reverse (xs++ys) == reverse xs ++ reverse ys
main = quickCheck prop_revapp
We install a variety of packages in the Haskell environment (including req
for HTTP requests). The output of cabal list --installed --simple
is below:
Cabal 2.4.0.1
HUnit 1.6.0.0
QuickCheck 2.13.1
RSA 2.3.1
SHA 1.6.4.4
aeson 1.4.3.0
ansi-terminal 0.9.1
array 0.5.3.0
asn1-encoding 0.9.5
asn1-parse 0.9.4
asn1-types 0.3.2
async 2.2.1
attoparsec 0.13.2.2
attoparsec-iso8601 1.0.1.0
authenticate-oauth 1.6
base 4.12.0.0
base-compat 0.10.5
base-orphans 0.8.1
base64-bytestring 1.0.0.2
basement 0.0.10
binary 0.8.6.0
blaze-builder 0.4.1.0
bytestring 0.10.8.2
cabal-doctest 1.0.6
call-stack 0.1.0
case-insensitive 1.2.1.0
cereal 0.5.8.0
clock 0.8
colour 2.3.5
connection 0.3.0
containers 0.6.0.1
cookie 0.4.4
crypto-api 0.13.3
crypto-pubkey-types 0.4.3
cryptonite 0.25
data-default 0.7.1.1
data-default-class 0.1.2.0
data-default-instances-containers 0.0.1
data-default-instances-dlist 0.0.1
data-default-instances-old-locale 0.0.1
deepseq 1.4.4.0
directory 1.3.3.0
dlist 0.8.0.6
entropy 0.4.1.4
exceptions 0.10.2
filepath 1.4.2.1
ghc 8.6.5
ghc-boot 8.6.5
ghc-boot-th 8.6.5
ghc-compact 0.1.0.0
ghc-heap 8.6.5
ghc-prim 0.5.3
ghci 8.6.5
hashable 1.2.7.0
hashtables 1.2.3.1
haskeline 0.7.4.3
hourglass 0.2.12
hpc 0.6.0.3
hspec 2.7.1
hspec-core 2.7.1
hspec-discover 2.7.1
hspec-expectations 0.8.2
http-api-data 0.4
http-client 0.6.4
http-client-tls 0.3.5.3
http-types 0.12.3
integer-gmp 1.0.2.0
integer-logarithms 1.0.3
libiserv 8.6.3
memory 0.14.18
mime-types 0.1.0.9
monad-control 1.0.2.3
mtl 2.2.2
network 3.1.0.0
network-uri 2.6.1.0
old-locale 1.0.0.7
parsec 3.1.13.0
pem 0.2.4
pretty 1.1.3.6
primitive 0.6.4.0
process 1.6.5.0
quickcheck-io 0.2.0
random 1.1
req 2.0.1
retry 0.8.0.1
rts 1.0
scientific 0.3.6.2
setenv 0.1.1.3
socks 0.6.0
split 0.2.3.3
splitmix 0.0.2
stm 2.5.0.0
streaming-commons 0.2.1.0
tagged 0.8.6
template-haskell 2.14.0.0
terminfo 0.4.1.2
text 1.2.3.1
tf-random 0.5
th-abstraction 0.3.1.0
time 1.8.0.2
time-locale-compat 0.1.1.5
tls 1.4.1
transformers 0.5.6.2
transformers-base 0.4.5.2
transformers-compat 0.6.5
unix 2.7.2.2
unordered-containers 0.2.10.0
uuid-types 1.0.3
vector 0.12.0.3
vector-algorithms 0.8.0.1
x509 1.7.5
x509-store 1.6.7
x509-system 1.6.6
x509-validation 1.6.11
xhtml 3000.2.2.1
zlib 0.6.2
HTML/CSS/JS
Switch to HTML/CSS/JSSee sample code below to get started with React, Angular, or Vue.js.
Our HTML environment renders the pad within an iFrame in realtime. CSS and JS can be embedded. console.log
statements and JavaScript errors are reported within your developer console.
CSS and JS can be embedded or externally requested. The following example includes React and renders a small piece of JSX. The JSX is transpiled by including the babel transpiler and marking the JSX code with type="text/jsx"
(or text/babel
if you want to use certain ES6 features that may not be available in your browser).
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/jsx">
ReactDOM.render(
<h1>Hello, React!</h1>,
document.getElementById('root')
);
</script>
</body>
</html>
Sample “Hello World” for Angular 1:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<script>
angular.module('myApp', []).component('helloWorld', {
template: 'Hello World!',
})
</script>
<style>
body {
background-color: #1d2126;
color: white;
}
</style>
</head>
<body>
<div ng-app="myApp"><hello-world></hello-world></div>
</body>
</html>
Sample “Hello World” for Vue.js:
<html>
<head>
<script src="https://unpkg.com/vue"></script>
<style>
body {
background-color: #1d2126;
color: white;
}
</style>
</head>
<body>
<div id="app"><p>{{ message }}</p></div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello World!',
},
})
</script>
</body>
</html>
Java
Switch to JavaYou should define a public class named Solution
with a public static void main
. Your code is
compiled with -Xlint
(linting) and run with -ea
(assertions enabled).
A few libraries are included for your convenience, and are available on the classpath with no additional work from you. Simply import and fire away:
- json-simple for parsing/encoding JSON.
The google code project page has some useful examples.
guava provides immutable collections and other handy utility classes.
Apache Commons Lang for assorted utilities.
Has a bunch of useful stuff like date parsing. The import prefix is org.apache.commons.lang3
, so
you can perform imports by writing import org.apache.commons.lang3.ArrayUtils
.
- JUnit, the gold standard for testing in Java. If you want to ask your candidate to write JUnit-style tests during the interview, please format your Java code like so:
import org.junit.*;
import org.junit.runner.*;
public class Solution {
@Test
public void testNoop() {
Assert.assertTrue(true);
}
public static void main(String[] args) {
JUnitCore.main("Solution");
}
}
Stack traces originating from JUnit errors are trimmed for brevity.
In the future we may auto-detect the existence of @Test
annotations, so stay tuned.
- jMock, a library to assist with mocking in Java. Combining jMock with the previous JUnit example:
import org.jmock.*;
import org.junit.*;
import org.junit.runner.*;
interface Receiver {
void receive(String message);
}
public class Solution {
@Test
public void testMock() {
Mockery context = new Mockery();
Receiver receiver = context.mock(Receiver.class);
context.checking(new Expectations() {{
oneOf (receiver).receive("hello");
}});
receiver.receive("hello");
context.assertIsSatisfied();
}
public static void main(String[] args) {
JUnitCore.main("Solution");
}
}
JavaScript
Switch to JavaScriptUse HTML/CSS/JS for React, Angular, Vue.js, and other Javascript frameworks.
We provide a highly interactive REPL, which allows access to your runtime variables. If there were no errors, you will have a REPL with access to all of the global variables and functions defined in your script.
We run NodeJS with the --harmony
flag on, which gives you access to many staged new features coming to
the JavaScript spec. For a complete description of which modern JavaScript features are available, check
out the Node compatibility table.Your code is also run for you in strict mode
by default, which will enable features like const and let to work without configuration on your part.
We also have an array of interesting npm packages available for your use:
underscore, lodash, and ramda for many useful functional helpers. Fun fact: I managed to get _.sample added to underscore. You’re welcome.
chai, sinon, sinon-chai, and mocha testing libraries.
Here’s a quick example of how to use sinon
and chai
:
var chai = require('chai')
var sinon = require('sinon')
var sinonChai = require('sinon-chai')
chai.should()
chai.use(sinonChai)
function hello(name, cb) {
cb('hello ' + name)
}
var cb = sinon.spy()
hello('world', cb)
cb.should.have.been.calledWith('this test should fail')
as well as mocha
:
var Mocha = require('mocha')
var assert = require('assert')
var mocha = new Mocha()
// Bit of a hack, sorry!
mocha.suite.emit('pre-require', this, 'solution', mocha)
describe('Test suite', function() {
it('should work', function() {
assert(true)
})
})
mocha.run()
async, request, and isomorphic-fetch for making async HTTP a little more convenient.
q and bluebird are promise libraries to help make managing async in general easier.
jsdom is a library for mimicking an HTML DOM within our JS environment. Useful if you want to test how candidates can manipulate elements without using our full HTML/CSS/JS environment.
Kotlin
Switch to KotlinOur Kotlin environment is built on top of our Java environment, giving you access to any libraries we have installed there, too.
For example, to run a JUnit test in Kotlin:
import org.junit.*;
import org.junit.runner.*;
fun main(args: Array<String>) {
JUnitCore.main("Solution");
}
class Solution {
@Test
fun testNoop() {
Assert.assertTrue(true);
}
}
Markdown
Switch to MarkdownNo extra information available. It probably just works!
MySQL
Switch to MySQLMySQL mode spins up a MySQL server with a default database with some sample data in it. The schema of the default database looks like:
employees projects
+---------------+---------+ +---------------+---------+
| id | int |<----+ +->| id | int |
| first_name | varchar | | | | title | varchar |
| last_name | varchar | | | | start_date | date |
| salary | int | | | | end_date | date |
| department_id | int |--+ | | | budget | int |
+---------------+---------+ | | | +---------------+---------+
| | |
departments | | | employees_projects
+---------------+---------+ | | | +---------------+---------+
| id | int |<-+ | +--| project_id | int |
| name | varchar | +-----| employee_id | int |
+---------------+---------+ +---------------+---------+
The database is reset when the “Reset” button is clicked, or the pad switches to another language.
Output format
Having trouble seeing query results because of line wrapping? Try the \G option:
SELECT * from employees \G;
yields
*************************** 1. row ***************************
id: 1
first_name: John
last_name: Smith
salary: 20000
department_id: 1
*************************** 2. row ***************************
id: 2
first_name: Ava
last_name: Muffinson
salary: 10000
department_id: 5
...
Objective-C
Switch to Objective-CWhile we don’t run Objective-C on native OSX, we do run it in the latest clang with objc. This lets
you include classes like NSString
and so forth largely as you normally would.
Your code is compiled with
clang `gnustep-config --objc-flags` `gnustep-config --objc-libs` \
-fobjc-arc -fobjc-nonfragile-abi -lobjc -lgnustep-base -ldispatch
which activates automatic reference counting and the nonfragile ABI.
You should define an int main()
function.
To use the linked implementation of Apple’s
Grand Central Dispatch, call the appropriate
dispatch
methods:
#import <stdio.h>
#include <dispatch/dispatch.h>
static void timer_did_fire(void *context) {
printf("Strawberry fields...\n");
}
int main (int argc, const char * argv[])
{
dispatch_source_t timer = dispatch_source_create(
DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_event_handler_f(timer, timer_did_fire);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC,
0.5 * NSEC_PER_SEC);
dispatch_resume(timer);
dispatch_main();
}
OCaml
Switch to OCamlOur OCaml environment compiles your code with ocamlopt using all the default options. If there are no compilation errors it will then execute the resulting binary. We also build with the following libraries:
- Jane Street’s Async
- Batteries
- Jane Street’s Core
- OCaml Extended Standard Library (extlib)
- ppx_deriving
- ppx_jane
We also provide the standard OCaml toplevel when your code isn’t being compiled or executed. This is paired with rlwrap to give you access to your history using the up and down arrows.
Perl
Switch to PerlOur Perl environment ships with the following packages:
- Bundle::LWP
- Data::Dump::Streamer
- DateTime
- IO::Socket::SSL
- JSON
- Lexical::Persistence PPI
PHP
Switch to PHPYou must wrap your code in <?php
and ?>
tags. Text outside of those tags will output to stdout
without processing as PHP.
PHP’s mcrypt library is also installed.
Plain Text
Switch to Plain TextNo extra information available. It probably just works!
PostgreSQL
Switch to PostgreSQLPostgreSQL mode spins up a PostgreSQL server with a default database with some sample data in it. The schema of the default database looks like:
employees projects
+---------------+---------+ +---------------+---------+
| id | int |<----+ +->| id | int |
| first_name | varchar | | | | title | varchar |
| last_name | varchar | | | | start_date | date |
| salary | int | | | | end_date | date |
| department_id | int |--+ | | | budget | int |
+---------------+---------+ | | | +---------------+---------+
| | |
departments | | | employees_projects
+---------------+---------+ | | | +---------------+---------+
| id | int |<-+ | +--| project_id | int |
| name | varchar | +-----| employee_id | int |
+---------------+---------+ +---------------+---------+
The database is reset when the “Reset” button is clicked, or the pad switches to another language.
Output format
Having trouble seeing query results because of line wrapping? Try the \x
expanded output option:
SELECT * from employees \x
yields
-[ RECORD 1 ]-+----------
id | 1
first_name | John
last_name | Smith
salary | 20000
department_id | 1
-[ RECORD 2 ]-+----------
id | 2
first_name | Ava
last_name | Muffinson
salary | 10000
department_id | 5
...
Python 2
Switch to Python 2The Python environment is augmented with a few REPL features as well as some helpful libraries.
The REPL uses IPython to provide a REPL with history, highlighting, and autocomplete. Additionally, whenever you run scripts in CoderPad’s editor, the REPL will deposit you at the exact line and state of any exceptions. If there were no errors, you will have a REPL with access to all of the variables and functions defined in your script.
The libraries included and ready for importing are:
- requests for simpler HTTP requests.
- beautifulsoup4 for HTML parsing.
- numpy, scipy, pandas, scikit-learn, and statsmodels for advanced numerical analysis. Unfortunately, plotting does not work in CoderPad’s purely textual interface at this time.
Testing
We’ve got a few ways you can test your Python code in CoderPad:
The excellent unittest library that ships with Python by default. Here’s a quick example:
import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) def test_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) # s.split should throw when the separator is not a string with self.assertRaises(TypeError): s.split(2) unittest.main(exit=False)
The versatile pytest. The above snippet of code would look like the following when written for pytest:
import pytest def test_upper(): assert 'foo'.upper() == 'FOO' def test_isupper(): assert 'FOO'.isupper() assert not 'Foo'.isupper() def test_split(): s = 'hello world' assert s.split() == ['hello', 'world'] # s.split should throw when the separator is not a string with pytest.raises(TypeError): s.split(2) pytest.main()
mock is also available if you need to stub out some behavior. Here’s a quick usage example:
from mock import Mock mock = Mock() mock.method(1, 2, 3) mock.method.assert_called_with('this should break')
mock
can of course be combined withunittest
andpytest
for even more fun.hypothesis is available for property-based testing in Python. You can read more about it on their website, but here’s a stubbed example of how you might test that an encoding and decoding function both work:
from hypothesis import given from hypothesis.strategies import text def encode(string): # return encoded string def decode(string): # return decoded string @given(text()) def test_decode_inverts_encode(s): assert decode(encode(s)) == s test_decode_inverts_encode()
Calling
test_decode_inverts_encode()
fires up Hypothesis and tries to find an input that breaks your code.
Python 3
Switch to Python 3Python 3 in CoderPad is generally identical to the Python 2.x environment.
One small difference is that mock
is available in Python 3 in the stdlib, as unittest.mock
.
Information about the Python 2.x environment is reproduced below:
The Python environment is augmented with a few REPL features as well as some helpful libraries.
The REPL uses IPython to provide a REPL with history, highlighting, and autocomplete. Additionally, whenever you run scripts in CoderPad’s editor, the REPL will deposit you at the exact line and state of any exceptions. If there were no errors, you will have a REPL with access to all of the variables and functions defined in your script.
The libraries included and ready for importing are:
- requests for simpler HTTP requests.
- beautifulsoup4 for HTML parsing.
- numpy, scipy, pandas, scikit-learn, and statsmodels for advanced numerical analysis. Unfortunately, plotting does not work in CoderPad’s purely textual interface at this time.
Testing
We’ve got a few ways you can test your Python code in CoderPad:
The excellent unittest library that ships with Python by default. Here’s a quick example:
import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) def test_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) # s.split should throw when the separator is not a string with self.assertRaises(TypeError): s.split(2) unittest.main(exit=False)
The versatile pytest. The above snippet of code would look like the following when written for pytest:
import pytest def test_upper(): assert 'foo'.upper() == 'FOO' def test_isupper(): assert 'FOO'.isupper() assert not 'Foo'.isupper() def test_split(): s = 'hello world' assert s.split() == ['hello', 'world'] # s.split should throw when the separator is not a string with pytest.raises(TypeError): s.split(2) pytest.main()
mock is also available if you need to stub out some behavior. Here’s a quick usage example:
from mock import Mock mock = Mock() mock.method(1, 2, 3) mock.method.assert_called_with('this should break')
mock
can of course be combined withunittest
andpytest
for even more fun.hypothesis is available for property-based testing in Python. You can read more about it on their website, but here’s a stubbed example of how you might test that an encoding and decoding function both work:
from hypothesis import given from hypothesis.strategies import text def encode(string): # return encoded string def decode(string): # return decoded string @given(text()) def test_decode_inverts_encode(s): assert decode(encode(s)) == s test_decode_inverts_encode()
Calling
test_decode_inverts_encode()
fires up Hypothesis and tries to find an input that breaks your code.
Our R environment ships with the caret
, data.table
, forecast
, mlr
, plyr
, reshape2
,
tidyverse
, xts
, and zoo
packages installed. No graphical output is provided at this time, but
all your standard R computations should work normally.
Additionally, it should be noted that tidyverse
installs quite a few useful packages too (like
tidyr
and readr
): http://tidyverse.org.
You’ll need to invoke library
to load these packages, like so:
library(tidyverse)
patients <- read_csv("http://www-huber.embl.de/users/klaus/BasicR/Patients.csv")
Ruby
Switch to RubyThe Ruby environment is augmented with a few REPL features as well as some helpful libraries.
The REPL uses Pry to provide a REPL with history, highlighting, and autocomplete. Additionally, whenever you run scripts in CoderPad’s editor, the REPL will deposit you at the exact line and state of any exceptions. If there were no errors, you will have a REPL with access to all of the variables and functions defined in your script.
The libraries included and ready for require
ing are:
- minitest is a simple framework suitable for a variety of
testing needs, like unit testing, specs, and mocking. To run your tests, require
minitest/autorun
like so:
require 'minitest/autorun'
class Dog
def talk!
'BARK'
end
end
describe Dog do
it 'must bark when spoken to' do
Dog.new.talk!.must_equal 'BARK'
end
end
- RSpec is another very popular library for testing in Ruby. You trigger RSpec
in CoderPad by requiring
rspec/autorun
. The equivalent of the previous example in RSpec would be:
require 'rspec/autorun'
class Dog
def talk!
'BARK'
end
end
RSpec.describe Dog do
it 'barks when spoken to' do
expect(Dog.new.talk!).to eq('BARK')
end
end
algorithms is a gem with some useful data structure implementations.
ActiveSupport extends the Ruby language with a lot of useful features built up by the Rails team over the years.
Rust
Switch to RustRust builds with Cargo and ships a few crates:
anyhow = 1.0.32
bitflags = 1.2.1
chrono = 0.4.18
itertools = 0.9.0
nom = 5.1.2
rand = 0.7.3
rayon = 1.4.0
reqwest = 0.10.8
regex = 1.3.9
serde = 1.0.116
serde_json = 1.0.57
time = 0.2.22
url = 2.1.1
uuid = 0.8.1
Remember to declare crate dependencies with extern
, like so:
extern crate regex;
use regex::Regex;
fn main() {
let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
println!("Did our date match? {}", re.is_match("2014-01-01"));
}
You can use some basic asserts for testing as well:
fn main() {
assert!(true, "check boolean");
assert_eq!(2, 2, "compare numbers");
assert_eq!("abc", "abc", "compare strings");
assert_eq!([1,2,3], [1,2,3], "compare lists");
}
Scala
Switch to ScalaYou should define an object named Solution
that extends App
, like so:
object Solution extends App {
for (i <- 0 until 5) println("Hello, world!")
}
Alternatively, you can forego using the App
trait helper and define main
yourself:
object Solution {
def main(args: Array[String]) {
println("Hello, world!")
}
}
We include the Scala testing libraries ScalaCheck and ScalaTest for your convenience. Here’s a quick example of using ScalaTest driven by ScalaCheck generators:
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FreeSpec, Matchers}
class Testable extends FreeSpec
with Matchers
with GeneratorDrivenPropertyChecks {
def f (x: Int) = Math abs x
"f (x) should be >= 0" in forAll (
(x: Int) => f (x) should be >= 0
)
"f (x) should be >= 0 (sometimes!)" in forAll (
(x: Int) => whenever (x != Int.MinValue) (f (x) should be >= 0)
)
}
object Solution extends App {
new Testable().execute()
}
Here’s a quick rundown of the Scala libraries we have installed:
libraryDependencies ++= Seq (
"com.chuusai" %% "shapeless" % "2.3.2",
"org.scalacheck" %% "scalacheck" % "1.13.4",
"org.scalactic" %% "scalactic" % "3.0.1",
"org.scalamock" %% "scalamock-scalatest-support" % "3.5.0",
"org.scalatest" %% "scalatest" % "3.0.1",
"org.scalaz" %% "scalaz-core" % "7.2.12",
"org.typelevel" %% "cats" % "0.9.0"
)
Additionally, these Java libraries are available. Simply import and fire away:
- json-simple for parsing/encoding JSON.
The google code project page has some useful examples.
guava provides immutable collections and other handy utility classes.
junit, the gold standard for testing in Java, but quite usable in Scala as well.
import org.junit.Test
import org.junit.runner.JUnitCore
import org.junit.Assert
class TestClass {
@Test def testNoop() {
Assert.assertTrue(true)
}
}
object Solution {
def main(args: Array[String]) {
JUnitCore.main("TestClass")
}
}
- jMock, a library to assist with mocking in Java. The homepage has some useful examples, and can be adapted for Scala, too.
Swift 5
Switch to Swift 5We’re using Apple’s recently open sourced Swift implementation, on a recent Linux snapshot.
XCTest is included by default, but needs to be manually invoked. Here’s a template of how you can do that:
import XCTest
class MyTest : XCTestCase {
static var allTests = {
return [("testGoodNumber", testGoodNumber)]
}()
func testGoodNumber() {
XCTAssertTrue(41 == 42, "The number is wrong")
}
}
XCTMain([testCase(MyTest.allTests)])
Syntax highlighting might be a bit wonky, so please point out any issues via email! We also plan to add REPL support.
Tcl
Switch to TclNo extra information available. It probably just works!
TypeScript
Switch to TypeScriptTypeScript in CoderPad runs on top of the JavaScript environment.
Click “Run” to execute your code and see any type errors. We do not yet support inline diagnostics in the editor in TypeScript. (If you don’t see a “Run” button, your interviewer may have disabled execution.)
We also have an array of interesting npm packages available for your use:
underscore and lodash for many useful functional helpers.
chai, sinon, and sinon-chai testing libraries.
async, request, and isomorphic-fetch for making async HTTP a little more convenient.
jsdom is a library for mimicking an HTML DOM within our JS environment. Useful if you want to test how candidates can manipulate elements without using our full HTML/CSS/JS environment.
Note that packages must be require()
ed, not import
ed.
Here’s an example of a test using Chai:
const chai = require('chai')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
chai.should()
chai.use(sinonChai)
function hello(name: string, cb) {
cb('hello ' + name)
}
var cb = sinon.spy()
hello('world', cb)
cb.should.have.been.calledWith('hello world')
cb.should.have.been.calledWith('this test should fail')
Visual Basic
Switch to Visual BasicOur Visual Basic environment runs on Microsoft’s cross-platform .NET Core runtime.
Your code is compiled and run with debug mode enabled.
You can run NUnit tests w/ the following code:
Imports NUnit.Framework
Imports NUnitLite
Imports System
Imports System.Reflection
<TestFixture()>
Public Class TestGroup
<Test()>
Public Sub BasicTest()
Assert.AreEqual(2,2)
End Sub
End Class
Module Solution
Sub Main()
Dim autorunner As New AutoRun(Assembly.GetCallingAssembly())
autorunner.execute({"--noresult"})
End Sub
End Module
Verilog
Switch to VerilogNo extra information available. It probably just works!
Are there any libraries or settings we missed? Feel free to email us with suggestions!