Share Code Quickly

What is Harigami?

Harigami is a simple source code sharing service. You can share source code by an URL which is issued after submission.
You can also run your source code online such as Python, Ruby, JavaScript and so on.
For free.Use for code review.
Preferences
anonymous No title
Lisp
(define (app/cc ls1 ls2)
  (let/cc
   cont
   (if (null? ls1)
       (cont ls2)
       (cons (car ls1)
	     (app/cc (cdr ls1) ls2)))))
anonymous No title
Lisp
(define (app/cc ls1 ls2)
  (if (null? ls1)
      (let/cc cont
	      (cont ls2))
      (cons (car ls1)
	    (app/cc (cdr ls1) ls2))))
anonymous No title
C
#include <stdio.h>

int main(void)
{
    printf("Hello World!");
    return 0;
}
anonymous No title
Python
# coding: utf-8

from __future__ import division
import ui
import clipboard
from console import hud_alert

shows_result = False

def button_tapped(sender):
	'@type sender: ui.Button'
	# Get the button's title for the following logic:
	t = sender.title
	global shows_result
	# Get the labels:
	label = sender.superview['label1']
	label2 = sender.superview['label2']
	if t in '0123456789':
		if shows_result or label.text == '0':
			# Replace 0 or last result with number:
			label.text = t
		else:
			# Append number:
			label.text += t
	elif t == '.' and label.text[-1] != '.':
		# Append decimal point (if not already there)
		label.text += t
	elif t in '+-÷×':
		if label.text[-1] in '+-÷×':
			# Replace current operator
			label.text = label.text[:-1] + t
		else:
			# Append operator
			label.text += t
	elif t == 'AC':
		# Clear All
		label.text = '0'
	elif t == 'C':
		# Delete the last character:
		label.text = label.text[:-1]
		if len(label.text) == 0:
			label.text = '0'
	elif t == '=':
		# Evaluate the result:
		try:
			label2.text = label.text + ' ='
			expr = label.text.replace('÷', '/').replace('×', '*')
			label.text = str(eval(expr))
		except (SyntaxError, ZeroDivisionError):
			label.text = 'ERROR'
		shows_result = True
	if t != '=':
		shows_result = False
		label2.text = ''

def copy_action(sender):
	'@type sender: ui.Button'
	t1 = sender.superview['label1'].text
	t2 = sender.superview['label2'].text
	if t2:
		text = t2 + ' ' + t1
	else:
		text = t1
	clipboard.set(text)
	hud_alert('Copied')

v = ui.load_view('Calculator')

if min(ui.get_screen_size()) >= 768:
	# iPad
	v.frame = (0, 0, 360, 400)
	v.present('sheet')
else:
	# iPhone
	v.present(orientations=['portrait'])
anonymous No title
HTML
https://calendar.google.com/calendar/embed?height=600&wkst=1&bgcolor=%23ffffff&ctz=Asia%2FTokyo&src=NTViOHVodDZqZHRmZmU3Mm82b2pocGxzN29AZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ&src=amEuamFwYW5lc2UjaG9saWRheUBncm91cC52LmNhbGVuZGFyLmdvb2dsZS5jb20&color=%23F09300&color=%230B8043
anonymous No title
HTML
<iframe src="https://calendar.google.com/calendar/embed?src=fukuta%40uni-spot.com&ctz=Asia%2FTokyo" style="border: 0" width="800" height="600" frameborder="0" scrolling="no"></iframe>
anonymous No title
F#
printfn "Hello, world!"
anonymous No title
VBA
’ブックモジュールに記述

Option Explicit


Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)

    Dim shpCat          As Shape        '動作する画像
    Dim shpAroundRng    As Range        'ShpCatの配置されているセル範囲
    Dim appearRng       As Range        'ShpCatが出現するセル
    Dim activeRng       As Range        'ActiveCellを保持するための変数
    Dim SelectRng       As Range        'Selectionを保持するための変数
    Dim visiRng         As Range        '現在画面に表示されているセル範囲
    
    Set visiRng = ActiveWindow.VisibleRange
    Set activeRng = ActiveCell
    Set SelectRng = Selection
    
    
    Application.EnableEvents = False
    
    Set shpCat = getShp(shpName:="cat")
    Call delShp(shpName:="テキスト")
    
    If Not shpCat Is Nothing Then
        
        Set shpAroundRng = shpCat.Parent.Range(shpCat.TopLeftCell, shpCat.BottomRightCell)
        Set appearRng = getAppearRng(visiRng)
        Select Case True
            Case shpCat.Parent.Name <> Sh.Name, Intersect(visiRng, shpAroundRng) Is Nothing '画面内にShpCatが無ければ、shpCatをカットしappearRngに貼り付ける
                shpCat.Cut
                appearRng.Select
                Sh.Paste
                Set shpCat = Sh.Shapes(Selection.Name)
                Target.Select
        End Select
        
        
        Call 猫寄ってくる(activeRng, shpCat)
        
    End If
    
    SelectRng.Select
    Application.EnableEvents = True
    
End Sub


Private Function getShp(ByVal shpName As String) As Shape
    '名前がShpNameのShapeがSetされ次第関数を抜ける
    
    Dim ws          As Worksheet
    
    On Error Resume Next
    For Each ws In ThisWorkbook.Worksheets
        Set getShp = ws.Shapes(shpName)
        If Err.Number = 0 Then Exit For
        Err.Clear
    Next

End Function

Private Sub delShp(ByVal shpName As String)
    'ブック内の全てのShpNameのShapeを削除する
    
    Dim ws          As Worksheet
    
    On Error Resume Next
    For Each ws In ThisWorkbook.Worksheets
        ws.Shapes(shpName).Delete
    Next

End Sub

Private Function getAppearRng(ByVal rng As Range) As Range
    '引数rngの四隅(の一つ内側)のセルの内いずれかをランダムで返す関数
    '1:左上
    '2:右上
    '3:左下
    '4:右下
    
    Randomize
    Dim rndNum As Long
    rndNum = Int(Rnd * 4) + 1
    
    Select Case rndNum
        Case 1:     Set getAppearRng = rng(1).Offset(1, 1)
        Case 2:     Set getAppearRng = rng.Offset(, rng.Columns.Count - 1).Item(1).Offset(1, -1)
        Case 3:     Set getAppearRng = rng.Offset(rng.Rows.Count - 1).Item(1).Offset(-1, 1)
        Case 4:     Set getAppearRng = rng(rng.Count).Offset(-1, -1)
    End Select
        
    
End Function


Private Sub 猫寄ってくる(ByVal rng As Range, ByVal shp As Shape)
    'shpの縦位置がrngの縦位置に達するまで縦移動し続ける
    'shpの横位置がrngの横位置に達するまで横移動し続ける
    'shpとrngの位置が一致したらループを抜ける
    
    Dim sphCenterV      As Double   'shpの縦中央位置
    Dim sphCenterH      As Double   'shpの横中央位置
    Dim rngCenterV      As Double   'rngの縦中央位置
    Dim rngCenterH      As Double   'rngの横中央位置
    Dim beforeShpArea   As String   'shpの1ステップ移動前位置
    Dim afterShpArea    As String   'shpの1ステップ移動後位置
    Dim flgV            As Boolean  'shpの縦位置がrngの縦位置に達したらTrueにする
    Dim flgH            As Boolean  'shpの横位置がrngの横位置に達したらTrueにする
    Const speed As Double = 6
    
    rngCenterV = rng.Top + rng.Height / 2
    rngCenterH = rng.Left + rng.Width / 2
    
    Do
        DoEvents
        
        sphCenterV = shp.Top + shp.Height / 2
        sphCenterH = shp.Left + shp.Width / 2
        
        beforeShpArea = shp.Top & "|" & shp.Left
        If Not flgV Then shp.Top = IIf(sphCenterV - rngCenterV < 0, shp.Top + speed, shp.Top - speed)
        If Not flgH Then shp.Left = IIf(sphCenterH - rngCenterH < 0, shp.Left + speed, shp.Left - speed)
        afterShpArea = shp.Top & "|" & shp.Left
        
        
        If Abs(sphCenterV - rngCenterV) < speed Then flgV = True
        If Abs(sphCenterH - rngCenterH) < speed Then flgH = True
        
        If flgV And flgH Then Exit Do
        If afterShpArea = beforeShpArea Then Exit Do
        
        Application.Wait [Now()] + 0.001 / 86400
    Loop
    
    
    Call にゃーと鳴く(shp, shp.Parent)
    
    
    
End Sub



Private Sub にゃーと鳴く(ByVal shp As Shape, ByVal ws As Worksheet)
    'shpの右隣にテキストボックスを配置して「にゃーー」と入力するにゃ。
    
    Dim テキストTop     As Double
    Dim テキストleft    As Double
    Dim テキスト        As Shape
    
    テキストTop = shp.Top
    テキストleft = shp.Left + shp.Width

    ws.Shapes.AddTextbox( _
            Orientation:=msoTextOrientationHorizontal, _
            Left:=テキストleft, _
            Top:=テキストTop, _
            Width:=100, _
            Height:=60).Select
    
    With Selection
        .Name = "テキスト"
        .ShapeRange.TextFrame2.VerticalAnchor = msoAnchorMiddle
        .ShapeRange.TextFrame2.TextRange.ParagraphFormat.Alignment = msoAlignCenter
        .ShapeRange.Fill.ForeColor.RGB = 11854022
        .ShapeRange.Line.ForeColor.RGB = 0
        .ShapeRange.TextFrame.Characters.Text = "にゃーー"
        .ShapeRange.TextFrame2.TextRange.Font.Bold = msoTrue
        .ShapeRange.TextFrame2.TextRange.Font.Size = 16
    End With
    
End Sub


anonymous No title
VBA
'ブックモジュールに記述

Option Explicit


Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)

    Dim shpCat          As Shape        '動作する画像
    Dim shpAroundRng    As Range        'ShpCatの配置されているセル範囲
    Dim appearRng       As Range        'ShpCatが出現するセル
    Dim activeRng       As Range        'ActiveCellを保持するための変数
    Dim visiRng         As Range        '現在画面に表示されているセル範囲
    Set visiRng = ActiveWindow.VisibleRange
    Set activeRng = ActiveCell
    
    Application.EnableEvents = False
    
    Set shpCat = getShp(shpName:="cat")
    Call delShp(shpName:="テキスト")
    
    If Not shpCat Is Nothing Then
        
        Set shpAroundRng = shpCat.Parent.Range(shpCat.TopLeftCell, shpCat.BottomRightCell)
        Set appearRng = getAppearRng(visiRng)
        Select Case True
            Case shpCat.Parent.Name <> Sh.Name, Intersect(visiRng, shpAroundRng) Is Nothing '画面内にShpCatが無ければ、shpCatをカットしappearRngに貼り付ける
                shpCat.Cut
                appearRng.Select
                Sh.Paste
                Set shpCat = Sh.Shapes(Selection.Name)
                Target.Select
        End Select
        
        
        Call 猫寄ってくる(activeRng, shpCat)
        
    End If
    
    activeRng.Select
    Application.EnableEvents = True
    
End Sub


Private Function getShp(ByVal shpName As String) As Shape
    '名前がShpNameのShapeがSetされ次第関数を抜ける
    
    Dim ws          As Worksheet
    
    On Error Resume Next
    For Each ws In ThisWorkbook.Worksheets
        Set getShp = ws.Shapes(shpName)
        If Err.Number = 0 Then Exit For
        Err.Clear
    Next

End Function

Private Sub delShp(ByVal shpName As String)
    'ブック内の全てのShpNameのShapeを削除する
    
    Dim ws          As Worksheet
    
    On Error Resume Next
    For Each ws In ThisWorkbook.Worksheets
        ws.Shapes(shpName).Delete
    Next

End Sub

Private Function getAppearRng(ByVal rng As Range) As Range
    '引数rngの四隅(の一つ内側)のセルの内いずれかをランダムで返す関数
    '1:左上
    '2:右上
    '3:左下
    '4:右下
    
    Randomize
    Dim rndNum As Long
    rndNum = Int(Rnd * 4) + 1
    
    Select Case rndNum
        Case 1:     Set getAppearRng = rng(1).Offset(1, 1)
        Case 2:     Set getAppearRng = rng.Offset(, rng.Columns.Count - 1).Item(1).Offset(1, -1)
        Case 3:     Set getAppearRng = rng.Offset(rng.Rows.Count - 1).Item(1).Offset(-1, 1)
        Case 4:     Set getAppearRng = rng(rng.Count).Offset(-1, -1)
    End Select
        
    
End Function


Private Sub 猫寄ってくる(ByVal rng As Range, ByVal shp As Shape)
    'shpの縦位置がrngの縦位置に達するまで縦移動し続ける
    'shpの横位置がrngの横位置に達するまで横移動し続ける
    'shpとrngの位置が一致したらループを抜ける
    
    Dim sphCenterV      As Double   'shpの縦中央位置
    Dim sphCenterH      As Double   'shpの横中央位置
    Dim rngCenterV      As Double   'rngの縦中央位置
    Dim rngCenterH      As Double   'rngの横中央位置
    Dim beforeShpArea   As String   'shpの1ステップ移動前位置
    Dim afterShpArea    As String   'shpの1ステップ移動後位置
    Dim flgV            As Boolean  'shpの縦位置がrngの縦位置に達したらTrueにする
    Dim flgH            As Boolean  'shpの横位置がrngの横位置に達したらTrueにする
    Const speed As Double = 6
    
    rngCenterV = rng.Top + rng.Height / 2
    rngCenterH = rng.Left + rng.Width / 2
    
    Do
        DoEvents
        
        sphCenterV = shp.Top + shp.Height / 2
        sphCenterH = shp.Left + shp.Width / 2
        
        beforeShpArea = shp.Top & "|" & shp.Left
        If Not flgV Then shp.Top = IIf(sphCenterV - rngCenterV < 0, shp.Top + speed, shp.Top - speed)
        If Not flgH Then shp.Left = IIf(sphCenterH - rngCenterH < 0, shp.Left + speed, shp.Left - speed)
        afterShpArea = shp.Top & "|" & shp.Left
        
        
        If Abs(sphCenterV - rngCenterV) < speed Then flgV = True
        If Abs(sphCenterH - rngCenterH) < speed Then flgH = True
        
        If flgV And flgH Then Exit Do
        If afterShpArea = beforeShpArea Then Exit Do
        
        Application.Wait [Now()] + 0.001 / 86400
    Loop
    
    
    Call にゃーと鳴く(shp, shp.Parent)
    
    
    
End Sub



Private Sub にゃーと鳴く(ByVal shp As Shape, ByVal ws As Worksheet)
    'shpの右隣にテキストボックスを配置して「にゃーー」と入力するにゃ。
    
    Dim テキストTop     As Double
    Dim テキストleft    As Double
    Dim テキスト        As Shape
    
    テキストTop = shp.Top
    テキストleft = shp.Left + shp.Width

    ws.Shapes.AddTextbox( _
            Orientation:=msoTextOrientationHorizontal, _
            Left:=テキストleft, _
            Top:=テキストTop, _
            Width:=100, _
            Height:=60).Select
    
    With Selection
        .Name = "テキスト"
        .ShapeRange.TextFrame2.VerticalAnchor = msoAnchorMiddle
        .ShapeRange.TextFrame2.TextRange.ParagraphFormat.Alignment = msoAlignCenter
        .ShapeRange.Fill.ForeColor.RGB = 11854022
        .ShapeRange.Line.ForeColor.RGB = 0
        .ShapeRange.TextFrame.Characters.Text = "にゃーー"
        .ShapeRange.TextFrame2.TextRange.Font.Bold = msoTrue
        .ShapeRange.TextFrame2.TextRange.Font.Size = 16
    End With
    
End Sub


anonymous No title
Python
import gym
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from collections import deque
from tensorflow.keras.losses import Huber
import tensorflow as tf

for device in tf.config.list_physical_devices("GPU"):
    tf.config.experimental.set_memory_growth(device, True)

NUM_EPISODES = 500
MAX_STEPS = 200
GAMMA = 0.99
WARMUP = 10

E_START = 1.0
E_STOP = 0.01
E_DECAY_RATE = 0.001

MEMORY_SIZE = 10000
BATCH_SIZE = 32


class QNetwork:
    def __init__(self, input_size, output_size):
        self.model = Sequential()
        self.model.add(Dense(16, activation="relu", input_dim=input_size))
        self.model.add(Dense(16, activation="relu"))
        self.model.add(Dense(16, activation="relu"))
        self.model.add(Dense(output_size, activation="linear"))

        self.model.compile(loss=Huber(), optimizer=Adam(learning_rate=0.001))


class Memory:
    def __init__(self, memory_size):
        self.buffer = deque(maxlen=memory_size)

    def add(self, experience):
        self.buffer.append(experience)

    def sample(self, batch_size):
        idx = np.random.choice(np.arange(len(self.buffer)), size=batch_size, replace=False)
        return [self.buffer[i] for i in idx]

    def __len__(self):
        return len(self.buffer)


env = gym.make("CartPole-v0")
state_size = env.observation_space.shape[0]
action_size = env.action_space.n

main_qn = QNetwork(state_size, action_size)
target_qn = QNetwork(state_size, action_size)
memory = Memory(MEMORY_SIZE)

state = env.reset()
state = np.reshape(state, [1, state_size])

total_step = 0
success_count = 0
for episode in range(NUM_EPISODES):
    step = 0
    target_qn.model.set_weights(main_qn.model.get_weights())

    epsilon = E_START

    for _ in range(MAX_STEPS):
        step += 1
        total_step += 1
        epsilon = E_STOP + (E_START - E_STOP) * np.exp(-E_DECAY_RATE * total_step)

        if epsilon > np.random.rand():
            action = env.action_space.sample()
        else:
            action = np.argmax(main_qn.model.predict(state)[0])

        next_state, _, done, _ = env.step(action)
        next_state = np.reshape(next_state, [1, state_size])

        if done:
            if step >= 190:
                success_count += 1
                reward = 1
            else:
                success_count = 0
                reward = 0

            next_state = np.zeros(state.shape)

            if step > WARMUP:
                memory.add((state, action, reward, next_state))
        else:
            reward = 0

            if step > WARMUP:
                memory.add((state, action, reward, next_state))

            state = next_state

        if len(memory) >= BATCH_SIZE:
            inputs = np.zeros((BATCH_SIZE, 4))
            outputs = np.zeros((BATCH_SIZE, 2))

            mini_batch = memory.sample(BATCH_SIZE)

            for i, (state_b, action_b, reward_b, next_state_b) in enumerate(mini_batch):
                inputs[i] = state_b

                if not (next_state_b == np.zeros(state_b.shape)).all(axis=1):
                    output = reward_b + GAMMA * np.amax(target_qn.model.predict(next_state_b)[0])
                else:
                    output = reward_b

                outputs[i] = main_qn.model.predict(state_b)
                outputs[i][action_b] = output

            main_qn.model.fit(inputs, outputs, epochs=1, verbose=0)

        if done:
            break

    print("Episode: {}, Steps: {}, eps:{:.3f}".format(episode, step, epsilon))
    plt.plot(episode, step)

    if success_count >= 5:
        break

    state = env.reset()
    state = np.reshape(state, [1, state_size])

plt.xlabel("Episodes")
plt.ylabel("Steps")
plt.legend(loc="best")
plt.show()

main_qn.model.save("../models/dqn_cart_pole.h5")