code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
import Foundation
func repString(_ input: String) -> [String] {
return (1..<(1 + input.count / 2)).compactMap({x -> String? in
let i = input.index(input.startIndex, offsetBy: x)
return input.hasPrefix(input[i...])? String(input.prefix(x)): nil
})
}
let testCases = """
1001110011
... | 358Rep-string | 17swift | 98omj |
puts <<EOS
---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
EOS
.each_line.map {|line| line.split.reverse.join(' ')} | 349Reverse words in a string | 14ruby | blhkq |
null | 365Real constants and functions | 11kotlin | e59a4 |
object RemoveLinesFromAFile extends App {
args match {
case Array(filename, start, num) =>
import java.nio.file.{Files,Paths}
val lines = scala.io.Source.fromFile(filename).getLines
val keep = start.toInt - 1
val top = lines.take(keep).toList
val drop = lines.take(num.toInt).toList
... | 360Remove lines from a file | 16scala | ibkox |
const TEXT: &'static str =
"---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------";
fn main() {
println!("{}",
TEXT.lines() | 349Reverse words in a string | 15rust | p2kbu |
fun main(args: Array<String>) {
println("ha".repeat(5))
} | 359Repeat a string | 11kotlin | 8hh0q |
print $ unique [4, 5, 4, 2, 3, 3, 4]
[4,5,2,3] | 362Remove duplicate elements | 8haskell | 6qe3k |
str =
p if str =~ /string$/
p unless str =~ /^You/ | 356Regular expressions | 14ruby | 3x0z7 |
null | 341Roman numerals/Encode | 20typescript | 0hts3 |
use regex::Regex;
fn main() {
let s = "I am a string";
if Regex::new("string$").unwrap().is_match(s) {
println!("Ends with string.");
}
println!("{}", Regex::new(" a ").unwrap().replace(s, " another "));
} | 356Regular expressions | 15rust | 6q83l |
object ReverseWords extends App {
"""| ---------- Ice and Fire ------------
|
| fire, in end will world the say Some
| ice. in say Some
| desire of tasted I've what From
| fire. favor who those with hold I
|
| ... elided paragraph last ... ... | 349Reverse words in a string | 16scala | e51ab |
func addsub(x: Int, y: Int) -> (Int, Int) {
return (x + y, x - y)
} | 348Return multiple values | 17swift | utuvg |
val Bottles1 = "(\\d+) bottles of beer".r | 356Regular expressions | 16scala | 98nm5 |
sub rref
{our @m; local *m = shift;
@m or return;
my ($lead, $rows, $cols) = (0, scalar(@m), scalar(@{$m[0]}));
foreach my $r (0 .. $rows - 1)
{$lead < $cols or return;
my $i = $r;
until ($m[$i][$lead])
{++$i == $rows or next;
$i = $r;
++$lead == $cols and return;}... | 364Reduced row echelon form | 2perl | m0eyz |
math.exp(1)
math.pi
math.sqrt(x)
math.log(x)
math.log10(x)
math.exp(x)
math.abs(x)
math.floor(x)
math.ceil(x)
x^y | 365Real constants and functions | 1lua | w4cea |
<?php
function rref($matrix)
{
$lead = 0;
$rowCount = count($matrix);
if ($rowCount == 0)
return $matrix;
$columnCount = 0;
if (isset($matrix[0])) {
$columnCount = count($matrix[0]);
}
for ($r = 0; $r < $rowCount; $r++) {
if ($lead >= $columnCount)
break;... | 364Reduced row echelon form | 12php | e5ca9 |
function repeats(s, n) return n > 0 and s .. repeats(s, n-1) or "" end | 359Repeat a string | 1lua | okk8h |
import java.util.*;
class Test {
public static void main(String[] args) {
Object[] data = {1, 1, 2, 2, 3, 3, 3, "a", "a", "b", "b", "c", "d"};
Set<Object> uniqueSet = new HashSet<Object>(Arrays.asList(data));
for (Object o: uniqueSet)
System.out.printf("%s ", o);
}
} | 362Remove duplicate elements | 9java | nphih |
import Foundation
let str = "I am a string"
if let range = str.rangeOfString("string$", options: .RegularExpressionSearch) {
println("Ends with 'string'")
} | 356Regular expressions | 17swift | zwstu |
import Foundation | 349Reverse words in a string | 17swift | kcjhx |
function unique(ary) { | 362Remove duplicate elements | 10javascript | 3xaz0 |
def ToReducedRowEchelonForm( M):
if not M: return
lead = 0
rowCount = len(M)
columnCount = len(M[0])
for r in range(rowCount):
if lead >= columnCount:
return
i = r
while M[i][lead] == 0:
i += 1
if i == rowCount:
i = r
... | 364Reduced row echelon form | 3python | 98wmf |
rref <- function(m) {
pivot <- 1
norow <- nrow(m)
nocolumn <- ncol(m)
for(r in 1:norow) {
if ( nocolumn <= pivot ) break;
i <- r
while( m[i,pivot] == 0 ) {
i <- i + 1
if ( norow == i ) {
i <- r
pivot <- pivot + 1
if ( nocolumn == pivot ) return(m)
}
}
... | 364Reduced row echelon form | 13r | 3xpzt |
perl -n -0777 -e 'print "file len: ".length' stuff.txt | 363Read entire file | 2perl | 5tiu2 |
fun main(args: Array<String>) {
val data = listOf(1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d")
val set = data.distinct()
println(data)
println(set)
} | 362Remove duplicate elements | 11kotlin | s74q7 |
file_get_contents($filename) | 363Read entire file | 12php | okr85 |
def reduced_row_echelon_form(ary)
lead = 0
rows = ary.size
cols = ary[0].size
rary = convert_to(ary, :to_r)
catch :done do
rows.times do |r|
throw :done if cols <= lead
i = r
while rary[i][lead] == 0
i += 1
if rows == i
i = r
lead += 1
th... | 364Reduced row echelon form | 14ruby | liqcl |
fn main() {
let mut matrix_to_reduce: Vec<Vec<f64>> = vec![vec![1.0, 2.0 , -1.0, -4.0],
vec![2.0, 3.0, -1.0, -11.0],
vec![-2.0, 0.0, -3.0, 22.0]];
let mut r_mat_to_red = &mut matrix_to_reduce;
let rr_mat_to_red ... | 364Reduced row echelon form | 15rust | 2nslt |
open(filename).read() | 363Read entire file | 3python | 4zn5k |
items = {1,2,3,4,1,2,3,4,"bird","cat","dog","dog","bird"}
flags = {}
io.write('Unique items are:')
for i=1,#items do
if not flags[items[i]] then
io.write(' ' .. items[i])
flags[items[i]] = true
end
end
io.write('\n') | 362Remove duplicate elements | 1lua | 0jgsd |
use POSIX;
exp(1);
4 * atan2(1, 1);
sqrt($x);
log($x);
exp($x);
abs($x);
floor($x);
ceil($x);
$x ** $y;
use Math::Trig;
pi;
use Math::Complex;
pi; | 365Real constants and functions | 2perl | cow9a |
fname <- "notes.txt"
contents <- readChar(fname, file.info(fname)$size) | 363Read entire file | 13r | 2n0lg |
M_E;
M_PI;
sqrt(x);
log(x);
exp(x);
abs(x);
floor(x);
ceil(x);
pow(x,y); | 365Real constants and functions | 12php | xglw5 |
var lead = 0
for r in 0..<rows {
if (cols <= lead) { break }
var i = r
while (m[i][lead] == 0) {
i += 1
if (i == rows) {
i = r
lead += 1
if (cols == lead) {
lea... | 364Reduced row echelon form | 17swift | cox9t |
str = IO.read
str = IO.read | 363Read entire file | 14ruby | r6fgs |
use std::fs::File;
use std::io::Read;
fn main() {
let mut file = File::open("somefile.txt").unwrap();
let mut contents: Vec<u8> = Vec::new(); | 363Read entire file | 15rust | 7ytrc |
object TextFileSlurper extends App {
val fileLines =
try scala.io.Source.fromFile("my_file.txt", "UTF-8").mkString catch {
case e: java.io.FileNotFoundException => e.getLocalizedMessage()
}
} | 363Read entire file | 16scala | kc6hk |
"ha" x 5 | 359Repeat a string | 2perl | 4zz5d |
import math
math.e
math.pi
math.sqrt(x)
math.log(x)
math.log10(x)
math.exp(x)
abs(x)
math.floor(x)
math.ceil(x)
x ** y
pow(x, y[, n]) | 365Real constants and functions | 3python | lixcv |
exp(1)
pi
sqrt(x)
log(x)
log10(x)
log(x, y)
exp(x)
abs(x)
floor(x)
ceiling(x)
x^y | 365Real constants and functions | 13r | ys16h |
str_repeat(, 5) | 359Repeat a string | 12php | ibbov |
import Foundation
let path = "~/input.txt".stringByExpandingTildeInPath
if let string = String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
println(string) | 363Read entire file | 17swift | g3d49 |
x.abs
x.magnitude
x.floor
x.ceil
x ** y
include Math
E
PI
sqrt(x)
log(x)
log(x, y)
log10(x)
exp(x) | 365Real constants and functions | 14ruby | vds2n |
use std::f64::consts::*;
fn main() { | 365Real constants and functions | 15rust | uf0vj |
object RealConstantsFunctions extends App{
println(math.E) | 365Real constants and functions | 16scala | g3i4i |
package main
import (
"fmt"
"unicode"
"unicode/utf8"
) | 366Reverse a string | 0go | xgcwf |
* 5 | 359Repeat a string | 3python | g334h |
import Darwin
M_E | 365Real constants and functions | 17swift | 2nqlj |
println "Able was I, 'ere I saw Elba.".reverse() | 366Reverse a string | 7groovy | p23bo |
strrep("ha", 5) | 359Repeat a string | 13r | vdd27 |
reverse = foldl (flip (:)) [] | 366Reverse a string | 8haskell | ysp66 |
* 5 | 359Repeat a string | 14ruby | 7yyri |
std::iter::repeat("ha").take(5).collect::<String>(); | 359Repeat a string | 15rust | jmm72 |
use List::MoreUtils qw(uniq);
my @uniq = uniq qw(1 2 3 a b c 2 3 4 b c d); | 362Remove duplicate elements | 2perl | ufivr |
public static String reverseString(String s) {
return new StringBuffer(s).reverse().toString();
} | 366Reverse a string | 9java | d1rn9 |
"ha" * 5 | 359Repeat a string | 16scala | bllk6 |
int main(void)
{
char *locale = setlocale(LC_ALL, );
FILE *in = fopen(, );
wint_t c;
while ((c = fgetwc(in)) != WEOF)
putwchar(c);
fclose(in);
return EXIT_SUCCESS;
} | 367Read a file character by character/UTF8 | 5c | 7yirg |
null | 366Reverse a string | 10javascript | 6qb38 |
struct rate_state_s
{
time_t lastFlush;
time_t period;
size_t tickCount;
};
void tic_rate(struct rate_state_s* pRate)
{
pRate->tickCount += 1;
time_t now = time(NULL);
if((now - pRate->lastFlush) >= pRate->period)
{
size_t tps = 0.0;
if(pRate->tickCount > 0)
... | 368Rate counter | 5c | fagd3 |
$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');
$unique_list = array_unique($list); | 362Remove duplicate elements | 12php | 8hr0m |
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func Runer(r io.RuneReader) func() (rune, error) {
return func() (r rune, err error) {
r, _, err = r.ReadRune()
return
}
}
func main() {
runes := Runer(bufio.NewReader(os.Stdin))
for r, err := runes(); err != nil; r,err =... | 367Read a file character by character/UTF8 | 0go | d1gne |
SELECT rpad('', 10, 'ha') | 359Repeat a string | 19sql | auu1t |
#!/usr/bin/env runhaskell
import System.Environment (getArgs)
import System.IO (
Handle, IOMode (..),
hGetChar, hIsEOF, hSetEncoding, stdin, utf8, withFile
)
import Control.Monad (forM_, unless)
import Text.Printf (printf)
import Data.Char (ord)
processCharacters :: Handle -> IO ()
processCharac... | 367Read a file character by character/UTF8 | 8haskell | 5tsug |
fun main(args: Array<String>) {
println("asdf".reversed())
} | 366Reverse a string | 11kotlin | 0jvsf |
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws IOException {
var reader = new FileReader("input.txt", StandardCharsets.UTF_8);
while (true) {
int c = reader.read();
... | 367Read a file character by character/UTF8 | 9java | 981mu |
print(String(repeating:"*", count: 5)) | 359Repeat a string | 17swift | r66gg |
items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items)) | 362Remove duplicate elements | 3python | 5tnux |
null | 367Read a file character by character/UTF8 | 11kotlin | zwjts |
null | 367Read a file character by character/UTF8 | 1lua | 3xhzo |
package main
import (
"fmt"
"math/rand"
"time"
) | 368Rate counter | 0go | jmi7d |
items <- c(1,2,3,2,4,3,2)
unique (items) | 362Remove duplicate elements | 13r | li0ce |
import Control.Monad
import Control.Concurrent
import Data.Time
getTime :: IO DiffTime
getTime = fmap utctDayTime getCurrentTime
addSample :: MVar [a] -> a -> IO ()
addSample q v = modifyMVar_ q (return . (v:))
timeit :: Int -> IO a -> IO [DiffTime]
timeit n task = do
samples <- newMVar []
forM_ [0..n] $ \n ... | 368Rate counter | 8haskell | okv8p |
binmode STDOUT, ':utf8';
open my $fh, "<:encoding(UTF-8)", "input.txt" or die "$!\n";
while (read $fh, my $char, 1) {
printf "got character $char [U+%04x]\n", ord $char;
}
close $fh; | 367Read a file character by character/UTF8 | 2perl | bltk4 |
def get_next_character(f):
c = f.read(1)
while c:
while True:
try:
yield c.decode('utf-8')
except UnicodeDecodeError:
c += f.read(1)
else:
c = f.read(1)
break
with open(,) as f:
for c in get_next_character(f):
print(c) | 367Read a file character by character/UTF8 | 3python | p2zbm |
import java.util.function.Consumer;
public class RateCounter {
public static void main(String[] args) {
for (double d : benchmark(10, x -> System.out.print(""), 10))
System.out.println(d);
}
static double[] benchmark(int n, Consumer<Integer> f, int arg) {
double[] timings = ne... | 368Rate counter | 9java | w4yej |
function millis() { | 368Rate counter | 10javascript | 8h20l |
int read_file_line(const char *path, int line_no)
{
struct stat s;
char *buf;
off_t start = -1, end = -1;
size_t i;
int ln, fd, ret = 1;
if (line_no == 1) start = 0;
else if (line_no < 1){
warn();
return 0;
}
line_no--;
fd = open(path, O_RDONLY);
fstat(fd, &s);
buf = mmap(0, s.st_size, PROT_READ... | 369Read a specific line from a file | 5c | 0jcst |
ary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant']
p ary.uniq | 362Remove duplicate elements | 14ruby | g3f4q |
File.open('input.txt', 'r:utf-8') do |f|
f.each_char{|c| p c}
end | 367Read a file character by character/UTF8 | 14ruby | au61s |
null | 368Rate counter | 11kotlin | blfkb |
use std::collections::HashSet;
use std::hash::Hash;
fn remove_duplicate_elements_hashing<T: Hash + Eq>(elements: &mut Vec<T>) {
let set: HashSet<_> = elements.drain(..).collect();
elements.extend(set.into_iter());
}
fn remove_duplicate_elements_sorting<T: Ord>(elements: &mut Vec<T>) {
elements.sort_unstab... | 362Remove duplicate elements | 15rust | r6tg5 |
use std::{
convert::TryFrom,
fmt::{Debug, Display, Formatter},
io::Read,
};
pub struct ReadUtf8<I: Iterator> {
source: std::iter::Peekable<I>,
}
impl<R: Read> From<R> for ReadUtf8<std::io::Bytes<R>> {
fn from(source: R) -> Self {
ReadUtf8 {
source: source.bytes().peekable(),
... | 367Read a file character by character/UTF8 | 15rust | e5yaj |
(defn read-nth-line
"Read line-number from the given text file. The first line has the number 1."
[file line-number]
(with-open [rdr (clojure.java.io/reader file)]
(nth (line-seq rdr) (dec line-number)))) | 369Read a specific line from a file | 6clojure | d15nb |
val list = List(1,2,3,4,2,3,4,99)
val l2 = list.distinct | 362Remove duplicate elements | 16scala | h96ja |
theString = theString:reverse() | 366Reverse a string | 1lua | 8hu0e |
use Benchmark;
timethese COUNT,{ 'Job1' => &job1, 'Job2' => &job2 };
sub job1
{
...job1 code...
}
sub job2
{
...job2 code...
} | 368Rate counter | 2perl | 6qh36 |
WITH
FUNCTION remove_duplicate_elements(p_in_str IN varchar2, p_delimiter IN varchar2 DEFAULT ',') RETURN varchar2 IS
v_in_str varchar2(32767):= REPLACE(p_in_str,p_delimiter,',');
v_res varchar2(32767);
BEGIN
--
EXECUTE immediate 'select listagg(distinct cv,:p_delimiter) from (select (column_value).getstri... | 362Remove duplicate elements | 19sql | p29b1 |
println(Array(Set([3,2,1,2,3,4]))) | 362Remove duplicate elements | 17swift | 4zd5g |
import subprocess
import time
class Tlogger(object):
def __init__(self):
self.counts = 0
self.tottime = 0.0
self.laststart = 0.0
self.lastreport = time.time()
def logstart(self):
self.laststart = time.time()
def logend(self):
self.counts +=1
self.to... | 368Rate counter | 3python | ysk6q |
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
)
func main() {
if line, err := rsl("input.txt", 7); err == nil {
fmt.Println("7th line:")
fmt.Println(line)
} else {
fmt.Println("rsl:", err)
}
}
func rsl(fn string, n int) (string, error) {
if n < 1 {
return "", fmt.Errorf("invalid request: li... | 369Read a specific line from a file | 0go | ufwvt |
typedef struct { double x, y; } vec;
typedef struct { int n; vec* v; } polygon_t, *polygon;
BIN_V(sub, a.x - b.x, a.y - b.y);
BIN_V(add, a.x + b.x, a.y + b.y);
BIN_S(dot, a.x * b.x + a.y * b.y);
BIN_S(cross, a.x * b.y - a.y * b.x);
vec vmadd(vec a, double s, vec b)
{
vec c;
c.x = a.x + s * b.x;
c.y = a.y + s * ... | 370Ray-casting algorithm | 5c | d1unv |
def line = null
new File("lines.txt").eachLine { currentLine, lineNumber ->
if (lineNumber == 7) {
line = currentLine
}
}
println "Line 7 = $line" | 369Read a specific line from a file | 7groovy | 98bm4 |
main :: IO ()
main = do contents <- readFile filename
case drop 6 $ lines contents of
[] -> error "File has less than seven lines"
l:_ -> putStrLn l
where filename = "testfile" | 369Read a specific line from a file | 8haskell | w46ed |
require 'benchmark'
Document = Struct.new(:id,:a,:b,:c)
documents_a = []
documents_h = {}
1.upto(10_000) do |n|
d = Document.new(n)
documents_a << d
documents_h[d.id] = d
end
searchlist = Array.new(1000){ rand(10_000)+1 }
Benchmark.bm(10) do |x|
x.report('array'){searchlist.each{|el| documents_a.any?{|d| d.id ... | 368Rate counter | 14ruby | 98pmz |
typedef struct{
int score;
char name[100];
}entry;
void ordinalRanking(entry* list,int len){
int i;
printf();
for(i=0;i<len;i++)
printf(,i+1,list[i].score,list[i].name);
}
void standardRanking(entry* list,int len){
int i,j=1;
printf();
for(i=0;i<len;i++){
printf(,j,list[i].score,list[i].name);
if(... | 371Ranking methods | 5c | e5tav |
def task(n: Int) = Thread.sleep(n * 1000)
def rate(fs: List[() => Unit]) = {
val jobs = fs map (f => scala.actors.Futures.future(f()))
val cnt1 = scala.actors.Futures.awaitAll(5000, jobs: _*).count(_ != None)
val cnt2 = scala.actors.Futures.awaitAll(5000, jobs: _*).count(_ != None)
val cnt3 = scala.actors.Futur... | 368Rate counter | 16scala | vdw2s |
package linenbr7;
import java.io.*;
public class LineNbr7 {
public static void main(String[] args) throws Exception {
File f = new File(args[0]);
if (!f.isFile() || !f.canRead())
throw new IOException("can't read " + args[0]);
BufferedReader br = new BufferedReader(new FileRe... | 369Read a specific line from a file | 9java | kcnhm |
typedef struct range_tag {
double low;
double high;
} range_t;
void normalize_range(range_t* range) {
if (range->high < range->low) {
double tmp = range->low;
range->low = range->high;
range->high = tmp;
}
}
int range_compare(const void* p1, const void* p2) {
const range_t*... | 372Range consolidation | 5c | xgzwu |
null | 369Read a specific line from a file | 11kotlin | g3s4d |
(defn normalize [r]
(let [[n1 n2] r]
[(min n1 n2) (max n1 n2)]))
(defn touch? [r1 r2]
(let [[lo1 hi1] (normalize r1)
[lo2 hi2] (normalize r2)]
(or (<= lo2 lo1 hi2)
(<= lo2 hi1 hi2))))
(defn consolidate-touching-ranges [rs]
(let [lows (map #(apply min %) rs)
highs (map #(apply ma... | 372Range consolidation | 6clojure | ok98j |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.