青青草原综合久久大伊人导航_色综合久久天天综合_日日噜噜夜夜狠狠久久丁香五月_热久久这里只有精品

tommy

It's hard to tell the world we live in is either a reality or a dream
posts - 52, comments - 17, trackbacks - 0, articles - 0
  C++博客 :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

StatService.h
#pragma once

class StatService {
public:
    StatService();

    void trackPageView(const string &page);
    void trackEvent(const string &eventName, map<stringstring> &props);    

private:
    void getUrl(string url);
};

StatService.cpp
#include "StatService.h"
#include "GlobalConfig.h"
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/NetworkInterface.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StreamCopier.h>
#include <Poco/Path.h>
#include <Poco/URI.h>
#include <Poco/Exception.h> 
#include <Poco/Base64Encoder.h>

using namespace Poco::Net;
using namespace Poco;
using namespace std;

StatService::StatService() {
}

string GetIP() {
    NetworkInterface::NetworkInterfaceList list = NetworkInterface::list();
    for(NetworkInterface::NetworkInterfaceList::iterator i = list.begin(); i != list.end(); ++i) {
        NetworkInterface nt = *i;
        IPAddress addr = nt.address();
        if(!addr.isLoopback()) { 
            return addr.toString();
        }
    }
    return "";
}

void StatService::trackPageView(const string &page) {
    const GlobalConfig *gConfig = GlobalConfig::GetInstance();
    string eventName = "VisitPage";
    stringstream ss;
    ss << "{" <<
        "\"event\":\"" << eventName << "\"," <<
        "\"properties\": {" << 
        "\"page\":\"" << page << "\"," <<
        // "distinct_id" and "token" are
        
// special properties, described below.
        "\"distinct_id\":" << "\"" << GetIP() << "\"," <<
        "\"token\":\"" << gConfig->stat_token() << "\"";
    ss << "}}";

    //encode
    std::ostringstream base64Str;
    Base64Encoder encoder(base64Str);
    encoder << ss.str();
    encoder.close();
    //cout << base64Str.str() << endl;
    
    cout << ss.str() << endl;

    ostringstream url;
    url << gConfig->stat_endpoint() << "?data=" << base64Str.str();
    string sUrl = url.str();
    //cout << sUrl << endl;
    
    sUrl.erase(remove_if(sUrl.begin(), sUrl.end(), isspace), sUrl.end());
    //replaceAll(sUrl, "\n", "$");

    
//kick off
    getUrl(sUrl);    
}


void replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
        return;
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
}
void StatService::trackEvent(const string &eventName, map<string,string> &props) { 
    const GlobalConfig *gConfig = GlobalConfig::GetInstance();
    stringstream ss;
    ss << "{" <<
        "\"event\":\"" << eventName << "\"," <<
        "\"properties\": {" << 
        // "distinct_id" and "token" are
        
// special properties, described below.
        "\"distinct_id\":" << "\"" << GetIP() << "\"," <<
        "\"token\":\"" << gConfig->stat_token() << "\"";
    
    //plugin in properties 
    for(map<string,string>::const_iterator i = props.cbegin(); i != props.cend(); ++i) { 
        ss << ",\"" << i->first << "\":\"" << i->second << "\"";
    } 
    ss << "}}";

    //encode
    std::ostringstream base64Str;
    Base64Encoder encoder(base64Str);
    encoder << ss.str();
    encoder.close();
    //cout << base64Str.str() << endl;
    
    cout << ss.str() << endl;

    ostringstream url;
    url << gConfig->stat_endpoint() << "?data=" << base64Str.str();
    string sUrl = url.str();
    //cout << sUrl << endl;
    
    sUrl.erase(remove_if(sUrl.begin(), sUrl.end(), isspace), sUrl.end());
    //replaceAll(sUrl, "\n", "$");

    
//kick off
    getUrl(sUrl);
}
void StatService::getUrl(string url) {
    URI uri(url);
    HTTPClientSession session(uri.getHost(), uri.getPort());
    GlobalConfig * gConfig = GlobalConfig::GetInstance();
    if(gConfig->proxy().size() > 0) {
        session.setProxy(gConfig->proxy(), gConfig->proxy_port());
    }
    std::string path(uri.getPathAndQuery());
    if (path.empty()) path = "/";

    cout << "getUrl:path:" << path << endl;

    // send request
    HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
    session.sendRequest(req);

    HTTPResponse res;
    cout << res.getStatus() << " " << res.getReason() << endl;

    // print response
    istream &is = session.receiveResponse(res);
    StreamCopier::copyStream(is, cout);
}

posted @ 2015-01-24 22:48 Tommy Liang 閱讀(317) | 評(píng)論 (0)編輯 收藏

  1. "new" to create an object if no arguments are needed for initialization.
    e.g.   XYZObject *object = [XYZObject new];
2. Literals offers a concise object-creation syntax.
    NSString *someString = @"Hello, World !";
3. We can create NSNumber using boxed expression, like:
    NSNumber *myInt = @(80/12);
4. The "id" type defines a generic object pointer.  (object c is a dynamic language!  this is just like "var"         keyword in C#)
    
    id someObject = @"Hello, World!";
5.  Use "isEqual" to test whether two objects represent the same data, available from NSObject.
    if([firstObject isEqual:secondObject]) ...
6.  "compare" method is provided by basic Foundation types such as NSNumber, NSString and NSDate.
    if( [someDate compare:anotherDate] == NSOrderedAscending) ...
7. It's perfectly acceptable in Object-C to send a message to nil,  it's just ignored and return nil for object return type, 0 for numeric types and NO for BOOL types.
8. If you want to make sure an object is not null, use this syntax:
    if (somePerson) ... directly, as convenient as Javascript.
9. It's important to avoid strong reference cycles.
10. Accessor methods are created by compiler:
     NSString *firstName = [somePerson firstName];
     [somePerson setFirstName:@"John"];
11. The method used to set the value (the setter method) starts with the word "set" and then uses the capitalized property name.
12. "readonly" attribute can be added to a property declaration to specify that it should be readonly, don't want it to be changed via setter method.
      @property (readonly) NSString *fullname;
13. Custom name can be specified using attribute on the property:
     @property (getter=isFinished) BOOL finished;
14. Simply include the multiple attributes on property as a comma-separated list, like this:
     @property (readonly, getter=isFinished) BOOL finished;
15.  Dot syntax is a concise alternative to accessor method calls
     NSString *firstName = someperson.firstName;
     somePerson.firstName = @"johnny";
16. Should use accessor method or dot syntax for property access even if you're accessing an object's properties from within its own implementation, in such case, should use "self":
      -(void) someMethod {
          NSString *myString = @"An interesting string";
          self.someString = myString;
          //or
          [self setSomeString:myString];
      }
      except when writing initialization, deallocation or custom accessor methods.
17. There's a default instance variable created by compiler called _propertyName,  we can direct the compiler to synthesize the variable using the following syntax:
     @implementation YourClass
     @synthesize propertyName = instanceVariableName;
     ...
     @end
18. If using @synthesize without specifying an instance variable name, like this:
     @synthesize firstName;
     the instance variable name will bear the same name as the property. (without underscore as prefix)
19. It's best practice to use a property on an object any time you need to keep track of a value or another object.
20. If you need to define your own instance variables without declaring a property, add them inside braces at the top of the class interface or implementation, like this:
     @interface SomeClass: NSObject {
        NSString *_myNonPropertyInstanceVariable;                           
     }
    or
    @implementation SomeClass {
        NSString *_anotherCustomInstanceVariable;
    }
21. Should always access the instance variables directly from within the initialization methods, like:
    - (id) init {
        self = [super init];
        
        if (self) {
            //initialize instance variables here.
        }
        
        return self;
    }
22. An init method should assign self to the result of calling the superclass's initialization method before doing
    its own initialization. A superclass may fail to initialize the object correctly and return nil. so you should
    always check to make sure self is not nil before performing your own initialization.
23. Should decide which method is the designated initializaer. This is often the method that offers the most options
    for initialization (such as the method with the most arguments)
24. Should call the superclass's designated initializer (in place of [super init];) before doing any of your own initialization.
25. You can implement custom accessor methods which is not backed by their own instance variables. like:
    @property (readonly) NSString *fullname;
    
    - (NSString *)fullName {
        return [NSString stringWithFormat: @"%@ %@", self.firstName, self.lastName];
    }
26. If need to write a custom accessor method for a property that uses an instance variable, must access the vairable directly from within the method.
    like this "lazy initialize method":
    - (XYZObject *)someImportantObject {
        if(!_someImportantObject) {
            _someImportantObject = [[XYZObject alloc] init];
        }
        return _someImportantObject;
    }
27. The compiler will not synthesize an instance variable automatically if both getter and setter for a readwrite property or a getter for a readonly 
    property are implemented by you.
28. Properties are atomic by default, the synthesized accessors ensure that a value is always fully retrieved by the getter method or fully set
    via the setter method.
29. It's not possible to combine a synthesized accessor with an accessor method that you implement yourself, for example, to provide a custom setter
    for an atomic, readwrite property but leave the compiler to synthesize the getter.
30. If property has a "nonatomic" attribute, it's not thread safe, but it's faster to access a nonatomic property, and it's fine to combine a 
    synthesized setter, for example, with your own getter implementation.
31. Property atomicity is not synonymous with an object's thread safety, thing is more complicated when properties need cooperation.
32. When one object relies on other objects and effectively taking ownership of those other objects, the first object is said to have strong references
    to the other objects. an object is kept alive as long as it has at least one strong reference to it from another object.
33. If a group of objects is connected by a circle of strong relationships, they keep each other alive even if there are no strong references from 
    outside of the group, we should avoid the strong reference cycles.
34. One way to break the strong reference cycle is to subsitute one of the strong references for a weak reference.A week reference does not
    imply ownership or responsibility between two objects, and does not keep an object alive.  
35. To declare a weak reference, add an attribute of (weak) to the property, like this:
    @property (weak) id delegate;
36. If you don't want a variable to maintain a strong reference (which is default behaviour), you can declare it as __weak, like this:
    NSObject * __weka weakVariable;
37. Weak variables can be a source of confusion, particularly in code like this:
    NSObject * __weak someObject = [[NSObject alloc] init];
    in this example, the newly allocated object has no strong reference to it, so it is immediately deallocated and someObject is set to nil.
38. It's important to consider the implications of a method that needs to access a weak property several times, like this:
    - (void) someMethod {
        [self.weakProperty doSomething];
        ...
        [self.weakProperty doSomethingElse];
    }
    in this case, we should cache the weak property in a strong variable to ensure it is kept in memory as long as you need to use it.
    - (void) someMethod {
        NSObject *cachedObject = self.weakProperty;
        [cachedObject doSomething];
        [cachedObject doSomethingElse];
    }
    
39. It's important to keep in mind if you need to make sure a weak property is not nil before using it, it's not enough just to test it, like this:
    if (self.someWeakProperty) {
        [someObject doSomethingImportantWith:self.someWeakProperty];
    }
    because in a multi-threaded application, the property may be deallocated between the test and the method call, rendering the test useless.
    should to declare a strong local variable to cache the value instead, like this:
    NSObject *cachedObject = self.someWeakProperty;     //lock it
    if (cachedObject) {
        [someObject doSomethingImportantWith:cachedObject];
    }
    cachedObject = nil;
40. There are some classes in Cocoa and Cocoa Touch that don't yet support weak references, should use unsafe reference instead, like this
    @property (unsafe_unretained) NSObject *unsafeProperty;
    for variables, need to use __unsafe_unretained:
    NSObject * __unsafe_unretained unsafeReference;
    why it's call unsafe is because it won't be set to nil if the destination object is deallocated, so it's dangling.
41. The "copy" attribute. used for object to keep its own copy of any objects that are set for its properties.
    example:
    @interface XYZBadgeView: NSView
    @property NSString *firstName;
    @property NSString *lastName;
    @end
    Two NSString properties are declaredd, which both maintain implicit strong references to their objects.
    When another object create a string to set as one of the badge view's properties, like this:
    NSMutableString *nameString = [NSMutableString stringWithString:"John"];
    self.badgeView.firstName = nameString;
    then..
    [nameString appendString:@"ny"];
    the firstName property of badgeView is now "johnny" because the mutable string was changed.
    to avoid such case, add (copy) attribute to the properties, like this:
    @interface XYZBadgeView: NSView
    @property (copy) NSString *firstName;
    @property (copy) NSString *lastName;
    @end  
42. Any object that wish to set for a copy property must conform to the NSCopying protocol.
43. If need to set a copy property's instance variable directly, for example in an initializer method,
    don't forget to set a copy of the original object:
    ...
    self = [super init];
    if (self) {
        _instanceVariableForCopyProperty = [aString copy];
    }
    return self;
    ...
44. Categories add methods to existing classes:
    @interface ClassName (CategoryName)
    @end
    
45. At runtime, there's no difference between a method added by a category and one that is implemented by the original class.
46. A category is usually declared in a separated header file and implemented in a separate source code file.
47. As well as just adding methods to existing classes, you can also use categories to split the implementation of a complex class
    across multiple source code files.
48. Categories are not usually suitable for declaring additional properties. it's not possible to declare an additional instance variable in 
    a category.
49. In order to avoid undefined behavior, it's best practice to add a prefix to method names in cateogories on framework classes.
50. Class extensions extend the internal implementation.
    The methods declared by a class extension are implemented in the @implementation block for the original class.
51. The syntax to declare a class extension is similar to category:
    @interface ClassName ()
    @end
    that's why it's also called "anonymous categories"
52. Unlike regular categories, a class extension can add its own properties and instance variables to a class.
53. Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation
    of the class itself. for example, to define a property as readonly in the interface, but as readwrite in a class extension declared above
    the implementation, in order that the internal methods of the class can change the property value directly (in implementation file!)
    example:
    @interface XYZPerson: NSObject
    ...
    @property (readonly) NSString *uniqueIdentifier;
    - (void) assignUniqueIdentifier;
    @end
    this means it's not possible to change the property from other object directly through the property itself.
    in order for the XYZPersion class to be able to change the property internally, it make sense to redeclare it in a class extension:
    @interface XYZPerson ()
    @property (readwrite) NSString *uniqueIdentifier;
    @end
    @implementation XYZPerson
    ...
    @end
    
    this means that the compiler will now also synthesize a setter method, so any method inside the XYZPerson implementation will be able
    to set the property directly using either the setter or dot syntax.
    and because it's defined in implementation file, it means it's private.
54. It's common to have two header files for a class, for example,
    XYZPerson.h and XYZPersonPrivate.h, when you release the framework, only the public XYZPerson.h header file is released.
55. Other options for class customization:
    (1) leverage inheritance and leave the decisions in methods specifically designed to be overridden by subclasses.
    (2) use a delegate object, any decision that might limit resusablity can be delegated to another object, which is left to make those 
        decisions at runtime.
    (3) interact directly with the object-c runtime, such as adding "associative references" to an object.
56. Protocol, is used to declare methods and properties that are independent of any specific class.
    @protocol ProtocolName
    //list of methods and properties
    @end
    Protocols can inlcude declarations for both instance methods and class methods, as well as properties.
57. Delegate and data source properties are usually marked as weak for object graph management reasons.
58. Protocols can have optional methods
    @protocol DataSource
    - (NSUInteger)numberOfSegments;
    ...
    @optional
    - (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;
    @required
    - ...
    @end
59. Check the optional methods are implemented at runtime:
    if( [self.dataSource respondsToSelector:@selector(titleForSegmentAtIndex:)] {
    ...
60. Protocols inherit from other protocols:
    @protocol MyProtocol <NSObject>
    ...
61. Conforming to protocol:
    @interface MyClass: NSObject <MyProtocol>
    ...
    @end
62. Adopt multiple protocols:
    @interface MyClass: NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>
    ...
    @end
    be aware, if there are too many protocols adopted in a class, it's a sign of bad design.
63. Some protocols are used to indicate non-hierarchical similarities between classes.
64. Protocols are also useful in situations where the class of an object isn't known, or needs to stay hidden.
65. Some types like NSInteger and NSUInteger, are defined differently depending on the target architecture.
    it's best practice to use these platform-specific types if you might be passing values across API boundaries.
66. C structures can hold primitive values.
67. Strings are represented by instances of the NSString class
    NSString *str = @"Hello, World!";
68. The basic NSString class is immutable.
69. The NSMutableString class is the mutable subclass of NSString.
70. Numbers of represented by instances of the NSNumber class.
    it's possible to create NSNumber instances using Objective-C literal syntax:
    NSNumber *magicNumber = @42;
    it's possible to request the scalar value using one of the accessor methods:
    int scalarMagic = [magicNumber intValue];
    note:  NSNumber is actually a class cluster.
    NSNumber class is itself a subclass of the basic NSValue, NSValue can also be used to represent pointers and structures.
   
71. @encode compiler directive:
    typedef struct {
        int i;
        float f;
    } MyIntegerFloatStruct;
    struct MyIntegerFloatStruct aStruct;
    aStruct.i = 42;
    aStruct.f = 3.14;
    
    NSValue *structValue = [NSValue value:&aStruct
                                withObjCType:@encode(MyIntegerFloatStruct)];
72. Most collections are objects. 
    collection classes use strong references to keep track of their contents.
73. NSArray, NSSet and NSDictionary classes are immutable, each has a mutable subclass to allow you to add or remove objects at will.
74. NSArray is used to represent an ordered collection of objects, the only requirement is that each item is an Objective-C object.
75. The arrayWithObjects: and initWithObjects: methods both take nil-terminated, variable number of arguments.
    It's possible to truncate the list of items unintentionally if one of the provided values is nil.
76. It's possible to create an array using the Objective-C literal like this:
    NSArray *someArray = @[firstObject, secondObject, thirdObject];
    SHOULD NOT terminate the list of objects with nil when using this literal syntax.
    if you do need to represent a nil value in it, should use the NSNull singleton class.
77. When try to access item of array using "objectAtIndex" method, should always check the number of items first:
    if([someArray count] > 0) {
        NSLog(@"First item is: %@", [someArray objectAtIndex:0]);
    }
78. NSArray class offers methods to sort its collected objects, because it is immutable, each of these methods returns
    a new array containing the items in the sorted order.
79. Usage of NSMutableArray:
    NSMutableArray *mutableArray = [NSMutableArray array];
    [mutableArray addObject: @"gamma"];
    ...
    [mutableArray replaceObjectAtIndex:0 withObject:@"epision"];
80. Sort a mutable array in place, without creating a secondary array:
    [mutableArray sortUsingSelector:@selector(caseInsensitiveCompare:)];
81. Sets are unordered collections, they don't maintain order, and offer a performance improvement.
82. As with NSArray, the iniWithObjects: and setWithObjects: methods of NSSet both take a nil-terminated, variable number of arguments.
    The mutable NSSet subclass is NSMutableSet.
83. About NSDictionary, it's best practice to use string objects as dictionary keys.
84. Creating dictionaries:
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
        someObject, @"anObject",
        @"Hello, World!", @"hellowString",
        @42, @"magicNumber",
        someValue, @"aValue",
        nil];
    each object is specified before its key, and the list of objects and keys must be nil-terminated.
objectAtIndex" method, should always check the number of items first:
    if([someArray count] > 0) {
        NSLog(@"First item is: %@", [someArray objectAtIndex:0]);
    }
85. Like NSArray, NSDictionary also can be created in a literal form:
    NSDictionary *dictionary = @{
        @"anObject": someObject,
        @"helloString": @"Hello, World!",
        @magicNumber": @42,
        @"aValue": someValue
    };
    and with out nil-terminated,  the structure is just like Javascript object definition.
86. Query dictionary:
    NSNumber *storedNumber = [dictionary objectForKey:@"magicNumber"];
    if the object isn't found, nil will be returned.
    we can also use subscript syntax alternative like this:
    NSNumber *storedNumber = dictionary[@"magicNumber"];
87. Mutable version:  NSMutableDictionary
    [dictionary setObject:@another string" forKey:@"secondString"];
    [dictionary removeObjectForKey:@"anObject"];
88.Representing nil with NSNull
    NSArray *array = @[@"string", @42, [NSNull null]];
89. The NSArray and NSDictionary classes make it easy to write their contents directly to disk like this:
    NSURL *fileURL = ...
    NSArray *array = @[@"first", @"second", @"third"];
    BOOL success = [array writeToURL:fileURL atomically:YES];
    if(!success) {
        //an error occured
    }
    if every contained object is one of the property list types( NSArray, NSDictionary, NSString, NSData, NSDate and NSNumber),
    it's easy to recreate the entire hierarchy from disk:
    NSURL *fileURL = ...
    NSArray *array = [NSArray arrayWithContentsOfURL:fileURL];
    if(!array) {
        //an error occured
    }
90. If need to persist other types of objects, we can use an archiver object such as NSKeyedArchiver, the only requirement to 
    create an archive is that each object must support the NSCoding protocol.
91. Many collection classes conform to the NSFastEnumeration protocol, including NSArray, NSSet and NSDictionary, syntax:
    for (<type> <variable> in <colleciton>) {
        ...
    }
92. If you use fast enumeration with a dictionary, you iterate over the dictionary keys like this:
    for( NSString *eachKey in dictionary) {
        id object = dictionary[eachKey];
        NSLog(@"Object: %@ for key: %@", object,eachKey);
    }
93. You cannot mutate a collection during fast enumeration.
94. It's also possible to enumeratemany Coca and Cocoa Touch collections by using an NSEnumerator object.
    for (id eachObject in [array reverseObjectEnumerator]) {
        ...
    }
95. It's also possible to iterate through the contents by calling the enumerator's nextObject method repeatedly like this:
    id eachObject;
    while ( (eachObject = [enumerator nextObject]) ) {
        NSLog(@"Current object is: %@", eachObject);
    }
96. Because it's a common programmer error to use the C assignment operator (=) when you mean the quality test operator (==), 
    the compiler will warn you if you set a variable in a conditional branch or loop, like this:
    if (someVariable = YES) {
        ...
    }
    if you really want to do this,  indicate this by placing the assignment in parentheses like this:
    if ( (someVariable = YES ) ) {
        ...
    }
97. Many collections support block-based enumeration.
98. Blocks are like closures or lambdas in other programming language.
99. Syntax of blocks:
    ^{
        NSLog(@"This is a block");
    }
100.You can declare a variable to keep track of a block, like this:
    void (^simpleBlock)(void);
    the same syntax as function pointers:)
101.Block can operate just like a method, can have arguments and return value:
    ^ double (double firstValue, double secondValue) {
        return firstValue * secondValue;
    }
102.Blocks can capture values from the enclosing scope
    - (void)testMethod {
        int anInteger = 42;
        void (^testBlock)(void) = ^{
            NSLog(@"Integer is: %i", anInteger);
        };
        testBlock();
    }
103.The block cannot change the value of the original variable, or even the captured value (it's captured as a const variable)
104.Use __block variables to share storage:
    if you need to be able to change the value of a captured variable from within a block, use __block storage type modifier on the original
    variable declaration like this:
    
    __block int anInteger = 42;
    void (^testBlock)(void) = ^{
        NSLog(@"Integer is: %i", anInteger);
    }
    anInteger = 84;
    testBlock();
105.You can pass blocks as arguments to methods or functions, an simplify some tasks:
   - (IBAction)fetchRemoteInformation:(id)sender {
        [self showProgressIndicator];
        
        XYZWebTask *task = ...
        
        [task beginTaskWithCallbackBlock:^{
            [self hideProgressIndicator];
        }];
    }
    It's important to take care when capturing "self" because it's easy to create strong reference cycle.
106.A block should always be the last argument to a method.
107.We can use type definition to simplify block syntax, like this:
    typedef void (^XYZSimpleBlock)(void);
108.We can use properties to keep track of blocks, like this:
    @interface XYZObject: NSObject
    @property (copy) void (^blockProperty)(void);
    @end
109.It's possible to use type definition for block property declarations, like this:
    typedef void (^XYZSimpleBlock)(void);
    
    @interface XYZObject: NSObject
    @property (copy) XYZSimpleBlock blockProperty;
    @end
110.To avoid strong reference when capturing "self" in block, should use weak reference like this:
    - (void)configureBlock {
        XYZBlockKeeper * __weak weakSelf = self;
        self.block = ^{
            [weakSelf doSomething];
        }
    }
111.Blocks can simplify iteration:
    NSArray *array = ...
    [array enumerateObjectsUsingBlock:^ (id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"Object at index %lu is %@", idx, obj);
    }];
112.If the code in the enumeration block is process-intensive--and safe for concurrent execution-- can use this:
    [array enumerateObjectsWithOptions:NSEnumerationConcurrent
        usingBlock:^ (id obj, NSUInteger idx, BOOL *stop) {
        ...
    }];
113.Block based method in NSDictionary:
    NSDictionary *dictionary = ...
    [dictionary enumerateKeysAndObjectsUsingBlock:^ (id key, id obj, BOOL *stop) {
        NSLog(@"key:%@, value: %@", key, obj);
    }];
114.Blocks can simplify concurrent tasks, you can create NSOperation instance to encapsulate a unit of work along with
    any neccessary data, the add that operation to an NSOperationQueue for execution.
    although you can create your own custom NSOperation subclass to implement complex tasks, it's also possible to use
    the NSBlockOperation to create an operation using a block, like this:
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        ..
    }];
115.Queue:
    //schedule task on main queue:
    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    [mainQueue addOperation:operation];
    //schedule task on background queue:
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
116.Schedule blocks on dispatch queues with Grand Central Dispatch:
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        NSLog(@"Block for asynchronous execution");
    });
117.Only programming error using exception, all other errors are represented by instances of the NSError class.
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
    rather than making the requirement that every possible error have a unique numeric code, Cocoa and CocoaTouch 
    errors are divided into domains.
    example, the connection:didFailWithError: method above will privide an error from NSURLErrorDomain.
    the error object also incudes a localized description.
118.Some Methods pass errors by reference:
    - (BOOL)writeToURL:(NSURL *)aURL
        options:(NSDataWritingOptions)mask
        error:(NSError **)errorPtr;
    //invoke
    NSError *anyError;
    BOOL success = [receivedData writeToURL:someLocalFileURL
                        options:0
                        error:&anyError];
    if(!success) {
        NSLog(@"Write failed with error: %@", anyError);
        //present errors to user
    }
119.It's important to test the return value of the method to see whether an error occured, don't just test whether the
    error pointer was set to point to an error, it's not reliable.
120.Create your own errors:
    first you need to define your own error domain, like this:
    com.companyName.appOrFrameworkname.ErrorDomain
    you'll also need to pick a unique error code for each error that may occur in your domain, along with a suitable
    description, which is stored in the user info dictionary for the error, like this:
    NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
    NSString *desc = NSLocalizedString(@"Unable to...", @"");
    NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: desc };
    NSError *error = [NSError errorWithDomain:domain
                    code:-101
                    userInfo:userInfo];
121.If you need to pass back an error by reference as describe above your method signature should include a parameter for
    a pointer to a pointer to an NSError object. should also use the return value to indicate success or failure, like this:
    - (BOOL)doSomethingThatMayGenerateAnError:(NSError **)errorPtr {
        ...
        //error occured
        if (errorPtr) {
            *errorPtr = [NSError errorWithDomain:...
                                code:...
                                userInfo:...];
        }
        return NO;
    }
122.Exceptions are used for programming errors:
    @try {
        //do something that might throw an exception
    }
    @catch (NSException *exception) {
        //deal with the exception
    }
    @finally {
        //optional block of clean-up code
    }
123.Some naming conventions:
    NS -- Foundation (OSX and iOS) and Application Kit(OSX)
    UI -- UIKit (iOS)
    AB -- Address Book
    CA -- Core Animation
    CI -- Core Image
124.Method names do not have a prefix, and should start with a lowercase letter; camel case is used again for multiple words.
125.If a method includes an error pointer parameter to be set if an error occurred, this should be the last parameter to the method.
126.Accessor method names must follow conventions, the compiler automatically synthesizes the relevant getter and setter methods,
    a getter method should use the same name as property, the exception to this rule is for Boolean properties, for which the getter
    method should start with is.
127.the setter method for a property should use the form setPropertyname:
128.Althoug the @property syntax allows you to specify different accessor method names, you should only do so for situations like
    a Boolean property. It's essential to follow the conventions described here, otherwise technques like Key Value Coding won't work.
129.Class factory methods should always start with the name of the class (without the prefix) that they create, with the exception
    of subclasses of classes with existing factory methods. for example, NSArray, the factory methods start with array.
    the NSMutableArray class doesn't define any of its own class-specific factory methods, so the factory methods for a mutable array 
    still begin with array.

posted @ 2013-08-04 21:01 Tommy Liang 閱讀(493) | 評(píng)論 (0)編輯 收藏

資料轉(zhuǎn)自網(wǎng)絡(luò):
原文在此: http://www.qtcn.org/bbs/simple/?t52158.html

1  安裝vs2012 update1

2  下載qt5源碼包,記住,windows下要下載zip結(jié)尾的,不要看到tar.gz的小就下它,tar.gz的源碼包不能直接在windows下編譯

編譯

1) 我要編譯x86, 所以打開(kāi)vc x86命令提示符,其他版尚未成功

2) cd <path>\qt-everywhere-opensource-src-<version>
   configure -prefix %CD%\qtbase -opensource -nomake tests -nomake examples -mp

   如果想編譯例子,可以去掉-nomake examples

3) 執(zhí)行nmake 開(kāi)始編譯。

posted @ 2013-01-19 13:23 Tommy Liang 閱讀(2162) | 評(píng)論 (0)編輯 收藏

摘自 《The Boost Graph Library》
代碼示例在 vc2012下編譯通過(guò)。

圖類(lèi)與適配器

1.類(lèi)

adjacency_list 用于稀疏圖,用例如下:
#include <iostream>
#include <vector>
#include <string>
#include <boost/graph/adjacency_list.hpp>
#include <boost/tuple/tuple.hpp>

enum family { Jeanie, Debbie, Rick, John, Amanda, Margaret, Benjamin, N };

int main()
{
    using namespace boost;
    const char *name[] = {"Jeanie", "Debbie", "Rick", "John", "Amanda", "Margaret", "Benjamin"};
    adjacency_list<> g(N);
    add_edge(Jeanie,Debbie,g);
    add_edge(Jeanie,Rick,g);
    add_edge(Jeanie,John,g);
    add_edge(Debbie,Amanda,g);
    add_edge(Rick,Margaret,g);
    add_edge(John,Benjamin,g);

    graph_traits<adjacency_list<> >::vertex_iterator i,end;
    graph_traits<adjacency_list<> >::adjacency_iterator ai,a_end;
    property_map<adjacency_list<>,vertex_index_t>::type index_map = get(vertex_index,g);

    for(tie(i,end) = vertices(g); i != end; ++i) {
        std::cout << name[get(index_map,*i)];

        boost::tie(ai,a_end) = adjacent_vertices(*i, g);
        if(ai == a_end)
            std::cout << " has no children.";
        else
            std::cout << " is the parent of "; 
        for(; ai != a_end; ++ai) {
            std::cout << name[get(index_map, *ai)];
            if(boost::next(ai) != a_end)
                std::cout << ", ";
        }
        std::cout << std::endl;
    }
    return EXIT_SUCCESS;
}  


2. 拓?fù)渑判蛩惴?br />
#include <deque>
#include <vector>
#include <list>
#include <iostream>
#include <boost/graph/vector_as_graph.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/graph/adjacency_list.hpp>

int main()
{
    using namespace boost;

    const char *tasks[] = {
        "pick up kids from school",
        "buy groceries snacks",
        "get cash at ATM",
        "drop off kids at soccer practice",
        "cook dinner",
        "pick up kids from soccer",
        "eat dinner",
        "before drop off"
    };
    const int n_tasks = sizeof(tasks) / sizeof(char*);
    /*
    std::vector<std::list<int> > g(n_tasks);
    g[0].push_back(3);
    g[1].push_back(3);
    g[1].push_back(4);
    g[2].push_back(1);
    g[3].push_back(5);
    g[4].push_back(6);
    g[5].push_back(6);
    
*/
    adjacency_list<listS,vecS,directedS> g(n_tasks);
    add_edge(7,3,g);

    add_edge(0,3,g);
    add_edge(1,3,g);
    add_edge(1,4,g);
    add_edge(2,1,g);
    add_edge(3,5,g);
    
    add_edge(5,6,g);
     
    add_edge(4,6,g);
    

    //perform the topological sort and output the result
    std::deque<int> topo_order;
    topological_sort(g, std::front_inserter(topo_order),
        vertex_index_map(identity_property_map()));
    int n = 1;
    for(std::deque<int>::iterator i=topo_order.begin();
        i != topo_order.end(); ++i, ++n)
        std::cout << tasks[*i] << std::endl;

    return EXIT_SUCCESS;
}

今天還學(xué)習(xí)了 BCCL 庫(kù),即  Boost concept check library, 檢查模型是否滿足模板要求并提供較精準(zhǔn)的編譯錯(cuò)誤信息。

關(guān)于如何存取BGL的算法: 應(yīng)加boost前綴,如 boost:breadth_first_search

posted @ 2012-12-29 20:17 Tommy Liang 閱讀(571) | 評(píng)論 (0)編輯 收藏

I need to package PyQt program to windows executable file, there's Alchemy library used.
when "setup.py" file prepared and run, "No module named Alchemy" encountered.

so trace to mf.py file, py2exe just parse the lib directory to find modules, so I checked python27 folder,
in the lib directory, there's no sqlalchemy found, so i decide to download the sources of sqlalchemy,
check the site and several steps needed:

1. download Mercurial and install it.
2. use Mercurial to clone sqlalchemy's source
3. copy the module source folder (with __init__.py inside) to python27/lib/, like this: c:\python27\lib\sqlalchemy

now run setup.py again, problem resolved.

posted @ 2012-05-24 15:16 Tommy Liang 閱讀(402) | 評(píng)論 (0)編輯 收藏

Syntax best practice:
  • List Comprehensions
    >>> [i for i in range(10if i % 2 == 0]

    Enumeration:
    >>> def _treatment(pos, element):
     return '%d: %s' % (pos, element)

    >>> seq = ["one""two""three"]
    >>> [_treatment(i, el) for i, el in enumerate(seq)]
    ['0: one''1: two''2: three']

    Iterators and Generators
    >>> def fibonacci():
     a, b = 0, 1
     while True:
     yield b  # 這里返回 generator,一個(gè)特殊的iterator
     a, b = b, a + b

    >>> fib = fibonacci()
    >>> fib.next()
    1
    >>> fib.next()
    1
    >>> fib.next()
    2
    >>> [fib.next() for i in range(10)]
    [3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
    generators should be considered every time you deal with a
    function that returns a sequence or works in a loop;
    It is better to have a lot of simple iterable functions that work over
    sequences of values than a complex function that computes the result for
    one value at a time.
    >>> def my_generator():
     try:
     yield 'something'
     except ValueError:
     yield 'dealing with the exception'
     finally:
     print "ok let's clean"

    >>> gen = my_generator()
    >>> gen.next()
    'something'
    >>> gen.throw(ValueError('mean mean mean'))
    'dealing with the exception'
    >>> gen.close()
    ok let's clean
    >>> gen.next()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    StopIteration

posted @ 2012-04-19 02:09 Tommy Liang 閱讀(332) | 評(píng)論 (0)編輯 收藏

http://codebetter.com/jeremymiller/2007/07/06/build-your-own-cab-13-embedded-controllers-with-a-dash-of-dsl/ 

posted @ 2012-03-23 14:51 Tommy Liang 閱讀(228) | 評(píng)論 (0)編輯 收藏

<script language=javascript>
function ceil(number,significance){
if(significance){
return Math.ceil(number/significance) * significance;
}
return Math.ceil(number);
}
document.write(ceil((2025.4/(2000+2*19.05-12.7)).toFixed(3),1));
document.write("<br/>");
document.write(ceil(2.98,2));
</script>

note:  ceil((2025.4/(2000+2*19.05-12.7)),1) = 2, because of float problem, toFixed(prec) fix the problem.

posted @ 2011-11-22 18:16 Tommy Liang 閱讀(349) | 評(píng)論 (0)編輯 收藏



Hmm the output from the system monitor is weired, you can’t have a process not using memory at all (the virtual memory is huge but matches with the way you configured your VM).

 

I advise you to use “top” in a terminal, as root, to get some reliable info.

Concerning your performance problem, you should not swap within the virtual machine with such an impressive of allocated memory.

How much physical memory do you have ? Maybe, the problem is that your machine lacks of memory and makes your Ubuntu swapping…

To boost performance, I use the following settings :

(1) in the options of VMWare, I deactivate “taking snapshots in the background” and, in the memory section, I force all the virtual memory to fit in the available physical memory (no swap)

(2) I also adjust the swappiness parameter of the linux kernel.

By default, the linux kernel uses quite often the swap even if you still have plenty of free memory.

You can change this behaviour with this command :
echo “15″ > /proc/sys/vm/swappiness

I use “15″, which gives a pretty high priority to the physical memory, before the kernel uses the swap. By default, the value is 60. The higher, the more it will use the swap.

After testing, you can make it permanent by adding such a line at the end of /etc/sysctl.conf :

vm.swappiness = 15

(3) I would, anyway, just try to reduce the memory amount you allocate to you VM. Just in case.

(4) Also check the processes runing on your XP when it is slow ! Are you sure that your Windows image did not get infected by some trojan or virus ?

(5) For graphics, did you set up VMWare tools ?

posted @ 2011-11-11 07:02 Tommy Liang 閱讀(296) | 評(píng)論 (0)編輯 收藏

here is the screen capture video demo: 
http://youtu.be/CO0mHBMWmmg

Qt/OpenGL UI imitate UNITY

Dynamic 3D view control

Easy to rotate (yaw/pitch) parts with mouse left button and pan with right button. With the mouse wheel you can scale it and double clicking to locate the central point of the view;

Easy manipulate apparatus

Rotate or move individual parts with mouse, the parts can move correctly according to the joint relations, current support pairs: prismatic-pair and revolute-turning-pair;

Free room dimension set up

rooms width、length、height and other parameters can be manually setup and modified;



Parts Library

Apparatus parts can be dragged from the parts library into the 3D scene, and assembled to the anchor points of the pre-assembled parts; assembled parts are removable;



· Part joints dynamically changed 

Change the part joints motion-constraint-parameters dynamically, like the hanging arms rotation angle range, i.e. change it from 360 degree to 90 degree, the scene will respond the changed data immediately;



· Collision detection

If the apparatus collide with each other or the room’s walls, it will turn red to indicate the collision occurring as to adjust the equipments position;



· Real-time dimension measure

User can switch to Dimension measure mode to measure chosen points from apparatus to the wall/floor/ceiling or points on the other apparatus, when press Ctrl
the scene will enter 
transparency dimension measure mode, when user move or rotate the apparatus parts, related dimension numbers will change accordingly;



· Apparatus library management

user can manage the parts category hierarchy as deep as needed; support OBJ file imported into the library and preview; user can manage the parts motion-pair parameter dynamically;

· Data export

Scene can be saved as project file and reopen; the structure of the scene including all the apparatus parameters can be exported to word/excel files; the scene can also be exported to 
an independent window
s executable file (exe, prototype written with MFC), when opened, user can also control the scene and the apparatus without CMaxSpore product installed;
The exported executable support only observation but not parameter manipulation;



Technical Key points

· Qt library (open source version)

· OpenGL

· Computer graphics

· OOA,OOD

· Multi-threading

· MFC/Win32 SDK

Constructing features

NVidia Optix-Real-time-ray-tracing engine embed 



Exploring ideas

· Import rooms from AutoCAD DWG file; (AutoCAD API/Pattern recognition)

· Export scene to AutoCAD DWG file directly;

· JavaScript engine embed;

· Apparatus parts data network storage and multiple-user rights control;

· I18;

· Augmented reality support;

· Flash publishing

 

 

posted @ 2011-11-03 11:14 Tommy Liang 閱讀(400) | 評(píng)論 (0)編輯 收藏

僅列出標(biāo)題
共6頁(yè): 1 2 3 4 5 6 
青青草原综合久久大伊人导航_色综合久久天天综合_日日噜噜夜夜狠狠久久丁香五月_热久久这里只有精品
  • <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            一本色道久久88亚洲综合88| 在线精品在线| 亚洲主播在线播放| 亚洲视频在线观看三级| 亚洲免费av网站| 亚洲美女在线观看| 日韩亚洲欧美中文三级| 在线视频你懂得一区二区三区| 亚洲毛片在线看| 夜夜爽www精品| 亚洲欧美日韩国产综合在线| 午夜视频精品| 美女视频黄a大片欧美| 免费观看在线综合| 欧美日韩一区在线观看视频| 国产精品久久久久7777婷婷| 国产精品一区久久| 1024亚洲| 欧美精选午夜久久久乱码6080| 国产精品观看| 怡红院av一区二区三区| 亚洲少妇一区| 欧美专区第一页| 欧美国产精品va在线观看| 日韩亚洲一区在线播放| 欧美在线观看日本一区| 欧美日韩第一区| 好吊视频一区二区三区四区| 一区二区三区欧美在线| 久久久久久尹人网香蕉| 亚洲日本中文字幕| 亚洲视频在线二区| 久久亚洲免费| 国产精品日韩欧美大师| 亚洲精品久久久久久下一站| 欧美一区91| 亚洲激情一区二区| 欧美一区午夜精品| 国产精品草莓在线免费观看| 亚洲国产免费看| 久久精品国产v日韩v亚洲 | 日韩视频中午一区| 欧美一区二区精美| 亚洲人在线视频| 久久夜精品va视频免费观看| 国产精品欧美在线| 一区二区高清| 欧美国产日韩一二三区| 久久精品视频播放| 国产欧美日韩不卡| 午夜精品久久久久久久男人的天堂| 亚洲国产精品va在线观看黑人 | 亚洲激情视频在线| 久久大香伊蕉在人线观看热2| 欧美午夜一区二区三区免费大片| 亚洲欧洲一区二区在线观看| 免费在线看成人av| 久久久久国产精品一区三寸 | 欧美日本韩国一区| 亚洲国产日韩欧美| 欧美大片免费看| 蜜桃av一区二区| 在线视频国内自拍亚洲视频| 久久人人爽人人| 久久久av网站| 欧美一区二区在线播放| 欧美人交a欧美精品| 欧美特黄视频| 亚洲在线日韩| 亚洲一二三区精品| 国产精品夜夜夜一区二区三区尤| 亚洲综合成人婷婷小说| 亚洲一区二区精品在线观看| 国产精品一区二区三区乱码 | 欧美成人午夜免费视在线看片| 久久一区二区精品| 亚洲精品你懂的| 日韩一级网站| 国产免费成人| 美女在线一区二区| 欧美成在线观看| 亚洲视频在线观看| 亚洲在线中文字幕| 红桃视频成人| 亚洲成人在线视频播放 | 激情综合五月天| 美女视频黄免费的久久| 蜜臀av性久久久久蜜臀aⅴ| 99re8这里有精品热视频免费| 一本一本a久久| 国产精品一区二区欧美| 久久蜜臀精品av| 欧美国产一区二区在线观看| 亚洲摸下面视频| 久久精品在线视频| 99精品福利视频| 亚洲欧美一级二级三级| 亚洲高清不卡在线| 亚洲毛片在线免费观看| 国产综合色一区二区三区 | 欧美日韩国产经典色站一区二区三区| 亚洲欧美激情在线视频| 久久三级福利| 亚洲桃花岛网站| 久久久水蜜桃| 亚洲欧美日韩在线综合| 老色鬼精品视频在线观看播放| 亚洲一区二区三区在线观看视频| 久久国产精品网站| 国产精品99久久久久久人| 久久久国产亚洲精品| 亚洲影院一区| 欧美电影在线播放| 久久亚洲电影| 国产精品一二一区| 日韩亚洲在线| 亚洲茄子视频| 久久国产福利| 性做久久久久久免费观看欧美| 欧美国产极速在线| 另类图片综合电影| 国产亚洲成精品久久| 一本色道久久88精品综合| 亚洲六月丁香色婷婷综合久久| 久久精品国产综合精品| 欧美亚洲免费| 国产毛片一区二区| 亚洲视频 欧洲视频| 一区二区三区高清在线| 欧美成人高清| 欧美成人综合| 亚洲国产毛片完整版| 久久免费视频在线| 麻豆freexxxx性91精品| 国产主播精品在线| 欧美一区1区三区3区公司| 欧美中文字幕久久| 国产伦精品一区二区三区| 亚洲影音一区| 欧美综合国产精品久久丁香| 国产精品日韩欧美一区二区| 夜夜夜久久久| 亚洲影院污污.| 国产精品亚洲成人| 亚洲在线免费视频| 久久国产精品久久w女人spa| 国产香蕉97碰碰久久人人| 久久狠狠亚洲综合| 欧美aⅴ一区二区三区视频| 影音先锋久久资源网| 久久精品免费| 欧美国产综合| 亚洲视频一区在线| 国产欧美一区二区三区久久人妖| 欧美一区不卡| 亚洲第一搞黄网站| 一区二区三区高清| 国产乱人伦精品一区二区| 久久国产视频网站| 亚洲国产国产亚洲一二三| 在线午夜精品自拍| 国产精品久久久久7777婷婷| 久久精品72免费观看| 欧美激情久久久| 亚洲一区中文| 国内精品视频在线观看| 欧美96在线丨欧| 亚洲网在线观看| 久久人体大胆视频| 亚洲免费精品| 国产婷婷色一区二区三区| 欧美88av| 亚洲欧美一级二级三级| 欧美韩国在线| 性做久久久久久久久| 亚洲高清在线观看| 欧美视频在线观看一区二区| 午夜精品区一区二区三| 亚洲高清av| 午夜精品福利视频| 亚洲国产欧美精品| 国产免费成人| 欧美特黄一级| 欧美国产精品| 久久久久久999| 亚洲综合色婷婷| 亚洲精品一区二区三区99| 久久综合给合| 欧美一区二区三区精品 | 久久成人免费日本黄色| 永久免费视频成人| 国产精品久久一卡二卡| 麻豆精品视频在线观看视频| 亚洲欧美国产高清va在线播| 亚洲精品视频免费| 免费av成人在线| 午夜在线视频一区二区区别| 日韩视频免费在线观看| 亚洲国产欧美一区| 国内精品免费在线观看|