Category Archives: Development

「C#入門」今日以前の古いファイルを削除する

サンプルコード:
//フォルダパス
string strDirPath = Server.MapPath(“~”) + “\\excel\\”;
DirectoryInfo dyInfo = new DirectoryInfo(strDirPath);
//フォルダのファイルを取得
foreach (FileInfo cftInfo in dyInfo.GetFiles())
{
//日付比較
if (cftInfo.CreationTime < DateTime.Today)
cftInfo.Delete();
}

[python開発]マルチスレッドでhttp負荷検証を実現する

pythonコード:
# Python version 3.3
__author__ = ‘Toil’
import sys, getopt
import threading
def httpGet(url, file):
import http.client
conn = http.client.HTTPConnection(url)
conn.request(“GET”, file)
r = conn.getresponse()
#print(r.getheaders())
while not r.closed:
r.read(200)
conn.close()
def Usage():
print(”’
Options are:
-c concurrency Number of multiple requests to make
-u host The host
-f file File on web
Example: httpget.py -c 100 -u www.test.com -f /
”’)
if __name__ == ‘__main__’:
opts, args = getopt.getopt(sys.argv[1:], “hc:u:f:”)
global u, c, f
for op, value in opts:
if op == ‘-c’:
c = int(value)
elif op == ‘-u’:
u = value
elif op == ‘-f’:
f = value
elif op == ‘-h’:
Usage()
sys.exit(0)
else:
sys.exit(0)
threads = []
times = c
print(‘Test for ‘, u, f)
print(‘waiting…’)
for i in range(0, times):
t = threading.Thread(target=httpGet(u, f))
threads.append(t)
for i in range(0, times):
threads[i].start()
for i in range(0, times):
threads[i].join()

golang入門–json形のデータを操作するサンプルコード

サンプルコード

package main
import (
“fmt”
“encoding/json”
)

type User struct {
Username string
Password string
FriendName []string
}
func main() {

user:=User{}
user.Username=”Tamura”
user.Password=”pwd3456″
user.FriendName=[]string{“Suzuki”,”kaoli”}

//struct->json
if userJSON,err:=json.Marshal(user);err==nil{
fmt.Println(string(userJSON))
}

//slice->json
arr:=[]string{“Apple”,”Orange”,”Banana”}
if arrJSON,err:=json.Marshal(arr);err==nil{
fmt.Println(string(arrJSON))
}

//map->json
m:=map[string]string{“東京都”:”品川区”,”埼玉県”:”西川口”}
if mJSON,err:=json.Marshal(m);err==nil{
fmt.Println(string(mJSON))
}

//json->struct
jsonStr:='{“Username”:”Tamura”,”Password”:”pwd3456″,”FriendName”:[“Suzuki”,”kaoli”]}’
var userJSON User
if err:=json.Unmarshal([]byte(jsonStr),&userJSON);err==nil{
fmt.Println(userJSON)
}

//json->slice
jsonFruit:='[“Apple”,”Orange”,”Banana”]’
var arrFruit []string
if err:=json.Unmarshal([]byte(jsonFruit),&arrFruit);err==nil{
fmt.Println(arrFruit)
}

//json->map
jsonCity:='{“東京都”:”品川区”,”埼玉県”:”西川口”}’
var mapCity map[string]string
if err:=json.Unmarshal([]byte(jsonCity),&mapCity);err==nil{
fmt.Println(mapCity)
}
}

go開発ツールbeegoの基本使い方

1.beegoでapiプロジェクトを作成
bee api ad-core -driver=mysql -conn=root:root@tcp(127.0.0.1:3306)/database

2.beegoでテーブルの操作apiを追加
bee generate appcode -tables=”one_table” -driver=mysql -conn=”root:root@tcp(127.0.0.1:3306)/schema_one” -level=3

3.beegoツールコマンドを取得
go get github.com/beego/bee

4.apiプロジェクトを実行
bee run data-core > /mnt/logs/data-core/data-core.log &

5.DBに接続文字列を解決
root:passwd@tcp(localhost:3306)/dbname?charset=utf8&loc=Local

PDFファイルをExcelに変換するサンプルコード

Option Explicit
Dim rowsNum
rowsNum = 0
‘—————————————————————————–
‘ Main function
‘—————————————————————————–
‘ Get the current active model
Dim Model
Set Model = ActiveModel
If (Model Is Nothing) Or (Not Model.IsKindOf(PdPDM.cls_Model)) Then
MsgBox “The current model is not an PDM model.”
Else
‘ Get the tables collection
‘EXCEL APPを作成
dim beginrow
DIM EXCEL, SHEET
set EXCEL = CREATEOBJECT(“Excel.Application”)
EXCEL.workbooks.add(-4167)’ワークシートを追加
EXCEL.workbooks(1).sheets(1).name =”test”
set sheet = EXCEL.workbooks(1).sheets(“test”)
ShowProperties Model, SHEET
EXCEL.visible = true

‘列幅と改行を設定
sheet.Columns(1).ColumnWidth = 20
sheet.Columns(2).ColumnWidth = 40
sheet.Columns(4).ColumnWidth = 20
sheet.Columns(5).ColumnWidth = 20
sheet.Columns(6).ColumnWidth = 15
sheet.Columns(1).WrapText =true
sheet.Columns(2).WrapText =true
sheet.Columns(4).WrapText =true
End If
‘—————————————————————————–
‘ Show properties of tables
‘—————————————————————————–
Sub ShowProperties(mdl, sheet)
‘ Show tables of the current model/package
rowsNum=0
beginrow = rowsNum+1
‘ For each table
output “begin”
Dim tab
For Each tab In mdl.tables
ShowTable tab,sheet
Next
if mdl.tables.count > 0 then
sheet.Range(“A” & beginrow + 1 & “:A” & rowsNum).Rows.Group
end if
output “end”
End Sub
‘—————————————————————————–
‘ Show table properties
‘—————————————————————————–
Sub ShowTable(tab, sheet)
If IsObject(tab) Then
Dim rangFlag
rowsNum = rowsNum + 1
‘ Show properties
Output “================================”
sheet.cells(rowsNum, 1) = “エンティティ名”
sheet.cells(rowsNum, 2) =tab.name
sheet.cells(rowsNum, 3) = “”
sheet.cells(rowsNum, 4) = “tableName”
sheet.cells(rowsNum, 5) = tab.code
sheet.Range(sheet.cells(rowsNum, 5),sheet.cells(rowsNum, 6)).Merge
rowsNum = rowsNum + 1
sheet.cells(rowsNum, 1) = “Property”
sheet.cells(rowsNum, 2) = “説明”
sheet.cells(rowsNum, 3) = “”
sheet.cells(rowsNum, 4) = “カラム日本語名”
sheet.cells(rowsNum, 5) = “カラム”
sheet.cells(rowsNum, 6) = “カラムタイプ”
‘境界線を設定
sheet.Range(sheet.cells(rowsNum-1, 1),sheet.cells(rowsNum, 2)).Borders.LineStyle = “1”
sheet.Range(sheet.cells(rowsNum-1, 4),sheet.cells(rowsNum, 6)).Borders.LineStyle = “1”
Dim col ‘ running column
Dim colsNum
colsNum = 0
for each col in tab.columns
rowsNum = rowsNum + 1
colsNum = colsNum + 1
sheet.cells(rowsNum, 1) = col.name
sheet.cells(rowsNum, 2) = col.comment
sheet.cells(rowsNum, 3) = “”
sheet.cells(rowsNum, 4) = col.name
sheet.cells(rowsNum, 5) = col.code
sheet.cells(rowsNum, 6) = col.datatype
next
sheet.Range(sheet.cells(rowsNum-colsNum+1,1),sheet.cells(rowsNum,2)).Borders.LineStyle = “2”
sheet.Range(sheet.cells(rowsNum-colsNum+1,4),sheet.cells(rowsNum,6)).Borders.LineStyle = “2”
rowsNum = rowsNum + 1
Output “FullDescription: ” + tab.Name
End If

Pythonでフォルダのツリーを作成するプログラム

ファイル名:
directorytree.py
pythonコード:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import optparse

LOCATION_NONE = ‘NONE’
LOCATION_MID = ‘MID’
LOCATION_MID_GAP = ‘MID_GAP’
LOCATION_TAIL = ‘TAIL’
LOCATION_TAIL_GAP = ‘TAIL_GAP’

Notations = {
LOCATION_NONE: ”,
LOCATION_MID: ‘├─’,
LOCATION_MID_GAP: ‘│ ‘,
LOCATION_TAIL: ‘└─’,
LOCATION_TAIL_GAP: ‘ ‘
}

class Node(object):
def __init__(self, name, depth, parent=None, location=LOCATION_NONE):
self.name = name
self.depth = depth
self.parent = parent
self.location = location
self.children = []

def __str__(self):
sections = [self.name]
parent = self.has_parent()
if parent:
if self.is_tail():
sections.insert(0, Notations[LOCATION_TAIL])
else:
sections.insert(0, Notations[LOCATION_MID])
self.__insert_gaps(self, sections)
return ”.join(sections)

def __insert_gaps(self, node, sections):
parent = node.has_parent()
# parent exists and parent’s parent is not the root node
if parent and parent.has_parent():
if parent.is_tail():
sections.insert(0, Notations[LOCATION_TAIL_GAP])
else:
sections.insert(0, Notations[LOCATION_MID_GAP])
self.__insert_gaps(parent, sections)

def has_parent(self):
return self.parent

def has_children(self):
return self.children

def add_child(self, node):
self.children.append(node)

def is_tail(self):
return self.location == LOCATION_TAIL

class Tree(object):
def __init__(self):
self.nodes = []

def debug_print(self):
for node in self.nodes:
print(str(node) + ‘/’)

def write2file(self, filename):
try:
with open(filename, ‘w’) as fp:
fp.writelines(str(node) + ‘/\n’
for node in self.nodes)
except IOError as e:
print(e)
return 0
return 1

def build(self, path):
self.__build(path, 0, None, LOCATION_NONE)

def __build(self, path, depth, parent, location):
if os.path.isdir(path):
name = os.path.basename(path)
node = Node(name, depth, parent, location)
self.add_node(node)
if parent:
parent.add_child(node)

entries = self.list_folder(path)
end_index = len(entries) – 1
for i, entry in enumerate(entries):
childpath = os.path.join(path, entry)
location = LOCATION_TAIL if i == end_index else LOCATION_MID
self.__build(childpath, depth + 1, node, location)

def list_folder(self, path):
“””Folders only.”””
return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
# for entry in os.listdir(path):
# childpath = os.path.join(path, entry)
# if os.path.isdir(childpath):
# yield entry

def add_node(self, node):
self.nodes.append(node)

def _parse_args():
parser = optparse.OptionParser()
parser.add_option(
‘-p’, ‘–path’, dest=’path’, action=’store’, type=’string’,
default=’./’, help=’the path to generate the tree [default: %default]’)
parser.add_option(
‘-o’, ‘–out’, dest=’file’, action=’store’, type=’string’,
help=’the file to save the result [default: pathname.trees]’)
options, args = parser.parse_args()
# positional arguments are ignored
return options

def main():
options = _parse_args()
path = options.path
if not os.path.isdir(path):
print(‘%s is not a directory’ % path)
return 2

if not path or path == ‘./’:
filepath = os.path.realpath(__file__) # for linux
path = os.path.dirname(filepath)
tree = Tree()
tree.build(path)
# tree.debug_print()
if options.file:
filename = options.file
else:
name = os.path.basename(path)
filename = ‘%s.trees’ % name
return tree.write2file(filename)

if __name__ == ‘__main__’:
import sys
sys.exit(main())

結果:

gtest_start/
├─build/
├─lib/
│  └─gtest/
├─output/
│  ├─primer/
│  │  ├─Debug/
│  │  │  ├─lib/
│  │  │  └─obj/
│  │  └─Release/
│  │      ├─lib/
│  │      └─obj/
│  └─thoughts/
│      ├─Debug/
│      │  ├─lib/
│      │  └─obj/
│      └─Release/
│          ├─lib/
│          └─obj/
├─src/
│  ├─primer/
│  └─thoughts/
├─test/
│  ├─primer/
│  └─thoughts/
├─third_party/
│  └─gtest/
└─tools/

pythonでファイルを読み取って、文字列を操作する

pythonコード:
f = open(‘c:\\names_startnews24.txt’);
lang =0;
result =””;
for line in f:
name = line.strip();
name_ = name[::-1];
leng = len(name);
if(name ==name_ and leng>=lang):
lang = leng;
result = name;
# print name;
print “result “,result;
f.close();

HTML5とCanvasで作られたclockのサンプル

htmlコード
<img src=”clogo.png” id=”simg” style=”display:none” />

<canvas id=”cav” width=”400″ height=”400″ style=”margin-left:auto; margin-right:auto; width:100%” ></canvas>

javascriptコード:
var imgsrc=document.getElementById(“simg”);

var ctx = document.getElementById(‘cav’).getContext(‘2d’);

ctx.clearRect(0,0,400,400);
function draw(ctx,cx,cy){

rd=180;
for(i=1;i<=60;i++){

ctx.strokeStyle=”#333″;
ctx.lineWidth=1;
ctx.beginPath();
rarc=i/60*2*Math.PI;
y=2*200*Math.sin(rarc/2.0)*Math.sin(rarc/2.0);
x=y/(Math.tan(rarc/2));
x2=(x*rd)/200;
y2=200-((200-y)*x2/x);
x3=(x*(rd-20))/200;
y3=200-((200-y)*x3/x);
ctx.moveTo(200+x,y);
ctx.lineTo(200+x2,y2);
ctx.closePath();
ctx.fill();
ctx.stroke();

}

for(i=1;i<=12;i++){
ctx.strokeStyle=”#f00″;
ctx.lineWidth=8;
ctx.beginPath();
rarc=i/12*2*Math.PI;
y=2*200*Math.sin(rarc/2.0)*Math.sin(rarc/2.0);
x=y/(Math.tan(rarc/2));
x2=(x*rd)/200;
y2=200-((200-y)*x2/x);
x3=(x*(rd-20))/200;
y3=200-((200-y)*x3/x);
ctx.moveTo(200+x,y);
ctx.lineTo(200+x2,y2);
ctx.closePath();
ctx.fill();
ctx.stroke();

ctx.beginPath();
ctx.font=”20px Arial”;
ctx.fillStyle=”#000″;
ctx.textAlign=”center”;
ctx.textBaseline=”middle”;
ctx.fillText(i,200+x3,y3);
ctx.closePath();
ctx.stroke();
ctx.restore();
}

var date=new Date();
var yy=date.getYear();
var MM=date.getMonth() + 1;
var dd=date.getDay();
var hh=date.getHours();
var mm=date.getMinutes();
var ss=date.getSeconds();
var sss=date.getMilliseconds();
rd=140;
ctx.strokeStyle=”#777″;
ctx.lineWidth=3;
ctx.beginPath();
rarc=(mm/60+(1/60)*(ss/60)+(1/60)*(1/60)*(sss/1000))*2*Math.PI;
y=2*200*Math.sin(rarc/2.0)*Math.sin(rarc/2.0);
x=y/(Math.tan(rarc/2));
x2=(x*rd)/200;
y2=200-((200-y)*x2/x);
x3=(x*(rd-20))/200;
y3=200-((200-y)*x3/x);
ctx.moveTo(200,200);
ctx.lineTo(200+x2,y2);
ctx.closePath();
ctx.fill();
ctx.stroke();

rd=120;
ctx.strokeStyle=”#999″;
ctx.lineWidth=6;
ctx.beginPath();
rarc=(hh/12+ mm/60*(1/12)+(1/60)*(ss/60)*(1/12)+(1/60)*(1/60)*(sss/1000)*(1/12))*2*Math.PI;
y=2*200*Math.sin(rarc/2.0)*Math.sin(rarc/2.0);
x=y/(Math.tan(rarc/2));
x2=(x*rd)/200;
y2=200-((200-y)*x2/x);
x3=(x*(rd-20))/200;
y3=200-((200-y)*x3/x);
ctx.moveTo(200,200);
ctx.lineTo(200+x2,y2);
ctx.closePath();
ctx.fill();
ctx.stroke();

rd=180;

ctx.strokeStyle=”#333″;
ctx.lineWidth=1;
ctx.beginPath();
rarc=((ss/60)-1+(1/60)*(sss/1000))*2*Math.PI;
y=2*200*Math.sin(rarc/2.0)*Math.sin(rarc/2.0);
x=y/(Math.tan(rarc/2));
x2=(x*rd)/200;
y2=200-((200-y)*x2/x);
x3=(x*(rd-60))/200;
y3=200-((200-y)*x3/x);
ctx.moveTo(200,200);
ctx.lineTo(200+x2,y2);

ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.strokeStyle=”#999″;
ctx.beginPath();
ctx.fillStyle=”#f00″;
ctx.arc(200+x3, y3,15,0,2*Math.PI);
ctx.closePath();
ctx.fill();
ctx.stroke();

ctx.drawImage(imgsrc, 200+x3-10, y3-10,20,20);

}
//draw(ctx,200,200,200);

function drawClock(){
ctx.clearRect(0,0,400,400);
draw(ctx,200,200);
}
setInterval(drawClock,60/1000);

javascriptで最初の文字は大文字を変換する

例: path->Path , list->List

javascriptコード:
“arkgame.com is a technical site”.replace(/(\w){1}/,function(v){return v.toUpperCase()});

Redmineのプラグインのインストール

1.必要なプラグインはすべてredmineのpluginsフォルダにコピーする

2.必要なGEMSをインストール
bundle install –without development test rmagick

3.プラグインのマージを実行
bundle exec rake redmine:plugins NAME=$PLUGIN_NAME RAILS_ENV=production

1 / 3112345...102030...最後 »