Monthly Archives: 1月 2015

RegVizサイトを利用してJavaScript正規表現式を画面でデバックする

特徴:
画面でマッチした箇所を確認しながらデバッグすることができる
正規表現のグループがどの文字列にマッチする
マッチ対象の文字列を画面から指定できる
公式HP
http://regviz.org/

Ubuntuでnano操作するコマンドまとめ

操作コマンド

^G ==(F1) Invoke the help menu
^X ==(F2) Close currently loaded file/Exit from nano
^O ==(F3) Write the current file to disk == ^O WriteOut

^J ==(F4) Justify the current paragraph
^R ==(F5) Insert another file into the current one
^W ==(F6) Search for text within the editor
^Y ==(F7) Move to the previous screen
^V == ( F8 ) Move to the next screen

^K ==(F9) Cut the current line and store it in the cutbuffer
^U ==(F10) Uncut from the cutbuffer into the current line
^C ==(F11) Show the position of the cursor

^T ==(F12) Invoke the spell checker, if available
^N Move down one line
M-> Open next loaded file
M-I Auto indent enable/disable
M-Z Suspend enable/disable
M-Y Color syntax highlighting enable/disable

「python初心者」関数、クラス、オブジェクトの定義サンプルコード

1.関数定義def
def example(a,b,c):
return a+b*c

>>> tuna=(5,7,3)
>>> example(*tuna)
26
>>> example(5,7,3)
26
>>> def example2(**this):
print this

2.オブジェクトclass
class exampleClass:
eyes=”blue”
age=25
def thisMethod(self):
return ‘hey this method worked’
exampleClass

exampleObject=exampleClass()
>>> exampleObject.eyes
‘blue’
>>> exampleObject.age
25
>>> exampleObject.thisMethod()
‘hey this method worked’

3.selfの利用方法
class className:
def createName(self,name):
self.name=name
def displayName(self):
return self.name
def saying(self):
print “hello %s” % self.name

>>> first=className()
>>> second = className()
>>> first.createName(‘bucky’)
>>> second.createName(‘tondy’)
>>> first.displayName()
‘bucky’
>>> first.saying()
hello bucky

4.親クラス、サブクラス
class parentClass:
var1=”i am var1″
var2=”i am var2″

>>> class childClass(parentClass):
pass

>>> parentObject=parentClass()
>>> parentObject.var1
‘i am var1’
>>> childObject=childClass()
>>> childObject.var1
‘i am var1’
>>> childObject.var2
‘i am var2’

5.親クラスをオーパーライド
class parent:
var1=”bacc”
var2=”snausage”

>>> class child(parent):
var2=”toast”

>>> pob=parent()
>>> cob=child()
>>> pob.var1
‘bacc’
>>> pob.var2
‘snausage’
>>> cob.var1
‘bacc’
>>> cob.var2
‘toast’

「Objective-C」iOS開発で位置情報を取得するサンプルコード

1.blockの宣言、定義
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@interface GpsManager : NSObject <CLLocationManagerDelegate> {
CLLocationManager *manager;
void (^saveGpsCallback) (double lat, double lng);
}
+ (void) getGps:( void (^)(double lat, double lng) )cb;
+ (void) stop;

@end

2.GpsManagerの定義
#import “GpsManager.h”
#import <CoreLocation/CoreLocation.h>
#import <UIKit/UIKit.h>

@implementation GpsManager

+ (id) sharedGpsManager {
static id s;
if (s == nil) {
s = [[GpsManager alloc] init];
}
return s;
}
– (id)init {
self = [super init];
if (self) {
manager = [[CLLocationManager alloc] init];
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest;

//iOS8.0を互換
/* Info.plistに2つ項目を追加
NSLocationAlwaysUsageDescription Boolean YES
NSLocationWhenInUseUsageDescription Boolean YES
*/

if ([manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[manager requestWhenInUseAuthorization];
[manager requestAlwaysAuthorization];
}

float osVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if (osVersion >= 8) {
[manager requestWhenInUseAuthorization];
[manager requestAlwaysAuthorization];
}
}
return self;
}
– (void) getGps:( void (^)(double lat, double lng) )cb {
if ([CLLocationManager locationServicesEnabled] == FALSE) {
return;
}
// copyメソッド
saveGpsCallback = [cb copy];
[manager stopUpdatingLocation];
// 新しいデータ位置
[manager startUpdatingLocation];
}

+ (void) getGps:( void (^)(double lat, double lng) )cb {
[[GpsManager sharedGpsManager] getGps:cb];
}

– (void) stop {
[manager stopUpdatingLocation];
}
+ (void) stop {
[[GpsManager sharedGpsManager] stop];
}

– (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
for (CLLocation *loc in locations) {
CLLocationCoordinate2D l = loc.coordinate;
double lat = l.latitude;
double lnt = l.longitude;

//blocksを利用
if (saveGpsCallback) {
saveGpsCallback(lat, lnt);
}
}
}

3.getGpsの処理
__block BOOL isOnece = YES;
[GpsManager getGps:^(double lat, double lng) {
isOnece = NO;

NSLog(@”lat lng (%f, %f)”, lat, lng);

if (!isOnece) {
[GpsManager stop];
}
}];

[GpsManager getGps:^(double lat, double lng) {

NSLog(@”lat lng (%f, %f)”, lat, lng);
}];

「ios開発」tcp通信サンプルプログラム

#import <UIKit/UIKit.h>
#import “GCDAsyncSocket.h”

@interface ViewController : UIViewController {
GCDAsyncSocket *serverSocket;
NSMutableArray *allClientArray;
}
#import “ViewController.h”
#import “SendViewController.h”

@interface ViewController ()
@end
@implementation ViewController

– (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.navigationItem.title = @”メッセージを取得”;
[self showNavItem];

[self createTcpSocket];
}
– (void) createTcpSocket {
allClientArray = [NSMutableArray array];
dispatch_queue_t dQueue = dispatch_queue_create(“My socket queue”, NULL);
serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dQueue socketQueue:nil];
[serverSocket acceptOnPort:12345 error:nil];
}

– (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
NSString *ip = [newSocket connectedHost];
uint16_t port = [newSocket connectedPort];
NSLog(@”new socket [%@:%d] is %@”, ip, port, newSocket);
[allClientArray addObject:newSocket];
[newSocket readDataWithTimeout:-1 tag:200];
NSString *s = @”Welcome”;
NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];
[newSocket writeData:data withTimeout:60 tag:300];
}

– (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSString *ip = [sock connectedHost];
uint16_t port = [sock connectedPort];
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@”received tcp [%@:%d] %@”, ip, port, s);
NSString *s2 = [NSString stringWithFormat:@”データ:%@”, s];
NSData *databack = [s2 dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:databack withTimeout:60 tag:400];

[sock readDataWithTimeout:-1 tag:200];
}

– (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
NSLog(@”lost connect %@”, err);
[allClientArray removeObject:sock];
}

– (void) showNavItem {
UIBarButtonItem *sendMyself = [[UIBarButtonItem alloc] initWithTitle:@”send” style:UIBarButtonItemStylePlain target:self action:@selector(sendMyself)];
self.navigationItem.rightBarButtonItem = sendMyself;
}
– (void) sendMyself {
SendViewController *svc = [[SendViewController alloc] init];
[self.navigationController pushViewController:svc animated:YES];
}

「JavaScript」JSONデータをフォーマットする方法

サンプルコード:

var JSONFormat = (function(){
var _toString = Object.prototype.toString;
function format(object, indent_count){
var html_fragment = ”;
switch(_typeof(object)){
case ‘Null’ :0
html_fragment = _format_null(object);
break;
case ‘Boolean’ :
html_fragment = _format_boolean(object);
break;
case ‘Number’ :
html_fragment = _format_number(object);
break;
case ‘String’ :
html_fragment = _format_string(object);
break;
case ‘Array’ :
html_fragment = _format_array(object, indent_count);
break;
case ‘Object’ :
html_fragment = _format_object(object, indent_count);
break;
}
return html_fragment;
};

function _format_null(object){
return ‘<span class=”json_null”>null</span>’;
}

function _format_boolean(object){
return ‘<span class=”json_boolean”>’ + object + ‘</span>’;
}

function _format_number(object){
return ‘<span class=”json_number”>’ + object + ‘</span>’;
}

function _format_string(object){
if(0 <= object.search(/^http/)){
object = ‘<a href=”‘ + object + ‘” target=”_blank” class=”json_link”>’ + object + ‘</a>’
}
return ‘<span class=”json_string”>”‘ + object + ‘”</span>’;
}

function _format_array(object, indent_count){
var tmp_array = [];
for(var i = 0, size = object.length; i < size; ++i){
tmp_array.push(indent_tab(indent_count) + format(object[i], indent_count + 1));
}
return ‘[\n’
+ tmp_array.join(‘,\n’)
+ ‘\n’ + indent_tab(indent_count – 1) + ‘]’;
}

function _format_object(object, indent_count){
var tmp_array = [];
for(var key in object){
tmp_array.push( indent_tab(indent_count) + ‘<span class=”json_key”>”‘ + key + ‘”</span>:’ + format(object[key], indent_count + 1));
}
return ‘{\n’
+ tmp_array.join(‘,\n’)
+ ‘\n’ + indent_tab(indent_count – 1) + ‘}’;
}

function indent_tab(indent_count){
return (new Array(indent_count + 1)).join(‘ ‘);
}

function _typeof(object){
var tf = typeof object,
ts = _toString.call(object);
return null === object ? ‘Null’ :
‘undefined’ == tf ? ‘Undefined’ :
‘boolean’ == tf ? ‘Boolean’ :
‘number’ == tf ? ‘Number’ :
‘string’ == tf ? ‘String’ :
‘[object Function]’ == ts ? ‘Function’ :
‘[object Array]’ == ts ? ‘Array’ :
‘[object Date]’ == ts ? ‘Date’ : ‘Object’;
};
function loadCssString(){
var style = document.createElement(‘style’);
style.type = ‘text/css’;
var code = Array.prototype.slice.apply(arguments).join(”);
try{
style.appendChild(document.createTextNode(code));
}catch(ex){
style.styleSheet.cssText = code;
}
document.getElementsByTagName(‘head’)[0].appendChild(style);
}
loadCssString(
‘.json_key{ color: purple;}’,
‘.json_null{color: red;}’,
‘.json_string{ color: #077;}’,
‘.json_link{ color: #717171;}’,
‘.json_array_brackets{}’);

var _JSONFormat = function(origin_data){
this.data = ‘string’ != typeof origin_data ? origin_data :
JSON && JSON.parse ? JSON.parse(origin_data) : eval(‘(‘ + origin_data + ‘)’);
};
_JSONFormat.prototype = {
constructor : JSONFormat,
toString : function(){
return format(this.data, 1);
}
}

return _JSONFormat;

})();

function create_result_contatiner(){
var $result = $(‘<pre id=”result” style=” width: 100%; height: 100%; overflow: scroll; overflow-x: scroll; overflow-y:scroll”></pre>’)
var $result_container = $(‘<div id=”result_container” style=”position: fixed; top: 1%; right: 8px; width: 5%; height: 97%; margin: 0; padding: 0; border:1px solid skyblue; background: #f8f8f8; line-height: 1.2em; font-size: 14px; cursor: pointer;”></div>’);
$result_container.append($result);
$result_container.hover(function(){
$(this).stop(true).animate({width:’50%’}, ‘slow’);
}, function(){
$(this).stop(true).animate({width:’5%’}, ‘slow’);
});
$(‘body’).append($result_container);
return [$result_container, $result];
}

(function request_intercept(args){
var $result_container = args[0],
$result = args[1];
$(‘form *[type=”submit”]’).bind(‘click’, function(){
var _form = $(this).parents(‘form’),
_action = (_form.attr(‘action’) || ‘./’),
_method = (_form.attr(‘method’) || ‘get’).toLowerCase(),
_params = {};
_form.find(‘input[type=”text”]’).each(function(){
var item = $(this);
_params[item.attr(‘name’)] = item.val();
});
$[‘get’ == _method ? ‘get’ : ‘post’](_action, _params, function(response){
try{
var j = new JSONFormat(JSON && JSON.parse ? JSON.parse(response) : eval(‘(‘ + response + ‘)’));
$result.html(j.toString());
}catch (e){
$result.html($result.text(response).html());
}
$result_container.stop(true).animate({width:’50%’}, ‘slow’);
});
return false;
});
})(create_result_contatiner());

「android開発」javascriptのTouchSlideの使い方

サンプルコード:

[html]

<div class=”demo horizontal”>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>

[script]

new TouchSlide(containerId or ) //default horizontal slide

or

new TouchSlide(containerId, {
‘orientation’: TouchSlide.VERTICAL
}) // vertical slide

「Objective-C」ios開発でNSTimerの使い方を紹介するサンプルコード

1.Timerの基本設定
-(void)initializeTimer {
//Timerの周波数を設定、30回/秒
float theInterval = 1.0/30.0;
fpsLabel.text = [NSString stringWithFormat:@”%0.3f”, theInterval];

//Timerが正式に起動
[NSTimer scheduledTimerWithTimeInterval:theInterval
target:self
selector:@selector(countTotalFrames:)
userInfo:nil
repeats:YES];
}

2.使い方
-(void)countTotalFrames:(NSTimer *)theTimer {
frameCount ++;
framesLabel.text = [NSString stringWithFormat:@”%d”, frameCount];
}

「Objective-C」iosのシステム時刻を取得する

サンプルコード
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *date = [NSDate date];

timeLabel.text = [formatter stringFromDate:date];
[formatter release];

[formatter setTimeStyle:NSDateFormatterFullStyle];
[formatter setTimeStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];

「Objective-C」ios開発で現在時刻を取得する

方法1
NSDateFormatter*formatter = [[NSDateFormatteralloc] init];
[formatter setDateFormat:@”yyyy-MM-dd hh:mm:ss”];
NSString *locationString=[formatter stringFromDate: [NSDate date]];

方法2
-(NSString *)getDate
{
NSDateFormatter*formatter = [[NSDateFormatteralloc] init];
[formatter setDateFormat:@”yyyy-MM-dd EEEE HH:mm:ss a”];
NSString *locationString=[formatter stringFromDate: [NSDate date]];
[formatter release];
return locationString;

1 / 512345