WeixiangYan/CodeTransOcean huggingface dataset:
Task: Dynamic variable names



C#: using System;
using System.Dynamic;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string varname = Console.ReadLine();
        
        dynamic expando = new ExpandoObject();
        var map = expando as IDictionary<string, object>;
        map.Add(varname, "Hello world!");
 
        Console.WriteLine(expando.foo);
    }
}


Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strconv"
    "strings"
)

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    n := 0
    for n < 1 || n > 5 {
        fmt.Print("How many integer variables do you want to create (max 5) : ")
        scanner.Scan()
        n, _ = strconv.Atoi(scanner.Text())
        check(scanner.Err())
    }
    vars := make(map[string]int)
    fmt.Println("OK, enter the variable names and their values, below")
    for i := 1; i <= n; {
        fmt.Println("\n  Variable", i)
        fmt.Print("    Name  : ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        if _, ok := vars[name]; ok {
            fmt.Println("  Sorry, you've already created a variable of that name, try again")
            continue
        }
        var value int
        var err error
        for {
            fmt.Print("    Value : ")
            scanner.Scan()
            value, err = strconv.Atoi(scanner.Text())
            check(scanner.Err())
            if err != nil {
                fmt.Println("  Not a valid integer, try again")
            } else {
                break
            }
        }
        vars[name] = value
        i++
    }
    fmt.Println("\nEnter q to quit")
    for {
        fmt.Print("\nWhich variable do you want to inspect : ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        if s := strings.ToLower(name); s == "q" {
            return
        }
        v, ok := vars[name]
        if !ok {
            fmt.Println("Sorry there's no variable of that name, try again")
        } else {
            fmt.Println("It's value is", v)
        }
    }
}
Task: Largest palindrome product



C#: using System;
class Program {

  static bool isPal(int n) {
    int rev = 0, lr = -1, rem;
    while (n > rev) {
      n = Math.DivRem(n, 10, out rem);
      if (lr < 0 && rem == 0) return false;
      lr = rev; rev = 10 * rev + rem;
      if (n == rev || n == lr) return true;
    } return false; }

  static void Main(string[] args) {
    var sw = System.Diagnostics.Stopwatch.StartNew();
    int x = 900009, y = (int)Math.Sqrt(x), y10, max = 999, max9 = max - 9, z, p, bp = x, ld, c;
    var a = new int[]{ 0,9,0,3,0,0,0,7,0,1 }; string bs = "";
    y /= 11;
    if ((y & 1) == 0) y--;
    if (y % 5 == 0) y -= 2;
    y *= 11;
    while (y <= max) {
      c = 0;
      y10 = y * 10;
      z = max9 + a[ld = y % 10];
      p = y * z;
      while (p >= bp) {
        if (isPal(p)) {
          if (p > bp) bp = p;
          bs = string.Format("{0} x {1} = {2}", y, z - c, bp);
        }
        p -= y10; c += 10;
      }
      y += ld == 3 ? 44 : 22;
    }
    sw.Stop();
    Console.Write("{0} {1} μs", bs, sw.Elapsed.TotalMilliseconds * 1000.0);
  }
}


Go: package main

import "fmt"

func reverse(n uint64) uint64 {
    r := uint64(0)
    for n > 0 {
        r = n%10 + r*10
        n /= 10
    }
    return r
}

func main() {
    pow := uint64(10)
nextN:
    for n := 2; n < 10; n++ {
        low := pow * 9
        pow *= 10
        high := pow - 1
        fmt.Printf("Largest palindromic product of two %d-digit integers: ", n)
        for i := high; i >= low; i-- {
            j := reverse(i)
            p := i*pow + j
            
            for k := high; k > low; k -= 2 {
                if k % 10 == 5 {
                    continue
                }
                l := p / k
                if l > high {
                    break
                }
                if p%k == 0 {
                    fmt.Printf("%d x %d = %d\n", k, l, p)
                    continue nextN
                }
            }
        }
    }
}
Task: Kosaraju



C#: using System;
using System.Collections.Generic;

class Node
{
	public enum Colors
	{
		Black, White, Gray
	}

	public Colors color { get; set; }
	public int N { get; }
	
	public Node(int n)
	{
		N = n;
		color = Colors.White;
	}
}

class Graph
{
	public HashSet<Node> V { get; }
	public Dictionary<Node, HashSet<Node>> Adj { get; }

	
	
	
	public void Kosaraju()
	{
		var L = new HashSet<Node>();

		Action<Node> Visit = null;
		Visit = (u) =>
		{
			if (u.color == Node.Colors.White)
			{
				u.color = Node.Colors.Gray;

				foreach (var v in Adj[u])
					Visit(v);

				L.Add(u);
			}
		};

		Action<Node, Node> Assign = null;
		Assign = (u, root) =>
		{
			if (u.color != Node.Colors.Black)
			{
				if (u == root)
					Console.Write("SCC: ");

				Console.Write(u.N + " ");
				u.color = Node.Colors.Black;

				foreach (var v in Adj[u])
					Assign(v, root);

				if (u == root)
					Console.WriteLine();
			}
		};

		foreach (var u in V)
			Visit(u);

		foreach (var u in L)
			Assign(u, u);
	}
}


Go: package main

import "fmt"

var g = [][]int{
    0: {1},
    1: {2},
    2: {0},
    3: {1, 2, 4},
    4: {3, 5},
    5: {2, 6},
    6: {5},
    7: {4, 6, 7},
}

func main() {
    fmt.Println(kosaraju(g))
}

func kosaraju(g [][]int) []int {
    
    vis := make([]bool, len(g))
    L := make([]int, len(g))
    x := len(L)                
    t := make([][]int, len(g)) 
    
    var Visit func(int)
    Visit = func(u int) {
        if !vis[u] {
            vis[u] = true
            for _, v := range g[u] {
                Visit(v)
                t[v] = append(t[v], u) 
            }
            x--
            L[x] = u
        }
    }
    
    for u := range g {
        Visit(u)
    }
    c := make([]int, len(g)) 
    
    var Assign func(int, int)
    Assign = func(u, root int) {
        if vis[u] { 
            vis[u] = false
            c[u] = root
            for _, v := range t[u] {
                Assign(v, root)
            }
        }
    }
    
    for _, u := range L {
        Assign(u, u)
    }
    return c
}
Task: Reflection_List methods



C#: using System;
using System.Reflection;

public class Rosetta
{
    public static void Main()
    {
        
        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static
            | BindingFlags.Public | BindingFlags.NonPublic
            | BindingFlags.DeclaredOnly;

        foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))
            Console.WriteLine(method);
    }
    
    class TestForMethodReflection
    {
        public void MyPublicMethod() {}
        private void MyPrivateMethod() {}
        
        public static void MyPublicStaticMethod() {}
        private static void MyPrivateStaticMethod() {}
    }
    
}


Go: package main

import (
	"fmt"
	"image"
	"reflect"
)

type t int 


func (r t) Twice() t       { return r * 2 }
func (r t) Half() t        { return r / 2 }
func (r t) Less(r2 t) bool { return r < r2 }
func (r t) privateMethod() {}

func main() {
	report(t(0))
	report(image.Point{})
}

func report(x interface{}) {
	v := reflect.ValueOf(x)
	t := reflect.TypeOf(x) 
	n := t.NumMethod()
	fmt.Printf("Type %v has %d exported methods:\n", t, n)
	const format = "%-6s %-46s %s\n"
	fmt.Printf(format, "Name", "Method expression", "Method value")
	for i := 0; i < n; i++ {
		fmt.Printf(format,
			t.Method(i).Name,
			t.Method(i).Func.Type(),
			v.Method(i).Type(),
		)
	}
	fmt.Println()
}
Task: Send an unknown method call



C#: using System;

class Example
{
    public int foo(int x)
    {
        return 42 + x;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var example = new Example();
        var method = "foo";
        
        var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 });
        Console.WriteLine("{0}(5) = {1}", method, result);
    }
}


Go: package main

import (
    "fmt"
    "reflect"
)

type example struct{}


func (example) Foo() int {
    return 42
}

func main() {
    
    var e example
    
    m := reflect.ValueOf(e).MethodByName("Foo")
    
    r := m.Call(nil)
    
    fmt.Println(r[0].Int()) 
}
Task: Add a variable to a class instance at runtime



C#: 







using System;
using System.Dynamic;

namespace DynamicClassVariable
{
    internal static class Program
    {
        #region Static Members

        private static void Main()
        {
            
            
            dynamic sampleObj = new ExpandoObject();
            
            sampleObj.bar = 1;
            Console.WriteLine( "sampleObj.bar = {0}", sampleObj.bar );

            
            
            
            
            Console.WriteLine( "< Press any key >" );
            Console.ReadKey();
        }

        #endregion
    }
}


Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

type SomeStruct struct {
    runtimeFields map[string]string
}

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    ss := SomeStruct{make(map[string]string)}
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Println("Create two fields at runtime: ")
    for i := 1; i <= 2; i++ {
        fmt.Printf("  Field #%d:\n", i)
        fmt.Print("       Enter name  : ")
        scanner.Scan()
        name := scanner.Text()
        fmt.Print("       Enter value : ")
        scanner.Scan()
        value := scanner.Text()
        check(scanner.Err())
        ss.runtimeFields[name] = value
        fmt.Println()
    }
    for {
        fmt.Print("Which field do you want to inspect ? ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        value, ok := ss.runtimeFields[name]
        if !ok {
            fmt.Println("There is no field of that name, try again")
        } else {
            fmt.Printf("Its value is '%s'\n", value)
            return
        }
    }
}
Task: Y combinator

C: #include <stdio.h>
#include <stdlib.h>


typedef struct func_t *func;
typedef struct func_t {
        func (*fn) (func, func);
        func _;
        int num;
} func_t;

func new(func(*f)(func, func), func _) {
        func x = malloc(sizeof(func_t));
        x->fn = f;
        x->_ = _;       
        x->num = 0;
        return x;
}

func call(func f, func n) {
        return f->fn(f, n);
}

func Y(func(*f)(func, func)) {
        func g = new(f, 0);
        g->_ = g;
        return g;
}

func num(int n) {
        func x = new(0, 0);
        x->num = n;
        return x;
}


func fac(func self, func n) {
        int nn = n->num;
        return nn > 1   ? num(nn * call(self->_, num(nn - 1))->num)
                        : num(1);
}

func fib(func self, func n) {
        int nn = n->num;
        return nn > 1
                ? num(  call(self->_, num(nn - 1))->num +
                        call(self->_, num(nn - 2))->num )
                : num(1);
}

void show(func n) { printf(" %d", n->num); }

int main() {
        int i;
        func f = Y(fac);
        printf("fac: ");
        for (i = 1; i < 10; i++)
                show( call(f, num(i)) );
        printf("\n");

        f = Y(fib);
        printf("fib: ");
        for (i = 1; i < 10; i++)
                show( call(f, num(i)) );
        printf("\n");

        return 0;
}







Python: >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i in range(10) ]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Task: Return multiple values

C: #include<stdio.h>

typedef struct{
	int integer;
	float decimal;
	char letter;
	char string[100];
	double bigDecimal;
}Composite;

Composite example()
{
	Composite C = {1, 2.3, 'a', "Hello World", 45.678};
	return C;
}


int main()
{
	Composite C = example();

	printf("Values from a function returning a structure : { %d, %f, %c, %s, %f}\n", C.integer, C.decimal, C.letter, C.string, C.bigDecimal);

	return 0;
}







Python: def addsub(x, y):
  return x + y, x - y
Task: Van Eck sequence

C: #include <stdlib.h>
#include <stdio.h>

int main(int argc, const char *argv[]) {
  const int max = 1000;
  int *a = malloc(max * sizeof(int));
  for (int n = 0; n < max - 1; n ++) {
    for (int m = n - 1; m >= 0; m --) {
      if (a[m] == a[n]) {
        a[n+1] = n - m;
        break;
      }
    }
  }

  printf("The first ten terms of the Van Eck sequence are:\n");
  for (int i = 0; i < 10; i ++) printf("%d ", a[i]);
  printf("\n\nTerms 991 to 1000 of the sequence are:\n");
  for (int i = 990; i < 1000; i ++) printf("%d ", a[i]);
  putchar('\n');

  return 0;
}







Python: def van_eck():
    n, seen, val = 0, {}, 0
    while True:
        yield val
        last = {val: n}
        val = n - seen.get(val, n)
        seen.update(last)
        n += 1

if __name__ == '__main__':
    print("Van Eck: first 10 terms:  ", list(islice(van_eck(), 10)))
    print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
Task: FTP

C: #include <ftplib.h>

int main(void)
{
    netbuf *nbuf;

    FtpInit();
    FtpConnect("kernel.org", &nbuf);
    FtpLogin("anonymous", "", nbuf);
    FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf);
    FtpChdir("pub/linux/kernel", nbuf);
    FtpDir((void*)0, ".", nbuf);
    FtpGet("ftp.README", "README", FTPLIB_ASCII, nbuf);
    FtpQuit(nbuf);

    return 0;
}







Python: from ftplib import FTP
ftp = FTP('kernel.org')
ftp.login()
ftp.cwd('/pub/linux/kernel')
ftp.set_pasv(True) 
print ftp.retrlines('LIST')
print ftp.retrbinary('RETR README', open('README', 'wb').write)
ftp.quit()
Task: Loops_Continue

C: for(int i = 1;i <= 10; i++){
   printf("%d", i);
   if(i % 5 == 0){
      printf("\n");
      continue;
   }
   printf(", ");
}







Python: for i in range(1, 11):
    if i % 5 == 0:
        print(i)
        continue
    print(i, end=', ')
Task: Colour bars_Display

C: #include<conio.h>

#define COLOURS 8

int main()
{
	int colour=0,i,j,MAXROW,MAXCOL;
	struct text_info tInfo;
	gettextinfo(&tInfo);
	MAXROW = tInfo.screenheight;
	MAXCOL = tInfo.screenwidth;
	textbackground(BLACK);     
	clrscr();
	
	for(colour=0;colour<COLOURS;colour++)
	{
		getch();                              
		gotoxy(1+colour*MAXCOL/COLOURS,1);
		textbackground(colour);
		for(j=0;j<MAXROW;j++){
			for(i=0;i<MAXCOL/COLOURS;i++){
				cprintf(" ");
			}
		gotoxy(1+colour*MAXCOL/COLOURS,1+j);
		}
	}

	getch();
	textbackground(BLACK);

	return 0;
}







Python: 


from livewires import *

horiz=640; vert=480
begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black)
NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"]
stepik=horiz/len(NameColors)

for index,each in enumerate(NameColors):
	ExcStrng="set_colour(Colour."+each+")"
	exec ExcStrng
	box(index*stepik,0,(index+1)*stepik,vert,filled=1)

while keys_pressed() != ['x']: 
	pass

end_graphics()
Task: General FizzBuzz

C: #include <stdio.h>
#include <stdlib.h>

struct replace_info {
    int n;
    char *text;
};

int compare(const void *a, const void *b)
{
    struct replace_info *x = (struct replace_info *) a;
    struct replace_info *y = (struct replace_info *) b;
    return x->n - y->n;
}

void generic_fizz_buzz(int max, struct replace_info *info, int info_length)
{
    int i, it;
    int found_word;

    for (i = 1; i < max; ++i) {
        found_word = 0;

        
        for (it = 0; it < info_length; ++it) {
            if (0 == i % info[it].n) {
                printf("%s", info[it].text);
                found_word = 1;
            }
        }

        if (0 == found_word)
            printf("%d", i);

        printf("\n");
    }
}

int main(void)
{
    struct replace_info info[3] = {
        {5, "Buzz"},
        {7, "Baxx"},
        {3, "Fizz"}
    };

    
    qsort(info, 3, sizeof(struct replace_info), compare);

    
    generic_fizz_buzz(20, info, 3);
    return 0;
}







Python: def genfizzbuzz(factorwords, numbers):
    
    factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
    lines = []
    for num in numbers:
        words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
        lines.append(words if words else str(num))
    return '\n'.join(lines)

if __name__ == '__main__':
    print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
Task: Read a specific line from a file

C: #include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>


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("line_no too small");
		return 0; 
	}

	line_no--; 

	fd = open(path, O_RDONLY);
	fstat(fd, &s);

	
	buf = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);

	
	madvise(buf, s.st_size, MADV_SEQUENTIAL);

	for (i = ln = 0; i < s.st_size && ln <= line_no; i++) {
		if (buf[i] != '\n') continue;

		if (++ln == line_no) start = i + 1;
		else if (ln == line_no + 1) end = i + 1;
	}

	if (start >= s.st_size || start < 0) {
		warn("file does not have line %d", line_no + 1);
		ret = 0;
	} else {
		
	}

	munmap(buf, s.st_size);
	close(fd);

	return ret;
}







Python: with open('xxx.txt') as f:
    for i, line in enumerate(f):
        if i == 6:
            break
    else:
        print('Not 7 lines in file')
        line = None
Task: File extension is in extensions list

C: 

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <locale.h>
#include <string.h>

#ifdef _Bool
#include <stdbool.h>
#else
#define bool int
#define true  1
#define false 0
#endif


int checkFileExtension(char* fileName, char* fileExtensions)
{
    char* fileExtension = fileExtensions;

    if ( *fileName )
    {
        while ( *fileExtension )
        {
            int fileNameLength = strlen(fileName);
            int extensionLength = strlen(fileExtension);
            if ( fileNameLength >= extensionLength )
            {
                char* a = fileName + fileNameLength - extensionLength;
                char* b = fileExtension;
                while ( *a && toupper(*a++) == toupper(*b++) )
                    ;
                if ( !*a )
                    return true;
            }
            fileExtension += extensionLength + 1;
        }
    }
    return false;
}

void printExtensions(char* extensions)
{
    while( *extensions )
    {
        printf("%s\n", extensions);
        extensions += strlen(extensions) + 1;
    }
}

bool test(char* fileName, char* extension, bool expectedResult)
{
    bool result = checkFileExtension(fileName,extension);
    bool returnValue = result == expectedResult;
    printf("%20s  result: %-5s  expected: %-5s  test %s\n", 
        fileName,
        result         ? "true"   : "false",
        expectedResult ? "true"   : "false", 
        returnValue    ? "passed" : "failed" );
    return returnValue;
}

int main(void)
{
    static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0";

    setlocale(LC_ALL,"");

    printExtensions(extensions);
    printf("\n");

    if ( test("MyData.a##",         extensions,true )
    &&   test("MyData.tar.Gz",      extensions,true )
    &&   test("MyData.gzip",        extensions,false)
    &&   test("MyData.7z.backup",   extensions,false)
    &&   test("MyData...",          extensions,false)
    &&   test("MyData",             extensions,false)
    &&   test("MyData_v1.0.tar.bz2",extensions,true )
    &&   test("MyData_v1.0.bz2",    extensions,false) 
    &&   test("filename",           extensions,false)
    )
        printf("\n%s\n", "All tests passed.");
    else
        printf("\n%s\n", "Last test failed.");

    printf("\n%s\n", "press enter");
    getchar();
    return 0;
}







Python: def isExt(fileName, extensions):
  return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
Task: Checkpoint synchronization

C: #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>

int main()
{
        int jobs = 41, tid;
        omp_set_num_threads(5);

        #pragma omp parallel shared(jobs) private(tid)
        {
                tid = omp_get_thread_num();
                while (jobs > 0) {
                        
                        #pragma omp barrier
                        if (!jobs) break;

                        printf("%d: taking job %d\n", tid, jobs--);
                        usleep(100000 + rand() / (double) RAND_MAX * 3000000);
                        printf("%d: done job\n", tid);
                }

                printf("[%d] leaving\n", tid);

                
                #pragma omp barrier
        }

        return 0;
}







Python: 

import threading
import time
import random


def worker(workernum, barrier):
    
    sleeptime = random.random()
    print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
    time.sleep(sleeptime)
    print('Exiting worker'+str(workernum))
    barrier.wait()
    
    sleeptime = random.random()
    print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
    time.sleep(sleeptime)
    print('Exiting worker'+str(workernum))

barrier = threading.Barrier(3)

w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))

w1.start()
w2.start()
w3.start()
Task: Variable-length quantity

C: #include <stdio.h>
#include <stdint.h>

void to_seq(uint64_t x, uint8_t *out)
{
	int i, j;
	for (i = 9; i > 0; i--) {
		if (x & 127ULL << i * 7) break;
	}
	for (j = 0; j <= i; j++)
		out[j] = ((x >> ((i - j) * 7)) & 127) | 128;

	out[i] ^= 128;
}

uint64_t from_seq(uint8_t *in)
{
	uint64_t r = 0;

	do {
		r = (r << 7) | (uint64_t)(*in & 127);
	} while (*in++ & 128);

	return r;
}

int main()
{
	uint8_t s[10];
	uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};

	int i, j;
	for (j = 0; j < sizeof(x)/8; j++) {
		to_seq(x[j], s);
		printf("seq from %llx: [ ", x[j]);

		i = 0;
		do { printf("%02x ", s[i]); } while ((s[i++] & 128));
		printf("] back: %llx\n", from_seq(s));
	}

	return 0;
}







Python: def tobits(n, _group=8, _sep='_', _pad=False):
    'Express n as binary bits with separator'
    bits = '{0:b}'.format(n)[::-1]
    if _pad:
        bits = '{0:0{1}b}'.format(n,
                                  ((_group+len(bits)-1)//_group)*_group)[::-1]
        answer = _sep.join(bits[i:i+_group]
                                 for i in range(0, len(bits), _group))[::-1]
        answer = '0'*(len(_sep)-1) + answer
    else:
        answer = _sep.join(bits[i:i+_group]
                           for i in range(0, len(bits), _group))[::-1]
    return answer

def tovlq(n):
    return tobits(n, _group=7, _sep='1_', _pad=True)

def toint(vlq):
    return int(''.join(vlq.split('_1')), 2)    

def vlqsend(vlq):
    for i, byte in enumerate(vlq.split('_')[::-1]):
        print('Sent byte {0:3}: {1:
Task: Record sound

C: #include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

void * record(size_t bytes)
{
	int fd;
	if (-1 == (fd = open("/dev/dsp", O_RDONLY))) return 0;
	void *a = malloc(bytes);
	read(fd, a, bytes);
	close(fd);
	return a;
}

int play(void *buf, size_t len)
{
	int fd;
	if (-1 == (fd = open("/dev/dsp", O_WRONLY))) return 0;
	write(fd, buf, len);
	close(fd);
	return 1;
}

int main()
{
	void *p = record(65536);
	play(p, 65536);
	return 0;
}







Python: import pyaudio

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100

p = pyaudio.PyAudio()

stream = p.open(format = FORMAT,
                channels = CHANNELS,
                rate = RATE,
                input = True,
                frames_per_buffer = chunk)

data = stream.read(chunk)
print [ord(i) for i in data]