WeixiangYan/CodeTransOcean huggingface dataset:
Task: Kosaraju




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
}




Python: def kosaraju(g):
    class nonlocal: pass

    
    size = len(g)

    vis = [False]*size 
    l = [0]*size
    nonlocal.x = size
    t = [[]]*size   

    def visit(u):
        if not vis[u]:
            vis[u] = True
            for v in g[u]:
                visit(v)
                t[v] = t[v] + [u]
            nonlocal.x = nonlocal.x - 1
            l[nonlocal.x] = u

    
    for u in range(len(g)):
        visit(u)
    c = [0]*size

    def assign(u, root):
        if vis[u]:
            vis[u] = False
            c[u] = root
            for v in t[u]:
                assign(v, root)

    
    for u in l:
        assign(u, u)

    return c

g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]
print kosaraju(g)
Task: Reflection_List methods




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()
}




Python: import inspect


class Super(object):
  def __init__(self, name):
    self.name = name
  
  def __str__(self):
    return "Super(%s)" % (self.name,)
  
  def doSup(self):
    return 'did super stuff'
  
  @classmethod
  def cls(cls):
    return 'cls method (in sup)'
  
  @classmethod
  def supCls(cls):
    return 'Super method'
  
  @staticmethod
  def supStatic():
    return 'static method'

class Other(object):
  def otherMethod(self):
    return 'other method'

class Sub(Other, Super):
  def __init__(self, name, *args):
    super(Sub, self).__init__(name);
    self.rest = args;
    self.methods = {}
  
  def __dir__(self):
    return list(set( \
        sum([dir(base) for base in type(self).__bases__], []) \
        + type(self).__dict__.keys() \
        + self.__dict__.keys() \
        + self.methods.keys() \
      ))
  
  def __getattr__(self, name):
    if name in self.methods:
      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:
        if self.methods[name].__code__.co_varnames[0] == 'self':
          return self.methods[name].__get__(self, type(self))
        if self.methods[name].__code__.co_varnames[0] == 'cls':
          return self.methods[name].__get__(type(self), type)
      return self.methods[name]
    raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
  
  def __str__(self):
    return "Sub(%s)" % self.name
  
  def doSub():
    return 'did sub stuff'
  
  @classmethod
  def cls(cls):
    return 'cls method (in Sub)'
  
  @classmethod
  def subCls(cls):
    return 'Sub method'
  
  @staticmethod
  def subStatic():
    return 'Sub method'

sup = Super('sup')
sub = Sub('sub', 0, 'I', 'two')
sub.methods['incr'] = lambda x: x+1
sub.methods['strs'] = lambda self, x: str(self) * x


[method for method in dir(sub) if callable(getattr(sub, method))]

[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]


[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]


[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]



inspect.getmembers(sub, predicate=inspect.ismethod)

map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
Task: Send an unknown method call




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()) 
}




Python: class Example(object):
     def foo(self, x):
             return 42 + x

name = "foo"
getattr(Example(), name)(5)
Task: Variables




Go: x := 3




Python: 
example1 = 3
example2 = 3.0
example3 = True
example4 = "hello"


example1 = "goodbye"
Task: Interactive programming (repl)




Go: package main

import "fmt"

func f(s1, s2, sep string) string {
	return s1 + sep + sep + s2
}

func main() {
	fmt.Println(f("Rosetta", "Code", ":"))
}




Python: python
Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(string1, string2, separator):
	return separator.join([string1, '', string2])

>>> f('Rosetta', 'Code', ':')
'Rosetta::Code'
>>>
Task: Index finite lists of positive integers




Go: package main

import (
    "fmt"
    "math/big"
)

func rank(l []uint) (r big.Int) {
    for _, n := range l {
        r.Lsh(&r, n+1)
        r.SetBit(&r, int(n), 1)
    }
    return
}

func unrank(n big.Int) (l []uint) {
    m := new(big.Int).Set(&n)
    for a := m.BitLen(); a > 0; {
        m.SetBit(m, a-1, 0)
        b := m.BitLen()
        l = append(l, uint(a-b-1))
        a = b
    }
    return
}

func main() {
    var b big.Int
    for i := 0; i <= 10; i++ {
        b.SetInt64(int64(i))
        u := unrank(b)
        r := rank(u)
        fmt.Println(i, u, &r)
    }
    b.SetString("12345678901234567890", 10)
    u := unrank(b)
    r := rank(u)
    fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r)
}




Python: def rank(x): return int('a'.join(map(str, [1] + x)), 11)

def unrank(n):
	s = ''
	while n: s,n = "0123456789a"[n%11] + s, n//11
	return map(int, s.split('a'))[1:]

l = [1, 2, 3, 10, 100, 987654321]
print l
n = rank(l)
print n
l = unrank(n)
print l
Task: Make a backup file




Go: package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    fn := "myth"
    bx := ".backup"
    
    var err error
    if tf, err := os.Readlink(fn); err == nil {
        fn = tf
    }
    
    var fi os.FileInfo
    if fi, err = os.Stat(fn); err != nil {
        fmt.Println(err)
        return
    }
    
    if err = os.Rename(fn, fn+bx); err != nil {
        fmt.Println(err)
        return
    }
    
    err = ioutil.WriteFile(fn, []byte("you too!\n"), fi.Mode().Perm())
    if err != nil {
        fmt.Println(err)
    }
}




Python: import os
targetfile = "pycon-china"
os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak")
f = open(os.path.realpath(targetfile), "w")
f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011")
f.close()
Task: Reverse the gender of a string




Go: package main

import (
    "fmt"
    "strings"
)

func reverseGender(s string) string {
    if strings.Contains(s, "She") {
        return strings.Replace(s, "She", "He", -1)
    } else if strings.Contains(s, "He") {
        return strings.Replace(s, "He", "She", -1)
    }
    return s
}

func main() {
    s := "She was a soul stripper. She took my heart!"
    t := reverseGender(s)
    fmt.Println(t)
    fmt.Println(reverseGender(t))
}




Python: 

 
import re
male2female=u
 
re_nl=re.compile(r",[ \n]*")
m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ]
 
switch={}
words=[]
 
 
re_plural=re.compile("E*S$")
re_ES=re.compile("ES$")
 
def gen_pluralize(m,f):

  yield re_plural.sub("",m),re_plural.sub("",f)
  yield re_ES.sub("es",m),re_ES.sub("es",f)
  yield re_plural.sub("s",m),re_plural.sub("s",f)
 
def gen_capitalize_pluralize(m,f):
  for m,f in gen_pluralize(m,f):
    yield m.capitalize(), f.capitalize()
    yield m,f
 
def gen_switch_role_capitalize_pluralize(m,f):
  for m,f in gen_capitalize_pluralize(m,f):
    yield m,f
    yield f,m
 
for m,f in m2f:
  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):
    if xy not in switch: 
      switch[xy]=xx
      words.append(xy)
 
words="|".join(words)
 
re_word=re.compile(ur"\b("+words+ur")\b")
 
text=u
 
 
def rev_gender(text):
  text=re_word.split(text)
  return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]
 
print rev_gender(text)
Task: Audio alarm




Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "os/exec"
    "strconv"
    "time"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    number := 0
    for number < 1 {
        fmt.Print("Enter number of seconds delay > 0 : ")
        scanner.Scan()
        input := scanner.Text()
        if err := scanner.Err(); err != nil {
            log.Fatal(err)
        }
        number, _ = strconv.Atoi(input)
    }

    filename := ""
    for filename == "" {
        fmt.Print("Enter name of .mp3 file to play (without extension) : ")
        scanner.Scan()
        filename = scanner.Text()
        if err := scanner.Err(); err != nil {
            log.Fatal(err)
        }
    }

    cls := "\033[2J\033[0;0H" 
    fmt.Printf("%sAlarm will sound in %d seconds...", cls, number)
    time.Sleep(time.Duration(number) * time.Second)
    fmt.Printf(cls)
    cmd := exec.Command("play", filename+".mp3")
    if err := cmd.Run(); err != nil {
        log.Fatal(err)
    }
}




Python: import time
import os

seconds = input("Enter a number of seconds: ")
sound = input("Enter an mp3 filename: ")

time.sleep(float(seconds))
os.startfile(sound + ".mp3")
Task: Decimal floating point number to binary




Go: package main

import (
    "fmt"
    "math"
    "strconv"
    "strings"
)

func decToBin(d float64) string {
    whole := int64(math.Floor(d))
    binary := strconv.FormatInt(whole, 2) + "."
    dd := d - float64(whole)
    for dd > 0.0 {
        r := dd * 2.0
        if r >= 1.0 {
            binary += "1"
            dd = r - 1.0
        } else {
            binary += "0"
            dd = r
        }
    }
    return binary
}

func binToDec(s string) float64 {
    ss := strings.Replace(s, ".", "", 1)
    num, _ := strconv.ParseInt(ss, 2, 64)
    ss = strings.Split(s, ".")[1]
    ss = strings.Replace(ss, "1", "0", -1)
    den, _ := strconv.ParseInt("1" + ss, 2, 64)
    return float64(num) / float64(den)
}

func main() {
    f := 23.34375
    fmt.Printf("%v\t => %s\n", f, decToBin(f))
    s := "1011.11101"
    fmt.Printf("%s\t => %v\n", s, binToDec(s))
}




Python: hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))

def float_dec2bin(d):
    neg = False
    if d < 0:
        d = -d
        neg = True
    hx = float(d).hex()
    p = hx.index('p')
    bn = ''.join(hex2bin.get(char, char) for char in hx[2:p])
    return (('-' if neg else '') + bn.strip('0') + hx[p:p+2]
            + bin(int(hx[p+2:]))[2:])

def float_bin2dec(bn):
    neg = False
    if bn[0] == '-':
        bn = bn[1:]
        neg = True
    dp = bn.index('.')
    extra0 = '0' * (4 - (dp % 4))
    bn2 = extra0 + bn
    dp = bn2.index('.')
    p = bn2.index('p')
    hx = ''.join(bin2hex.get(bn2[i:min(i+4, p)].lstrip('0'), bn2[i])
                 for i in range(0, dp+1, 4))
    bn3 = bn2[dp+1:p]
    extra0 = '0' * (4 - (len(bn3) % 4))
    bn4 = bn3 + extra0
    hx += ''.join(bin2hex.get(bn4[i:i+4].lstrip('0'))
                  for i in range(0, len(bn4), 4))
    hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]
          + str(int('0b' + bn2[p+2:], 2)))
    return float.fromhex(hx)
Task: Runtime evaluation_In an environment




Go: package main

import (
    "bitbucket.org/binet/go-eval/pkg/eval"
    "fmt"
    "go/parser"
    "go/token"
)

func main() {
    
    squareExpr := "x*x"

    
    fset := token.NewFileSet()
    squareAst, err := parser.ParseExpr(squareExpr)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    w := eval.NewWorld()

    
    wVar := new(intV)

    
    err = w.DefineVar("x", eval.IntType, wVar)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    squareCode, err := w.CompileExpr(fset, squareAst)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    *wVar = 5
    
    r0, err := squareCode.Run()
    if err != nil {
        fmt.Println(err)
        return
    }
    
    *wVar--
    
    r1, err := squareCode.Run()
    if err != nil {
        fmt.Println(err)
        return
    }
    
    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))
}


type intV int64

func (v *intV) String() string              { return fmt.Sprint(*v) }
func (v *intV) Get(*eval.Thread) int64      { return int64(*v) }
func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }
func (v *intV) Assign(t *eval.Thread, o eval.Value) {
    *v = intV(o.(eval.IntValue).Get(t))
}




Python: >>> def eval_with_x(code, a, b):
	return eval(code, {'x':b}) - eval(code, {'x':a})

>>> eval_with_x('2 ** x', 3, 5)
24
Task: Check Machin-like formulas




Go: package main

import (
    "fmt"
    "math/big"
)

type mTerm struct {
    a, n, d int64
}

var testCases = [][]mTerm{
    {{1, 1, 2}, {1, 1, 3}},
    {{2, 1, 3}, {1, 1, 7}},
    {{4, 1, 5}, {-1, 1, 239}},
    {{5, 1, 7}, {2, 3, 79}},
    {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}},
    {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}},
    {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}},
    {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}},
    {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}},
    {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}},
    {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}},
    {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}},
    {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}},
    {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}},
    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}},
    {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}},
}

func main() {
    for _, m := range testCases {
        fmt.Printf("tan %v = %v\n", m, tans(m))
    }
}

var one = big.NewRat(1, 1)

func tans(m []mTerm) *big.Rat {
    if len(m) == 1 {
        return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d))
    }
    half := len(m) / 2
    a := tans(m[:half])
    b := tans(m[half:])
    r := new(big.Rat)
    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}

func tanEval(coef int64, f *big.Rat) *big.Rat {
    if coef == 1 {
        return f
    }
    if coef < 0 {
        r := tanEval(-coef, f)
        return r.Neg(r)
    }
    ca := coef / 2
    cb := coef - ca
    a := tanEval(ca, f)
    b := tanEval(cb, f)
    r := new(big.Rat)
    return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b)))
}




Python: import re
from fractions import Fraction
from pprint import pprint as pp


equationtext = 

def parse_eqn(equationtext=equationtext):
    eqn_re = re.compile(r)

    found = eqn_re.findall(equationtext)
    machins, part = [], []
    for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):
        if lhs and part:
            machins.append(part)
            part = []
        part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),
                       Fraction(int(numer), (int(denom) if denom else 1)) ) )
    machins.append(part)
    return machins


def tans(xs):
    xslen = len(xs)
    if xslen == 1:
        return tanEval(*xs[0])
    aa, bb = xs[:xslen//2], xs[xslen//2:]
    a, b = tans(aa), tans(bb)
    return (a + b) / (1 - a * b)

def tanEval(coef, f):
    if coef == 1:
        return f
    if coef < 0:
        return -tanEval(-coef, f)
    ca = coef // 2
    cb = coef - ca
    a, b = tanEval(ca, f), tanEval(cb, f)
    return (a + b) / (1 - a * b)


if __name__ == '__main__':
    machins = parse_eqn()
    
    for machin, eqn in zip(machins, equationtext.split('\n')):
        ans = tans(machin)
        print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
Task: Generate random numbers without repeating a value




Go: package main

import (
    "fmt"
    "log"
    "math/rand"
    "time"
)




func generate(from, to int64) {
    if to < from || from < 0 {
        log.Fatal("Invalid range.")
    }
    span := to - from + 1
    generated := make([]bool, span) 
    count := span
    for count > 0 {
        n := from + rand.Int63n(span) 
        if !generated[n-from] {
            generated[n-from] = true
            fmt.Printf("%2d ", n)
            count--
        }
    }
    fmt.Println()
}

func main() {
    rand.Seed(time.Now().UnixNano())

    
    for i := 1; i <= 5; i++ {
        generate(1, 20)
    }
}




Python: import random

print(random.sample(range(1, 21), 20))
Task: History variables




Go: package main

import (
    "fmt"
    "sort"
    "sync"
    "time"
)


type history struct {
    timestamp tsFunc
    hs        []hset
}


type tsFunc func() time.Time


type hset struct {
    int           
    t   time.Time 
}


func newHistory(ts tsFunc) history {
    return history{ts, []hset{{t: ts()}}}
}   
    

func (h history) int() int {
    return h.hs[len(h.hs)-1].int
}
    

func (h *history) set(x int) time.Time {
    t := h.timestamp()
    h.hs = append(h.hs, hset{x, t})
    return t
}


func (h history) dump() {
    for _, hs := range h.hs {
        fmt.Println(hs.t.Format(time.StampNano), hs.int)
    }
}   
    


func (h history) recall(t time.Time) (int,  bool) {
    i := sort.Search(len(h.hs), func(i int) bool {
        return h.hs[i].t.After(t)
    })
    if i > 0 {
        return h.hs[i-1].int, true
    }
    return 0, false
}





func newTimestamper() tsFunc {
    var last time.Time
    return func() time.Time {
        if t := time.Now(); t.After(last) {
            last = t
        } else {
            last.Add(1)
        }
        return last
    }
}



func newProtectedTimestamper() tsFunc {
    var last time.Time
    var m sync.Mutex
    return func() (t time.Time) {
        t = time.Now()
        m.Lock() 
        if t.After(last) {
            last = t
        } else {
            last.Add(1)
            t = last
        }
        m.Unlock()
        return
    }
}

func main() {
    
    ts := newTimestamper()
    
    h := newHistory(ts)
    
    ref := []time.Time{h.set(3), h.set(1), h.set(4)}
    
    fmt.Println("History of variable h:")
    h.dump() 
    
    
    fmt.Println("Recalling values:")
    for _, t := range ref {
        rv, _ := h.recall(t)
        fmt.Println(rv)
    }
}




Python: import sys

HIST = {}

def trace(frame, event, arg):
    for name,val in frame.f_locals.items():
        if name not in HIST:
            HIST[name] = []
        else:
            if HIST[name][-1] is val:
                continue
        HIST[name].append(val)
    return trace

def undo(name):
    HIST[name].pop(-1)
    return HIST[name][-1]

def main():
    a = 10
    a = 20

    for i in range(5):
        c = i

    print "c:", c, "-> undo x3 ->",
    c = undo('c')
    c = undo('c')
    c = undo('c')
    print c
    print 'HIST:', HIST

sys.settrace(trace)
main()
Task: Runtime evaluation




Go: package main
import (
	"fmt"
	"bitbucket.org/binet/go-eval/pkg/eval"
	"go/token"
)

func main() {
	w := eval.NewWorld();
	fset := token.NewFileSet();

	code, err := w.Compile(fset, "1 + 2")
	if err != nil {
		fmt.Println("Compile error");
		return
	}

	val, err := code.Run();
	if err != nil {
		fmt.Println("Run time error");
		return;
	}
	fmt.Println("Return value:", val) 

}




Python: >>> exec 
10
Task: Use a REST API




Go: package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"
)

var key string

func init() {
	
	
	const keyFile = "api_key.txt"
	f, err := os.Open(keyFile)
	if err != nil {
		log.Fatal(err)
	}
	keydata, err := ioutil.ReadAll(f)
	if err != nil {
		log.Fatal(err)
	}
	key = strings.TrimSpace(string(keydata))
}

type EventResponse struct {
	Results []Result
	
}

type Result struct {
	ID          string
	Status      string
	Name        string
	EventURL    string `json:"event_url"`
	Description string
	Time        EventTime
	
}



type EventTime struct{ time.Time }

func (et *EventTime) UnmarshalJSON(data []byte) error {
	var msec int64
	if err := json.Unmarshal(data, &msec); err != nil {
		return err
	}
	et.Time = time.Unix(0, msec*int64(time.Millisecond))
	return nil
}

func (et EventTime) MarshalJSON() ([]byte, error) {
	msec := et.UnixNano() / int64(time.Millisecond)
	return json.Marshal(msec)
}


func (r *Result) String() string {
	var b bytes.Buffer
	fmt.Fprintln(&b, "ID:", r.ID)
	fmt.Fprintln(&b, "URL:", r.EventURL)
	fmt.Fprintln(&b, "Time:", r.Time.Format(time.UnixDate))
	d := r.Description
	const limit = 65
	if len(d) > limit {
		d = d[:limit-1] + "…"
	}
	fmt.Fprintln(&b, "Description:", d)
	return b.String()
}

func main() {
	v := url.Values{
		
		
		"topic": []string{"photo"},
		"time":  []string{",1w"},
		"key":   []string{key},
	}
	u := url.URL{
		Scheme:   "http",
		Host:     "api.meetup.com",
		Path:     "2/open_events.json",
		RawQuery: v.Encode(),
	}
	

	resp, err := http.Get(u.String())
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	log.Println("HTTP Status:", resp.Status)

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	
	var buf bytes.Buffer
	if err = json.Indent(&buf, body, "", "  "); err != nil {
		log.Fatal(err)
	}
	

	var evresp EventResponse
	json.Unmarshal(body, &evresp)
	

	fmt.Println("Got", len(evresp.Results), "events")
	if len(evresp.Results) > 0 {
		fmt.Println("First event:\n", &evresp.Results[0])
	}
}




Python: 
import requests
import json

city = None
topic = None

def getEvent(url_path, key) :
    responseString = ""
    
    params = {'city':city, 'key':key,'topic':topic}
    r = requests.get(url_path, params = params)    
    print(r.url)    
    responseString = r.text
    return responseString


def getApiKey(key_path):
    key = ""
    f = open(key_path, 'r')
    key = f.read()
    return key


def submitEvent(url_path,params):
    r = requests.post(url_path, data=json.dumps(params))        
    print(r.text+" : Event Submitted")