Python Private variableds

0 意見

class Mine:
    def __init__(self):
        self.x = 2
        self.__y = 3
    def print_y(self):
        print(self.__y)

m = Mine()
m.print_y()
>>> 3
m.__y
>>> Error

Python String operations

0 意見

Int to String
pyStr = str(10)

String append
"hello" + "world"

Length
pyStr = "GoodBye"
len(pyStr)
>>> 7

Substring
pyStr[:-1]
>>> GoodBy

pyStr[1:4]
>>> ood

Split
pyStr = "Hello world everybody"
segment = pyStr.split(" ")
>>> ['Hello', 'world', 'everybody']


digit   alpha   
x = "123"
x.isdigit()
>>> True
x.isalpha()
>>> False

lower  upper
x = "M"
x.islower()
>>> False
x.isupper()
>>> True

%
str ="%s is %s " % ( "Apple", "Fruit")
>>> Apple is Fruit

format
'We are the {} who say "{}!"'.format('knights', 'Ni')
>>> We are the knights who say "Ni!"

Python class

0 意見

Attribute
modname.the_ans 代表 the_ans 是 Object modname的一個attribute

modname.the_ans = 42
若 modname可讀寫的話,這樣的寫法是被允許的
當然也可以寫 del modname.the_ans 來移除 the_ans 這個 attribute


namespace
根據Python上定義:Namespaces are created at different moments and have different lifetimes. The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted.

Class objects support two kinds of operations: attribute references and instantiation.

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>

class MyClass:
    i = 12345
    def f(self):
        return 'hello world'

class Complex:
 def __init__(self, realpart, imagpart):
  self.r = realpart
  self.i = imagpart

x = Complex(3.0, -4.5)
""" x.r, x.i ==> (3.0, -4.5) """

Python program and module

0 意見

if __name__ == '__main__':
    main()
else:
    # module-specific initialization code if any
It its's called as a script, it will be run with the name __main__ and the controlling function, main, well be called. If it has been imported into an interactive session or another module, its name will be its filename.

Python The optparse module

0 意見

configure a script to accept command-line options as well as arguments.
need to import optparse module

from optparse import OptionParser

def main():
    parser = OptionParser()
    parser.add_option("-f", "--file", dest="filename",  help="write report to FILE",  metavar="FILE")

    parser.add_option("-x", "--xray", dest="xray", help="specify xray strength factor")

    parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status message to stdout")
    (options, args) = parser.parse_args()

    print("options:", str(options))
    print("arguments:", args)

main()

network layer representive naming

0 意見

Application : message
Transport : segment
Network : datagram
Link : frame or packet

10Base5 ⇒ 10Mbps signal aapproximately 500 meters (expensive)
10BaseT ⇒ 10Mbps baseband signal, Ethernet over twisted-pair
100BaseTx ⇒ 100Mbps twisted-pair ( four pairs of twisted-pair wire)


 Crossover Cable

Android set default keyboard hidden

0 意見

//AndroidManifest.xml
<activity android:name="act" android:windowSoftInputMode="stateHidden"></activity>

iOS list all the fonts

0 意見

It is really simple.

NSLog(@"Available fonts: %@", [UIFont familyNames]);

iOS show a alert view

0 意見

AlertView
UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"Message!" message:@"Callout" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
       
[alert show];

iOS Timer Selector with argument

0 意見

updateTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(updateTable:) userInfo:[NSDictionary dictionaryWithObject:indexPath forKey:@"idx"] repeats:YES];


   
- (void)updateTable:(NSTimer *)timer
{
   NSIndexPath *indexPath = [[timer userInfo] objectForKey:@"idx"];
   Clock *currentCell = [timerListData objectAtIndex:indexPath.row];

   NSLog(@"idx:%d",indexPath.row);
   
   [myTableView reloadData];
}



cancel a timer
[timer invalidate];
timer = nil;

iOS Passing argument to selector with addtarget

0 意見

you have a switcher object named switcher


switcher.tag = indexPath.row;

[switcher addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];


- (void) switchChanged:(id)sender{
   UISwitch *switchControl = sender;
   
   NSInteger idx = switchControl.tag;
   
   NSLog(@"%d switch to %@",idx,switchControl.on ? @"Y": @"N");
}



if you use tableview, you can also use this function instead

- (void) switchChanged:(id)sender{
UISwitch *switchControl = sender;


   UITableViewCell *parentCell = (UITableViewCell *)[[switchControl superview] superview];
   NSIndexPath *indexPath = [self.myTableView indexPathForCell:parentCell];
   
   NSLog(@"row %d clicked",indexPath.row);
}

iOS get navigation bar tint color by RGB

0 意見

CGFloat c[4];
UIColor *color = self.navigationController.navigationBar.tintColor;
[color getRed:&c[0] green:&c[1] blue:&c[2] alpha:&c[3]];
NSLog(@"%f %f %f %f", c[0], c[1], c[2], c[3]);

iOS remove all subview

0 意見

how the remove all subview

NSArray *viewsToRemove = [self.mainView subviews];
for (UIView *v in viewsToRemove) 

{
       [v removeFromSuperview];
       NSLog(@"%@ view removed",v);
}

iOS set radius to button by layer

0 意見

#import

CALayer * layer = [deltaButton layer];
[layer setMasksToBounds:YES];
[layer setCornerRadius:1.0]; //note that when radius is 0, the border is a rectangle
[layer setBorderWidth:2.0];
[layer setBorderColor:[[UIColor grayColor] CGColor]];

iOS get current time

0 意見


NSDate *now = [NSDate date];
NSDateFormatter *currentTime = [[NSDateFormatter alloc] init];
currentTime.dateFormat = @"yyyy:mm:dd:hh:mm:ss";
[currentTime setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(@"time:%@",[currentTime stringFromDate:now]);

iOS NSNumber transform

0 意見

NSNumber to int
NSNumber *myNum;
int intValue = [ myNum  intValue];


Int to NSNumber
NSNumber number = [NSNumber numberWithInt:10];


Double to NSNumber

dobule dx = 1.1, double dy = 2.2
NSNumber *nsx = [NSNumber numberWithDouble:x];
NSNumber *nsy = [NSNumber numberWithDouble:y];


NSNumber to Double

NSNumber *ns, *ny;
double latitude  = [ns doubleValue];
double longitude = [ny doubleValue];


NSNumber to NSString

NSString *myString = [NSNumber stringValue];

iOS UIKit Framework

0 意見


click to zoom-out
see more detail in iOS developer Library

Python Send http post example

0 意見


HTTPResponse instances have the following methods and attributes:

read()
Reads and returns the response body.


getheader(name[, default])
Get the contents of the header name, or default if there is no matching header.


msg
A mimetools.Message instance containing the response headers.


version
HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.


status
Status code returned by server.


reason
Reason phrase returned by server.


import httplib, urllib

params = urllib.urlencode({'acc': 'user', 'pw': 'pw'})
headers = {"Content-type": "application/x-www-form-urlencoded",
		   "Accept": "text/plain"}
conn = httplib.HTTPConnection("192.168.1.1")
conn.request("POST", "/m_login", params, headers)
response = conn.getresponse()
#print response.status, response.reason, response.msg

cookie = response.getheader("Set-Cookie")

data = response.read()
print "\r\n", data, "\r\n"
conn.close()

Python TCP server and client tutorial

0 意見

TCP server

HOST = '192.168.1.1'
PORT = 7777
ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ts.bind((HOST, PORT))
ts.listen(1)

print 'TCP waiting to receive data'
conn, addr = ts.accept()
print 'Connected by', addr
while True:
   data = conn.recv(1024)
   if not data: break
   conn.send(data.upper())
	
conn.close()

TCP client
HOST = '192.168.1.1'
PORT = 7777
tc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tc.connect((HOST, PORT))

say = raw_input('say something\r\n')
tc.send(str(say))

received = tc.recv(1024)
tc.close()

print "Sent:     {}".format(say)
print "Received: {}".format(received)

Python UDP server and client tutorial

0 意見

UDP server

HOST = '192.168.1.1'
PORT = 7777
us = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
us.bind((HOST, PORT))
print 'UDP waiting to receive data'
while True:
data, (addr, port) = us.recvfrom( 1024 )
print 'Data:', data, ',  Connected:', addr, ":", port
us.sendto(data.upper(), (addr,port))	
us.close()

UDP client
HOST = '192.168.1.1'
PORT = 7777
uc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
say = raw_input('say something\r\n')
uc.sendto(str(say), (HOST,PORT))
received = uc.recv(1024)
print "Sent:     {}".format(say)
print "Received: {}".format(received)

Android set style in xml

0 意見

Setting the new style to activity, just add a new style in style.xml and use the style in activity or view.

// style.xml
<style name="HintFont" parent="android:Theme.Holo.Light.DarkActionBar">
     <item name="android:textColor">#BBBBBB</item>
     <item name="android:textSize">18dp</item>
</style>

//AndroidManifest.xml (whole activity)
<activity android:name="mainActivity" android:theme="@style/HintFont"></activity>

// layout.xml (singal view)
style="@style/HintFont"

Java Integer to String

0 意見

Integer to String

int intVal = 123;
String str = Integer.toString(123);
String str = "" + intVal;
String str = String.valueOf(intVal);
String to Integer
String strVal = "123";
int i = Integer.parseInt(strVal); 

Android dynamically add row to tablelayout

0 意見

The way to add row to tablelayout in android.

  1. Find the table layout id. 
  2. New a row for table.
  3. Add the view you want.( EditText for this example) 
  4. Add the new EditText to row.
  5. Add the row to tablelayout.
  6. Done
public void touchToAddRow()
{
	TableLayout tl = (TableLayout)findViewById(R.id.tableLayout);

	TableRow tr = new TableRow(this);
	tr.setLayoutParams(new LayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

	EditText et1 = new EditText(this);
	et1.setId(100+rows*6+0);

	rows++;

	tr.addView(et1);
tl.addView(tr, new LayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
}

Android how to know the view type by id

0 意見

We may handle different view, sometimes it is inconvinient if we don't know the view type. Just use "instanceof" to know what kind of view type would coming.

View view = findViewById(R.id.viewid);
					
if(view instanceof EditText)
	Log.v("debug", "EditText");
else if(view instanceof TextView)
	Log.v("debug", "TextView");
else
	Log.v("debug","Wrong Type"+i);

Android Radio Group Tutorial

0 意見

Learn how to write RadioGroup and Radio in xml file
In Java code use function to get which radio button been selected.

// sex.xml
<RadioGroup
	android:id="@+id/radioGroupSex"
	android:orientation="horizontal"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">

	<RadioButton
		android:id="@+id/radioPatSex1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:checked="true"
		android:text="@string/sex_val1" />

	<RadioButton
		android:id="@+id/radioPatSex2"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="@string/sex_val2" />
</RadioGroup>
// sex.java
public static int getRadioIndex(RadioGroup g)
{
	int radioButtonID = g.getCheckedRadioButtonId();
	View radioButton = g.findViewById(radioButtonID);
	int idx = g.indexOfChild(radioButton);
	Log.v("debug","idx="+idx);
	return idx;
}

RadioGroup gRadio = (RadioGroup) findViewById(R.id.radioGroup1);

int selected = getRadioIndex(gRadio);

Android How to new a intent

0 意見

// 1. new a new_win.class
// 2. in AndroidManifest.xml 
<activity android:name="new_win"></activity>

// 3. in Activity.java
Intent i= new Intent();
i.setClass(this, new_win.class);
startActivity(i);

StrictMode.ThreadPolicy

0 意見

StrictMode.ThreadPolicy was introduced since API Level 9 and the default thread policy had been changed since API Level 11, which in short, does not allow network operation (include HttpClient and HttpUrlConnection) get executed on UI thread. if you do this, you get NetworkOnMainThreadException.

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = 
    new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}