问:
Trying to copy all strings from char*[] but get segmentation fault
I am trying to figure out why I am getting a segmentation fault when trying to copy the arguments from one array of strings to another but just leaving out the > </p>

```<code>int main(){
     char *args[] = {"sort", "myshell.c", ">", "2"};
     int size = 4*sizeof(args)/sizeof(args);
     char *temp[size];
     int i;

     printf("SIZE: %d\n", size);
     for(i = 0; i < size; ++i){
            if(strcmp(args[i], ">") > 0 || strcmp(args[i], ">") < 0 ){
                strcpy(temp[i],args[i]);

            }
            printf("arg: %s\n", temp[i]);
     }
</code>```

答:
You are trying to copy data (strings in this case) into the memory pointed by temp[i] - but this pointer is uninitialized and no memory is allocated.
You should allocate memory:

temp[i] = (char )malloc(sizeof(char)(strlen(args[i])+1))

To leave out the ">", you can just test for != 0. You will need a secondary index for the copied strings.

What is the purpose of sizeof(args)/sizeof(args)?
Try:

```<code>int main()
{
     char *args[] = {"sort", "myshell.c", ">", "2"};
     int size = sizeof(args)/sizeof(char *);
     char *temp[size];
     int i, j;

     printf("SIZE: %d\n", size);
     for (j = 0, i = 0; i < size; ++i)
     {
            if (strcmp(args[i], ">") != 0)
            {
                temp[j] = (char *)malloc(sizeof(char)*(strlen(args[i])+1));
                strcpy(temp[j],args[i]);
                printf("arg: %s\n", temp[j]);
                j++;
            }
     }
}
</code>```

Body:
I am trying to figure out why I am getting a segmentation fault when trying to copy the arguments from one array of strings to another but just leaving out the >

int main(){
     char *args[] = {"sort", "myshell.c", ">", "2"};
     int size = 4*sizeof(args)/sizeof(args);
     char *temp[size];
     int i;

     printf("SIZE: %d\n", size);
     for(i = 0; i < size; ++i){
            if(strcmp(args[i], ">") > 0 || strcmp(args[i], ">") < 0 ){
                strcpy(temp[i],args[i]);

            }
            printf("arg: %s\n", temp[i]);
     }

Body:
You are trying to copy data (strings in this case) into the memory pointed by temp[i] - but this pointer is uninitialized and no memory is allocated.
You should allocate memory:

temp[i] = (char )malloc(sizeof(char)(strlen(args[i])+1))

To leave out the ">", you can just test for != 0. You will need a secondary index for the copied strings.

What is the purpose of sizeof(args)/sizeof(args)?
Try:

int main()
{
     char *args[] = {"sort", "myshell.c", ">", "2"};
     int size = sizeof(args)/sizeof(char *);
     char *temp[size];
     int i, j;

     printf("SIZE: %d\n", size);
     for (j = 0, i = 0; i < size; ++i)
     {
            if (strcmp(args[i], ">") != 0)
            {
                temp[j] = (char *)malloc(sizeof(char)*(strlen(args[i])+1));
                strcpy(temp[j],args[i]);
                printf("arg: %s\n", temp[j]);
                j++;
            }
     }
}


来源: stackexchange

问:
Raise event to ListView from List ItemView
I have a custom ItemView that I am trying to implement and I want to raise event back to ListView that is a parent. How do I go about doing that?

For example my ItemView has.  How do I get the ListView owner to invoke event?

```<code>public partial class MyItemView : ContentView, INotifyPropertyChanged
{
}
</code>```

答:
You can get the ListView from the item of ListView by iterating View's parent till we get the ListView.</p>

```<code>public partial class MyItemView : ContentView, INotifyPropertyChanged
{
    ListView listView;

    protected override void LayoutChildren(double x, double y, double width, double height)
    {
        base.LayoutChildren(x, y, width, height);

        Element list = this;

        while(list.GetType() != typeof(ListView))
        {
            list = list.Parent;
        }

        listView = list as ListView;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a custom ItemView that I am trying to implement and I want to raise event back to ListView that is a parent. How do I go about doing that?

For example my ItemView has.  How do I get the ListView owner to invoke event?

public partial class MyItemView : ContentView, INotifyPropertyChanged
{
}

Body:
You can get the ListView from the item of ListView by iterating View's parent till we get the ListView.

public partial class MyItemView : ContentView, INotifyPropertyChanged
{
    ListView listView;

    protected override void LayoutChildren(double x, double y, double width, double height)
    {
        base.LayoutChildren(x, y, width, height);

        Element list = this;

        while(list.GetType() != typeof(ListView))
        {
            list = list.Parent;
        }

        listView = list as ListView;
    }
}


问:
Codename One - test-for-ios-device and test-for-android-device ant tasks
This question is related to the previous ones: Codename One - Test Recorder: execute a test on a real device and Codename One - tests.dat file needed when using build.unitTest=1

My "test-for-ios-device" and "test-for-android-device" ant tasks produces IPAs and APKs that don't run any tests (actually the build server generates a .bin file that I rename to .ipa). Instead my tests work correctly in the Codename One Simulator. The tests are not trivial and all the logs plus one screenshot are sent to me by e-mail automatically during the test (using the Simulator), and I receive the report by e-mail without problems. Instead on real devices nothing happens.

I report the build.xml (I removed some irrilevant tasks in this copy) and the logs of Samsung Galaxy S6 and iPhone8.

```<code><?xml version="1.0" encoding="UTF-8"?>
    <!--build_version=3.7-->
    <!--
    This build script was generated by Codename One to build native mobile applications using Java.
    To learn more about Codename One go to https://www.codenameone.com/
    -->

    <project name="Myapp" default="default" basedir=".">
    <description>Builds, tests, and runs the project Myapp.</description>
    <import file="nbproject/build-impl.xml"/>
    <property file="codenameone_settings.properties"/>
    <property name="automated" value="false" />
    <taskdef name="codeNameOne" classname="com.codename1.build.client.CodeNameOneBuildTask" classpath="CodeNameOneBuildClient.jar"/>
    <taskdef name="prepareTests" classname="com.codename1.build.client.PrepareTestsTask" classpath="CodeNameOneBuildClient.jar"/>
    <taskdef name="installLibs" classname="com.codename1.build.client.InstallLibsTask" classpath="CodeNameOneBuildClient.jar"/>
    <taskdef name="verifyDir" classname="com.codename1.build.client.VerifyDir" classpath="CodeNameOneBuildClient.jar"/>
    <taskdef name="generateGuiSources" classname="com.codename1.build.client.GenerateGuiSources" classpath="CodeNameOneBuildClient.jar"/>
    <taskdef name="initOfflineBuilder" classname="com.codename1.build.client.InitOfflineBuilder" classpath="CodeNameOneBuildClient.jar"/>

    <target depends="init,compile,jar" name="compile-test">
        <mkdir dir="${build.test.classes.dir}" />
        <mkdir dir="${test.src.dir}" />
        <javac destdir="${build.test.classes.dir}"
            encoding="${source.encoding}"
            source="1.8"
            target="1.8"
            bootclasspath="CLDC11.jar" excludes="${excludes}"
            classpath="${javac.classpath}:${build.classes.dir}">
            <src path="${test.src.dir}"/>
        </javac>
        <prepareTests classesDir="${build.classes.dir}" testClassesDir="${build.test.classes.dir}" seJar="JavaSE.jar" metaDataFile="${build.test.classes.dir}/tests.dat" />
        <jar jarfile="dist/unitTests.jar">
            <fileset dir="${build.classes.dir}"/>
            <fileset dir="${build.test.classes.dir}"/>
            <fileset dir="lib/impl/cls"/>
        </jar>
    </target>

    <target depends="compile-test" name="-do-test-run">
        <!-- JavaSE.jar is added here since the test execution might fail otherwise for a pre-existing project -->
        <java classpath="dist/unitTests.jar:${javac.test.classpath}:${file.reference.JavaSE.jar}" classname="com.codename1.impl.javase.TestRunner" fork="true">
            <arg value="${codename1.packageName}.${codename1.mainName}" />
        </java>
    </target>

    <target depends="-do-test-run" description="Run unit tests." name="test"/>

    <target name="-pre-compile">
        <echo>Compile is forcing compliance to the supported API's/features for maximum device compatibility. This allows smaller
        code size and wider device support</echo>
        <mkdir dir="build/tmp"/>
        <javac destdir="build/tmp"
            encoding="${source.encoding}"
            source="1.8"
            target="1.8"
            bootclasspath="lib/CLDC11.jar" excludes="${excludes}"
            classpath="${javac.classpath}:${build.classes.dir}">
            <src path="${src.dir}"/>
        </javac>
    </target>

    <target name="-post-compile">
        <delete>
            <fileset dir="${build.classes.dir}" includes="**/package-info.class"/>
        </delete>
        <delete>
            <fileset dir="${build.classes.dir}" includes="**/package-info.class"/>
        </delete>
        <delete>
            <fileset dir="${build.classes.dir}" includes="**/Thumbs.db"/>
        </delete>
    </target>

    <target name="build-for-ios-device" depends="clean,copy-ios-override,copy-libs,jar,clean-override">
        <codeNameOne
            jarFile="${dist.jar}"
            displayName="${codename1.displayName}"
            packageName = "${codename1.packageName}"
            mainClassName = "${codename1.mainName}"
            version="${codename1.version}"
            icon="${codename1.icon}"
            vendor="${codename1.vendor}"
            subtitle="${codename1.secondaryTitle}"

            targetType="iphone"
            certificate="${codename1.ios.debug.certificate}"
            certPassword="${codename1.ios.debug.certificatePassword}"
            provisioningProfile="${codename1.ios.debug.provision}"
            appid="${codename1.ios.appid}"
            automated="${automated}"
            />
    </target>

    <target name="test-for-ios-device" depends="clean,copy-ios-override,copy-libs,compile-test,clean-override">
        <codeNameOne
            jarFile="dist/unitTests.jar"
            displayName="${codename1.displayName}"
            packageName = "${codename1.packageName}"
            mainClassName = "${codename1.mainName}"
            version="${codename1.version}"
            icon="${codename1.icon}"
            vendor="${codename1.vendor}"
            subtitle="${codename1.secondaryTitle}"
            buildArgs="build.unitTest=1"
            targetType="iphone"
            certificate="${codename1.ios.debug.certificate}"
            certPassword="${codename1.ios.debug.certificatePassword}"
            provisioningProfile="${codename1.ios.debug.provision}"
            appid="${codename1.ios.appid}"
            automated="${automated}"
            />
    </target>

    <target name="test-for-android-device" depends="clean,copy-android-override,copy-libs,compile-test,clean-override">
        <codeNameOne
            jarFile="dist/unitTests.jar"
            displayName="${codename1.displayName}"
            packageName = "${codename1.packageName}"
            mainClassName = "${codename1.mainName}"
            version="${codename1.version}"
            icon="${codename1.icon}"
            vendor="${codename1.vendor}"
            subtitle="${codename1.secondaryTitle}"
            buildArgs="build.unitTest=1"
            targetType="android"
            keystoreAlias="${codename1.android.keystoreAlias}"
            keystore="${codename1.android.keystore}"
            certPassword="${codename1.android.keystorePassword}"
            automated="${automated}"
            />
    </target>

    <target name="build-for-ios-device-release" depends="clean,copy-ios-override,copy-libs,jar,clean-override">
        <codeNameOne
            jarFile="${dist.jar}"
            displayName="${codename1.displayName}"
            packageName = "${codename1.packageName}"
            mainClassName = "${codename1.mainName}"
            version="${codename1.version}"
            icon="${codename1.icon}"
            vendor="${codename1.vendor}"
            subtitle="${codename1.secondaryTitle}"
            appStoreBuild="true"
            production="true"
            targetType="iphone"
            certificate="${codename1.ios.release.certificate}"
            certPassword="${codename1.ios.release.certificatePassword}"
            provisioningProfile="${codename1.ios.release.provision}"
            appid="${codename1.ios.appid}"
            automated="${automated}"
            />
    </target>

    <target name="copy-libs" depends="init">
        <copy todir="${build.classes.dir}">
            <fileset dir="lib/impl/cls" />
        </copy>
    </target>

    <target name="copy-android-override">
        <mkdir dir="${build.classes.dir}" />
        <mkdir dir="override" />
        <copy todir="${build.classes.dir}">
            <fileset dir="override" includes="**/*_android.ovr"/>
            <fileset dir="override" includes="**/*_android-phone.ovr"/>
            <fileset dir="override" includes="**/*_android-tab.ovr"/>
            <fileset dir="override" includes="**/*_phone.ovr"/>
            <fileset dir="override" includes="**/*_tablet.ovr"/>
        </copy>
        <copy todir="${build.classes.dir}">
            <fileset dir="native/android" includes="**/*"/>
            <fileset dir="lib/impl/native/android" includes="**/*"/>
        </copy>
    </target>

    <target name="copy-ios-override">
        <mkdir dir="${build.classes.dir}" />
        <mkdir dir="override" />
        <copy todir="${build.classes.dir}">
            <fileset dir="override" includes="**/*_ios.ovr"/>
            <fileset dir="override" includes="**/*_iphone.ovr"/>
            <fileset dir="override" includes="**/*_ipad.ovr"/>
            <fileset dir="override" includes="**/*_phone.ovr"/>
            <fileset dir="override" includes="**/*_tablet.ovr"/>
        </copy>
        <copy todir="${build.classes.dir}">
            <fileset dir="native/ios" includes="**/*"/>
            <fileset dir="lib/impl/native/ios" includes="**/*"/>
        </copy>
    </target>

    <target name="clean-override">
        <delete>
            <fileset dir="${build.classes.dir}" includes="**/*.ovr"/>
            <fileset dir="${build.classes.dir}" includes="**/*.java"/>
            <fileset dir="${build.classes.dir}" includes="**/*.m"/>
            <fileset dir="${build.classes.dir}" includes="**/*.h"/>
        </delete>
    </target>

    <target name="build-for-android-device" depends="clean,copy-android-override,copy-libs,jar,clean-override">
        <codeNameOne
            jarFile="${dist.jar}"
            displayName="${codename1.displayName}"
            packageName = "${codename1.packageName}"
            mainClassName = "${codename1.mainName}"
            version="${codename1.version}"
            icon="${codename1.icon}"
            vendor="${codename1.vendor}"
            subtitle="${codename1.secondaryTitle}"

            targetType="android"
            keystoreAlias="${codename1.android.keystoreAlias}"
            keystore="${codename1.android.keystore}"
            certPassword="${codename1.android.keystorePassword}"
            automated="${automated}"
            />
    </target>

    <target name="-pre-init">
        <property name="application.args" value="${codename1.packageName}.${codename1.mainName}"/>
        <property name="javac.source" value="1.8" />
        <property name="javac.target" value="1.8" />
        <mkdir dir="native/javase" />
        <mkdir dir="native/android" />
        <mkdir dir="native/internal_tmp" />
        <mkdir dir="native/ios" />
        <mkdir dir="native/j2me" />
        <mkdir dir="native/rim" />
        <mkdir dir="native/win" />
        <mkdir dir="native/javascript" />
        <mkdir dir="lib/impl/cls" />
        <mkdir dir="lib/impl/stubs" />
        <mkdir dir="lib/impl/native" />
        <mkdir dir="lib/impl/native/android" />
        <mkdir dir="lib/impl/native/ios" />
        <mkdir dir="lib/impl/native/j2me" />
        <mkdir dir="lib/impl/native/rim" />
        <mkdir dir="lib/impl/native/win" />
        <mkdir dir="lib/impl/native/javascript" />
        <installLibs lib="lib" dest="lib/impl" />
        <generateGuiSources srcDir="src" encoding="UTF-8" guiDir="res/guibuilder"  />
    </target>

    <target name="-post-jar">
        <mkdir dir="native/javase" />
        <mkdir dir="native/internal_tmp" />
        <mkdir dir="lib/impl/native/javase" />
        <javac destdir="native/internal_tmp"
            encoding="${source.encoding}"
            source="1.8"
            target="1.8"
            bootclasspath="CLDC11.jar" excludes="${excludes}"
            classpath="${javac.classpath}:${build.classes.dir}">
            <src path="native/javase"/>
            <src path="lib/impl/native/javase"/>
        </javac>
    </target>

    <target name="-post-clean" depends="refresh-libs-impl">
    </target>

    <target name="refresh-libs" depends="refresh-libs-impl,jar">
    </target>

    <target name="refresh-libs-impl">
        <delete dir="lib/impl" />
        <installLibs lib="lib" dest="lib/impl" />
    </target>

</project>
</code>```

Samsung Galaxy S6 (only the relevant part of the log):

```<code>-----STARTING TESTS-----
>   12-08 13:19:05.751 D/Myapp( 6834): [EDT] 0:0:0,10 - Failed to create instance of cool.myapp.app.tests.LoginPageTest
>   12-08 13:19:05.751 D/Myapp( 6834): [EDT] 0:0:0,10 - Verify the class is public and doesn't have a specialized constructor
>   12-08 13:19:05.751 D/Myapp( 6834): [EDT] 0:0:0,11 - Exception: java.lang.ClassNotFoundException - cool.myapp.app.tests.LoginPageTest
>   12-08 13:19:05.751 W/System.err( 6834): java.lang.ClassNotFoundException: cool.myapp.app.tests.LoginPageTest
</code>```

Note that LoginPageTest is public and without any constructor defined by me.

iPhone 8:

```<code>> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(libAccessibility.dylib)[35170] <Notice>: Retrieving resting unlock: 0
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(FrontBoardServices)[35170] <Notice>: [FBDisplayManager=0x1d404b1f0] silently connecting <FBSDisplayConfiguration: 0x1d4177e80; Main; mode: "375x667@2x 60Hz p3"> {
>     CADisplay.name = LCD;
>     CADisplay.deviceName = primary;
>     CADisplay.seed = 2;
>     tags = 0;
>     currentMode = <FBSDisplayMode: 0x1d4268140; 375x667@2x (750x1334/2) 60Hz p3>;
>     safeOverscanRatio = {0.89999997615814209, 0.89999997615814209};
>     nativeCenter = {375, 667};
>     pixelSize = {750, 1334};
>     bounds = {{0, 0}, {375, 667}};
>     CADisplay = <CADisplay:LCD primary>;
> }
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(UserNotifications)[35170] <Notice>: [cool.myapp.app] Setting badge number to 0
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(UserNotifications)[35170] <Notice>: [cool.myapp.app] Set badge number [ hasCompletionHandler: 0 hasError: 0 ]
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(HangTracer)[35170] <Notice>: refreshPreferences: HangTracerEnabled: 0
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(HangTracer)[35170] <Notice>: refreshPreferences: HangTracerDuration: 500
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(HangTracer)[35170] <Notice>: refreshPreferences: ActivationLoggingEnabled: 0 ActivationLoggingTaskedOffByDA:0
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(UserNotifications)[35170] <Notice>: [cool.myapp.app] Setting badge number to 0
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(UserNotifications)[35170] <Notice>: [cool.myapp.app] Set badge number [ hasCompletionHandler: 0 hasError: 0 ]
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(CoreGraphics)[35170] <Error>: CGContextSetAllowsAntialiasing: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(UIAccessibility)[35170] <Notice>: loading ax info now. wasCoalesced: 1
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC Enabling TLS [1:0x1d4366840]
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TCP Conn Start [1:0x1d4366840]
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Task <1F77BFCA-1D0F-42ED-BAE8-4E0A54D579F7>.<0> setting up Connection 1
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Sending CFNA PAC query
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Received CFNA PAC response
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TCP Conn Connected [1:0x1d4366840]: Err(16)
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TCP Conn Event [1:0x1d4366840]: 1
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC Enabling TLS [1:0x1d4366840]
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 1, Pending(0)
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(UIAccessibility)[35170] <Notice>: loading ax info now. wasCoalesced: 1
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 2, Pending(0)
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(libboringssl.dylib)[35170] <Error>: Function boringssl_context_get_peer_sct_list: line 1754 received sct extension length is less than sct data length
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 11, Pending(0)
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 12, Pending(0)
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 14, Pending(0)
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Trust Result [1:0x1d4366840]: 0
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 20, Pending(0)
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TCP Conn Event [1:0x1d4366840]: 8
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Handshake Complete [1:0x1d4366840]
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Task <1F77BFCA-1D0F-42ED-BAE8-4E0A54D579F7>.<0> now using Connection 1
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Task <1F77BFCA-1D0F-42ED-BAE8-4E0A54D579F7>.<0> sent request, body N
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Task <1F77BFCA-1D0F-42ED-BAE8-4E0A54D579F7>.<0> received response, status 200 content K
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Task <1F77BFCA-1D0F-42ED-BAE8-4E0A54D579F7>.<0> response ended
</code>```

答:
I just sent a test build for iOS and got back a proper IPA.

I sent it by going to the files section of netbeans expanding the build.xml file and selecting the target then clicking "run target":

I even got the "included source" which lets me debug the output of the unit tests.

I suggest checking that the unit tests get packaged properly into the unit test jar with the app. This is my test for iOS device target which looks identical to yours:

```<code><target name="test-for-ios-device" depends="clean,copy-ios-override,copy-libs,compile-test,clean-override">
    <codeNameOne
        jarFile="dist/unitTests.jar"
        displayName="${codename1.displayName}"
        packageName = "${codename1.packageName}"
        mainClassName = "${codename1.mainName}"
        version="${codename1.version}"
        icon="${codename1.icon}"
        vendor="${codename1.vendor}"
        subtitle="${codename1.secondaryTitle}"
        buildArgs="build.unitTest=1"
        targetType="iphone"
        certificate="${codename1.ios.debug.certificate}"
        certPassword="${codename1.ios.debug.certificatePassword}"
        provisioningProfile="${codename1.ios.debug.provision}"
        appid="${codename1.ios.appid}"
        automated="${automated}"
        />
</target>
</code>```

This is my compile-tests target:

```<code><target depends="init,compile,jar" name="compile-test">
    <mkdir dir="${build.test.classes.dir}" />
    <mkdir dir="${test.src.dir}" />
    <javac destdir="${build.test.classes.dir}"
        encoding="${source.encoding}"
        source="1.8"
        target="1.8"
        bootclasspath="CLDC11.jar" excludes="${excludes}"
        classpath="${javac.classpath}:${build.classes.dir}">
        <src path="${test.src.dir}"/>
    </javac>
    <prepareTests classesDir="${build.classes.dir}" testClassesDir="${build.test.classes.dir}" seJar="JavaSE.jar" metaDataFile="${build.test.classes.dir}/tests.dat" />
    <jar jarfile="dist/unitTests.jar">
        <fileset dir="${build.classes.dir}"/>
        <fileset dir="${build.test.classes.dir}"/>
        <fileset dir="lib/impl/cls"/>
    </jar>
</target>
</code>```

Body:
This question is related to the previous ones: Codename One - Test Recorder: execute a test on a real device and Codename One - tests.dat file needed when using build.unitTest=1

My "test-for-ios-device" and "test-for-android-device" ant tasks produces IPAs and APKs that don't run any tests (actually the build server generates a .bin file that I rename to .ipa). Instead my tests work correctly in the Codename One Simulator. The tests are not trivial and all the logs plus one screenshot are sent to me by e-mail automatically during the test (using the Simulator), and I receive the report by e-mail without problems. Instead on real devices nothing happens.

I report the build.xml (I removed some irrilevant tasks in this copy) and the logs of Samsung Galaxy S6 and iPhone8.

<?xml version="1.0" encoding="UTF-8"?>

    <project name="Myapp" default="default" basedir=".">
    <description>Builds, tests, and runs the project Myapp.</description>
    <import file="nbproject/build-impl.xml"/>
    <property file="codenameone_settings.properties"/>
    <property name="automated" value="false" />
    <taskdef name="codeNameOne" classname="com.codename1.build.client.CodeNameOneBuildTask" classpath="CodeNameOneBuildClient.jar"/>
    <taskdef name="prepareTests" classname="com.codename1.build.client.PrepareTestsTask" classpath="CodeNameOneBuildClient.jar"/>
    <taskdef name="installLibs" classname="com.codename1.build.client.InstallLibsTask" classpath="CodeNameOneBuildClient.jar"/>
    <taskdef name="verifyDir" classname="com.codename1.build.client.VerifyDir" classpath="CodeNameOneBuildClient.jar"/>
    <taskdef name="generateGuiSources" classname="com.codename1.build.client.GenerateGuiSources" classpath="CodeNameOneBuildClient.jar"/>
    <taskdef name="initOfflineBuilder" classname="com.codename1.build.client.InitOfflineBuilder" classpath="CodeNameOneBuildClient.jar"/>

    <target depends="init,compile,jar" name="compile-test">
        <mkdir dir="${build.test.classes.dir}" />
        <mkdir dir="${test.src.dir}" />
        <javac destdir="${build.test.classes.dir}"
            encoding="${source.encoding}"
            source="1.8"
            target="1.8"
            bootclasspath="CLDC11.jar" excludes="${excludes}"
            classpath="${javac.classpath}:${build.classes.dir}">
            <src path="${test.src.dir}"/>
        </javac>
        <prepareTests classesDir="${build.classes.dir}" testClassesDir="${build.test.classes.dir}" seJar="JavaSE.jar" metaDataFile="${build.test.classes.dir}/tests.dat" />
        <jar jarfile="dist/unitTests.jar">
            <fileset dir="${build.classes.dir}"/>
            <fileset dir="${build.test.classes.dir}"/>
            <fileset dir="lib/impl/cls"/>
        </jar>
    </target>

    <target depends="compile-test" name="-do-test-run">

        <java classpath="dist/unitTests.jar:${javac.test.classpath}:${file.reference.JavaSE.jar}" classname="com.codename1.impl.javase.TestRunner" fork="true">
            <arg value="${codename1.packageName}.${codename1.mainName}" />
        </java>
    </target>

    <target depends="-do-test-run" description="Run unit tests." name="test"/>

    <target name="-pre-compile">
        <echo>Compile is forcing compliance to the supported API's/features for maximum device compatibility. This allows smaller
        code size and wider device support</echo>
        <mkdir dir="build/tmp"/>
        <javac destdir="build/tmp"
            encoding="${source.encoding}"
            source="1.8"
            target="1.8"
            bootclasspath="lib/CLDC11.jar" excludes="${excludes}"
            classpath="${javac.classpath}:${build.classes.dir}">
            <src path="${src.dir}"/>
        </javac>
    </target>

    <target name="-post-compile">
        <delete>
            <fileset dir="${build.classes.dir}" includes="**/package-info.class"/>
        </delete>
        <delete>
            <fileset dir="${build.classes.dir}" includes="**/package-info.class"/>
        </delete>
        <delete>
            <fileset dir="${build.classes.dir}" includes="**/Thumbs.db"/>
        </delete>
    </target>

    <target name="build-for-ios-device" depends="clean,copy-ios-override,copy-libs,jar,clean-override">
        <codeNameOne
            jarFile="${dist.jar}"
            displayName="${codename1.displayName}"
            packageName = "${codename1.packageName}"
            mainClassName = "${codename1.mainName}"
            version="${codename1.version}"
            icon="${codename1.icon}"
            vendor="${codename1.vendor}"
            subtitle="${codename1.secondaryTitle}"

            targetType="iphone"
            certificate="${codename1.ios.debug.certificate}"
            certPassword="${codename1.ios.debug.certificatePassword}"
            provisioningProfile="${codename1.ios.debug.provision}"
            appid="${codename1.ios.appid}"
            automated="${automated}"
            />
    </target>

    <target name="test-for-ios-device" depends="clean,copy-ios-override,copy-libs,compile-test,clean-override">
        <codeNameOne
            jarFile="dist/unitTests.jar"
            displayName="${codename1.displayName}"
            packageName = "${codename1.packageName}"
            mainClassName = "${codename1.mainName}"
            version="${codename1.version}"
            icon="${codename1.icon}"
            vendor="${codename1.vendor}"
            subtitle="${codename1.secondaryTitle}"
            buildArgs="build.unitTest=1"
            targetType="iphone"
            certificate="${codename1.ios.debug.certificate}"
            certPassword="${codename1.ios.debug.certificatePassword}"
            provisioningProfile="${codename1.ios.debug.provision}"
            appid="${codename1.ios.appid}"
            automated="${automated}"
            />
    </target>

    <target name="test-for-android-device" depends="clean,copy-android-override,copy-libs,compile-test,clean-override">
        <codeNameOne
            jarFile="dist/unitTests.jar"
            displayName="${codename1.displayName}"
            packageName = "${codename1.packageName}"
            mainClassName = "${codename1.mainName}"
            version="${codename1.version}"
            icon="${codename1.icon}"
            vendor="${codename1.vendor}"
            subtitle="${codename1.secondaryTitle}"
            buildArgs="build.unitTest=1"
            targetType="android"
            keystoreAlias="${codename1.android.keystoreAlias}"
            keystore="${codename1.android.keystore}"
            certPassword="${codename1.android.keystorePassword}"
            automated="${automated}"
            />
    </target>

    <target name="build-for-ios-device-release" depends="clean,copy-ios-override,copy-libs,jar,clean-override">
        <codeNameOne
            jarFile="${dist.jar}"
            displayName="${codename1.displayName}"
            packageName = "${codename1.packageName}"
            mainClassName = "${codename1.mainName}"
            version="${codename1.version}"
            icon="${codename1.icon}"
            vendor="${codename1.vendor}"
            subtitle="${codename1.secondaryTitle}"
            appStoreBuild="true"
            production="true"
            targetType="iphone"
            certificate="${codename1.ios.release.certificate}"
            certPassword="${codename1.ios.release.certificatePassword}"
            provisioningProfile="${codename1.ios.release.provision}"
            appid="${codename1.ios.appid}"
            automated="${automated}"
            />
    </target>

    <target name="copy-libs" depends="init">
        <copy todir="${build.classes.dir}">
            <fileset dir="lib/impl/cls" />
        </copy>
    </target>

    <target name="copy-android-override">
        <mkdir dir="${build.classes.dir}" />
        <mkdir dir="override" />
        <copy todir="${build.classes.dir}">
            <fileset dir="override" includes="**/*_android.ovr"/>
            <fileset dir="override" includes="**/*_android-phone.ovr"/>
            <fileset dir="override" includes="**/*_android-tab.ovr"/>
            <fileset dir="override" includes="**/*_phone.ovr"/>
            <fileset dir="override" includes="**/*_tablet.ovr"/>
        </copy>
        <copy todir="${build.classes.dir}">
            <fileset dir="native/android" includes="**/*"/>
            <fileset dir="lib/impl/native/android" includes="**/*"/>
        </copy>
    </target>

    <target name="copy-ios-override">
        <mkdir dir="${build.classes.dir}" />
        <mkdir dir="override" />
        <copy todir="${build.classes.dir}">
            <fileset dir="override" includes="**/*_ios.ovr"/>
            <fileset dir="override" includes="**/*_iphone.ovr"/>
            <fileset dir="override" includes="**/*_ipad.ovr"/>
            <fileset dir="override" includes="**/*_phone.ovr"/>
            <fileset dir="override" includes="**/*_tablet.ovr"/>
        </copy>
        <copy todir="${build.classes.dir}">
            <fileset dir="native/ios" includes="**/*"/>
            <fileset dir="lib/impl/native/ios" includes="**/*"/>
        </copy>
    </target>

    <target name="clean-override">
        <delete>
            <fileset dir="${build.classes.dir}" includes="**/*.ovr"/>
            <fileset dir="${build.classes.dir}" includes="**/*.java"/>
            <fileset dir="${build.classes.dir}" includes="**/*.m"/>
            <fileset dir="${build.classes.dir}" includes="**/*.h"/>
        </delete>
    </target>

    <target name="build-for-android-device" depends="clean,copy-android-override,copy-libs,jar,clean-override">
        <codeNameOne
            jarFile="${dist.jar}"
            displayName="${codename1.displayName}"
            packageName = "${codename1.packageName}"
            mainClassName = "${codename1.mainName}"
            version="${codename1.version}"
            icon="${codename1.icon}"
            vendor="${codename1.vendor}"
            subtitle="${codename1.secondaryTitle}"

            targetType="android"
            keystoreAlias="${codename1.android.keystoreAlias}"
            keystore="${codename1.android.keystore}"
            certPassword="${codename1.android.keystorePassword}"
            automated="${automated}"
            />
    </target>

    <target name="-pre-init">
        <property name="application.args" value="${codename1.packageName}.${codename1.mainName}"/>
        <property name="javac.source" value="1.8" />
        <property name="javac.target" value="1.8" />
        <mkdir dir="native/javase" />
        <mkdir dir="native/android" />
        <mkdir dir="native/internal_tmp" />
        <mkdir dir="native/ios" />
        <mkdir dir="native/j2me" />
        <mkdir dir="native/rim" />
        <mkdir dir="native/win" />
        <mkdir dir="native/javascript" />
        <mkdir dir="lib/impl/cls" />
        <mkdir dir="lib/impl/stubs" />
        <mkdir dir="lib/impl/native" />
        <mkdir dir="lib/impl/native/android" />
        <mkdir dir="lib/impl/native/ios" />
        <mkdir dir="lib/impl/native/j2me" />
        <mkdir dir="lib/impl/native/rim" />
        <mkdir dir="lib/impl/native/win" />
        <mkdir dir="lib/impl/native/javascript" />
        <installLibs lib="lib" dest="lib/impl" />
        <generateGuiSources srcDir="src" encoding="UTF-8" guiDir="res/guibuilder"  />
    </target>

    <target name="-post-jar">
        <mkdir dir="native/javase" />
        <mkdir dir="native/internal_tmp" />
        <mkdir dir="lib/impl/native/javase" />
        <javac destdir="native/internal_tmp"
            encoding="${source.encoding}"
            source="1.8"
            target="1.8"
            bootclasspath="CLDC11.jar" excludes="${excludes}"
            classpath="${javac.classpath}:${build.classes.dir}">
            <src path="native/javase"/>
            <src path="lib/impl/native/javase"/>
        </javac>
    </target>

    <target name="-post-clean" depends="refresh-libs-impl">
    </target>

    <target name="refresh-libs" depends="refresh-libs-impl,jar">
    </target>

    <target name="refresh-libs-impl">
        <delete dir="lib/impl" />
        <installLibs lib="lib" dest="lib/impl" />
    </target>

</project>

Samsung Galaxy S6 (only the relevant part of the log):

-----STARTING TESTS-----
>   12-08 13:19:05.751 D/Myapp( 6834): [EDT] 0:0:0,10 - Failed to create instance of cool.myapp.app.tests.LoginPageTest
>   12-08 13:19:05.751 D/Myapp( 6834): [EDT] 0:0:0,10 - Verify the class is public and doesn't have a specialized constructor
>   12-08 13:19:05.751 D/Myapp( 6834): [EDT] 0:0:0,11 - Exception: java.lang.ClassNotFoundException - cool.myapp.app.tests.LoginPageTest
>   12-08 13:19:05.751 W/System.err( 6834): java.lang.ClassNotFoundException: cool.myapp.app.tests.LoginPageTest

Note that LoginPageTest is public and without any constructor defined by me.

iPhone 8:

> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(libAccessibility.dylib)[35170] <Notice>: Retrieving resting unlock: 0
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(FrontBoardServices)[35170] <Notice>: [FBDisplayManager=0x1d404b1f0] silently connecting <FBSDisplayConfiguration: 0x1d4177e80; Main; mode: "375x667@2x 60Hz p3"> {
>     CADisplay.name = LCD;
>     CADisplay.deviceName = primary;
>     CADisplay.seed = 2;
>     tags = 0;
>     currentMode = <FBSDisplayMode: 0x1d4268140; 375x667@2x (750x1334/2) 60Hz p3>;
>     safeOverscanRatio = {0.89999997615814209, 0.89999997615814209};
>     nativeCenter = {375, 667};
>     pixelSize = {750, 1334};
>     bounds = {{0, 0}, {375, 667}};
>     CADisplay = <CADisplay:LCD primary>;
> }
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(UserNotifications)[35170] <Notice>: [cool.myapp.app] Setting badge number to 0
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(UserNotifications)[35170] <Notice>: [cool.myapp.app] Set badge number [ hasCompletionHandler: 0 hasError: 0 ]
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(HangTracer)[35170] <Notice>: refreshPreferences: HangTracerEnabled: 0
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(HangTracer)[35170] <Notice>: refreshPreferences: HangTracerDuration: 500
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(HangTracer)[35170] <Notice>: refreshPreferences: ActivationLoggingEnabled: 0 ActivationLoggingTaskedOffByDA:0
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(UserNotifications)[35170] <Notice>: [cool.myapp.app] Setting badge number to 0
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(UserNotifications)[35170] <Notice>: [cool.myapp.app] Set badge number [ hasCompletionHandler: 0 hasError: 0 ]
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(CoreGraphics)[35170] <Error>: CGContextSetAllowsAntialiasing: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
> Dec  8 13:26:35 iPhone CodenameOneUnitTestExecutor(UIAccessibility)[35170] <Notice>: loading ax info now. wasCoalesced: 1
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC Enabling TLS [1:0x1d4366840]
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TCP Conn Start [1:0x1d4366840]
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Task <1F77BFCA-1D0F-42ED-BAE8-4E0A54D579F7>.<0> setting up Connection 1
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Sending CFNA PAC query
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Received CFNA PAC response
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TCP Conn Connected [1:0x1d4366840]: Err(16)
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TCP Conn Event [1:0x1d4366840]: 1
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC Enabling TLS [1:0x1d4366840]
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 1, Pending(0)
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(UIAccessibility)[35170] <Notice>: loading ax info now. wasCoalesced: 1
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 2, Pending(0)
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(libboringssl.dylib)[35170] <Error>: Function boringssl_context_get_peer_sct_list: line 1754 received sct extension length is less than sct data length
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 11, Pending(0)
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 12, Pending(0)
> Dec  8 13:26:36 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 14, Pending(0)
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Trust Result [1:0x1d4366840]: 0
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Event [1:0x1d4366840]: 20, Pending(0)
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TCP Conn Event [1:0x1d4366840]: 8
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: TIC TLS Handshake Complete [1:0x1d4366840]
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Task <1F77BFCA-1D0F-42ED-BAE8-4E0A54D579F7>.<0> now using Connection 1
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Task <1F77BFCA-1D0F-42ED-BAE8-4E0A54D579F7>.<0> sent request, body N
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Task <1F77BFCA-1D0F-42ED-BAE8-4E0A54D579F7>.<0> received response, status 200 content K
> Dec  8 13:26:37 iPhone CodenameOneUnitTestExecutor(CFNetwork)[35170] <Notice>: Task <1F77BFCA-1D0F-42ED-BAE8-4E0A54D579F7>.<0> response ended

Body:
I just sent a test build for iOS and got back a proper IPA.

I sent it by going to the files section of netbeans expanding the build.xml file and selecting the target then clicking "run target":

I even got the "included source" which lets me debug the output of the unit tests.

I suggest checking that the unit tests get packaged properly into the unit test jar with the app. This is my test for iOS device target which looks identical to yours:

<target name="test-for-ios-device" depends="clean,copy-ios-override,copy-libs,compile-test,clean-override">
    <codeNameOne
        jarFile="dist/unitTests.jar"
        displayName="${codename1.displayName}"
        packageName = "${codename1.packageName}"
        mainClassName = "${codename1.mainName}"
        version="${codename1.version}"
        icon="${codename1.icon}"
        vendor="${codename1.vendor}"
        subtitle="${codename1.secondaryTitle}"
        buildArgs="build.unitTest=1"
        targetType="iphone"
        certificate="${codename1.ios.debug.certificate}"
        certPassword="${codename1.ios.debug.certificatePassword}"
        provisioningProfile="${codename1.ios.debug.provision}"
        appid="${codename1.ios.appid}"
        automated="${automated}"
        />
</target>

This is my compile-tests target:

<target depends="init,compile,jar" name="compile-test">
    <mkdir dir="${build.test.classes.dir}" />
    <mkdir dir="${test.src.dir}" />
    <javac destdir="${build.test.classes.dir}"
        encoding="${source.encoding}"
        source="1.8"
        target="1.8"
        bootclasspath="CLDC11.jar" excludes="${excludes}"
        classpath="${javac.classpath}:${build.classes.dir}">
        <src path="${test.src.dir}"/>
    </javac>
    <prepareTests classesDir="${build.classes.dir}" testClassesDir="${build.test.classes.dir}" seJar="JavaSE.jar" metaDataFile="${build.test.classes.dir}/tests.dat" />
    <jar jarfile="dist/unitTests.jar">
        <fileset dir="${build.classes.dir}"/>
        <fileset dir="${build.test.classes.dir}"/>
        <fileset dir="lib/impl/cls"/>
    </jar>
</target>


问:
Vectorising a for loop where logic spans rows
The table below shows an example of a strategy where a signal is generated in row 2 and then an opposite signal is generated in row 5.

```<code>     row     open_signal     close_signal      live
      1           0               0             0
      2           1               0             1
      3           0               0             1
      4           0               0             1
      5           0               1             0
      6           0               0             0
</code>```

I want to optimise the calculation of the live column.

Is there a way to vectorise this problem in either Pandas or Numpy for improved performance, generating the same result as the for loop example below?

```<code>import pandas as pd
from datetime import datetime

example = {'date': [str(datetime(2017,1,1)), str(datetime(2017,1,2)),str(datetime(2017,1,3)),str(datetime(2017,1,4)),str(datetime(2017,1,5)),str(datetime(2017,1,6)),
                    str(datetime(2017,1,7)), str(datetime(2017,1,8)),str(datetime(2017,1,9)), str(datetime(2017,1,10)),str(datetime(2017,1,11)), str(datetime(2017,1,12)),
                    str(datetime(2017,1,13)),str(datetime(2017,1,14))],
           'open':        [142.11, 142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75],
           'close':       [142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75, 142.11],
           'open_signal': [False,  False,  False,  False,  False,  True,  False,  False,  False,  False,  False,  False,  False,  False],
           'close_signal':[False,  False,  False,  False,  False,  False,  False,  False,  False,   True,  False,  False,  False,  False]
           }

data = pd.DataFrame(example)

in_trade = False
for i in data.iterrows():
    if i[1].open_signal:
        in_trade = True
    if i[1].close_signal:
        in_trade = False
    data.loc[i[0],'in_trade'] = in_trade
</code>```

答:
Simplistic case

For the simplistic case as in the posted sample, here's one vectorized way with NumPy -

```<code>ar = np.zeros(len(data), dtype=int)
ar[data.open_signal.values] = 1
ar[data.close_signal.values] = -1
data['out'] = ar.cumsum().astype(bool)
</code>```

Runtime test -

Using the sample dataset and scaling it 100000 times along the rows for the testing.

```<code>In [191]: data = pd.concat([data]*100000,axis=0); data.index = range(len(data))

# @Dark's soln with int output
In [192]: %timeit data['new'] = data['open_signal'].cumsum().ne(data['close_signal'].cumsum()).astype(int)
100 loops, best of 3: 13.4 ms per loop

# @Dark's soln with bool output
In [194]: %timeit data['new'] = data['open_signal'].cumsum().ne(data['close_signal'].cumsum()).astype(bool)
100 loops, best of 3: 10 ms per loop

# Proposed in this post
In [195]: %%timeit
     ...: ar = np.zeros(len(data), dtype=int)
     ...: ar[data.open_signal.values] = 1
     ...: ar[data.close_signal.values] = -1
     ...: data['out'] = ar.cumsum().astype(bool)
100 loops, best of 3: 7.52 ms per loop
</code>```

Generic case

Now, to solve for a generic case with :

1] A closed signal coming after no prior open signal.

2] Multiple open signals coming prior to the next close signal.

3] Multiple close signals coming prior to the next open signal.

We would need few more steps.

Approach #1 : Here's one based upon searchsorted -

```<code>s0 = np.flatnonzero(data.open_signal.values)
s1 = np.flatnonzero(data.close_signal.values)

idx0 = np.searchsorted(s1,s0,'right')
s0c = s0[np.r_[True,idx0[1:] > idx0[:-1]]]

idx1 = np.searchsorted(s0c,s1,'right')
s1c = s1[np.r_[True,idx1[1:] > idx1[:-1]]]

ar = np.zeros(len(data), dtype=int)
ar[s0c] = 1
ar[s1c] = -1
if s1c[0] < s0c[0]:
    ar[s1c[0]] = 0
data['out'] = ar.cumsum().astype(bool)
</code>```

Sample output -

```<code>In [360]: data
Out[360]:
    close_signal  open_signal    out
0          False        False  False
1          False        False  False
2           True        False  False
3          False        False  False
4          False        False  False
5          False         True   True
6          False        False   True
7          False         True   True
8          False        False   True
9           True        False  False
10         False        False  False
11          True        False  False
12         False        False  False
13         False        False  False
</code>```

Approach #2 : Possibly faster one as we would avoid using searchsorted and instead leverage masking -

```<code>mix_arr = data.open_signal.values.astype(int) - data.close_signal.values
ar = np.zeros(len(data), dtype=int)
mix_mask = mix_arr!=0
mix_val = mix_arr[mix_mask]

valid_mask = np.r_[True, mix_val[1:] != mix_val[:-1]]
ar[mix_mask] = mix_arr[mix_mask]*valid_mask
if mix_val[0] == -1:
    ar[mix_mask.argmax()] = 0

data['out'] = ar.cumsum().astype(bool)
</code>```

Body:
The table below shows an example of a strategy where a signal is generated in row 2 and then an opposite signal is generated in row 5.

     row     open_signal     close_signal      live
      1           0               0             0
      2           1               0             1
      3           0               0             1
      4           0               0             1
      5           0               1             0
      6           0               0             0

I want to optimise the calculation of the live column.

Is there a way to vectorise this problem in either Pandas or Numpy for improved performance, generating the same result as the for loop example below?

import pandas as pd
from datetime import datetime

example = {'date': [str(datetime(2017,1,1)), str(datetime(2017,1,2)),str(datetime(2017,1,3)),str(datetime(2017,1,4)),str(datetime(2017,1,5)),str(datetime(2017,1,6)),
                    str(datetime(2017,1,7)), str(datetime(2017,1,8)),str(datetime(2017,1,9)), str(datetime(2017,1,10)),str(datetime(2017,1,11)), str(datetime(2017,1,12)),
                    str(datetime(2017,1,13)),str(datetime(2017,1,14))],
           'open':        [142.11, 142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75],
           'close':       [142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75, 142.11],
           'open_signal': [False,  False,  False,  False,  False,  True,  False,  False,  False,  False,  False,  False,  False,  False],
           'close_signal':[False,  False,  False,  False,  False,  False,  False,  False,  False,   True,  False,  False,  False,  False]
           }

data = pd.DataFrame(example)

in_trade = False
for i in data.iterrows():
    if i[1].open_signal:
        in_trade = True
    if i[1].close_signal:
        in_trade = False
    data.loc[i[0],'in_trade'] = in_trade

Body:
Simplistic case

For the simplistic case as in the posted sample, here's one vectorized way with NumPy -

ar = np.zeros(len(data), dtype=int)
ar[data.open_signal.values] = 1
ar[data.close_signal.values] = -1
data['out'] = ar.cumsum().astype(bool)

Runtime test -

Using the sample dataset and scaling it 100000 times along the rows for the testing.

In [191]: data = pd.concat([data]*100000,axis=0); data.index = range(len(data))

# @Dark's soln with int output
In [192]: %timeit data['new'] = data['open_signal'].cumsum().ne(data['close_signal'].cumsum()).astype(int)
100 loops, best of 3: 13.4 ms per loop

# @Dark's soln with bool output
In [194]: %timeit data['new'] = data['open_signal'].cumsum().ne(data['close_signal'].cumsum()).astype(bool)
100 loops, best of 3: 10 ms per loop

# Proposed in this post
In [195]: %%timeit
     ...: ar = np.zeros(len(data), dtype=int)
     ...: ar[data.open_signal.values] = 1
     ...: ar[data.close_signal.values] = -1
     ...: data['out'] = ar.cumsum().astype(bool)
100 loops, best of 3: 7.52 ms per loop

Generic case

Now, to solve for a generic case with :

1] A closed signal coming after no prior open signal.

2] Multiple open signals coming prior to the next close signal.

3] Multiple close signals coming prior to the next open signal.

We would need few more steps.

Approach #1 : Here's one based upon searchsorted -

s0 = np.flatnonzero(data.open_signal.values)
s1 = np.flatnonzero(data.close_signal.values)

idx0 = np.searchsorted(s1,s0,'right')
s0c = s0[np.r_[True,idx0[1:] > idx0[:-1]]]

idx1 = np.searchsorted(s0c,s1,'right')
s1c = s1[np.r_[True,idx1[1:] > idx1[:-1]]]

ar = np.zeros(len(data), dtype=int)
ar[s0c] = 1
ar[s1c] = -1
if s1c[0] < s0c[0]:
    ar[s1c[0]] = 0
data['out'] = ar.cumsum().astype(bool)

Sample output -

In [360]: data
Out[360]:
    close_signal  open_signal    out
0          False        False  False
1          False        False  False
2           True        False  False
3          False        False  False
4          False        False  False
5          False         True   True
6          False        False   True
7          False         True   True
8          False        False   True
9           True        False  False
10         False        False  False
11          True        False  False
12         False        False  False
13         False        False  False

Approach #2 : Possibly faster one as we would avoid using searchsorted and instead leverage masking -

mix_arr = data.open_signal.values.astype(int) - data.close_signal.values
ar = np.zeros(len(data), dtype=int)
mix_mask = mix_arr!=0
mix_val = mix_arr[mix_mask]

valid_mask = np.r_[True, mix_val[1:] != mix_val[:-1]]
ar[mix_mask] = mix_arr[mix_mask]*valid_mask
if mix_val[0] == -1:
    ar[mix_mask.argmax()] = 0

data['out'] = ar.cumsum().astype(bool)


问:
Why is Titan creating duplicate vertex keys which are configured unique?

Brief summary

Using latest Titan-0.5 snapshot. Our code creates vertices in concurrent threads. We are ending up in a state where we have multiple vertices with the same key. We expect this not to occur due to our constraints.

Configuring keys with following:

```<code>PropertyKey name = management.makePropertyKey(keyName)
                             .dataType(String.class)
                             .cardinality(Cardinality.SINGLE)
                             .make();

TitanGraphIndex nameIndex = management.buildIndex(keyName, Vertex.class)
                                      .indexKey(name)
                                      .unique()
                                      .buildCompositeIndex();

management.setConsistency(nameIndex, ConsistencyModifier.LOCK);
</code>```

Full Story

We have a Titan DB configured with unique vertex property keys. When writing to the DB within concurrent threads, we find Titan persisting multiple vertices with the same key.

I've distilled the issue down to a single test file:
https://gist.github.com/ubit-ee/8520304273cd2024af29
This was built against the latest from 0.5 branch.

The code spawns three threads, which are synchronized to start concurrently (as much as can be) via a countdown latch.
The threads then:
create vertex with key "KEY_VALUE_A"
create vertex with key "KEY_VALUE_B"
creates a label between the two
If the threads were to run sequentially, one would expect exceptions due to duplicate keys. I've been able to force this case.

When the threads run concurrently, I would expect at least one thread to succeed and any number fail. Regardless, I expect the final state of the graph to be two vertices and a single edge between the two.

Unfortunately, when I run this, the DB is repeatedly left in a state with more that 2 vertices and edges. There are vertices with duplicate keys.
The tests dumps the graph to XML. Example:
https://gist.github.com/ubit-ee/d5530e4fa4b87c752294

The test code in configured for berkeleydb, but I've repeated the issue against Cassandra as well.

Questions

Have I configured the schema correctly, such that the vertex key should be unique?

Should I be doing anything different with transactions?

Am I misunderstanding the expected behavior of Titan?

答:
I was having the same problem in JanusGraph 0.2 which is based on Titan. I solved the issue by following code. </p>

```<code>JanusGraphManagement management = graph.openManagement();
PropertyKey uniqueId =management.makePropertyKey("uniqueId").dataType(String.class).cardinality(Cardinality.SINGLE).make();
JanusGraphManagement.IndexBuilder uniqueIdIndexBuilder = management.buildIndex("uniqueId", Vertex.class).addKey(uniqueId).unique();
JanusGraphIndex uniqueIdIndex = uniqueIdIndexBuilder.buildCompositeIndex();
management.setConsistency(uniqueIdIndex, ConsistencyModifier.LOCK);
</code>```

Body:
Brief summary

Using latest Titan-0.5 snapshot. Our code creates vertices in concurrent threads. We are ending up in a state where we have multiple vertices with the same key. We expect this not to occur due to our constraints.

Configuring keys with following:

PropertyKey name = management.makePropertyKey(keyName)
                             .dataType(String.class)
                             .cardinality(Cardinality.SINGLE)
                             .make();

TitanGraphIndex nameIndex = management.buildIndex(keyName, Vertex.class)
                                      .indexKey(name)
                                      .unique()
                                      .buildCompositeIndex();

management.setConsistency(nameIndex, ConsistencyModifier.LOCK);

Full Story

We have a Titan DB configured with unique vertex property keys. When writing to the DB within concurrent threads, we find Titan persisting multiple vertices with the same key.

I've distilled the issue down to a single test file:
https://gist.github.com/ubit-ee/8520304273cd2024af29
This was built against the latest from 0.5 branch.

The code spawns three threads, which are synchronized to start concurrently (as much as can be) via a countdown latch.
The threads then:
create vertex with key "KEY_VALUE_A"
create vertex with key "KEY_VALUE_B"
creates a label between the two
If the threads were to run sequentially, one would expect exceptions due to duplicate keys. I've been able to force this case.

When the threads run concurrently, I would expect at least one thread to succeed and any number fail. Regardless, I expect the final state of the graph to be two vertices and a single edge between the two.

Unfortunately, when I run this, the DB is repeatedly left in a state with more that 2 vertices and edges. There are vertices with duplicate keys.
The tests dumps the graph to XML. Example:
https://gist.github.com/ubit-ee/d5530e4fa4b87c752294

The test code in configured for berkeleydb, but I've repeated the issue against Cassandra as well.

Questions

Have I configured the schema correctly, such that the vertex key should be unique?

Should I be doing anything different with transactions?

Am I misunderstanding the expected behavior of Titan?

Body:
I was having the same problem in JanusGraph 0.2 which is based on Titan. I solved the issue by following code.

JanusGraphManagement management = graph.openManagement();
PropertyKey uniqueId =management.makePropertyKey("uniqueId").dataType(String.class).cardinality(Cardinality.SINGLE).make();
JanusGraphManagement.IndexBuilder uniqueIdIndexBuilder = management.buildIndex("uniqueId", Vertex.class).addKey(uniqueId).unique();
JanusGraphIndex uniqueIdIndex = uniqueIdIndexBuilder.buildCompositeIndex();
management.setConsistency(uniqueIdIndex, ConsistencyModifier.LOCK);


问:
Print session variables in a

I am trying to print session variables that I get from page-1.php into page-2.php into a div. I have managed to get the values via session from page-1 to page-2 but I am not able to print the values into a div(one div) that comes right beneath the menu. When I echo the output, it gets printed on the top-left. Code is mentioned below:

```<code> .output{
    height:50px;
    width:150px;
    margin-top:10px;
    border: 1px solid black;
    }
    </style>
    <title>Untitled Document</title>
    </head>

    <body>
    <?php
    session_start();
    echo '<div class="output">$_SESSION["val-2"]</div>';    //get session variables
    echo '<div class="output">$_SESSION["val-1"]</div>';
    echo '<div class="output">$_SESSION["val"]</div>';
    ?>

    <div><h1>Page-2</h1></div>
    <div class="menu">
        <ul>
            <li><a href="page-1.php">Page-1</a></li>
            <li><a href="page-2.php">Page-2</a></li>
        </ul>
    </div>
    <div class="output"></div>
    </body>
</code>```

Output I am getting:

答:
Try to concatenate string and variable, it may work,

```<code><?php
session_start();
echo '<div class="output">'.$_SESSION["val-1"].'</div>';
echo '<div class="output">'.$_SESSION["val-2"].'</div>';
echo '<div class="output">'.$_SESSION["val-3"].'</div>';
?>
</code>```

UPDATE

```<code><?php
session_start();
echo '<div class="output">'.$_SESSION["val-1"].$_SESSION["val-2"].$_SESSION["val-3"].'</div>';
?>
</code>```

Hope this one helps.

Title: Print session variables in a <div>

Body:
I am trying to print session variables that I get from page-1.php into page-2.php into a div. I have managed to get the values via session from page-1 to page-2 but I am not able to print the values into a div(one div) that comes right beneath the menu. When I echo the output, it gets printed on the top-left. Code is mentioned below:

 .output{
    height:50px;
    width:150px;
    margin-top:10px;
    border: 1px solid black;
    }
    </style>
    <title>Untitled Document</title>

    <?php
    session_start();
    echo '
$_SESSION["val-2"]
';    //get session variables
    echo '
$_SESSION["val-1"]
';
    echo '
$_SESSION["val"]
';
    ?>

Page-2

Page-1

Page-2

Output I am getting:

Body:
Try to concatenate string and variable, it may work,

<?php
session_start();
echo '<div class="output">'.$_SESSION["val-1"].'</div>';
echo '<div class="output">'.$_SESSION["val-2"].'</div>';
echo '<div class="output">'.$_SESSION["val-3"].'</div>';
?>

UPDATE

<?php
session_start();
echo '<div class="output">'.$_SESSION["val-1"].$_SESSION["val-2"].$_SESSION["val-3"].'</div>';
?>

Hope this one helps.


问:
Importing pyodbc results as Internal server error in Apache HTTP Server
Executing the cmd as  c:\>pip install pyodbc

"pyodbc.cp36-win32.pyd" file will be created

```<code> Collecting pyodbc   Using cached
 pyodbc-4.0.21-cp36-cp36m-win32.whl Installing collected packages:
 pyodbc Successfully installed pyodbc-4.0.21
</code>```

When I try to run in Apache24 Server the below code results in Internal Server Error

```<code>import pyodbc
cnxn = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
                      "Server=DESKTOP;"
                      "Database=demo2017;"
                      "Trusted_Connection=yes;")

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Table')

for row in cursor:
    print('row = %r' % (row,))
</code>```

Running in python shell as

     C:\Apache24\htdocs>python mssql_odbc.py
Results will be displayed fine. But not at apache http server.

In httpd.conf file:

```<code> LoadModule pyodbc_module "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/pyodbc.cp36-win32.pyd"
</code>```

Results

```<code> httpd: Syntax error on line 571 of C:/Apache24/conf/httpd.conf: Can't
 locate API module structure `pyodbc_module' in file
 C:/Users/Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/pyodbc.cp36-win32.pyd:
 No error
</code>```

So are there any modules or code that should be imported/modified?

答:
In Apache 500 Internal Error Solved. Because of importing pypyodbc instead of import pyodbc.

In python shell I was able to connect successfully retrive the results in python shell as well as in Database.

Body:
Executing the cmd as  c:\>pip install pyodbc

"pyodbc.cp36-win32.pyd" file will be created

 Collecting pyodbc   Using cached
 pyodbc-4.0.21-cp36-cp36m-win32.whl Installing collected packages:
 pyodbc Successfully installed pyodbc-4.0.21

When I try to run in Apache24 Server the below code results in Internal Server Error

import pyodbc
cnxn = pyodbc.connect("Driver={ODBC Driver 13 for SQL Server};"
                      "Server=DESKTOP;"
                      "Database=demo2017;"
                      "Trusted_Connection=yes;")

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Table')

for row in cursor:
    print('row = %r' % (row,))

Running in python shell as

     C:\Apache24\htdocs>python mssql_odbc.py
Results will be displayed fine. But not at apache http server.

In httpd.conf file:

 LoadModule pyodbc_module "c:/users/desktop/appdata/local/programs/python/python36-32/lib/site-packages/pyodbc.cp36-win32.pyd"

Results

 httpd: Syntax error on line 571 of C:/Apache24/conf/httpd.conf: Can't
 locate API module structure `pyodbc_module' in file
 C:/Users/Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages/pyodbc.cp36-win32.pyd:
 No error

So are there any modules or code that should be imported/modified?


问:
Directions API total distance & duration with waypoints
I am getting directions including waypoints from Directions API in my Android app. It contains multiple "leg" segments which has its own distance and duration. Is there a way to sum all distances and durations get the total values?

Example: Stripped json segment from Direction API

```<code>legs": [
{
  "distance": {
    "text": "389 km",
    "value": 389438
  },
  "duration": {
   "text": "6 hours 31 mins",
   "value": 23452
  }
},
{
  "distance": {
   "text": "0.5 km",
   "value": 487
  },
  "duration": {
   "text": "2 mins",
   "value": 102
  }
}
]
</code>```

from the above response, is there a way to calculate and show the output like following:

Total distance: 389.5 km
Total duration: 6 hours 33 mins

答:
Distance Calculation method. Hope this ll help someone</p>

```<code>private String distanceCalculation(String[] distanceItems) {
    //String[] totalDis = {"50 km", "4.5 km"}; // as example for visibility
    String totalDis = "";
    float distance = 0;
    String[] splitArray;
    if (distanceItems.length > 1) {
        for (String distanceItem : distanceItems) {
            splitArray = distanceItem.split(" ");
            Log.e("distance List", splitArray[0]);
            distance = distance + Float.valueOf(splitArray[0]);
        }
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        float twoDigitsF = Float.valueOf(decimalFormat.format(distance));
        totalDis = String.valueOf(twoDigitsF) + " km";
        Log.e("Total km ", totalDis);
    } else {
        totalDis = distanceItems[0];
    }
    return totalDis;
}
</code>```

Body:
I am getting directions including waypoints from Directions API in my Android app. It contains multiple "leg" segments which has its own distance and duration. Is there a way to sum all distances and durations get the total values?

Example: Stripped json segment from Direction API

legs": [
{
  "distance": {
    "text": "389 km",
    "value": 389438
  },
  "duration": {
   "text": "6 hours 31 mins",
   "value": 23452
  }
},
{
  "distance": {
   "text": "0.5 km",
   "value": 487
  },
  "duration": {
   "text": "2 mins",
   "value": 102
  }
}
]

from the above response, is there a way to calculate and show the output like following:

Total distance: 389.5 km
Total duration: 6 hours 33 mins

Body:
Distance Calculation method. Hope this ll help someone

private String distanceCalculation(String[] distanceItems) {
    //String[] totalDis = {"50 km", "4.5 km"}; // as example for visibility
    String totalDis = "";
    float distance = 0;
    String[] splitArray;
    if (distanceItems.length > 1) {
        for (String distanceItem : distanceItems) {
            splitArray = distanceItem.split(" ");
            Log.e("distance List", splitArray[0]);
            distance = distance + Float.valueOf(splitArray[0]);
        }
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        float twoDigitsF = Float.valueOf(decimalFormat.format(distance));
        totalDis = String.valueOf(twoDigitsF) + " km";
        Log.e("Total km ", totalDis);
    } else {
        totalDis = distanceItems[0];
    }
    return totalDis;
}


答:
I'll think about it.  At first glance:

```<code>SELECT t1.id,
       t1.time_stamp AS check_in,
       COALESCE((SELECT min(t2.time_stamp)
                   FROM t t2
                  WHERE t1.id = t2.id
                    AND t1.time_stamp < t2.time_stamp
                    AND t2.access_type = 1), NULL) AS check_out
  INTO TEMPORARY TABLE tt
  FROM t t1
 WHERE t1.access_type = 0;

  SELECT id,
         check_in,
         check_out,
         CASE WHEN check_out IS NOT NULL
              THEN EXTRACT('epoch' FROM check_out) - EXTRACT('epoch' FROM check_in)
              ELSE 0
              END AS duration
    FROM tt
ORDER BY id, check_in;

DROP TEMPORARY TABLE tt;
</code>```

I don't know if that epoch code or temp table syntax works on your specific DB, you may need to adjust that part.

Title: How to get all intime and outtime of an employee using sql?

Body:
Given Table:

id       time_stamp                  Access Type
0301    2013-09-05 09:35:00         0
0302    2013-09-05 11:00:00         0
0301    2013-09-05 12:00:00         1
0302    2013-09-05 12:25:00          1
0301    2013-09-05 13:00:00          0
0302    2013-09-05 14:00:00         0
0301    2013-09-05 17:00:00          1
0302    2013-09-05 18:00:00         1

From the Above table I want to display Intime and Outtime for each and every employee... 0 as in and 1 as out.

Expected Output:

id      check_in    check_out duration check_in    check_out duration  date           Totalduration
0301    09:35       12:00      02:25   13:00       17:00      04:00   2013-09-05          08:00
0302    11:00       12:25      01:25   14:00       18:00      04:00    2013-09-05          07:00

The result will go on like this ..

Body:
I'll think about it.  At first glance:

SELECT t1.id,
       t1.time_stamp AS check_in,
       COALESCE((SELECT min(t2.time_stamp)
                   FROM t t2
                  WHERE t1.id = t2.id
                    AND t1.time_stamp < t2.time_stamp
                    AND t2.access_type = 1), NULL) AS check_out
  INTO TEMPORARY TABLE tt
  FROM t t1
 WHERE t1.access_type = 0;

  SELECT id,
         check_in,
         check_out,
         CASE WHEN check_out IS NOT NULL
              THEN EXTRACT('epoch' FROM check_out) - EXTRACT('epoch' FROM check_in)
              ELSE 0
              END AS duration
    FROM tt
ORDER BY id, check_in;

DROP TEMPORARY TABLE tt;

I don't know if that epoch code or temp table syntax works on your specific DB, you may need to adjust that part.


问:
How to Suppress Warnings in MariaDB for 'Incorrect decimal value'
I am trying to do a bulk data upload into a MariaDB database. The data file has over 3M records. When the SQL runs the LOAD DATA INFILE (see below) statement, I get over 9600 warnings where there were problems when the data was inserted, most of them for Incorrect decimal value: '' for column 'xxx' at row yyy.  The LOAD DATA statement is:

```<code>LOAD DATA LOCAL INFILE 'C:/Path to/Data File.txt'
    INTO TABLE xyz
    FIELDS TERMINATED BY '\t'
    LINES TERMINATED BY '\r\n';
</code>```

I tried the suggestion in "Incorrect decimal (integer) value: ' ' mySQL"
to use SET SESSION sql_mode = '' at the beginning of the script, but it has no effect.

As I see it, the fact that no value is being inserted into the affected columns is NOT an error and does not warrant a Warning.

I need to see the things that really ARE wrong, but all these Warnings are overwhelming me with garbage, and the important stuff is getting lost in all the noise. I've been searching for several days, but have found no solution -- How can I suppress Warnings for this issue?

答:
```<code>LOAD DATA ...
    INTO (a, b, ..., @d, ...)
    SET d = IF (@d = '', 0, @d)
</code>```

That is, load the column as a string into an @variable (@d), then decide what to do with the 'bad' string as you put it into the actual column (d)

Body:
I am trying to do a bulk data upload into a MariaDB database. The data file has over 3M records. When the SQL runs the LOAD DATA INFILE (see below) statement, I get over 9600 warnings where there were problems when the data was inserted, most of them for Incorrect decimal value: '' for column 'xxx' at row yyy.  The LOAD DATA statement is:

LOAD DATA LOCAL INFILE 'C:/Path to/Data File.txt'
    INTO TABLE xyz
    FIELDS TERMINATED BY '\t'
    LINES TERMINATED BY '\r\n';

I tried the suggestion in "Incorrect decimal (integer) value: ' ' mySQL"
to use SET SESSION sql_mode = '' at the beginning of the script, but it has no effect.

As I see it, the fact that no value is being inserted into the affected columns is NOT an error and does not warrant a Warning.

I need to see the things that really ARE wrong, but all these Warnings are overwhelming me with garbage, and the important stuff is getting lost in all the noise. I've been searching for several days, but have found no solution -- How can I suppress Warnings for this issue?

Body:
LOAD DATA ...
    INTO (a, b, ..., @d, ...)
    SET d = IF (@d = '', 0, @d)

That is, load the column as a string into an @variable (@d), then decide what to do with the 'bad' string as you put it into the actual column (d)


问:
Unix, find, ls, grep and sort
With this Unix command, I try to search text in a directory

```<code>find . -type f -iname *index*jsp -print | xargs ls -t | xargs grep body
</code>```

./apache-tomcat-6.0.18/a/index.jsp:

./apache-tomcat-6.0.18/b/index.jsp:

But this result is not perfect, I want to get the file creation date and line number of matched string, like

./apache-tomcat-6.0.18/a/index.jsp: 2011-1-2 Line 3

./apache-tomcat-6.0.18/b/index.jsp: 2011-1-1 Line 4

How can I achieve this?

答:
First of, there's no file creation date recorded in UNIX. For line numbers, this would fit:</p>

```<code>find . -type f -iname '*index*jsp' -exec grep -n body '{}' ';'
</code>```

Title: Unix, find, ls, grep and sort

Body:
With this Unix command, I try to search text in a directory

find . -type f -iname *index*jsp -print | xargs ls -t | xargs grep body

./apache-tomcat-6.0.18/a/index.jsp:

./apache-tomcat-6.0.18/b/index.jsp:

But this result is not perfect, I want to get the file creation date and line number of matched string, like

./apache-tomcat-6.0.18/a/index.jsp: 2011-1-2 Line 3

./apache-tomcat-6.0.18/b/index.jsp: 2011-1-1 Line 4

How can I achieve this?

Body:
First of, there's no file creation date recorded in UNIX. For line numbers, this would fit:

find . -type f -iname '*index*jsp' -exec grep -n body '{}' ';'

ContentLicense: CC BY-SA 2.5


问:
How to convert mic audio input to LINEAR16 encoding BASE64 string using javascript
I am using google cloud speech API to convert speech to text by using mic. I am getting the arraybuffer of audio, now I need to convert it to linear16 encoding base64 string in Javascript. Please suggest if any possible solution for this.</p>

答:
The Audio buffer Data Is in Float32 (PCM 32-bit data) bit format you need to convert it into int16 (Linear16).
conversion directly from the buffer

Then You can the convert the data to base64.


问:
Why it is storing just two characters instead of 4?
This is my code:

```<code> #include<stdio.h>
    int main()
    {

        char a[10][10];

        int i,n,m,j;

        n=2;
        m=2;

        for(i=0;i<n;i++)
            for(j=0;j<m;j++)
            {
                scanf("%c",&a[i][j]);
            }

        for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
            {
                printf("%c",a[i][j]);
            }
        }

    }
</code>```

Output:

a b c d

a b

Process returned 0 (0x0)   execution time : 3.965 s
Press any key to continue.

答:
Because they are storing and two of them is the space. That's why you don't see them.

Try this and you will understand

```<code>printf("[%c]",a[i][j]);
</code>```

To solve the issue you can do this

```<code>scanf(" %c",&a[i][j]);
</code>```

This consumes the white space character between the two character input.

From standard:- 7.21.6.2

Input white-space characters (as specified by the isspace function)
  are skipped, unless the specification includes a [, c, or n specifier

and this

A directive composed of white-space character(s) is executed by
  reading input up to the first non-white-space character (which remains
  unread), or until no more characters can be read. The directive never
  fails.

Body:
This is my code:

 #include<stdio.h>
    int main()
    {

        char a[10][10];

        int i,n,m,j;

        n=2;
        m=2;

        for(i=0;i<n;i++)
            for(j=0;j<m;j++)
            {
                scanf("%c",&a[i][j]);
            }

        for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
            {
                printf("%c",a[i][j]);
            }
        }

    }

Output:

a b c d

a b

Process returned 0 (0x0)   execution time : 3.965 s
Press any key to continue.

Body:
Because they are storing and two of them is the space. That's why you don't see them.

Try this and you will understand

printf("[%c]",a[i][j]);

To solve the issue you can do this

scanf(" %c",&a[i][j]);

This consumes the white space character between the two character input.

From standard:- 7.21.6.2

Input white-space characters (as specified by the isspace function)
  are skipped, unless the specification includes a [, c, or n specifier

and this

A directive composed of white-space character(s) is executed by
  reading input up to the first non-white-space character (which remains
  unread), or until no more characters can be read. The directive never
  fails.


问:
AlertBuilder showing an exception. DialogBox is not opening
In the following code I want to open the dialog box when the mIndex is 0.

The code is going in the 'if' part. But is not opening the dialog Box instead showing the following exception.

Code:

```<code>mIndex = (mIndex+1)%mQuestionBank.length;
    if(mIndex == 0 )
    {
        Log.d("Quizzler", "Inside IF");
        AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
        alert.setTitle("Game Over");
        alert.setCancelable(false);
        alert.setMessage("Your score is "+mScore);
        alert.setPositiveButton("Close Application", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        alert.show();
    }
</code>```

Exception:

```<code>FATAL EXCEPTION: main
                                                                  Process: com.londonappbrewery.quizzler, PID: 11560                                                                               android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
                                                                               at android.view.ViewRootImpl.setView(ViewRootImpl.java:714)
                                                                               at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                                                                               at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                                                                               at android.app.Dialog.show(Dialog.java:316)
                                                                               at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
                                                                               at com.londonappbrewery.quizzler.MainActivity.updateQuestion(MainActivity.java:100)
                                                                               at com.londonappbrewery.quizzler.MainActivity.access$100(MainActivity.java:16)
                                                                               at com.londonappbrewery.quizzler.MainActivity$1.onClick(MainActivity.java:69)
                                                                               at android.view.View.performClick(View.java:5609)
                                                                               at android.view.View$PerformClick.run(View.java:22263)
                                                                               at android.os.Handler.handleCallback(Handler.java:751)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

答:
Try this</p>

```<code>    AlertDialog.Builder alert = new AlertDialog.Builder(YourActivity.this);
    alert.setTitle("Game Over");
    alert.setCancelable(false);
    alert.setMessage("Your score is "+mScore);
    alert.setPositiveButton("Close Application", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }
    });

    AlertDialog alertDialog=alert.create();
    alertDialog.show();
</code>```

Body:
In the following code I want to open the dialog box when the mIndex is 0.

The code is going in the 'if' part. But is not opening the dialog Box instead showing the following exception.

Code:

mIndex = (mIndex+1)%mQuestionBank.length;
    if(mIndex == 0 )
    {
        Log.d("Quizzler", "Inside IF");
        AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
        alert.setTitle("Game Over");
        alert.setCancelable(false);
        alert.setMessage("Your score is "+mScore);
        alert.setPositiveButton("Close Application", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        alert.show();
    }

Exception:

FATAL EXCEPTION: main
                                                                  Process: com.londonappbrewery.quizzler, PID: 11560                                                                               android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
                                                                               at android.view.ViewRootImpl.setView(ViewRootImpl.java:714)
                                                                               at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                                                                               at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                                                                               at android.app.Dialog.show(Dialog.java:316)
                                                                               at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
                                                                               at com.londonappbrewery.quizzler.MainActivity.updateQuestion(MainActivity.java:100)
                                                                               at com.londonappbrewery.quizzler.MainActivity.access$100(MainActivity.java:16)
                                                                               at com.londonappbrewery.quizzler.MainActivity$1.onClick(MainActivity.java:69)
                                                                               at android.view.View.performClick(View.java:5609)
                                                                               at android.view.View$PerformClick.run(View.java:22263)
                                                                               at android.os.Handler.handleCallback(Handler.java:751)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Body:
Try this

    AlertDialog.Builder alert = new AlertDialog.Builder(YourActivity.this);
    alert.setTitle("Game Over");
    alert.setCancelable(false);
    alert.setMessage("Your score is "+mScore);
    alert.setPositiveButton("Close Application", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }
    });

    AlertDialog alertDialog=alert.create();
    alertDialog.show();


问:
How to calculate length of string in a tuple in scala
Given a list of tuples, where the 1st element of the tuple is an integer and the second element is a string,

```<code>scala> val tuple2 : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
tuple2: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))
</code>```

I want to print the numbers where the corresponding string length is 4.

Can this be done in one line ?

答:
I like @prayagupd answer using collect. But foldLeft is the one of my favourite function in Scala! you can use foldLeft:

```<code>  scala> val input : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
   input: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))

  scala> input.foldLeft(List.empty[Int]){case (acc, (n,str)) => if(str.length ==4) acc :+ n  else acc}
   res3: List[Int] = List(2, 4, 5)
</code>```

Body:
Given a list of tuples, where the 1st element of the tuple is an integer and the second element is a string,

scala> val tuple2 : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
tuple2: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))

I want to print the numbers where the corresponding string length is 4.

Can this be done in one line ?

Body:
I like @prayagupd answer using collect. But foldLeft is the one of my favourite function in Scala! you can use foldLeft:

  scala> val input : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
   input: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))

  scala> input.foldLeft(List.empty[Int]){case (acc, (n,str)) => if(str.length ==4) acc :+ n  else acc}
   res3: List[Int] = List(2, 4, 5)


问:
i cant upload sql file that have size 24000 kb
I can't import an sql file to phpmyadmin that have size 24000kb while the system said max size is 20000kb. I have edited php.ini in folder php. I've changed upload_max_filesize = 750M and post_max_size = 750M, but I still can't upload file that have size 24000 kb.

I use xampp v.5.6.12

Please help me to fix it!

答:
1.16 I cannot upload big dump files (memory, HTTP or timeout problems).
Starting with version 2.7.0, the import engine has been re–written and these problems should not occur. If possible, upgrade your phpMyAdmin to the latest version to take advantage of the new import features.

The first things to check (or ask your host provider to check) are the values of max_execution_time, upload_max_filesize, memory_limit and post_max_size in the php.ini configuration file. All of these three settings limit the maximum size of data that can be submitted and handled by PHP. Please note that post_max_size needs to be larger than upload_max_filesize. There exist several workarounds if your upload is too big or your hosting provider is unwilling to change the settings:

Look at the $cfg['UploadDir'] feature. This allows one to upload a file to the server via scp, ftp, or your favorite file transfer method. PhpMyAdmin is then able to import the files from the temporary directory. More information is available in the Configuration of this document.

Using a utility (such as BigDump) to split the files before uploading. We cannot support this or any third party applications, but are aware of users having success with it.

If you have shell (command line) access, use MySQL to import the files directly. You can do this by issuing the “source” command from within MySQL:

source filename.sql;


问:
Chromedriver out of memory
I recently changed from PhantomJS to Chromedriver. When running chromdriver in Docker, after a while, I get the pod evicted with 'The node was low on resource: nodefs.' and I see using 'kubectl describe nodes' 'OOMKilling' and 'Memory cgroup out of memory: Kill process 452 (chrome) score 1867 or sacrifice child' . So I think this is a memory leak/memory issue. I am running my driver with:

```<code>    options = webdriver.ChromeOptions()
    options.add_argument('--disable-extensions')
    options.add_argument('--headless')
    options.add_argument('--disable-gpu')
    options.add_argument('--no-sandbox')
    options.add_argument('--incognito')
    options.add_argument('--disable-application-cache')
</code>```

Is there anything else that I need to set/do?

答:
Nothing is wrong with the chromedriver. Its the docker instance that ran out of memory.

You need to move your docker instance on a system with more memory

. Other option is to optimize the OOM process killer and fine tune the processes. You can read more about the capacity tuning here.

Title: Chromedriver out of memory

Body:
I recently changed from PhantomJS to Chromedriver. When running chromdriver in Docker, after a while, I get the pod evicted with 'The node was low on resource: nodefs.' and I see using 'kubectl describe nodes' 'OOMKilling' and 'Memory cgroup out of memory: Kill process 452 (chrome) score 1867 or sacrifice child' . So I think this is a memory leak/memory issue. I am running my driver with:

    options = webdriver.ChromeOptions()
    options.add_argument('--disable-extensions')
    options.add_argument('--headless')
    options.add_argument('--disable-gpu')
    options.add_argument('--no-sandbox')
    options.add_argument('--incognito')
    options.add_argument('--disable-application-cache')

Is there anything else that I need to set/do?


问:
I want to store the characters in image. swift
I want to store the text in image.

I want to store text inside the image.
Is this possible? For example, the image contains various information such as location information.
I like to store my text inside the images like them.

I want to store the string inside the data of the image rather than the visual.

For example, you might want to store a small string that identifies the image in the image, so you want to separate it when you import the image.

I want to implement it in swift.

答:
Your Q still leaks of information, what you really want to do. But I'll try to give you an answer, which might be a step to a better Q.

If you are talking about "inside" the image, you might mean inside the pixel data itself. It is possible to add data to an image without changing the image for humans. This is called a digital watermark or fingerprint. Typically this is used for DRM. You will find some information about this by using a search machine like Qwant.

But I do not think, that you really want to do this. Likely you want to add information in an image file. First of all you need a file format supporting additional data. Tiff is an example. AFAIK there is no build-in facility to get partial TIFF data for the image with ability to add private tasks. You have to create the file your own.