问:
How to search(Predicate) content from list like Xcode suggestion?
I think everyone notice XCode suggestions list. Check this screenshot

As per Apple document doesn't provide what expected ouptut.

```<code>NSPredicate *inPredicate = [NSPredicate predicateWithFormat: @"attribute CONTAINS[cd] %@", aCollection];
</code>```

Provide continuous search text only.

Is this possible, How to search content like this?

答:
A possible solution, is to use a Regular Expression for that. We just need to insert .* between each letter (and before and after the string) which means "any character (except for line terminators)". It seems that's what's used for the search on XCode completion.

```<code>NSMutableArray *letters = [[NSMutableArray alloc] init];
[searchString enumerateSubstringsInRange:NSMakeRange(0, [searchString length])
                                 options:NSStringEnumerationByComposedCharacterSequences
                              usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
    [letters addObject:substring];
}];
NSMutableString *pattern = [[NSMutableString alloc] initWithString:@".*"];
[pattern appendString:[letters componentsJoinedByString:@".*"]];
[pattern appendString:@".*"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.%K MATCHES[C] %@", keyToFilter, pattern];
</code>```

Sample to play, insert just before:

```<code>NSString *keyToFilter = @"attribute";
NSArray *array = @[@{keyToFilter:@"UITextField"}, @{keyToFilter:@"nsarray"}, @{keyToFilter:@"uitf"}];
NSString *searchString = @"uitf";
</code>```

and just after:

```<code>NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
NSLog(@"SearchString: %@\nFiltered: %@", searchString, ([filtered count]?[filtered valueForKey:keyToFilter]:@"NO RESULT"));
</code>```

Output:

```<code>$>SearchString: uitf
Filtered: (
    UITextField,
    uitf
)
</code>```

The code taken for construction the array of letters is from here. Different solutions could have been used to create pattern, it's maybe not the best one, but it's a working one.

Bonus:

And for fun (I was intriguing on how doing it), a possible way to color the list (I made an array of NSAttributedString) to adapt (not fully tested or errors free):

```<code>NSMutableArray *filteredColored = [[NSMutableArray alloc] init];
for (NSDictionary *aDict in filtered) //or for (MyObjectClass *myObject in filtered)
{
    NSString *aFilteredValue = aDict[keyToFilter]; //or NSString *aFilteredValue = [myObject attribute]
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:aFilteredValue attributes:@{}];
    NSInteger currentIndex = 0;
    for (NSString *aLetter in letters)
    {
        NSRange rangeFound = [aFilteredValue rangeOfString:aLetter
                                                   options:NSCaseInsensitiveSearch
                                                     range:NSMakeRange(currentIndex, [aFilteredValue length]-currentIndex)];
        if (rangeFound.location != NSNotFound)
        {
            currentIndex = rangeFound.location+rangeFound.length;
            [attr addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:rangeFound];
        }
    }
    [filteredColored addObject:attr];
}
</code>```

Body:
I think everyone notice XCode suggestions list. Check this screenshot

As per Apple document doesn't provide what expected ouptut.

NSPredicate *inPredicate = [NSPredicate predicateWithFormat: @"attribute CONTAINS[cd] %@", aCollection];

Provide continuous search text only.

Is this possible, How to search content like this?

Body:
A possible solution, is to use a Regular Expression for that. We just need to insert .* between each letter (and before and after the string) which means "any character (except for line terminators)". It seems that's what's used for the search on XCode completion.

NSMutableArray *letters = [[NSMutableArray alloc] init];
[searchString enumerateSubstringsInRange:NSMakeRange(0, [searchString length])
                                 options:NSStringEnumerationByComposedCharacterSequences
                              usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
    [letters addObject:substring];
}];
NSMutableString *pattern = [[NSMutableString alloc] initWithString:@".*"];
[pattern appendString:[letters componentsJoinedByString:@".*"]];
[pattern appendString:@".*"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.%K MATCHES[C] %@", keyToFilter, pattern];

Sample to play, insert just before:

NSString *keyToFilter = @"attribute";
NSArray *array = @[@{keyToFilter:@"UITextField"}, @{keyToFilter:@"nsarray"}, @{keyToFilter:@"uitf"}];
NSString *searchString = @"uitf";

and just after:

NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
NSLog(@"SearchString: %@\nFiltered: %@", searchString, ([filtered count]?[filtered valueForKey:keyToFilter]:@"NO RESULT"));

Output:

$>SearchString: uitf
Filtered: (
    UITextField,
    uitf
)

The code taken for construction the array of letters is from here. Different solutions could have been used to create pattern, it's maybe not the best one, but it's a working one.

Bonus:

And for fun (I was intriguing on how doing it), a possible way to color the list (I made an array of NSAttributedString) to adapt (not fully tested or errors free):

NSMutableArray *filteredColored = [[NSMutableArray alloc] init];
for (NSDictionary *aDict in filtered) //or for (MyObjectClass *myObject in filtered)
{
    NSString *aFilteredValue = aDict[keyToFilter]; //or NSString *aFilteredValue = [myObject attribute]
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:aFilteredValue attributes:@{}];
    NSInteger currentIndex = 0;
    for (NSString *aLetter in letters)
    {
        NSRange rangeFound = [aFilteredValue rangeOfString:aLetter
                                                   options:NSCaseInsensitiveSearch
                                                     range:NSMakeRange(currentIndex, [aFilteredValue length]-currentIndex)];
        if (rangeFound.location != NSNotFound)
        {
            currentIndex = rangeFound.location+rangeFound.length;
            [attr addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:rangeFound];
        }
    }
    [filteredColored addObject:attr];
}


来源: stackexchange

问:
About the "delete" command of C++
I am a new C++ learner. I have a simple question. Here is the code from a book. Is it necessary to create a new pointer, "pCat"? Can I just use the "rCat" and delete it? If not, why? </p>

```<code>class SimpleCat
{
public:
    SimpleCat (int age, int weight);

    ~SimpleCat() {}

    int GetAge() { return itsAge; }
    int GetWeight() { return itsWeight; }

private:
    int itsAge;
    int itsWeight;
};

SimpleCat::SimpleCat(int age, int weight):
    itsAge(age), itsWeight(weight) {}

SimpleCat* TheFunction();

int main()
{
    SimpleCat* rCat = TheFunction();

    int age = rCat->GetAge();

    std::cout << "rCat is " << age << " years old!\n";

    std::cout << "rCat: " << rCat << "\n";
    // How do you get rid of that memory?
    SimpleCat* pCat = rCat;
    delete pCat;
    return 0;
}

SimpleCat* TheFunction()
{
    SimpleCat *pFrisky = new SimpleCat(5,9);``
    std::cout << "pFrisky: " << pFrisky << "\n";
    return pFrisky;
}
</code>```

答:
The rule is simple, you need to call delete on any pointer that's been allocated using new. (And you need to call delete exactly once.)

It's not necessary to assign the pointer to another variable, and call delete on that.

So therefore you could be even more minimal:

delete TheFunction();

would work too, although, of course, you wouldn't be able to do much with the cat.

ContentLicense: CC BY-SA 3.0

Title: About the "delete" command of C++

Body:
I am a new C++ learner. I have a simple question. Here is the code from a book. Is it necessary to create a new pointer, "pCat"? Can I just use the "rCat" and delete it? If not, why?

class SimpleCat
{
public:
    SimpleCat (int age, int weight);

    ~SimpleCat() {}

    int GetAge() { return itsAge; }
    int GetWeight() { return itsWeight; }

private:
    int itsAge;
    int itsWeight;
};

SimpleCat::SimpleCat(int age, int weight):
    itsAge(age), itsWeight(weight) {}

SimpleCat* TheFunction();

int main()
{
    SimpleCat* rCat = TheFunction();

    int age = rCat->GetAge();

    std::cout << "rCat is " << age << " years old!\n";

    std::cout << "rCat: " << rCat << "\n";
    // How do you get rid of that memory?
    SimpleCat* pCat = rCat;
    delete pCat;
    return 0;
}

SimpleCat* TheFunction()
{
    SimpleCat *pFrisky = new SimpleCat(5,9);``
    std::cout << "pFrisky: " << pFrisky << "\n";
    return pFrisky;
}


问:
Appium (Android): App not signed with debug cert
I was running my automation scripts on bamboo using below configuration and facing an issue while re-signing the app file on simulator. I have tried what I can but couldn't say what's the issue with, is it appium, or bamboo or emulator issue?

Earlier then this issue, I faced an issue same as in the below link. I have tried to solve that issue and started facing this issue.I have raised this issue in Appium discuss also.

Here is the link: https://discuss.appium.io/t/uiautomator2-error-cannot-read-property-isscreenlocked-of-undefined/15153

Appium: appium@1.6.4-beta and also tried with appium@1.6.3

jdk: 1.8.0_102

platformVersion: '7.1'

automationName: 'uiautomator2'

platformName: 'Android'

Logs:

```<code>[Appium] Welcome to Appium v1.6.3
[Appium] Appium REST http interface listener started on 0.0.0.0:4723
[HTTP] --> POST /wd/hub/session {"desiredCapabilities":{"app":"apk-path","newCommandTimeout":"600","platformVersion":"7.1","automationName":"uiautomator2","platformName":"Android","deviceName":"emulator-5554"}}
[debug] [MJSONWP] Calling AppiumDriver.createSession() with args: [{"app":"apk-path","newCommandTimeout":"600","platformVersion":"7.1","automationName":"uiautomator2","platformName":"Android","deviceName":"emulator-5554"},null,null,null,null]
[Appium] Creating new AndroidUiautomator2Driver session
[Appium] Capabilities:
[Appium] app: 'apk-path'
[Appium] newCommandTimeout: '600'
[Appium] platformVersion: '7.1'
[Appium] automationName: 'uiautomator2'
[Appium] platformName: 'Android'
[Appium] deviceName: 'emulator-5554'
[BaseDriver] Capability 'newCommandTimeout' changed from string ('600') to integer (600). This may cause unexpected behavior
[BaseDriver] Session created with session id: 25e878b1-f9cf-4fb5-9070-d88617c91374
[BaseDriver] Using local app 'apk-path'
[debug] [UiAutomator2] Checking whether app is actually present
[UiAutomator2] UIAutomator2 Driver version:0.2.3
[debug] [AndroidDriver] Getting Java version
[AndroidDriver] Java version is: 1.8.0_102
[ADB] Checking whether adb is present
[ADB] Using adb from /Users/admin/Library/Android/sdk/platform-tools/adb
[AndroidDriver] Retrieving device list
[debug] [ADB] Trying to find a connected android device
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[AndroidDriver] Looking for a device with Android '7.1'
[debug] [ADB] Setting device id to emulator-5554
[ADB] Getting device platform version
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","getprop","ro.build.version.release"]
[AndroidDriver] Using device: emulator-5554
[ADB] Checking whether adb is present
[ADB] Using adb from /Users/admin/Library/Android/sdk/platform-tools/adb
[debug] [ADB] Setting device id to emulator-5554
[debug] [AndroidDriver] Parsing package and activity from app manifest
[ADB] Checking whether aapt is present
[ADB] Using aapt from /Users/admin/Library/Android/sdk/build-tools/25.0.2/aapt
[ADB] Extracting package and launch activity from manifest
[debug] [ADB] badging package: package
[debug] [ADB] badging act: Activity
[debug] [AndroidDriver] Parsed package and activity are: package/Activity
[ADB] Getting device platform version
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","getprop","ro.build.version.release"]
[debug] [ADB] Attempting to kill all io.appium.uiautomator2.server processes
[debug] [ADB] Getting all processes with io.appium.uiautomator2.server
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","ps"]
[ADB] No io.appium.uiautomator2.server process found to kill, continuing...
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","wait-for-device"]
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","echo","ping"]
[debug] [Logcat] Starting logcat capture
[debug] [AndroidDriver] Pushing settings apk to device...
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","install","/usr/local/lib/node_modules/appium/node_modules/io.appium.settings/bin/settings_apk-debug.apk"]
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","install","/usr/local/lib/node_modules/appium/node_modules/io.appium.settings/bin/settings_apk-debug.apk"]
[debug] [ADB] Application '/usr/local/lib/node_modules/appium/node_modules/io.appium.settings/bin/settings_apk-debug.apk' already installed. Continuing.
[debug] [AndroidDriver] Pushing unlock helper app to device...
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","install","/usr/local/lib/node_modules/appium/node_modules/appium-unlock/bin/unlock_apk-debug.apk"]
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","install","/usr/local/lib/node_modules/appium/node_modules/appium-unlock/bin/unlock_apk-debug.apk"]
[debug] [ADB] Application '/usr/local/lib/node_modules/appium/node_modules/appium-unlock/bin/unlock_apk-debug.apk' already installed. Continuing.
[debug] [UiAutomator2] Forwarding UiAutomator2 Server port 6790 to 8200
[debug] [ADB] Forwarding system: 8200 to device: 6790
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","forward","tcp:8200","tcp:6790"]
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","dumpsys","window"]
[AndroidDriver] Screen already unlocked, doing nothing
[debug] [AndroidDriver] Extracting strings from apk apk-path null /var/folders/w3/85v473ln4n795wf2dd39mgjw0000gn/T/package
[debug] [ADB] Extracting strings for language: default
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","getprop","ro.build.version.sdk"]
[debug] [ADB] Device API level: 25
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","getprop","persist.sys.locale"]
[debug] [ADB] Current device property 'persist.sys.locale':
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","getprop","ro.product.locale"]
[debug] [ADB] Current device property 'ro.product.locale': en-US
[debug] [ADB] No strings.xml for language 'en', getting default strings.xml
[debug] [ADB] Reading strings from converted strings.json
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","push","/var/folders/w3/85v473ln4n795wf2dd39mgjw0000gn/T/package/strings.json","/data/local/tmp"]
[debug] [ADB] Checking app cert for apk-path.
[debug] [ADB] App not signed with debug cert.
[debug] [ADB] Resigning apk.
[ADB] Error: Could not sign with default ceritficate. Original error Command '/Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/bin/java -jar /usr/local/lib/node_modules/appium/node_modules/appium-adb/jars/sign.jar apk-path --override' exited with code 1
at Object.wrappedLogger.errorAndThrow (lib/logger.js:60:13)
at ADB.callee$0$0$ (../../../lib/tools/apk-signing.js:21:9)
at tryCatch (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:67:40)
at GeneratorFunctionPrototype.invoke as _invoke
at GeneratorFunctionPrototype.prototype.(anonymous function) as throw
at GeneratorFunctionPrototype.invoke (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:136:37)
at run (/usr/local/lib/node_modules/appium/node_modules/core-js/library/modules/es6.promise.js:108:47)
at /usr/local/lib/node_modules/appium/node_modules/core-js/library/modules/es6.promise.js:119:28
at flush (/usr/local/lib/node_modules/appium/node_modules/core-js/library/modules/$.microtask.js:19:5)
at combinedTickCallback (internal/process/nexttick.js:67:7)
at process.tickCallback (internal/process/nexttick.js:98:9)
[Error: Could not sign with default ceritficate. Original error Command '/Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/bin/java -jar /usr/local/lib/node_modules/appium/node_modules/appium-adb/jars/sign.jar apk-path --override' exited with code 1]
[debug] [UiAutomator2] Deleting UiAutomator2 session
[debug] [UiAutomator2] Deleting UiAutomator2 server session
[UiAutomator2] Did not get confirmation UiAutomator2 deleteSession worked; Error was: Error: Trying to proxy a session command without session id
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","am","force-stop","package"]
</code>```

Could someone help me on this please?

Thanks

答:
I'm running into the same problem. I was told to reset the factory settings on my Samsung Galaxy S8! That did not work. I've read that it's a network timeout so increase the network time out. I see you added newCommandTimeout: '600' I did the same and that did not work.

Did you have an older version of Appium running? I tried with the Windows U/I version 1.4.16! and then I tried with the beta version of the Windows U/I. I finally removed the U/I version and  installed the commandline version 1.6.5. I still run into the same problem.

Body:
I was running my automation scripts on bamboo using below configuration and facing an issue while re-signing the app file on simulator. I have tried what I can but couldn't say what's the issue with, is it appium, or bamboo or emulator issue?

Earlier then this issue, I faced an issue same as in the below link. I have tried to solve that issue and started facing this issue.I have raised this issue in Appium discuss also.

Here is the link: https://discuss.appium.io/t/uiautomator2-error-cannot-read-property-isscreenlocked-of-undefined/15153

Appium: appium@1.6.4-beta and also tried with appium@1.6.3

jdk: 1.8.0_102

platformVersion: '7.1'

automationName: 'uiautomator2'

platformName: 'Android'

Logs:

[Appium] Welcome to Appium v1.6.3
[Appium] Appium REST http interface listener started on 0.0.0.0:4723
[HTTP] --> POST /wd/hub/session {"desiredCapabilities":{"app":"apk-path","newCommandTimeout":"600","platformVersion":"7.1","automationName":"uiautomator2","platformName":"Android","deviceName":"emulator-5554"}}
[debug] [MJSONWP] Calling AppiumDriver.createSession() with args: [{"app":"apk-path","newCommandTimeout":"600","platformVersion":"7.1","automationName":"uiautomator2","platformName":"Android","deviceName":"emulator-5554"},null,null,null,null]
[Appium] Creating new AndroidUiautomator2Driver session
[Appium] Capabilities:
[Appium] app: 'apk-path'
[Appium] newCommandTimeout: '600'
[Appium] platformVersion: '7.1'
[Appium] automationName: 'uiautomator2'
[Appium] platformName: 'Android'
[Appium] deviceName: 'emulator-5554'
[BaseDriver] Capability 'newCommandTimeout' changed from string ('600') to integer (600). This may cause unexpected behavior
[BaseDriver] Session created with session id: 25e878b1-f9cf-4fb5-9070-d88617c91374
[BaseDriver] Using local app 'apk-path'
[debug] [UiAutomator2] Checking whether app is actually present
[UiAutomator2] UIAutomator2 Driver version:0.2.3
[debug] [AndroidDriver] Getting Java version
[AndroidDriver] Java version is: 1.8.0_102
[ADB] Checking whether adb is present
[ADB] Using adb from /Users/admin/Library/Android/sdk/platform-tools/adb
[AndroidDriver] Retrieving device list
[debug] [ADB] Trying to find a connected android device
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[AndroidDriver] Looking for a device with Android '7.1'
[debug] [ADB] Setting device id to emulator-5554
[ADB] Getting device platform version
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","getprop","ro.build.version.release"]
[AndroidDriver] Using device: emulator-5554
[ADB] Checking whether adb is present
[ADB] Using adb from /Users/admin/Library/Android/sdk/platform-tools/adb
[debug] [ADB] Setting device id to emulator-5554
[debug] [AndroidDriver] Parsing package and activity from app manifest
[ADB] Checking whether aapt is present
[ADB] Using aapt from /Users/admin/Library/Android/sdk/build-tools/25.0.2/aapt
[ADB] Extracting package and launch activity from manifest
[debug] [ADB] badging package: package
[debug] [ADB] badging act: Activity
[debug] [AndroidDriver] Parsed package and activity are: package/Activity
[ADB] Getting device platform version
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","getprop","ro.build.version.release"]
[debug] [ADB] Attempting to kill all io.appium.uiautomator2.server processes
[debug] [ADB] Getting all processes with io.appium.uiautomator2.server
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","ps"]
[ADB] No io.appium.uiautomator2.server process found to kill, continuing...
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","wait-for-device"]
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","echo","ping"]
[debug] [Logcat] Starting logcat capture
[debug] [AndroidDriver] Pushing settings apk to device...
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","install","/usr/local/lib/node_modules/appium/node_modules/io.appium.settings/bin/settings_apk-debug.apk"]
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","install","/usr/local/lib/node_modules/appium/node_modules/io.appium.settings/bin/settings_apk-debug.apk"]
[debug] [ADB] Application '/usr/local/lib/node_modules/appium/node_modules/io.appium.settings/bin/settings_apk-debug.apk' already installed. Continuing.
[debug] [AndroidDriver] Pushing unlock helper app to device...
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","install","/usr/local/lib/node_modules/appium/node_modules/appium-unlock/bin/unlock_apk-debug.apk"]
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","install","/usr/local/lib/node_modules/appium/node_modules/appium-unlock/bin/unlock_apk-debug.apk"]
[debug] [ADB] Application '/usr/local/lib/node_modules/appium/node_modules/appium-unlock/bin/unlock_apk-debug.apk' already installed. Continuing.
[debug] [UiAutomator2] Forwarding UiAutomator2 Server port 6790 to 8200
[debug] [ADB] Forwarding system: 8200 to device: 6790
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","forward","tcp:8200","tcp:6790"]
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","dumpsys","window"]
[AndroidDriver] Screen already unlocked, doing nothing
[debug] [AndroidDriver] Extracting strings from apk apk-path null /var/folders/w3/85v473ln4n795wf2dd39mgjw0000gn/T/package
[debug] [ADB] Extracting strings for language: default
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","getprop","ro.build.version.sdk"]
[debug] [ADB] Device API level: 25
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","getprop","persist.sys.locale"]
[debug] [ADB] Current device property 'persist.sys.locale':
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","getprop","ro.product.locale"]
[debug] [ADB] Current device property 'ro.product.locale': en-US
[debug] [ADB] No strings.xml for language 'en', getting default strings.xml
[debug] [ADB] Reading strings from converted strings.json
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","push","/var/folders/w3/85v473ln4n795wf2dd39mgjw0000gn/T/package/strings.json","/data/local/tmp"]
[debug] [ADB] Checking app cert for apk-path.
[debug] [ADB] App not signed with debug cert.
[debug] [ADB] Resigning apk.
[ADB] Error: Could not sign with default ceritficate. Original error Command '/Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/bin/java -jar /usr/local/lib/node_modules/appium/node_modules/appium-adb/jars/sign.jar apk-path --override' exited with code 1
at Object.wrappedLogger.errorAndThrow (lib/logger.js:60:13)
at ADB.callee$0$0$ (../../../lib/tools/apk-signing.js:21:9)
at tryCatch (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:67:40)
at GeneratorFunctionPrototype.invoke as _invoke
at GeneratorFunctionPrototype.prototype.(anonymous function) as throw
at GeneratorFunctionPrototype.invoke (/usr/local/lib/node_modules/appium/node_modules/babel-runtime/regenerator/runtime.js:136:37)
at run (/usr/local/lib/node_modules/appium/node_modules/core-js/library/modules/es6.promise.js:108:47)
at /usr/local/lib/node_modules/appium/node_modules/core-js/library/modules/es6.promise.js:119:28
at flush (/usr/local/lib/node_modules/appium/node_modules/core-js/library/modules/$.microtask.js:19:5)
at combinedTickCallback (internal/process/nexttick.js:67:7)
at process.tickCallback (internal/process/nexttick.js:98:9)
[Error: Could not sign with default ceritficate. Original error Command '/Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/bin/java -jar /usr/local/lib/node_modules/appium/node_modules/appium-adb/jars/sign.jar apk-path --override' exited with code 1]
[debug] [UiAutomator2] Deleting UiAutomator2 session
[debug] [UiAutomator2] Deleting UiAutomator2 server session
[UiAutomator2] Did not get confirmation UiAutomator2 deleteSession worked; Error was: Error: Trying to proxy a session command without session id
[debug] [ADB] Getting connected devices...
[debug] [ADB] 1 device(s) connected
[debug] [ADB] Running '/Users/admin/Library/Android/sdk/platform-tools/adb' with args: ["-P",5037,"-s","emulator-5554","shell","am","force-stop","package"]

Could someone help me on this please?

Thanks


问:
How to align the text inside the TextView in Android?
I have a multiline TextView in Android. It is a child of a LinearLayout. It is already centered horizontally and I also want to have the text inside it centered.

Here's what I have now:

```<code>_ _ _ _ _ _| aaaaaaaaaaaaaaaaaaaaa
_ _ _ _ _ _| aaaaaaaa
_ _ _ _ _ _| aaaaaaaaaaaaaa
</code>```

What I want is:

```<code>_ _ _ _ _ _| aaaaaaaaaaaaaaaaaaaaa
_ _ _ _ _ _|       aaaaaaaa
_ _ _ _ _ _|     aaaaaaaaaaaaaa
</code>```

Where:

_ _ _ _ = the space on the side of the TextView

| = the TextView edge

答: Yes, use android:gravity attribute to change the position of data inside views.

Body:
I have a multiline TextView in Android. It is a child of a LinearLayout. It is already centered horizontally and I also want to have the text inside it centered.

Here's what I have now:

_ _ _ _ _ _| aaaaaaaaaaaaaaaaaaaaa
_ _ _ _ _ _| aaaaaaaa
_ _ _ _ _ _| aaaaaaaaaaaaaa

What I want is:

_ _ _ _ _ _| aaaaaaaaaaaaaaaaaaaaa
_ _ _ _ _ _|       aaaaaaaa
_ _ _ _ _ _|     aaaaaaaaaaaaaa

Where:

_ _ _ _ = the space on the side of the TextView

| = the TextView edge


问:
feof() returning true when EOF is not reached
I'm trying to read from a file at a specific offset (simplified version):

```<code>typedef unsigned char u8;
FILE *data_fp = fopen("C:\\some_file.dat", "r");
fseek(data_fp, 0x004d0a68, SEEK_SET); // move filepointer to offset
u8 *data = new u8[0x3F0];
fread(data, 0x3F0, 1, data_fp);
delete[] data;
fclose(data_fp);
</code>```

The problem becomes, that data will not contain 1008 bytes, but 529 (seems random). When it reaches 529 bytes, calls to feof(data_fp) will start returning true.

I've also tried to read in smaller chunks (8 bytes at a time) but it just looks like it's hitting EOF when it's not there yet.

A simple look in a hex editor shows there are plenty of bytes left.

答: Is the file being written to in parallel by some other application? Perhaps there's a race condition, so that the file ends at wherever the read stops, when the read is running, but later when you inspect it the rest has been written. That would explain the randomness, too.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to read from a file at a specific offset (simplified version):

typedef unsigned char u8;
FILE *data_fp = fopen("C:\\some_file.dat", "r");
fseek(data_fp, 0x004d0a68, SEEK_SET); // move filepointer to offset
u8 *data = new u8[0x3F0];
fread(data, 0x3F0, 1, data_fp);
delete[] data;
fclose(data_fp);

The problem becomes, that data will not contain 1008 bytes, but 529 (seems random). When it reaches 529 bytes, calls to feof(data_fp) will start returning true.

I've also tried to read in smaller chunks (8 bytes at a time) but it just looks like it's hitting EOF when it's not there yet.

A simple look in a hex editor shows there are plenty of bytes left.


答: Pivot is your best option here. Hard to answer fully without a little more detail; table names etc.</p>

Title: Row value as a column

Body:
I have following records

DocNo   PrnOrd  DESCR   ITEMCD  AMT
1          1    D1      16844   43330
1          2    D2      16844
1          7    D7      16844   2166.5
1         21    D21     16844   0.5
1          1    D1        937   58188
1          7    D7        937   2909.4
1         21    D21       937
1         23    D23       937   -0.02

want to present like this

DocNo,ITEMCD,   D1,    D2,     D7, D21,  D23,
1    , 16844,43330,      , 2166.5, 0.5,     ,
1    ,   937,58188,2909.4,       ,    ,-0.02,

DESCR field value as a column and its AMT as a value


问:
python map drive programmatically in Windows 10
I'm trying to map a remote path on Windows 10 for serveral hours but i don't get it to work. At first i tried it with WNetAddConnection2 but no matter what credentials or flags i use, when I type net use the mapped drive has always the status not available.

Manually i can map drives without problems, I only have problems when i map the drive programmatically.

```<code>import win32wnet
import win32netcon

nr = win32wnet.NETRESOURCE()
nr.dwScope = win32netcon.RESOURCE_GLOBALNET
nr.dwType = win32netcon.RESOURCETYPE_DISK
nr.dwUsage = win32netcon.RESOURCEUSAGE_CONNECTABLE
nr.lpLocalName = 'Z:'
nr.lpRemoteName = '\\\\192.168.178.46\\Test'

win32wnet.WNetAddConnection2(nr, None, None, 25)
</code>```

The 25 is a flag set of interactive and prompt. I don't get any errors and the drive is listed when i type net use, but the status is always not available and the drive is not visible under workstation.

After that I tried NetUseAdd:

```<code>import win32net
win32net.NetUseAdd(None, 3, {'remote': r'\\192.168.178.46\Test',
    'local': 'Z:', 'username': 'Admin', 'password': '123',
    'status': 0, 'flags': 1, 'asg_type': 0})
</code>```

It runs successfully but net use doesn't list anything and no mapped drives are visible under workstation.

A solution without subprocess would be nice. Can someone help please?

EDIT: Now i understand why it doesn't work. The app is running in admin context and I'm current logged in as non-admin. This behaviour is expalined here: https://superuser.com/questions/495370/why-isnt-a-mapped-drive-available-under-an-elevated-cmd-prompt-but-is-under-a-r

Is it possible to run the app as admin but the WNetAddConnection2 method as current user??

EDIT 2: Following the instructions from eryksun i came up with this:

```<code>import ctypes
from win32security import TOKEN_IMPERSONATE, TOKEN_ALL_ACCESS
from win32process import GetWindowThreadProcessId
from win32api import OpenProcess
from win32security import OpenProcessToken
from win32security import ImpersonateLoggedOnUser
from win32security import RevertToSelf

user32 = ctypes.WinDLL('user32', use_last_error=True);

user32.GetShellWindow.restype = ctypes.c_void_p
handle = user32.GetShellWindow()

threadId, processId = GetWindowThreadProcessId(handle)

handle_op = OpenProcess(TOKEN_ALL_ACCESS, True, processId)

handle_opt = OpenProcessToken(handle_op, TOKEN_IMPERSONATE)
ImpersonateLoggedOnUser(handle_opt) # throws access denied error
</code>```

SOLUTION:

```<code>    import ctypes
    from win32process import GetWindowThreadProcessId
    from win32api import OpenProcess
    from win32security import OpenProcessToken, ImpersonateLoggedOnUser, RevertToSelf, TOKEN_QUERY, TOKEN_DUPLICATE

    from win32con import PROCESS_QUERY_INFORMATION

    user32 = ctypes.WinDLL('user32', use_last_error=True);

    user32.GetShellWindow.restype = ctypes.c_void_p
    handle = user32.GetShellWindow()

    threadId, processId = GetWindowThreadProcessId(handle)

    handle_op = OpenProcess(PROCESS_QUERY_INFORMATION, False, processId)

    handle_opt = OpenProcessToken(handle_op, TOKEN_QUERY | TOKEN_DUPLICATE)
    ImpersonateLoggedOnUser(handle_opt)

    try:
        nr = win32wnet.NETRESOURCE()
        nr.dwScope = win32netcon.RESOURCE_GLOBALNET
        nr.dwType = DISK
        nr.dwUsage = win32netcon.RESOURCEUSAGE_CONNECTABLE
        nr.lpLocalName = 'Z:'
        nr.lpRemoteName = '\\\\192.168.178.46\\Test'

        win32wnet.WNetAddConnection3(None, nr, None, None, 25)
    except:
        print("Unexpected error...")

    RevertToSelf()
</code>```

答:
```<code>win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive,
    networkPath, None, user, password)
</code>```

Drive is the local drive you want to map the network drive to, e.g. X:\

For networkpath add \\ in the beginning of the path, e.g. \\\\networkpath02 if you can access the path with \\networkpath02 in explorer.

Body:
I'm trying to map a remote path on Windows 10 for serveral hours but i don't get it to work. At first i tried it with WNetAddConnection2 but no matter what credentials or flags i use, when I type net use the mapped drive has always the status not available.

Manually i can map drives without problems, I only have problems when i map the drive programmatically.

import win32wnet
import win32netcon

nr = win32wnet.NETRESOURCE()
nr.dwScope = win32netcon.RESOURCE_GLOBALNET
nr.dwType = win32netcon.RESOURCETYPE_DISK
nr.dwUsage = win32netcon.RESOURCEUSAGE_CONNECTABLE
nr.lpLocalName = 'Z:'
nr.lpRemoteName = '\\\\192.168.178.46\\Test'

win32wnet.WNetAddConnection2(nr, None, None, 25)

The 25 is a flag set of interactive and prompt. I don't get any errors and the drive is listed when i type net use, but the status is always not available and the drive is not visible under workstation.

After that I tried NetUseAdd:

import win32net
win32net.NetUseAdd(None, 3, {'remote': r'\\192.168.178.46\Test',
    'local': 'Z:', 'username': 'Admin', 'password': '123',
    'status': 0, 'flags': 1, 'asg_type': 0})

It runs successfully but net use doesn't list anything and no mapped drives are visible under workstation.

A solution without subprocess would be nice. Can someone help please?

EDIT: Now i understand why it doesn't work. The app is running in admin context and I'm current logged in as non-admin. This behaviour is expalined here: https://superuser.com/questions/495370/why-isnt-a-mapped-drive-available-under-an-elevated-cmd-prompt-but-is-under-a-r

Is it possible to run the app as admin but the WNetAddConnection2 method as current user??

EDIT 2: Following the instructions from eryksun i came up with this:

import ctypes
from win32security import TOKEN_IMPERSONATE, TOKEN_ALL_ACCESS
from win32process import GetWindowThreadProcessId
from win32api import OpenProcess
from win32security import OpenProcessToken
from win32security import ImpersonateLoggedOnUser
from win32security import RevertToSelf

user32 = ctypes.WinDLL('user32', use_last_error=True);

user32.GetShellWindow.restype = ctypes.c_void_p
handle = user32.GetShellWindow()

threadId, processId = GetWindowThreadProcessId(handle)

handle_op = OpenProcess(TOKEN_ALL_ACCESS, True, processId)

handle_opt = OpenProcessToken(handle_op, TOKEN_IMPERSONATE)
ImpersonateLoggedOnUser(handle_opt) # throws access denied error

SOLUTION:

    import ctypes
    from win32process import GetWindowThreadProcessId
    from win32api import OpenProcess
    from win32security import OpenProcessToken, ImpersonateLoggedOnUser, RevertToSelf, TOKEN_QUERY, TOKEN_DUPLICATE

    from win32con import PROCESS_QUERY_INFORMATION

    user32 = ctypes.WinDLL('user32', use_last_error=True);

    user32.GetShellWindow.restype = ctypes.c_void_p
    handle = user32.GetShellWindow()

    threadId, processId = GetWindowThreadProcessId(handle)

    handle_op = OpenProcess(PROCESS_QUERY_INFORMATION, False, processId)

    handle_opt = OpenProcessToken(handle_op, TOKEN_QUERY | TOKEN_DUPLICATE)
    ImpersonateLoggedOnUser(handle_opt)

    try:
        nr = win32wnet.NETRESOURCE()
        nr.dwScope = win32netcon.RESOURCE_GLOBALNET
        nr.dwType = DISK
        nr.dwUsage = win32netcon.RESOURCEUSAGE_CONNECTABLE
        nr.lpLocalName = 'Z:'
        nr.lpRemoteName = '\\\\192.168.178.46\\Test'

        win32wnet.WNetAddConnection3(None, nr, None, None, 25)
    except:
        print("Unexpected error...")

    RevertToSelf()

Body:
win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive,
    networkPath, None, user, password)

Drive is the local drive you want to map the network drive to, e.g. X:\

For networkpath add \\ in the beginning of the path, e.g. \\\\networkpath02 if you can access the path with \\networkpath02 in explorer.


问:
why call the method first will disconnect automatically after discovery
I am a newer for RxJava, and when i read the demo of rxandroidble library, I am wondering  why the first can disconnect the ble.</p>

```<code>@OnClick(R.id.connect)
    public void onConnectToggleClick() {
        bleDevice.establishConnection(false)
                .flatMap(RxBleConnection::discoverServices)
                .first() // Disconnect automatically after discovery
                .compose(bindUntilEvent(PAUSE))
                .observeOn(AndroidSchedulers.mainThread())
                .doOnUnsubscribe(this::updateUI)
                .subscribe(adapter::swapScanResult, this::onConnectionFailure);

        updateUI();
    }
</code>```

答:
The RxAndroidBle Observable behaviour of establishConnection() states, that only a single value is emitted, while the stream is not completed. It's also stated that unsubscribing the observable disconnects the connection.

Whenever you are no longer interested in keeping the connection open you should unsubscribe from it which will cause disconnection and cleanup of resources.

But the first() operator emits a single value and completes the stream after. Since bindUntilEvent(PAUSE) will also complete the stream when pausing, you don't need to use first() at all. So just remove it and everything should be fine.

Body:
I am a newer for RxJava, and when i read the demo of rxandroidble library, I am wondering  why the first can disconnect the ble.

@OnClick(R.id.connect)
    public void onConnectToggleClick() {
        bleDevice.establishConnection(false)
                .flatMap(RxBleConnection::discoverServices)
                .first() // Disconnect automatically after discovery
                .compose(bindUntilEvent(PAUSE))
                .observeOn(AndroidSchedulers.mainThread())
                .doOnUnsubscribe(this::updateUI)
                .subscribe(adapter::swapScanResult, this::onConnectionFailure);

        updateUI();
    }


问:
How can i get the DD/MM/YYYY formar in my datepicker?
im from spain and i need to put the DD/MM/YYYY format in my datepicker, here is the code

Inicio de castigo

  <input type='text' id="from" name="from" class="form-control" readonly />

Final de castigo

  <input type='text' name="to" id="to" class="form-control" readonly />

```
</div>
</div>
</p>

<p>I put in the script the MM-DD-YYYY fromat but when i pick the calendar he gives me the MM-DD-YYYY format, that is the uk hour. Today is 07 of June of 2017, and when i open it, it says that is 6 of July 2017. How can i solve that? It can be a problem of the datetimepicker.es.js files? . Thanks for the help guys :)</p>

<p>I have more information in that file, there are all the scripts i use</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="<?=$base_url?>js/es-ES.js"></script>
<script src="<?=$base_url?>js/jquery.min.js"></script>
<script src="<?=$base_url?>js/moment.js"></script>
<script src="<?=$base_url?>js/bootstrap.min.js"></script>
<script src="<?=$base_url?>js/bootstrap-datetimepicker.js"></script>
<link rel="stylesheet" href="<?=$base_url?>css/bootstrap-datetimepicker.min.css" />
<script src="<?=$base_url?>js/bootstrap-datetimepicker.es.js"></script></code>```

答:
Change  format: 'DD-MM-YYYY' To format: 'DD/MM/YYYY':</p>

```<code> <script type="text/javascript">
        $(function () {
            $('#from').datetimepicker({

               format: 'DD/MM/YYYY',
                maxViewMode: 0,
                language: 'es',
                daysOfWeekDisabled: '0,6',
                todayHighlight: true,
                minDate: new Date(1, 1, 2017),
                pickTime: false

            });
            $('#to').datetimepicker({

                format: 'DD/MM/YYYY',
                maxViewMode: 0,
                language: 'es',
                daysOfWeekDisabled: '0,6',
                todayHighlight: true,
                minDate: new Date(1, 1, 2017),
                pickTime: false
            });

        });

    </script>
</code>```

Body:
im from spain and i need to put the DD/MM/YYYY format in my datepicker, here is the code

Inicio de castigo

  <input type='text' id="from" name="from" class="form-control" readonly />

Final de castigo

  <input type='text' name="to" id="to" class="form-control" readonly />

I put in the script the MM-DD-YYYY fromat but when i pick the calendar he gives me the MM-DD-YYYY format, that is the uk hour. Today is 07 of June of 2017, and when i open it, it says that is 6 of July 2017. How can i solve that? It can be a problem of the datetimepicker.es.js files? . Thanks for the help guys :)

I have more information in that file, there are all the scripts i use

<link rel="stylesheet" href="<?=$base_url?>css/bootstrap-datetimepicker.min.css" />

Body:
Change  format: 'DD-MM-YYYY' To format: 'DD/MM/YYYY':

 <script type="text/javascript">
        $(function () {
            $('#from').datetimepicker({

               format: 'DD/MM/YYYY',
                maxViewMode: 0,
                language: 'es',
                daysOfWeekDisabled: '0,6',
                todayHighlight: true,
                minDate: new Date(1, 1, 2017),
                pickTime: false

            });
            $('#to').datetimepicker({

                format: 'DD/MM/YYYY',
                maxViewMode: 0,
                language: 'es',
                daysOfWeekDisabled: '0,6',
                todayHighlight: true,
                minDate: new Date(1, 1, 2017),
                pickTime: false
            });

        });

    </script>


问:
Arduino format integer into 4 bytes for send to I2C
I have 2 arduinos that communicate as master / slave using I2C. The slave one have to send to the master one a value that is changing like a rpm value.
This rpm value can be from 0 to 9999 rpm.
I want to send this value from slave to master as 4 bytes message

```<code> Wire.write(rpm); // respond with message of 4 bytes
</code>```

How can i make sure that rpm will be always 4 bytes?

答:
On this link you can check list of arduinos datatypes

https://playground.arduino.cc/Code/DatatypePractices

You may want to use long or unsigned long. Another way is to convert your rpm value to string and filling zeros when needed at left.

```<code>Wire.write(""+rpm);
</code>```

Zero filling example:

```<code>String zeros = "";
if(rpm < 1000)
    zeros += "0";
if(rpm < 100)
    zeros += "0";
if(rpm < 10)
    zeros += "0";

Wire.write(zeros + rpm);
</code>```

Body:
I have 2 arduinos that communicate as master / slave using I2C. The slave one have to send to the master one a value that is changing like a rpm value.
This rpm value can be from 0 to 9999 rpm.
I want to send this value from slave to master as 4 bytes message

 Wire.write(rpm); // respond with message of 4 bytes

How can i make sure that rpm will be always 4 bytes?

Body:
On this link you can check list of arduinos datatypes

https://playground.arduino.cc/Code/DatatypePractices

You may want to use long or unsigned long. Another way is to convert your rpm value to string and filling zeros when needed at left.

Wire.write(""+rpm);

Zero filling example:

String zeros = "";
if(rpm < 1000)
    zeros += "0";
if(rpm < 100)
    zeros += "0";
if(rpm < 10)
    zeros += "0";

Wire.write(zeros + rpm);


问:
Dim declaration with assignment and Option Strict
I have run into an issue with my code, as follows:

```<code>Option Explicit Off

Option Strict On 'Results in Compiler Error. Expected base or compare or explicit or private

Sub DoSomething()

     Dim intOne As Integer 'This line works

     intOne = 1 'This line works

     Dim intTwo as Integer = 2 'Results in Compiler Error: Expected end of statement

End Sub
</code>```

My issues are written as comments in the code above.

Even with a completely empty module, I am unable to enable the Option Strict option.

I think the solution is somewhere in Visual Studio's options.

Note: I have manually translated the error messages from German, so please expect a difference between the above and the official English versions.

答:
Option Explicit and Option Strict must be set at the very top, followed by any Imports followed by the class itself followed by the methods:

```<code>Option Explicit On
Option Strict On

Imports System.Net

Public Class Class1

    Private Sub DoSomething()
         Dim intOne As Integer
         intOne = 1

         Dim intTwo as Integer = 2
    End Sub

End Class
</code>```

This is the same for modules:

```<code>Option Explicit On
Option Strict On

Imports System.Net

Module Module1

    Public Sub DoSomething()

        Dim intOne As Integer
        intOne = 1

        Dim intTwo As Integer = 2
    End Sub

End Module
</code>```

If you want to turn these options on or off for the entire project you can do so in the project properties:

Note that the settings in individual files (if any) will take precedence over the default settings set within the project properties.

Have a look at the documentation for more information on setting Option Explicit and Option  Strict.

Body:
I have run into an issue with my code, as follows:

Option Explicit Off

Option Strict On 'Results in Compiler Error. Expected base or compare or explicit or private

Sub DoSomething()

     Dim intOne As Integer 'This line works

     intOne = 1 'This line works

     Dim intTwo as Integer = 2 'Results in Compiler Error: Expected end of statement

End Sub

My issues are written as comments in the code above.

Even with a completely empty module, I am unable to enable the Option Strict option.

I think the solution is somewhere in Visual Studio's options.

Note: I have manually translated the error messages from German, so please expect a difference between the above and the official English versions.

Body:
Option Explicit and Option Strict must be set at the very top, followed by any Imports followed by the class itself followed by the methods:

Option Explicit On
Option Strict On

Imports System.Net

Public Class Class1

    Private Sub DoSomething()
         Dim intOne As Integer
         intOne = 1

         Dim intTwo as Integer = 2
    End Sub

End Class

This is the same for modules:

Option Explicit On
Option Strict On

Imports System.Net

Module Module1

    Public Sub DoSomething()

        Dim intOne As Integer
        intOne = 1

        Dim intTwo As Integer = 2
    End Sub

End Module

If you want to turn these options on or off for the entire project you can do so in the project properties:

Note that the settings in individual files (if any) will take precedence over the default settings set within the project properties.

Have a look at the documentation for more information on setting Option Explicit and Option  Strict.


问:
ORACLE "before update" trigger does not fire when column is changed within another trigger
I am using ORACLE 12c.

On a table I have 2 triggers, both "before update".
One of the triggers fires while updating a column and within this trigger another column gets a new value. The second trigger should fire while updating this second column. But he did not.

```<code>create table TRIGGER_TEST
(
    col1 varchar2(64),
    col2 varchar2(64),
    col3 varchar2(64)
);

create or replace trigger TR_TRIGGER_TEST_1
before update of COL1 on TRIGGER_TEST
for each row
begin
    dbms_output.put_line('here we are in TR_TRIGGER_TEST_1');
    :new.col2 := 'only testing';
end;
/

create or replace trigger TR_TRIGGER_TEST_2
before update of COL2 on TRIGGER_TEST
for each row
begin
    dbms_output.put_line('here we are in TR_TRIGGER_TEST_2');
    :new.col3 := 'trigger_test_2 has fired';
end;
/

insert into TRIGGER_TEST values ('1_col1','1_col2','1_col3');
select * from TRIGGER_TEST;

COL1                 COL2              COL3
----------------------------------------------------------------
1_col1               1_col2            1_col3
</code>```

After I have inserted the row I perform an UPDATE. And I expect COL1=
"now we will see", COL2="only testing" and COL3 = "trigger_test_2 has fired".

```<code>update TRIGGER_TEST set COL1 = 'now we will see';
</code>```

But what I get is this:

```<code>select * from TRIGGER_TEST;

COL1                 COL2              COL3
----------------------------------------------------------------
now we will see      only testing      1_col3
</code>```

Can anybody explain this to me? I am really sure, that with former ORACLE versions this szenario has worked. But now it does not.

答:
I am really sure, that with former ORACLE versions this szenario has worked.

It has not. I ran your code in 11gR2 and got the same result:

```<code>set serveroutput on

update TRIGGER_TEST set COL1 = 'now we will see';

here we are in TR_TRIGGER_TEST_1

1 row updated.

select * from TRIGGER_TEST;

COL1                           COL2                           COL3
------------------------------ ------------------------------ ------------------------------
now we will see                only testing                   1_col3
</code>```

The before update of COL2 on TRIGGER_TEST is a DML event clause. You are creating simple DML triggers:

A DML trigger is created on either a table or view, and its triggering event is composed of the DML statements DELETE, INSERT, and UPDATE. ...

When you issue your update that DML causes the first trigger to fire. But when you assign a new value inside that trigger:

```<code>    :new.col2 := 'only testing';
</code>```

.. that is not a DML statement - it is not a separate update.

If assigning a value in that way did cause a trigger to fire, then if you instead did:

```<code>    :new.col1 := 'something';
</code>```

... then that first trigger would fire again, recursively, until you hit the error ORA-00036: maximum number of recursive SQL levels (50) exceeded. That would obviously be bad.

You will have to repeat the assignment of col3 in the first trigger if that is what you need to happen. For more complicated side-effects that you want to happen whether you hit either trigger, you could have a procedure that does any necessary actions (that don't affect this table), and then call that from both triggers. Although then you'd need a mechanism to make sure the procedure isn't called twice if a DML update touches both columns - which would cause both triggers to fire.

Body:
I am using ORACLE 12c.

On a table I have 2 triggers, both "before update".
One of the triggers fires while updating a column and within this trigger another column gets a new value. The second trigger should fire while updating this second column. But he did not.

create table TRIGGER_TEST
(
    col1 varchar2(64),
    col2 varchar2(64),
    col3 varchar2(64)
);

create or replace trigger TR_TRIGGER_TEST_1
before update of COL1 on TRIGGER_TEST
for each row
begin
    dbms_output.put_line('here we are in TR_TRIGGER_TEST_1');
    :new.col2 := 'only testing';
end;
/

create or replace trigger TR_TRIGGER_TEST_2
before update of COL2 on TRIGGER_TEST
for each row
begin
    dbms_output.put_line('here we are in TR_TRIGGER_TEST_2');
    :new.col3 := 'trigger_test_2 has fired';
end;
/

insert into TRIGGER_TEST values ('1_col1','1_col2','1_col3');
select * from TRIGGER_TEST;

COL1                 COL2              COL3
----------------------------------------------------------------
1_col1               1_col2            1_col3

After I have inserted the row I perform an UPDATE. And I expect COL1=
"now we will see", COL2="only testing" and COL3 = "trigger_test_2 has fired".

update TRIGGER_TEST set COL1 = 'now we will see';

But what I get is this:

select * from TRIGGER_TEST;

COL1                 COL2              COL3
----------------------------------------------------------------
now we will see      only testing      1_col3

Can anybody explain this to me? I am really sure, that with former ORACLE versions this szenario has worked. But now it does not.

Body:
I am really sure, that with former ORACLE versions this szenario has worked.

It has not. I ran your code in 11gR2 and got the same result:

set serveroutput on

update TRIGGER_TEST set COL1 = 'now we will see';

here we are in TR_TRIGGER_TEST_1

1 row updated.

select * from TRIGGER_TEST;

COL1                           COL2                           COL3
------------------------------ ------------------------------ ------------------------------
now we will see                only testing                   1_col3

The before update of COL2 on TRIGGER_TEST is a DML event clause. You are creating simple DML triggers:

A DML trigger is created on either a table or view, and its triggering event is composed of the DML statements DELETE, INSERT, and UPDATE. ...

When you issue your update that DML causes the first trigger to fire. But when you assign a new value inside that trigger:

    :new.col2 := 'only testing';

.. that is not a DML statement - it is not a separate update.

If assigning a value in that way did cause a trigger to fire, then if you instead did:

    :new.col1 := 'something';

... then that first trigger would fire again, recursively, until you hit the error ORA-00036: maximum number of recursive SQL levels (50) exceeded. That would obviously be bad.

You will have to repeat the assignment of col3 in the first trigger if that is what you need to happen. For more complicated side-effects that you want to happen whether you hit either trigger, you could have a procedure that does any necessary actions (that don't affect this table), and then call that from both triggers. Although then you'd need a mechanism to make sure the procedure isn't called twice if a DML update touches both columns - which would cause both triggers to fire.


问:
React display line breaks from saved textarea
Using Facebook React.
In a settings page, I have a multiline textarea where a user can enter multiline text (in my case, an address).

```<code><textarea value={address} />
</code>```

When I try to display the address, so something like {address}, it doesn't show the line breaks and is all on one line.

```<code><p>{address}</p>
</code>```

Any ideas how to solve this?

答:
There's no reason to use JS. You can easily tell the browser how to handle newline using the white-space CSS property:

```<code>white-space: pre-line;
</code>```

pre-line

Sequences of whitespace are collapsed. Lines are broken at
newline characters, at
, and as necessary to fill line boxes.

Check out this demo:

<textarea id="textarea"></textarea>

```

Body:
Using Facebook React.
In a settings page, I have a multiline textarea where a user can enter multiline text (in my case, an address).

<textarea value={address} />

When I try to display the address, so something like {address}, it doesn't show the line breaks and is all on one line.

{address}

Any ideas how to solve this?

Body:
There's no reason to use JS. You can easily tell the browser how to handle newline using the white-space CSS property:

white-space: pre-line;

pre-line

Sequences of whitespace are collapsed. Lines are broken at
newline characters, at <br>, and as necessary to fill line boxes.

Check out this demo:

<style>
  #p_wrap {
    white-space: pre-line;
  }
</style>

<textarea id="textarea"></textarea>
<p id="p_standard"></p>
<hr>
<p id="p_wrap"></p>
<script>
  textarea.addEventListener('keypress', function(e) {
    p_standard.textContent = e.target.value
    p_wrap.textContent = e.target.value
  })
</script>

ContentLicense: CC BY-SA 4.0


问:
Symfony3 change form field type in the controller
I have a form builder which builds a form

```<code>public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->
        add('typeTask',TextType::class,array('label'=>"Вид заявка"))->
        add('description',TextareaType::class,array('label'=>"Описание"))->
        add('term',DateType::class, array(
            'widget' => 'choice',
            'label'=>"Краен срок"
        ))->
        add('designer',TextareaType::class,array('label'=>"Дизайнер",
            "required"=>false))->
        add('executioner',TextareaType::class,array('label'=>"Под изпълнител",
            "required"=>false))->
        add("file",TextType::class,array('label'=>"Файл",
            "required"=>false))->
        add("ergent",CheckboxType::class,array('label'=>"Спешно",
            "required"=>false))->add("approved",HiddenType::class,array(
            "required"=>false
        ))->add("rejected",HiddenType::class,array(
            'required'=>false
        ));
    }
</code>```

As you see I have 2 fields which are "approved" which can be true or false and rejected which can also be true and false. Usually they are hidden because only 1 type of user can access them - ROLE_ADMIN and the rest is for ROLE_EDITOR.  In my case the ADMIN needs to only approve or reject it and the EDITOR can't do that. The biggest issue is that I don't need a whole form, but rather 2 buttons -  "Approve" and "Reject" when the Project is shown ("show" action), but the action which changes the Project is "edit" and so what I tried so far is from "show" to send a form to "edit" and then when the edit action is over to load the "show" action again.I tried achieving this by creating 2 forms - approveForm and rejectForm which can hold only 1 property each and send and flush them to "edit" function, but the edit function doesn't accept the form and also if it did it would have deleted everything else. Here is my code so far

In show action -

```<code>$projectFormApprove = $this->createForm('AppBundle\Form\ProjectType', $project,array(
            "method"=>"post"
        ));
        $projectFormApprove->remove("description");
        $projectFormApprove->remove("designer");
        $projectFormApprove->remove("executioner");
        $projectFormApprove->remove("term");
        $projectFormApprove->remove("typeTask");
        $projectFormApprove->remove("file");
        $projectFormApprove->remove("ergent");
        $projectFormApprove->remove("approved");
        $projectFormApprove->remove("rejected");
        $projectFormApprove->add("approved",HiddenType::class,array(
            "data"=>true
        ));
        $projectFormReject = $projectFormApprove;
        $projectFormReject->remove("approved");
        $projectFormReject->add("rejected",HiddenType::class,array(
            'data'=>true
        ));
</code>```

This will create 2 forms each having 1 property and here is what happens in my twig template

```<code>  <tr>
        <td>
           {{ form_start(approveForm, {'action': path('project_edit', { 'id': project.id })}) }}
           {{ form_widget(approveForm) }}
               <input type="submit" value="Approve" />
           {{ form_end(approveForm) }}
        </td>
   </tr>
   <tr>
       <td>
        {{ form_start(rejectedForm,{'action': path('project_edit', { 'id': project.id })}) }}
               {{ form_widget(rejectedForm) }}
                 <input type="submit" value="Reject" />
               {{ form_end(rejectedForm) }}
           </td>
       </tr>
</code>```

I need two forms since there are 2 buttons which simply submit them and no one actually changes the value ( this is the reason why in "show" function the created property have "data"=>true. If the form is submitted it will do it automatically.
Here is what is in my "edit" function -

```<code>/** @var  $user User */
        $user = $this->getUser();
        $project = new Project();
        $form = $this->createForm('AppBundle\Form\ProjectType', $project);
        if($user->getType() != "LittleBoss"){
            $form->remove("designer");
            $form->remove("executioner");
        }
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
        $project->setFromUser($user->getUsername());
        $project->setDepartment($user->getDepartment());
        $project->setIsOver(false);
        $project->setDate(new \DateTime());
        $project->setSeenByDesigner(false);
        $project->setSeenByExecutioner(false);
        $project->setSeenByLittleBoss(false);
        $project->setSeenByManager(false);
            $em = $this->getDoctrine()->getManager();
            $em->persist($project);
            $em->flush();

            return $this->redirectToRoute('project_show', array('id' => $project->getId()));
        }

        return $this->render('project/new.html.twig', array(
            'project' => $project,
            'form' => $form->createView(),
        ));
</code>```

Now to my actual problem - As you see I first remove "approved" field and then I add new one with predefined value. What I want is to change not the values, but the type  of description and the rest fields. Is there a way to say $form->change();  or anything that can change the types of the fields without having to remove them. The type I want them to be is HiddenType and set their data so that when I submit one of the 2 forms it will be accepted as valid in the "edit" action then flushed to the database and everything will be fine. So far when one of the buttons - "Approve" or "Reject" is clicked in the "edit" action  $edit_form->IsSubmited() returns false.

答:
I suggest you to create seperate forms, one for editor and another for admin. Then in controller use the form you need by permissions of the logged in user.

```<code>if ($this->authorizationChecker->isGranted('ROLE_EDITOR')) {
     $form = $this->createForm(EditorType::class);
} elseif ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
     $form = $this->createForm(AdminType::class);
}

$form->handleRequest($request);
</code>```

In both forms you can use same entity, but different fields.

Body:
I have a form builder which builds a form

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->
        add('typeTask',TextType::class,array('label'=>"Вид заявка"))->
        add('description',TextareaType::class,array('label'=>"Описание"))->
        add('term',DateType::class, array(
            'widget' => 'choice',
            'label'=>"Краен срок"
        ))->
        add('designer',TextareaType::class,array('label'=>"Дизайнер",
            "required"=>false))->
        add('executioner',TextareaType::class,array('label'=>"Под изпълнител",
            "required"=>false))->
        add("file",TextType::class,array('label'=>"Файл",
            "required"=>false))->
        add("ergent",CheckboxType::class,array('label'=>"Спешно",
            "required"=>false))->add("approved",HiddenType::class,array(
            "required"=>false
        ))->add("rejected",HiddenType::class,array(
            'required'=>false
        ));
    }

As you see I have 2 fields which are "approved" which can be true or false and rejected which can also be true and false. Usually they are hidden because only 1 type of user can access them - ROLE_ADMIN and the rest is for ROLE_EDITOR.  In my case the ADMIN needs to only approve or reject it and the EDITOR can't do that. The biggest issue is that I don't need a whole form, but rather 2 buttons -  "Approve" and "Reject" when the Project is shown ("show" action), but the action which changes the Project is "edit" and so what I tried so far is from "show" to send a form to "edit" and then when the edit action is over to load the "show" action again.I tried achieving this by creating 2 forms - approveForm and rejectForm which can hold only 1 property each and send and flush them to "edit" function, but the edit function doesn't accept the form and also if it did it would have deleted everything else. Here is my code so far

In show action -

$projectFormApprove = $this->createForm('AppBundle\Form\ProjectType', $project,array(
            "method"=>"post"
        ));
        $projectFormApprove->remove("description");
        $projectFormApprove->remove("designer");
        $projectFormApprove->remove("executioner");
        $projectFormApprove->remove("term");
        $projectFormApprove->remove("typeTask");
        $projectFormApprove->remove("file");
        $projectFormApprove->remove("ergent");
        $projectFormApprove->remove("approved");
        $projectFormApprove->remove("rejected");
        $projectFormApprove->add("approved",HiddenType::class,array(
            "data"=>true
        ));
        $projectFormReject = $projectFormApprove;
        $projectFormReject->remove("approved");
        $projectFormReject->add("rejected",HiddenType::class,array(
            'data'=>true
        ));

This will create 2 forms each having 1 property and here is what happens in my twig template

           {{ form_start(approveForm, {'action': path('project_edit', { 'id': project.id })}) }}
           {{ form_widget(approveForm) }}
               <input type="submit" value="Approve" />
           {{ form_end(approveForm) }}

        {{ form_start(rejectedForm,{'action': path('project_edit', { 'id': project.id })}) }}
               {{ form_widget(rejectedForm) }}
                 <input type="submit" value="Reject" />
               {{ form_end(rejectedForm) }}

I need two forms since there are 2 buttons which simply submit them and no one actually changes the value ( this is the reason why in "show" function the created property have "data"=>true. If the form is submitted it will do it automatically.
Here is what is in my "edit" function -

/** @var  $user User */
        $user = $this->getUser();
        $project = new Project();
        $form = $this->createForm('AppBundle\Form\ProjectType', $project);
        if($user->getType() != "LittleBoss"){
            $form->remove("designer");
            $form->remove("executioner");
        }
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
        $project->setFromUser($user->getUsername());
        $project->setDepartment($user->getDepartment());
        $project->setIsOver(false);
        $project->setDate(new \DateTime());
        $project->setSeenByDesigner(false);
        $project->setSeenByExecutioner(false);
        $project->setSeenByLittleBoss(false);
        $project->setSeenByManager(false);
            $em = $this->getDoctrine()->getManager();
            $em->persist($project);
            $em->flush();

            return $this->redirectToRoute('project_show', array('id' => $project->getId()));
        }

        return $this->render('project/new.html.twig', array(
            'project' => $project,
            'form' => $form->createView(),
        ));

Now to my actual problem - As you see I first remove "approved" field and then I add new one with predefined value. What I want is to change not the values, but the type  of description and the rest fields. Is there a way to say $form->change();  or anything that can change the types of the fields without having to remove them. The type I want them to be is HiddenType and set their data so that when I submit one of the 2 forms it will be accepted as valid in the "edit" action then flushed to the database and everything will be fine. So far when one of the buttons - "Approve" or "Reject" is clicked in the "edit" action  $edit_form->IsSubmited() returns false.

Body:
I suggest you to create seperate forms, one for editor and another for admin. Then in controller use the form you need by permissions of the logged in user.

if ($this->authorizationChecker->isGranted('ROLE_EDITOR')) {
     $form = $this->createForm(EditorType::class);
} elseif ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
     $form = $this->createForm(AdminType::class);
}

$form->handleRequest($request);

In both forms you can use same entity, but different fields.


问:
Need some help understanding private / protected / public inheritance
Currently, I am learning OOP, and I've tried many inheritance examples. I just tested this code:

```<code>#include <iostream>
using namespace std;

class B
{
    int a;
protected:
    B(int i=0)
    {
        a=i;
    }

    int get_b()
    {
        return a;
    }
};

class D: private B
{
public:
    D(int x=0): B(x) {}

    int get_a()
    {
        return get_b();
    }
};

int main()
{
    D d(-89);
    cout << d.get_a();
    return 0;
}
</code>```

Why does this work? Why can I use the get_b() function? Why does the constructor B(x) work? Why doesn't it work if I change protected to private then?

Later Edit : By using the protected keyword on the constructor and function get_b() means that derived classes have acces to them if the inheritance is public. However, in this case by using private inheritance I would expect that the constructor and the get_b() function would be inaccesible from class D.

答:
Private/protected/public inheritance is all about deciding who is aware of the inheritance. In public inheritance, all outside code is aware of it. In protected inheritance, only the children are aware. In private, only the inheriting class is aware. On top of that, the same keywords apply on members, but are not affected by the inheritance visibility. If the class is aware of the inheritance, a member is visible as usual. If it is not aware of the inheritance, it is even less aware of members, be them public, private or protected.

To answer your specific question, if you created a class E inheriting (publicly) your class D, you wouldn't be able to call get_b, but you could still call get_a

Body:
Currently, I am learning OOP, and I've tried many inheritance examples. I just tested this code:

#include <iostream>
using namespace std;

class B
{
    int a;
protected:
    B(int i=0)
    {
        a=i;
    }

    int get_b()
    {
        return a;
    }
};

class D: private B
{
public:
    D(int x=0): B(x) {}

    int get_a()
    {
        return get_b();
    }
};

int main()
{
    D d(-89);
    cout << d.get_a();
    return 0;
}

Why does this work? Why can I use the get_b() function? Why does the constructor B(x) work? Why doesn't it work if I change protected to private then?

Later Edit : By using the protected keyword on the constructor and function get_b() means that derived classes have acces to them if the inheritance is public. However, in this case by using private inheritance I would expect that the constructor and the get_b() function would be inaccesible from class D.


问:
Why jQuery does not work in nested Ajax functions?
While calling nested Ajax, which innermost ajax doesn't work. As seen in the following example, I 'm calling getInnerResp into getResult.

Normally, when I debug with firebug is works interestingly. I think it behaves as async false but I setted async property as false didn't work again. Furthermore, I tried to get result set using callback function in getInnerResp function. Unfortunately I didn't succeed in any way. Also ftbl variable in getResult function returns null. getInnerResp only returns followed result;

Result

```<code><tr><td colspan='3'></td></tr><tr><td colspan='3'></td></tr><tr><td colspan='3'></td></tr><tr><td colspan='3'></td></tr>
</code>```

Javascript

```<code>function getResult(year){

    var visible  = true;
    var table    = $(".tbl"), tbody = $(".result").find("tbody"), ftbl = "";

    table.find("tbody>tr").each(function(){
        var data = {
            course : $(this).find(".course").val(),
            year   : year,
            prog   : $(this).find(".program").val()
        }

        if(year.length < 1){
          alert("Year field can not be empty!!");
          visible = false;
          return false;
        }

        $.ajax({
            url : "result.php",
            method : "GET",
            data : data,
            contentType: "application/json; charset=utf-8",
            traditional : true,
            success : function(d){
                tbody.append("<tr><td>" + course + "</td><td>" + d.enrolledStudent + "</td><td>" + d.failedStudent + "</td>");
                if(visible){
                    ftbl += getInnerResp(course, year);
                    console.log("inner" + ftbl);
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown){
                alert("Javascript runtime error: " + textStatus);
            }
        });
    });

    if(visible){
        tbody.append(ftbl);
    }
}

function getInnerResp(course, year){

    var tbl = "";

    var data = {
        course : course,
        year   : year
    }

    for(var i = 0; i < 5; i++){
        tbl += "<tr><td colspan='3'></td></tr>";
    }

    $.ajax({
        url : "course.php",
        method : "GET",
        data : data,
        contentType: "application/json; charset=utf-8",
        success : function(json){
            $.each(json, function(i, val){
                tbl += "<tr><td>" + course + "</td><td colspan='2'>" + val + "</td></tr>";
            });
        },
        error : function(XMLHttpRequest, textStatus, errorThrown){
            alert(textStatus);
        }
    });

    return tbl;
}
</code>```

答: In getResult function ajax success callback, 'course' variable is being used but it was not defined anywhere. It might be causing exception, which makes script execution to stop before calling getInnerResp.</p>

Body:
While calling nested Ajax, which innermost ajax doesn't work. As seen in the following example, I 'm calling getInnerResp into getResult.

Normally, when I debug with firebug is works interestingly. I think it behaves as async false but I setted async property as false didn't work again. Furthermore, I tried to get result set using callback function in getInnerResp function. Unfortunately I didn't succeed in any way. Also ftbl variable in getResult function returns null. getInnerResp only returns followed result;

Result

Javascript

function getResult(year){

    var visible  = true;
    var table    = $(".tbl"), tbody = $(".result").find("tbody"), ftbl = "";

    table.find("tbody>tr").each(function(){
        var data = {
            course : $(this).find(".course").val(),
            year   : year,
            prog   : $(this).find(".program").val()
        }

        if(year.length < 1){
          alert("Year field can not be empty!!");
          visible = false;
          return false;
        }

        $.ajax({
            url : "result.php",
            method : "GET",
            data : data,
            contentType: "application/json; charset=utf-8",
            traditional : true,
            success : function(d){
                tbody.append("
" + course + "	" + d.enrolledStudent + "	" + d.failedStudent + "	");
                if(visible){
                    ftbl += getInnerResp(course, year);
                    console.log("inner" + ftbl);
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown){
                alert("Javascript runtime error: " + textStatus);
            }
        });
    });

    if(visible){
        tbody.append(ftbl);
    }
}

function getInnerResp(course, year){

    var tbl = "";

    var data = {
        course : course,
        year   : year
    }

    for(var i = 0; i < 5; i++){
        tbl += "

";
    }

    $.ajax({
        url : "course.php",
        method : "GET",
        data : data,
        contentType: "application/json; charset=utf-8",
        success : function(json){
            $.each(json, function(i, val){
                tbl += "
" + course + "	" + val + "
";
            });
        },
        error : function(XMLHttpRequest, textStatus, errorThrown){
            alert(textStatus);
        }
    });

    return tbl;
}


问:
How to create Kafka consumer groups?
I'm new to Kafka.  I'm trying to implement a simple queueing system using 1 topic and 1 consumer group assigned to that topic.  However I couldn't figure out how to create a consumer group.

p.s. I'm using Ruby, with the kafka-rb gem.

Thanks!
Eric

答:
Update: we (Zendesk) have since released Racecar, a simplified Kafka consumer framework built on top of ruby-kafka.

A Racecar consumer would look like this:

```<code># simple_consumer.rb
class SimpleConsumer < Racecar::Consumer
  subscribes_to "some-topic"

  def process(message)
    puts message.value
  end
end
</code>```

In order to run it, simply execute the following:

```<code>$ gem install racecar
$ racecar --require my_consumer MyConsumer
</code>```

Read more on Github: https://github.com/zendesk/racecar

Original post:

Here's how you'd do it in ruby-kafka:

```<code>require "kafka"

kafka = Kafka.new(seed_brokers: ["kafka1", "kafka2"])
consumer = kafka.consumer(group_id: "my-group")

consumer.subscribe("my-topic")

consumer.each_message do |message|
  puts message.value
end
</code>```

See also the README for more information.

Title: How to create Kafka consumer groups?

Body:
Update: we (Zendesk) have since released Racecar, a simplified Kafka consumer framework built on top of ruby-kafka.

A Racecar consumer would look like this:

# simple_consumer.rb
class SimpleConsumer < Racecar::Consumer
  subscribes_to "some-topic"

  def process(message)
    puts message.value
  end
end

In order to run it, simply execute the following:

$ gem install racecar
$ racecar --require my_consumer MyConsumer

Read more on Github: https://github.com/zendesk/racecar

Original post:

Here's how you'd do it in ruby-kafka:

require "kafka"

kafka = Kafka.new(seed_brokers: ["kafka1", "kafka2"])
consumer = kafka.consumer(group_id: "my-group")

consumer.subscribe("my-topic")

consumer.each_message do |message|
  puts message.value
end

See also the README for more information.


问:
MySQL how to implement condition in virtual field definition
I'm using the PHP function below to calculate checksums for strings in PHP. The xor is required to produce the same value on 32 and 64 bit php platforms.

I would like to create a virtual field in MySQL select queries that will have the same value.
SELECT ABS(CRC32(ui_data)) As checksum FROM user_data works but I don't know how to implement the if part in a SELECT statement to make it fully compatible to the PHP function.

10X

```<code>function checksum ($orig_id) {
    $crc= abs (crc32($orig_id));
    if( $crc & 0x80000000){
      $crc ^= 0xffffffff;
      $crc += 1;
     }
    return $crc;
}
</code>```

答:
```<code>SELECT IF(@crc & 0x80000000, @crc ^ 0xffffffff, @crc + 1)
FROM (SELECT @crc := ABS(CRC32('your_value'))) v
</code>```

https://dev.mysql.com/doc/refman/5.7/en/bit-functions.html

Body:
I'm using the PHP function below to calculate checksums for strings in PHP. The xor is required to produce the same value on 32 and 64 bit php platforms.

I would like to create a virtual field in MySQL select queries that will have the same value.
SELECT ABS(CRC32(ui_data)) As checksum FROM user_data works but I don't know how to implement the if part in a SELECT statement to make it fully compatible to the PHP function.

10X

function checksum ($orig_id) {
    $crc= abs (crc32($orig_id));
    if( $crc & 0x80000000){
      $crc ^= 0xffffffff;
      $crc += 1;
     }
    return $crc;
}

Body:
SELECT IF(@crc & 0x80000000, @crc ^ 0xffffffff, @crc + 1)
FROM (SELECT @crc := ABS(CRC32('your_value'))) v

https://dev.mysql.com/doc/refman/5.7/en/bit-functions.html


Title: How can i get the DD/MM/YYYY formar in my datepicker?

Body:
im from spain and i need to put the DD/MM/YYYY format in my datepicker, here is the code

Inicio de castigo

  <input type='text' id="from" name="from" class="form-control" readonly />

Final de castigo

  <input type='text' name="to" id="to" class="form-control" readonly />

I put in the script the MM-DD-YYYY fromat but when i pick the calendar he gives me the MM-DD-YYYY format, that is the uk hour. Today is 07 of June of 2017, and when i open it, it says that is 6 of July 2017. How can i solve that? It can be a problem of the datetimepicker.es.js files? . Thanks for the help guys :)

I have more information in that file, there are all the scripts i use

<link rel="stylesheet" href="<?=$base_url?>css/bootstrap-datetimepicker.min.css" />

Body:
<script>
jQuery(document).ready(function () {

    jQuery('.datepicker').datetimepicker({ format: 'DD/MM/YYYY' });
    jQuery('.datetimepicker').datetimepicker();

});
</script>


问:
SQL using TRANSFORM to reformat my table in MS-Access
I need help reformatting my table using TRANSFORM. I've tried a few things but for some reason it just won't work. Here's an example of what I have to do. Say I have this table:

```<code>     table1:

| in/out | year   |
|   in   | 2011-12|
|   in   | 2011-12|
|   in   | 2012-13|
|   out  | 2011-12|
|   out  |2012-13 |
|   out  |2012-13 |
</code>```

I want to reformat this table to look like this:

```<code>|in/out| 2011-12 | 2012-13
|  in  |   2     |   1
|  out |   1     |   2
</code>```

The first column is the in/out and the rest are just the years where the numbers under them is just a count of for example how many ins or outs happened that year. Any help would be greatly appreciated. Thanks in advance.

答:
I found the solution. It's this:</p>

```<code>Transform Count(*)
SELECT [in/out] FROM table1 GROUP BY [in/out]
PIVOT year IN("2011-12", "2012-13");
</code>```

Body:
I need help reformatting my table using TRANSFORM. I've tried a few things but for some reason it just won't work. Here's an example of what I have to do. Say I have this table:

     table1:

| in/out | year   |
|   in   | 2011-12|
|   in   | 2011-12|
|   in   | 2012-13|
|   out  | 2011-12|
|   out  |2012-13 |
|   out  |2012-13 |

I want to reformat this table to look like this:

|in/out| 2011-12 | 2012-13
|  in  |   2     |   1
|  out |   1     |   2

The first column is the in/out and the rest are just the years where the numbers under them is just a count of for example how many ins or outs happened that year. Any help would be greatly appreciated. Thanks in advance.

Body:
I found the solution. It's this:

Transform Count(*)
SELECT [in/out] FROM table1 GROUP BY [in/out]
PIVOT year IN("2011-12", "2012-13");


问:
How do I make Syntastic work with the Dockerfile plugin?
I use the vim plugins Syntastic and Dockerfile.vim.

Syntastic has some checkers now for (lower-case) dockerfile file types, which is a built-in filetype for vim, but with only rudimentary syntax support.  The better support with the Dockerfile.vim plugin sets a file type of (upper-cased) Dockerfile, which isn't detected by Syntastic.

I can locally tweak the Syntastic installation to copy the dockerfile checker directory to Dockerfile, and make a few associated case changes in the checker, but that seems clumsy.

Maybe there's a way to mess with my filetype detection so I simultaneously get the benefit of both plugins?  Maybe Dockerfile.vim should be building on/replacing the dockerfile filetype, and not adding a new Dockerfile?

Any suggestions?

答:
Per lcd047's comment above, Use syntastic_filetype_map:

*'syntastic_filetype_map'* Type: dictionary Default: {} Use this option to map non-standard
  filetypes to standard ones.  Corresponding checkers are mapped
  accordingly, which allows syntastic to check files with non-standard
  filetypes: >
      let g:syntastic_filetype_map = {
          \ "plaintex": "tex",
          \ "gentoo-metadata": "xml" }

So: let g:syntastic_filetype_map = {"Dockerfile": "dockerfile"}


问:
What are some optimization techniques for MySQL table with 300+ million records?
I am looking at storing some JMX data from JVMs on many servers for about 90 days.  This data would be statistics like heap size and thread count.  This will mean that one of the tables will have around 388 million records.

From this data I am building some graphs so you can compare the stats retrieved from the Mbeans.  This means I will be grabbing some data at an interval using timestamps.

So the real question is, Is there anyway to optimize the table or query so you can perform these queries in a reasonable amount of time?

Thanks,

Josh

答:
3 suggestions:

index

index

index

p.s. for timestamps you may run into performance issues -- depending on how MySQL handles DATETIME and TIMESTAMP internally, it may be better to store timestamps as integers. (# secs since 1970 or whatever)

OwnerDisplayName: Josh Harris

OwnerDisplayName: Jason S


问:
NullPointerException in Java with no StackTrace
I've had instances of our Java code catch a NullPointerException, but when I try to log the StackTrace (which basically ends up calling Throwable.printStackTrace() ), all I get is:

```<code>java.lang.NullPointerException
</code>```

Has anyone else come across this? I tried googling for "java null pointer empty stack trace" but didn't come across anything like this.

答:
When you are using AspectJ in your project, it may happen that some aspect hides its portion of the stack trace. For example, today I had:

```<code>java.lang.NullPointerException:
  at com.company.product.MyTest.test(MyTest.java:37)
</code>```

This stack trace was printed when running the test via Maven's surefire.

On the other hand, when running the test in IntelliJ, a different stack trace was printed:

```<code>java.lang.NullPointerException
  at com.company.product.library.ArgumentChecker.nonNull(ArgumentChecker.java:67)
  at ...
  at com.company.product.aspects.CheckArgumentsAspect.wrap(CheckArgumentsAspect.java:82)
  at ...
  at com.company.product.MyTest.test(MyTest.java:37)
</code>```

Body:
I've had instances of our Java code catch a NullPointerException, but when I try to log the StackTrace (which basically ends up calling Throwable.printStackTrace() ), all I get is:

java.lang.NullPointerException

Has anyone else come across this? I tried googling for "java null pointer empty stack trace" but didn't come across anything like this.

Body:
When you are using AspectJ in your project, it may happen that some aspect hides its portion of the stack trace. For example, today I had:

java.lang.NullPointerException:
  at com.company.product.MyTest.test(MyTest.java:37)

This stack trace was printed when running the test via Maven's surefire.

On the other hand, when running the test in IntelliJ, a different stack trace was printed:

java.lang.NullPointerException
  at com.company.product.library.ArgumentChecker.nonNull(ArgumentChecker.java:67)
  at ...
  at com.company.product.aspects.CheckArgumentsAspect.wrap(CheckArgumentsAspect.java:82)
  at ...
  at com.company.product.MyTest.test(MyTest.java:37)


问:
python pandas dataFrame create single json column of multiple columns value
In python pandas dataFrame i wanted create single json column of multiple columns value.

Assuming following dataFrame:

Example:

```<code>| -   | col1 | col2 | col3 | col4|
| 1   | abc  | def  | ghi  |  8  |
| 2   | xab  | xcd  | xef  |  9  |
</code>```

This is the result i want.

```<code>|     |col1 | json_col|br
|1    | abc |   {"col2":"def","col3":"ghi","col4":8}|
|2    | xab |   {"col2":"xcd","col3":"xef","col4":9}|
</code>```

How can i create the single column(json type) of selected columns?

答:
You can use apply with to_json, last remove columns by drop:

```<code>cols = ['col2','col3','col4']
df['json_col'] = df[cols].apply(lambda x: x.to_json(), axis=1)
df = df.drop(cols, axis=1)
print (df)
   - col1                              json_col
0  1  abc  {"col2":"def","col3":"ghi","col4":8}
1  2  xab  {"col2":"xcd","col3":"xef","col4":9}
</code>```

Body:
In python pandas dataFrame i wanted create single json column of multiple columns value.

Assuming following dataFrame:

Example:

| -   | col1 | col2 | col3 | col4|
| 1   | abc  | def  | ghi  |  8  |
| 2   | xab  | xcd  | xef  |  9  |

This is the result i want.

|     |col1 | json_col|br
|1    | abc |   {"col2":"def","col3":"ghi","col4":8}|
|2    | xab |   {"col2":"xcd","col3":"xef","col4":9}|

How can i create the single column(json type) of selected columns?

Body:
You can use apply with to_json, last remove columns by drop:

cols = ['col2','col3','col4']
df['json_col'] = df[cols].apply(lambda x: x.to_json(), axis=1)
df = df.drop(cols, axis=1)
print (df)
   - col1                              json_col
0  1  abc  {"col2":"def","col3":"ghi","col4":8}
1  2  xab  {"col2":"xcd","col3":"xef","col4":9}