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 Private variableds
標籤: python 0 意見張貼者: kenywalker 於 晚上10:10
Python String operations
標籤: python 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']
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!"
張貼者: kenywalker 於 晚上8:48
Python class
標籤: python 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) """
張貼者: kenywalker 於 下午6:25
Python program and module
標籤: python 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.
張貼者: kenywalker 於 凌晨1:18
Python The optparse module
標籤: python 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()
張貼者: kenywalker 於 凌晨12:43
network layer representive naming
標籤: network 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
張貼者: kenywalker 於 晚上11:09
Android set default keyboard hidden
標籤: android 0 意見//AndroidManifest.xml <activity android:name="act" android:windowSoftInputMode="stateHidden"></activity>
張貼者: kenywalker 於 晚上11:05
iOS list all the fonts
標籤: iOS 0 意見It is really simple.
NSLog(@"Available fonts: %@", [UIFont familyNames]);
張貼者: kenywalker 於 晚上10:59
iOS show a alert view
標籤: iOS 0 意見AlertView
UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"Message!" message:@"Callout" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
張貼者: kenywalker 於 晚上10:58
iOS Timer Selector with argument
標籤: iOS 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;
張貼者: kenywalker 於 晚上10:56
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);
}
張貼者: kenywalker 於 晚上10:54
iOS get navigation bar tint color by RGB
標籤: iOS 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]);
張貼者: kenywalker 於 晚上10:50
iOS remove all subview
標籤: iOS 0 意見how the remove all subview
NSArray *viewsToRemove = [self.mainView subviews];
for (UIView *v in viewsToRemove)
{
[v removeFromSuperview];
NSLog(@"%@ view removed",v);
}
張貼者: kenywalker 於 晚上10:49
iOS set radius to button by layer
標籤: iOS 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]];
張貼者: kenywalker 於 晚上10:48
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]);
張貼者: kenywalker 於 晚上10:46
iOS NSNumber transform
標籤: iOS 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];
張貼者: kenywalker 於 晚上10:40
Python Send http post example
標籤: python 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()
張貼者: kenywalker 於 晚上10:20
Python TCP server and client tutorial
標籤: python 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)
張貼者: kenywalker 於 晚上10:17
Python UDP server and client tutorial
標籤: python 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)
張貼者: kenywalker 於 晚上10:11
Android set style in xml
標籤: android 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"
張貼者: kenywalker 於 晚上10:08
Java Integer to String
標籤: android, java 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);
張貼者: kenywalker 於 晚上10:02
Android dynamically add row to tablelayout
標籤: android 0 意見The way to add row to tablelayout in android.
- Find the table layout id.
- New a row for table.
- Add the view you want.( EditText for this example)
- Add the new EditText to row.
- Add the row to tablelayout.
- 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));
}
張貼者: kenywalker 於 晚上9:54
Android how to know the view type by id
標籤: android 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);
張貼者: kenywalker 於 晚上8:54
Android Radio Group Tutorial
標籤: android 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);
張貼者: kenywalker 於 晚上8:46
Android How to new a intent
標籤: android 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);
張貼者: kenywalker 於 晚上8:25
StrictMode.ThreadPolicy
標籤: android 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);
}
張貼者: kenywalker 於 晚上7:07
Diseño e iconos por N.Design Studio | A Blogger por Blog and Web

