WeixiangYan/CodeTransOcean huggingface dataset:
Task: Xiaolin Wu's line algorithm







Python: 
from __future__ import division
import sys

from PIL import Image


def _fpart(x):
    return x - int(x)

def _rfpart(x):
    return 1 - _fpart(x)

def putpixel(img, xy, color, alpha=1):
    
    compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))
    c = compose_color(img.getpixel(xy), color)
    img.putpixel(xy, c)

def draw_line(img, p1, p2, color):
    
    x1, y1 = p1
    x2, y2 = p2
    dx, dy = x2-x1, y2-y1
    steep = abs(dx) < abs(dy)
    p = lambda px, py: ((px,py), (py,px))[steep]

    if steep:
        x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx
    if x2 < x1:
        x1, x2, y1, y2 = x2, x1, y2, y1

    grad = dy/dx
    intery = y1 + _rfpart(x1) * grad
    def draw_endpoint(pt):
        x, y = pt
        xend = round(x)
        yend = y + grad * (xend - x)
        xgap = _rfpart(x + 0.5)
        px, py = int(xend), int(yend)
        putpixel(img, p(px, py), color, _rfpart(yend) * xgap)
        putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)
        return px

    xstart = draw_endpoint(p(*p1)) + 1
    xend = draw_endpoint(p(*p2))

    for x in range(xstart, xend):
        y = int(intery)
        putpixel(img, p(x, y), color, _rfpart(intery))
        putpixel(img, p(x, y+1), color, _fpart(intery))
        intery += grad


if __name__ == '__main__':
    if len(sys.argv) != 2:
        print 'usage: python xiaolinwu.py [output-file]'
        sys.exit(-1)

    blue = (0, 0, 255)
    yellow = (255, 255, 0)
    img = Image.new("RGB", (500,500), blue)
    for a in range(10, 431, 60):
        draw_line(img, (10, 10), (490, a), yellow)
        draw_line(img, (10, 10), (a, 490), yellow)
    draw_line(img, (10, 10), (490, 490), yellow)
    filename = sys.argv[1]
    img.save(filename)
    print 'image saved to', filename
Task: Next highest int from digits







Python: def closest_more_than(n, lst):
    "(index of) closest int from lst, to n that is also > n"
    large = max(lst) + 1
    return lst.index(min(lst, key=lambda x: (large if x <= n else x)))

def nexthigh(n):
    "Return nxt highest number from n's digits using scan & re-order"
    assert n == int(abs(n)), "n >= 0"
    this = list(int(digit) for digit in str(int(n)))[::-1]
    mx = this[0]
    for i, digit in enumerate(this[1:], 1):
        if digit < mx:
            mx_index = closest_more_than(digit, this[:i + 1])
            this[mx_index], this[i] = this[i], this[mx_index]
            this[:i] = sorted(this[:i], reverse=True)
            return int(''.join(str(d) for d in this[::-1]))
        elif digit > mx:
            mx, mx_index = digit, i
    return 0


if __name__ == '__main__':
    for x in [0, 9, 12, 21, 12453, 738440, 45072010, 95322020,
              9589776899767587796600]:
        print(f"{x:>12_d} -> {nexthigh(x):>12_d}")
Task: Simulate input_Keyboard







Python: import autopy
autopy.key.type_string("Hello, world!") 
autopy.key.type_string("Hello, world!", wpm=60) 
autopy.key.tap(autopy.key.Code.RETURN)
autopy.key.tap(autopy.key.Code.F1)
autopy.key.tap(autopy.key.Code.LEFT_ARROW)
Task: Two bullet roulette







Python: 
import numpy as np

class Revolver:
    

    def __init__(self):
        
        self.cylinder = np.array([False] * 6)

    def unload(self):
        
        self.cylinder[:] = False

    def load(self):
        
        while self.cylinder[1]:
            self.cylinder[:] = np.roll(self.cylinder, 1)
        self.cylinder[1] = True

    def spin(self):
        
        self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7))

    def fire(self):
        
        shot = self.cylinder[0]
        self.cylinder[:] = np.roll(self.cylinder, 1)
        return shot

    def LSLSFSF(self):
        
        self.unload()
        self.load()
        self.spin()
        self.load()
        self.spin()
        if self.fire():
            return True
        self.spin()
        if self.fire():
            return True
        return False

    def LSLSFF(self):
        
        self.unload()
        self.load()
        self.spin()
        self.load()
        self.spin()
        if self.fire():
            return True
        if self.fire():
            return True
        return False

    def LLSFSF(self):
        
        self.unload()
        self.load()
        self.load()
        self.spin()
        if self.fire():
            return True
        self.spin()
        if self.fire():
            return True
        return False

    def LLSFF(self):
        
        self.unload()
        self.load()
        self.load()
        self.spin()
        if self.fire():
            return True
        if self.fire():
            return True
        return False


if __name__ == '__main__':

    REV = Revolver()
    TESTCOUNT = 100000
    for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF],
                           ['load, spin, load, spin, fire, fire', REV.LSLSFF],
                           ['load, load, spin, fire, spin, fire', REV.LLSFSF],
                           ['load, load, spin, fire, fire', REV.LLSFF]]:

        percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT
        print("Method", name, "produces", percentage, "per cent deaths.")
Task: Sierpinski pentagon







Python: from turtle import *
import math
speed(0)      
hideturtle()  

part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)

hide_turtles = True   
path_color = "black"  
fill_color = "black"  


def pentagon(t, s):
  t.color(path_color, fill_color)
  t.pendown()
  t.right(36)
  t.begin_fill()
  for i in range(5):
    t.forward(s)
    t.right(72)
  t.end_fill()


def sierpinski(i, t, s):
  t.setheading(0)
  new_size = s * side_ratio
  
  if i > 1:
    i -= 1
    
    
    for j in range(4):
      t.right(36)
      short = s * side_ratio / part_ratio
      dist = [short, s, s, short][j]
      
      
      spawn = Turtle()
      if hide_turtles:spawn.hideturtle()
      spawn.penup()
      spawn.setposition(t.position())
      spawn.setheading(t.heading())
      spawn.forward(dist)
      
      
      sierpinski(i, spawn, new_size)
    
    
    sierpinski(i, t, new_size)
    
  else:
    
    pentagon(t, s)
    
    del t

def main():
  t = Turtle()
  t.hideturtle()
  t.penup()
  screen = t.getscreen()
  y = screen.window_height()
  t.goto(0, y/2-20)
  
  i = 5       
  size = 300  
  
  
  size *= part_ratio
  
  
  sierpinski(i, t, size)

main()
Task: Zhang-Suen thinning algorithm







Python: 


beforeTxt = 


smallrc01 = 

rc01 = 

def intarray(binstring):
    
    return [[1 if ch == '1' else 0 for ch in line] 
            for line in binstring.strip().split()]

def chararray(intmatrix):
    
    return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)

def toTxt(intmatrix):
    Return 8-neighbours of point p1 of picture, in order'''
    i = image
    x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
    
    return [i[y1][x],  i[y1][x1],   i[y][x1],  i[y_1][x1],  
            i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]  

def transitions(neighbours):
    n = neighbours + neighbours[0:1]    
    return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))

def zhangSuen(image):
    changing1 = changing2 = [(-1, -1)]
    while changing1 or changing2:
        
        changing1 = []
        for y in range(1, len(image) - 1):
            for x in range(1, len(image[0]) - 1):
                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
                if (image[y][x] == 1 and    
                    P4 * P6 * P8 == 0 and   
                    P2 * P4 * P6 == 0 and   
                    transitions(n) == 1 and 
                    2 <= sum(n) <= 6):      
                    changing1.append((x,y))
        for x, y in changing1: image[y][x] = 0
        
        changing2 = []
        for y in range(1, len(image) - 1):
            for x in range(1, len(image[0]) - 1):
                P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
                if (image[y][x] == 1 and    
                    P2 * P6 * P8 == 0 and   
                    P2 * P4 * P8 == 0 and   
                    transitions(n) == 1 and 
                    2 <= sum(n) <= 6):      
                    changing2.append((x,y))
        for x, y in changing2: image[y][x] = 0
        
        
    return image
            

if __name__ == '__main__':
    for picture in (beforeTxt, smallrc01, rc01):
        image = intarray(picture)
        print('\nFrom:\n%s' % toTxt(image))
        after = zhangSuen(image)
        print('\nTo thinned:\n%s' % toTxt(after))
Task: Write to Windows event log







Python: import win32api
import win32con
import win32evtlog
import win32security
import win32evtlogutil

ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ)
my_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]

applicationName = "My Application"
eventID = 1
category = 5	
myType = win32evtlog.EVENTLOG_WARNING_TYPE
descr = ["A warning", "An even more dire warning"]
data = "Application\0Data".encode("ascii")

win32evtlogutil.ReportEvent(applicationName, eventID, eventCategory=category, 
	eventType=myType, strings=descr, data=data, sid=my_sid)
Task: Parse an IP Address







Python: from ipaddress import ip_address
from urllib.parse import urlparse

tests = [
    "127.0.0.1",
    "127.0.0.1:80",
    "::1",
    "[::1]:80",
    "::192.168.0.1",
    "2605:2700:0:3::4713:93e3",
    "[2605:2700:0:3::4713:93e3]:80" ]

def parse_ip_port(netloc):
    try:
        ip = ip_address(netloc)
        port = None
    except ValueError:
        parsed = urlparse('//{}'.format(netloc))
        ip = ip_address(parsed.hostname)
        port = parsed.port
    return ip, port

for address in tests:
    ip, port = parse_ip_port(address)
    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))
    print("{:39s}  {:>32s}  IPv{}  port={}".format(
        str(ip), hex_ip, ip.version, port ))
Task: Long stairs







Python: 

from numpy import mean
from random import sample

def gen_long_stairs(start_step, start_length, climber_steps, add_steps):
    secs, behind, total = 0, start_step, start_length
    while True:
        behind += climber_steps
        behind += sum([behind > n for n in sample(range(total), add_steps)])
        total += add_steps
        secs += 1
        yield (secs, behind, total)
        

ls = gen_long_stairs(1, 100, 1, 5)

print("Seconds  Behind  Ahead\n----------------------")
while True:
    secs, pos, len = next(ls)
    if 600 <= secs < 610:
        print(secs, "     ", pos, "   ", len - pos)
    elif secs == 610:
        break

print("\nTen thousand trials to top:")
times, heights = [], []
for trial in range(10_000):
    trialstairs = gen_long_stairs(1, 100, 1, 5)
    while True:
        sec, step, height = next(trialstairs)
        if step >= height:
            times.append(sec)
            heights.append(height)
            break

print("Mean time:", mean(times), "secs. Mean height:", mean(heights))
Task: Largest prime factor







Python: 

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True

if __name__ == '__main__':
    n = 600851475143
    j = 3
    while not isPrime(n):
        if n % j == 0:
            n /= j
        j += 2
    print(n);
Task: Getting the number of decimal places







Python: In [6]: def dec(n):
   ...:     return len(n.rsplit('.')[-1]) if '.' in n else 0

In [7]: dec('12.345')
Out[7]: 3

In [8]: dec('12.3450')
Out[8]: 4

In [9]:
Task: Vibrating rectangles







Python: import turtle
from itertools import cycle
from time import sleep

def rect(t, x, y):
    x2, y2 = x/2, y/2
    t.setpos(-x2, -y2)
    t.pendown()
    for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: 
        t.goto(pos)
    t.penup()

def rects(t, colour, wait_between_rect=0.1):
    for x in range(550, 0, -25):
        t.color(colour)
        rect(t, x, x*.75)
        sleep(wait_between_rect)

tl=turtle.Turtle()
screen=turtle.Screen()
screen.setup(620,620)
screen.bgcolor('black')
screen.title('Rosetta Code Vibrating Rectangles')
tl.pensize(3)
tl.speed(0)
tl.penup()
tl.ht() 
colours = 'red green blue orange white yellow'.split()
for colour in cycle(colours):
    rects(tl, colour)
    sleep(0.5)
Task: Maximum difference between adjacent elements of list







Python: 



def maxDeltas(ns):
    
    pairs = [
        (abs(a - b), (a, b)) for a, b
        in zip(ns, ns[1:])
    ]
    delta = max(pairs, key=lambda ab: ab[0])[0]

    return [
        ab for ab in pairs
        if delta == ab[0]
    ]




def main():
    

    maxPairs = maxDeltas([
        1, 8, 2, -3, 0, 1, 1, -2.3, 0,
        5.5, 8, 6, 2, 9, 11, 10, 3
    ])

    for ab in maxPairs:
        print(ab)



if __name__ == '__main__':
    main()
Task: Solve a Hopido puzzle







Python: from sys import stdout

neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]
cnt = 0
pWid = 0
pHei = 0


def is_valid(a, b):
    return -1 < a < pWid and -1 < b < pHei


def iterate(pa, x, y, v):
    if v > cnt:
        return 1

    for i in range(len(neighbours)):
        a = x + neighbours[i][0]
        b = y + neighbours[i][1]
        if is_valid(a, b) and pa[a][b] == 0:
            pa[a][b] = v
            r = iterate(pa, a, b, v + 1)
            if r == 1:
                return r
            pa[a][b] = 0
    return 0


def solve(pz, w, h):
    global cnt, pWid, pHei

    pa = [[-1 for j in range(h)] for i in range(w)]
    f = 0
    pWid = w
    pHei = h
    for j in range(h):
        for i in range(w):
            if pz[f] == "1":
                pa[i][j] = 0
                cnt += 1
            f += 1

    for y in range(h):
        for x in range(w):
            if pa[x][y] == 0:
                pa[x][y] = 1
                if 1 == iterate(pa, x, y, 2):
                    return 1, pa
                pa[x][y] = 0

    return 0, pa

r = solve("011011011111111111111011111000111000001000", 7, 6)
if r[0] == 1:
    for j in range(6):
        for i in range(7):
            if r[1][i][j] == -1:
                stdout.write("   ")
            else:
                stdout.write(" {:0{}d}".format(r[1][i][j], 2))
        print()
else:
    stdout.write("No solution!")
Task: Solve a Numbrix puzzle







Python: from sys import stdout
neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]
exists = []
lastNumber = 0
wid = 0
hei = 0


def find_next(pa, x, y, z):
    for i in range(4):
        a = x + neighbours[i][0]
        b = y + neighbours[i][1]
        if wid > a > -1 and hei > b > -1:
            if pa[a][b] == z:
                return a, b

    return -1, -1


def find_solution(pa, x, y, z):
    if z > lastNumber:
        return 1
    if exists[z] == 1:
        s = find_next(pa, x, y, z)
        if s[0] < 0:
            return 0
        return find_solution(pa, s[0], s[1], z + 1)

    for i in range(4):
        a = x + neighbours[i][0]
        b = y + neighbours[i][1]
        if wid > a > -1 and hei > b > -1:
            if pa[a][b] == 0:
                pa[a][b] = z
                r = find_solution(pa, a, b, z + 1)
                if r == 1:
                    return 1
                pa[a][b] = 0

    return 0


def solve(pz, w, h):
    global lastNumber, wid, hei, exists

    lastNumber = w * h
    wid = w
    hei = h
    exists = [0 for j in range(lastNumber + 1)]

    pa = [[0 for j in range(h)] for i in range(w)]
    st = pz.split()
    idx = 0
    for j in range(h):
        for i in range(w):
            if st[idx] == ".":
                idx += 1
            else:
                pa[i][j] = int(st[idx])
                exists[pa[i][j]] = 1
                idx += 1

    x = 0
    y = 0
    t = w * h + 1
    for j in range(h):
        for i in range(w):
            if pa[i][j] != 0 and pa[i][j] < t:
                t = pa[i][j]
                x = i
                y = j

    return find_solution(pa, x, y, t + 1), pa


def show_result(r):
    if r[0] == 1:
        for j in range(hei):
            for i in range(wid):
                stdout.write(" {:0{}d}".format(r[1][i][j], 2))
            print()
    else:
        stdout.write("No Solution!\n")

    print()


r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17"
          " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1  2 . . . . . . . . . . .", 9, 9)
show_result(r)

r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . .  6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37"
          " .  1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9)
show_result(r)

r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . .  63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55"
          " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9)
show_result(r)
Task: Sierpinski curve







Python: import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import hsv_to_rgb as hsv

def curve(axiom, rules, angle, depth):
    for _ in range(depth):
        axiom = ''.join(rules[c] if c in rules else c for c in axiom)

    a, x, y = 0, [0], [0]
    for c in axiom:
        match c:
            case '+':
                a += 1
            case '-':
                a -= 1
            case 'F' | 'G':
                x.append(x[-1] + np.cos(a*angle*np.pi/180))
                y.append(y[-1] + np.sin(a*angle*np.pi/180))

    l = len(x)
    
    for i in range(l - 1):
        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))
    plt.gca().set_aspect(1)
    plt.show()

curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
Task: Selectively replace multiple instances of a character within a string







Python: from collections import defaultdict

rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}}
 
def trstring(oldstring, repdict):
    seen, newchars = defaultdict(lambda:1, {}), []
    for c in oldstring:
        i = seen[c]
        newchars.append(repdict[c][i] if c in repdict and i in repdict[c] else c)
        seen[c] += 1
    return ''.join(newchars)

print('abracadabra ->', trstring('abracadabra', rep))
Task: Nested templated data







Python: from pprint import pprint as pp

class Template():
    def __init__(self, structure):
        self.structure = structure
        self.used_payloads, self.missed_payloads = [], []
    
    def inject_payload(self, id2data):
        
        def _inject_payload(substruct, i2d, used, missed):
            used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d)
            missed.extend(f'??
                          for x in substruct if type(x) is not tuple and x not in i2d)
            return tuple(_inject_payload(x, i2d, used, missed) 
                           if type(x) is tuple 
                           else i2d.get(x, f'??
                         for x in substruct)
                           
        ans = _inject_payload(self.structure, id2data, 
                              self.used_payloads, self.missed_payloads)
        self.unused_payloads = sorted(set(id2data.values()) 
                                      - set(self.used_payloads))
        self.missed_payloads = sorted(set(self.missed_payloads))
        return ans

if __name__ == '__main__':
    index2data = {p: f'Payload
    print("
    print('\n  '.join(list(index2data.values())))
    for structure in [
     (((1, 2),
       (3, 4, 1),
       5),),
    
     (((1, 2),
       (10, 4, 1),
       5),)]:
        print("\n\n
        pp(structure, width=13)
        print("\n TEMPLATE WITH PAYLOADS:")
        t = Template(structure)
        out = t.inject_payload(index2data)
        pp(out)
        print("\n UNUSED PAYLOADS:\n  ", end='')
        unused = t.unused_payloads
        print('\n  '.join(unused) if unused else '-')
        print(" MISSING PAYLOADS:\n  ", end='')
        missed = t.missed_payloads
        print('\n  '.join(missed) if missed else '-')
Task: Range modifications







Python: class Sequence():
    
    def __init__(self, sequence_string):
        self.ranges = self.to_ranges(sequence_string)
        assert self.ranges == sorted(self.ranges), "Sequence order error"
        
    def to_ranges(self, txt):
        return [[int(x) for x in r.strip().split('-')]
                for r in txt.strip().split(',') if r]
    
    def remove(self, rem):
        ranges = self.ranges
        for i, r in enumerate(ranges):
            if r[0] <= rem <= r[1]:
                if r[0] == rem:     
                    if r[1] > rem:
                        r[0] += 1
                    else:
                        del ranges[i]
                elif r[1] == rem:   
                    if r[0] < rem:
                        r[1] -= 1
                    else:
                        del ranges[i]
                else:               
                    r[1], splitrange = rem - 1, [rem + 1, r[1]]
                    ranges.insert(i + 1, splitrange)
                break
            if r[0] > rem:  
                break
        return self
            
    def add(self, add):
        ranges = self.ranges
        for i, r in enumerate(ranges):
            if r[0] <= add <= r[1]:     
                break
            elif r[0] - 1 == add:      
                r[0] = add
                break
            elif r[1] + 1 == add:      
                r[1] = add
                break
            elif r[0] > add:      
                ranges.insert(i, [add, add])
                break
        else:
            ranges.append([add, add])
            return self
        return self.consolidate()
    
    def consolidate(self):
        "Combine overlapping ranges"
        ranges = self.ranges
        for this, that in zip(ranges, ranges[1:]):
            if this[1] + 1 >= that[0]:  
                if this[1] >= that[1]:  
                    this[:], that[:] = [], this
                else:   
                    this[:], that[:] = [], [this[0], that[1]]
        ranges[:] = [r for r in ranges if r]
        return self
    def __repr__(self):
        rr = self.ranges
        return ",".join(f"{r[0]}-{r[1]}" for r in rr)

def demo(opp_txt):
    by_line = opp_txt.strip().split('\n')
    start = by_line.pop(0)
    ex = Sequence(start.strip().split()[-1][1:-1])    
    lines = [line.strip().split() for line in by_line]
    opps = [((ex.add if word[0] == "add" else ex.remove), int(word[1]))
            for word in lines]
    print(f"Start: \"{ex}\"")
    for op, val in opps:
        print(f"    {op.__name__:>6} {val:2} => {op(val)}")
    print()
                    
if __name__ == '__main__':
    demo()
    demo()
    demo()