问:
Clear MATLAB command window from mex function
I have a for loop in a mexFunction, which displays some information at every iteration. Consider this simple code, which will print 100 lines in the MATLAB command window and update at every iteration:

```<code>#include "mex.h"
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
    int nrhs, const mxArray *prhs[])
{
    int numiters = 100;
    /* initialize random seed: */
    srand(time(NULL));

    for (int iter = 1; iter <= numiters; ++iter)
    {
        int rand_num = rand() % 100 + 1;

        /* Print info in matlab */
        std::ostringstream buffer;
        buffer << "iter = " << iter << " of " << numiters <<
            ". random number = " << rand_num << endl;

        /* need something similar to clc here */
        mexPrintf("%s", buffer.str().c_str());
    }
    return;
}
</code>```

At every iteration I wish to clear MATLAB's command window before calling mexPrintf().

I am aware that I can use mexCallMATLAB, to invoke MATLAB's clc, but I am not sure if invoking MATLAB at every iteration is very efficient, hence I need a solution native to C++.

答:
My assumption about mexCallMATLAB being inefficient was wrong, thanks to @Ander Biguri for the heads up. I used the following test code to compare times with and without mexCallMATLAB.

TL;DR - TIMING RESULTS

With mexCallMATLAB(0, NULL, 0, NULL, "clc");: mean time per iteration = 0.1016885 sec

Without mexCallMATLAB(0, NULL, 0, NULL, "clc");: mean time per iteration = 0.0978730 sec

DETAILS

Test Bench Summary

Create a vector with 1 million random integers and take the mean.

Repeat for 500 iterations.

Compute time required for each iteration and save in vector.

Average iteration times to get mean time per iteration.

Code

```<code>#include "mex.h"
#include <iostream>
#include <sstream>
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <ctime>
#include <vector>

using namespace std;
extern bool ioFlush(void);

/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
    int nrhs, const mxArray *prhs[])
{
    int numiters = 500;
    /* initialize random seed: */
    srand(time(NULL));

    std::vector<double> all_times(numiters);

    for (int iter = 1; iter <= numiters; ++iter)
    {
        /* tic */
        clock_t begin = clock();

        std::vector<int> rand_vec;

        for(std::size_t i = 0; i < 1000000; ++i)
            rand_vec.push_back( rand() % 100 + 1 );

        double vec_mean = 0.0;
        for(std::size_t i = 0; i < rand_vec.size(); ++i)
            vec_mean += rand_vec[i];

        vec_mean /= rand_vec.size();

        /* clear screen */
        mexCallMATLAB(0, NULL, 0, NULL, "clc");

        /* toc */
        double time_elapsed = double(clock() - begin) / CLOCKS_PER_SEC;

        /* Print data in matlab */
        std::ostringstream buffer;
        buffer << "iter " << iter << " of " << numiters <<
                ". random vector mean = " << vec_mean <<
                ". in " << time_elapsed << "s" << endl;

        mexPrintf("%s", buffer.str().c_str());
        ioFlush();

        all_times[iter] = time_elapsed;
    }

    double avg_time = 0.0;
    for(std::size_t i = 0; i < all_times.size(); ++i)
        avg_time += all_times[i];

    avg_time /= all_times.size();
    mexPrintf("\navg time per iter = %3.7f\n", avg_time);

    return;
}
</code>```

Note the use of ioFlush() which is an undocumented function needed to update command window at every iteration. See more details about it here.

To Compile

On Windows using Visual Studio: Add #pragma comment(lib, "libmwservices.lib") in source file.

On Ubuntu using gcc: Compile using mex yourFile.cpp -lmwservices

Body:
I have a for loop in a mexFunction, which displays some information at every iteration. Consider this simple code, which will print 100 lines in the MATLAB command window and update at every iteration:

#include "mex.h"
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
    int nrhs, const mxArray *prhs[])
{
    int numiters = 100;
    /* initialize random seed: */
    srand(time(NULL));

    for (int iter = 1; iter <= numiters; ++iter)
    {
        int rand_num = rand() % 100 + 1;

        /* Print info in matlab */
        std::ostringstream buffer;
        buffer << "iter = " << iter << " of " << numiters <<
            ". random number = " << rand_num << endl;

        /* need something similar to clc here */
        mexPrintf("%s", buffer.str().c_str());
    }
    return;
}

At every iteration I wish to clear MATLAB's command window before calling mexPrintf().

I am aware that I can use mexCallMATLAB, to invoke MATLAB's clc, but I am not sure if invoking MATLAB at every iteration is very efficient, hence I need a solution native to C++.

Body:
My assumption about mexCallMATLAB being inefficient was wrong, thanks to @Ander Biguri for the heads up. I used the following test code to compare times with and without mexCallMATLAB.

TL;DR - TIMING RESULTS

With mexCallMATLAB(0, NULL, 0, NULL, "clc");: mean time per iteration = 0.1016885 sec

Without mexCallMATLAB(0, NULL, 0, NULL, "clc");: mean time per iteration = 0.0978730 sec

DETAILS

Test Bench Summary

Create a vector with 1 million random integers and take the mean.

Repeat for 500 iterations.

Compute time required for each iteration and save in vector.

Average iteration times to get mean time per iteration.

Code

#include "mex.h"
#include <iostream>
#include <sstream>
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <ctime>
#include <vector>

using namespace std;
extern bool ioFlush(void);

/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[],
    int nrhs, const mxArray *prhs[])
{
    int numiters = 500;
    /* initialize random seed: */
    srand(time(NULL));

    std::vector<double> all_times(numiters);

    for (int iter = 1; iter <= numiters; ++iter)
    {
        /* tic */
        clock_t begin = clock();

        std::vector<int> rand_vec;

        for(std::size_t i = 0; i < 1000000; ++i)
            rand_vec.push_back( rand() % 100 + 1 );

        double vec_mean = 0.0;
        for(std::size_t i = 0; i < rand_vec.size(); ++i)
            vec_mean += rand_vec[i];

        vec_mean /= rand_vec.size();

        /* clear screen */
        mexCallMATLAB(0, NULL, 0, NULL, "clc");

        /* toc */
        double time_elapsed = double(clock() - begin) / CLOCKS_PER_SEC;

        /* Print data in matlab */
        std::ostringstream buffer;
        buffer << "iter " << iter << " of " << numiters <<
                ". random vector mean = " << vec_mean <<
                ". in " << time_elapsed << "s" << endl;

        mexPrintf("%s", buffer.str().c_str());
        ioFlush();

        all_times[iter] = time_elapsed;
    }

    double avg_time = 0.0;
    for(std::size_t i = 0; i < all_times.size(); ++i)
        avg_time += all_times[i];

    avg_time /= all_times.size();
    mexPrintf("\navg time per iter = %3.7f\n", avg_time);

    return;
}

Note the use of ioFlush() which is an undocumented function needed to update command window at every iteration. See more details about it here.

To Compile

On Windows using Visual Studio: Add #pragma comment(lib, "libmwservices.lib") in source file.

On Ubuntu using gcc: Compile using mex yourFile.cpp -lmwservices


来源: stackexchange

问:
Php: How can one automate a script to change dates everyday?
```<code>#!/usr/bin/php

<?php
$username = "user";
$password = "pass";
$url      = '10.168.8.666';
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}

$localDir  = 'file:///home/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        if (substr($file, 0, 11)=='07-Jun-2017'){
            # code...
              ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");

        }

    }
  }
}
?>
</code>```

I use this script to download backups from an sftp server everyday but i ve to manually change the date (in bold) in the script everyday. Question: is there a way i can make the script to change the date automatically so that i can set up a cron job?

答:
Use date().

```<code>date('d-M-Y')
</code>```

It will become

```<code>#!/usr/bin/php

<?php
$username = "user";
$password = "pass";
$url      = '10.168.8.666';
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}

$localDir  = 'file:///home/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {

        if (substr($file, 0, 11) == date('d-M-Y')) {
            # code...
              ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");

        }

    }
  }
}
?>
</code>```

If you want it to always be, let's say, yesterday, you may use it with strtotime(), so

```<code>date('d-M-Y', strtotime('yesterday'))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
#!/usr/bin/php

<?php
$username = "user";
$password = "pass";
$url      = '10.168.8.666';
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}

$localDir  = 'file:///home/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        if (substr($file, 0, 11)=='07-Jun-2017'){
            # code...
              ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");

        }

    }
  }
}
?>

I use this script to download backups from an sftp server everyday but i ve to manually change the date (in bold) in the script everyday. Question: is there a way i can make the script to change the date automatically so that i can set up a cron job?

Body:
Use date().

date('d-M-Y')

It will become

#!/usr/bin/php

<?php
$username = "user";
$password = "pass";
$url      = '10.168.8.666';
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password))
     {echo('Unable to connect.');}

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection))
     {echo ('Unable to create SFTP connection.');}

$localDir  = 'file:///home/batman/Downloads/dbs';
$remoteDir = '/home/batbackup/Dropbox/dbs';
// download all the files
$files = scandir ('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {

        if (substr($file, 0, 11) == date('d-M-Y')) {
            # code...
              ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");

        }

    }
  }
}
?>

If you want it to always be, let's say, yesterday, you may use it with strtotime(), so

date('d-M-Y', strtotime('yesterday'))

ContentLicense: CC BY-SA 3.0


问:
unescape converting Chinese characters to unreadable content
I have an SVG string like in below code sample. I am using it as the background image.

For converting it to a image I am doing below step:

```<code> var asImage = "data:image/svg+xml; base64," + window.btoa(unescape(encodeURIComponent(markupDataStr)));
</code>```

But the problem is, the SVG contains some Chinese text 測試. When I run encodeURIComponent and unescape it is converting the Chinese text to some unreadable characters like this æ¸¬è©¦.

But here in SO example, it does not alter the text above. Am I missing something here?

var str = window.holder.value;

var asImage = "data:image/svg+xml; base64," + unescape(encodeURIComponent(str));

console.log(str);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="holder">
 <svg xmlns="http://www.w3.org/2000/svg" style="position:absolute;left:0;top:0;-ms-transform:scale(1, -1);-webkit-transform:scale(1, -1);-moz-transform:scale(1, -1);-o-transform:scale(1, -1);transform:scale(1, -1);cursor:crosshair"
    class="design-review-container" viewBox="-1331.9027181688125 -1000 2663.805436337625 2000" width="931" height="699" xmlns:xlink="http://www.w3.org/1999/xlink">
    <g type="Pencil" guid="b36bf28d-78f7-434a-9601-ee1b7e3cb645">
        <path fill="none" stroke="rgba(255,40,79,1)" stroke-width="21.459227467811047" undefined="#ff284f" transform="translate(96.99569069094242, -24.034317300384487) rotate(0)"
            guid="b36bf28d-78f7-434a-9601-ee1b7e3cb645" d="M5.5317294330442195 128.46922431039877 L11.444938779729966 128.4692243103988 L17.657896065648615 128.06047712053572 L23.334940369302373 127.19756638638036 L25.751090424937402 126.75248611297391 L31.473551083020382 125.32187094845317 L37.19601174110336 123.89125578393244 L43.776841497898815 120.7439024219868 L50.35767125469421 117.59654906004114 L56.36625494568132 113.59082659938306 L62.37483863666846 109.58510413872497 L67.81117626184725 104.72101257935444 L73.24751388702607 99.85692101998391 L78.68385151220495 94.42058339480509 L84.12018913738378 88.98424576962626 L88.98428069675428 82.97566207863913 L93.84837225612482 76.96707838765201 L96.99572561807044 71.24461772956903 L100.14307898001606 65.52215707148605 L102.71818627615339 59.22745034759479 L105.29329357229075 52.93274362370352 L107.58227783552393 46.06579083400395 L109.87126209875713 39.198838044304374 L111.30187726327789 32.04576222170065 L112.73249242779865 24.892686399096934 L113.59086152651106 17.739610576493213 L114.44923062522356 10.586534753889492 L115.02147669103185 3.7195819641899206 L115.59372275684011 -3.147370825509647 L115.59372275684011 -9.442077549400928 L115.59372275684011 -15.736784273292201 L114.73535365812766 -21.745367964279318 L113.87698455941522 -27.75395165526644 L112.44636939489446 -33.47641231334942 L111.01575423037373 -39.1988729714324 L107.86840086842811 -45.20745666241953 L104.72104750648244 -51.216040353406655 L100.42920201292024 -57.224624044393764 L96.137356519358 -63.23320773538089 L90.41489586127501 -69.24179142636801 L84.69243520319206 -75.25037511735513 L78.11160544639664 -80.4005897096298 L71.53077568960119 -85.55080430190449 L62.947084702476715 -91.27326495998746 L54.3633937153523 -96.99572561807042 L46.06582576113199 -101.28757111163267 L37.76825780691165 -105.57941660519492 L28.89844378688302 -109.29901603294886 L20.028629766854422 -113.01861546070279 L10.872692713921666 -116.16596882264841 L1.716755660988909 -119.31332218459406 L-7.725304424848005 -121.88842948073142 L-17.16736451068492 -124.46353677686875 L-25.17880943200109 -125.60802890848535 L-33.19025435331724 -126.75252104010195 L-41.20169927463342 -127.6108901388144 L-49.21314419594958 -128.46925923752684 L-56.93846608436159 -128.1831362046227 L-64.6637879727736 -127.89701317171853 L-70.95849469666489 -126.4663980071978 L-77.25320142055615 -125.03578284267704 L-83.54790814444743 -121.60230644782723 L-89.8426148683387 -118.16883005297743 L-96.28038310868206 -115.45066124038806 L-102.24127962751848 -110.92037988607237 L-107.00999684258764 -104.72104750648248 L-115.5936878297121 -94.70674135483726 "
            style="pointer-events: none;" />
    </g>
    <g type="Text" clip-path="url(#29caee92-3443-41a7-9897-efc666d77842)" guid="29caee92-3443-41a7-9897-efc666d77842">
        <rect fill="rgba(255,40,79,0)" stroke="rgba(255,40,79,1)" stroke-width="21.459227467811047" undefined="#ff284f" font-size="51.50214592274665"
            text-decoration="normal" font-style="normal" font-weight="normal" font-family="Helvetica Neue" transform="translate(-396.2804005722461, -22.019982508494266) rotate(0) scale(1, -1)"
            guid="29caee92-3443-41a7-9897-efc666d77842" x="-257.51072961373393" y="-89.25889524096924" height="178.53339592274642"
            width="515.0214592274677" style="pointer-events: none;" />
        <text alignment-baseline="middle" style="pointer-events:none" fill="#ff284f" undefined="#ff284f" font-size="51.50214592274665"
            text-decoration="normal" font-style="normal" font-weight="normal" font-family="Helvetica Neue" transform="translate(-396.2804005722461, -22.019982508494266) rotate(0) scale(1, -1)"
            guid="29caee92-3443-41a7-9897-efc666d77842">
            <tspan x="-231.75965665236072" y="-22.306105541398594">t4mkgl35yhm5y</tspan>
            <tspan x="-231.75965665236072" y="44.64668415817205">測試</tspan>
        </text>
        <clipPath id="29caee92-3443-41a7-9897-efc666d77842" style="pointer-events: none;">
            <rect guid="29caee92-3443-41a7-9897-efc666d77842" fill="rgba(255,40,79,0)" stroke="rgba(255,40,79,1)" stroke-width="21.459227467811047"
                undefined="#ff284f" font-size="51.50214592274665" text-decoration="normal" font-style="normal" font-weight="normal"
                font-family="Helvetica Neue" transform="translate(-396.2804005722461, -22.019982508494266) rotate(0) scale(1, -1)"
                x="-257.51072961373393" y="-89.25889524096924" height="178.53339592274642" width="515.0214592274677" />
        </clipPath>
    </g>
</svg>
</textarea></code>```

答:
when using encodeURIComponent to encode, use decodeURIComponent to decode;

when using escape to encode, use unescape to decode.

so, unescape(encodeURIComponent(markupDataStr)) should be
decodeURIComponent(encodeURIComponent(markupDataStr))

by the way, escape is not recommended.

Body:
I have an SVG string like in below code sample. I am using it as the background image.

For converting it to a image I am doing below step:

 var asImage = "data:image/svg+xml; base64," + window.btoa(unescape(encodeURIComponent(markupDataStr)));

But the problem is, the SVG contains some Chinese text 測試. When I run encodeURIComponent and unescape it is converting the Chinese text to some unreadable characters like this æ¸¬è©¦.

But here in SO example, it does not alter the text above. Am I missing something here?

var str = window.holder.value;

var asImage = "data:image/svg+xml; base64," + unescape(encodeURIComponent(str));

console.log(str);

<textarea id="holder">
 <svg xmlns="http://www.w3.org/2000/svg" style="position:absolute;left:0;top:0;-ms-transform:scale(1, -1);-webkit-transform:scale(1, -1);-moz-transform:scale(1, -1);-o-transform:scale(1, -1);transform:scale(1, -1);cursor:crosshair"
    class="design-review-container" viewBox="-1331.9027181688125 -1000 2663.805436337625 2000" width="931" height="699" xmlns:xlink="http://www.w3.org/1999/xlink">
    <g type="Pencil" guid="b36bf28d-78f7-434a-9601-ee1b7e3cb645">
        <path fill="none" stroke="rgba(255,40,79,1)" stroke-width="21.459227467811047" undefined="#ff284f" transform="translate(96.99569069094242, -24.034317300384487) rotate(0)"
            guid="b36bf28d-78f7-434a-9601-ee1b7e3cb645" d="M5.5317294330442195 128.46922431039877 L11.444938779729966 128.4692243103988 L17.657896065648615 128.06047712053572 L23.334940369302373 127.19756638638036 L25.751090424937402 126.75248611297391 L31.473551083020382 125.32187094845317 L37.19601174110336 123.89125578393244 L43.776841497898815 120.7439024219868 L50.35767125469421 117.59654906004114 L56.36625494568132 113.59082659938306 L62.37483863666846 109.58510413872497 L67.81117626184725 104.72101257935444 L73.24751388702607 99.85692101998391 L78.68385151220495 94.42058339480509 L84.12018913738378 88.98424576962626 L88.98428069675428 82.97566207863913 L93.84837225612482 76.96707838765201 L96.99572561807044 71.24461772956903 L100.14307898001606 65.52215707148605 L102.71818627615339 59.22745034759479 L105.29329357229075 52.93274362370352 L107.58227783552393 46.06579083400395 L109.87126209875713 39.198838044304374 L111.30187726327789 32.04576222170065 L112.73249242779865 24.892686399096934 L113.59086152651106 17.739610576493213 L114.44923062522356 10.586534753889492 L115.02147669103185 3.7195819641899206 L115.59372275684011 -3.147370825509647 L115.59372275684011 -9.442077549400928 L115.59372275684011 -15.736784273292201 L114.73535365812766 -21.745367964279318 L113.87698455941522 -27.75395165526644 L112.44636939489446 -33.47641231334942 L111.01575423037373 -39.1988729714324 L107.86840086842811 -45.20745666241953 L104.72104750648244 -51.216040353406655 L100.42920201292024 -57.224624044393764 L96.137356519358 -63.23320773538089 L90.41489586127501 -69.24179142636801 L84.69243520319206 -75.25037511735513 L78.11160544639664 -80.4005897096298 L71.53077568960119 -85.55080430190449 L62.947084702476715 -91.27326495998746 L54.3633937153523 -96.99572561807042 L46.06582576113199 -101.28757111163267 L37.76825780691165 -105.57941660519492 L28.89844378688302 -109.29901603294886 L20.028629766854422 -113.01861546070279 L10.872692713921666 -116.16596882264841 L1.716755660988909 -119.31332218459406 L-7.725304424848005 -121.88842948073142 L-17.16736451068492 -124.46353677686875 L-25.17880943200109 -125.60802890848535 L-33.19025435331724 -126.75252104010195 L-41.20169927463342 -127.6108901388144 L-49.21314419594958 -128.46925923752684 L-56.93846608436159 -128.1831362046227 L-64.6637879727736 -127.89701317171853 L-70.95849469666489 -126.4663980071978 L-77.25320142055615 -125.03578284267704 L-83.54790814444743 -121.60230644782723 L-89.8426148683387 -118.16883005297743 L-96.28038310868206 -115.45066124038806 L-102.24127962751848 -110.92037988607237 L-107.00999684258764 -104.72104750648248 L-115.5936878297121 -94.70674135483726 "
            style="pointer-events: none;" />
    </g>
    <g type="Text" clip-path="url(#29caee92-3443-41a7-9897-efc666d77842)" guid="29caee92-3443-41a7-9897-efc666d77842">
        <rect fill="rgba(255,40,79,0)" stroke="rgba(255,40,79,1)" stroke-width="21.459227467811047" undefined="#ff284f" font-size="51.50214592274665"
            text-decoration="normal" font-style="normal" font-weight="normal" font-family="Helvetica Neue" transform="translate(-396.2804005722461, -22.019982508494266) rotate(0) scale(1, -1)"
            guid="29caee92-3443-41a7-9897-efc666d77842" x="-257.51072961373393" y="-89.25889524096924" height="178.53339592274642"
            width="515.0214592274677" style="pointer-events: none;" />
        <text alignment-baseline="middle" style="pointer-events:none" fill="#ff284f" undefined="#ff284f" font-size="51.50214592274665"
            text-decoration="normal" font-style="normal" font-weight="normal" font-family="Helvetica Neue" transform="translate(-396.2804005722461, -22.019982508494266) rotate(0) scale(1, -1)"
            guid="29caee92-3443-41a7-9897-efc666d77842">
            <tspan x="-231.75965665236072" y="-22.306105541398594">t4mkgl35yhm5y</tspan>
            <tspan x="-231.75965665236072" y="44.64668415817205">測試</tspan>
        </text>
        <clipPath id="29caee92-3443-41a7-9897-efc666d77842" style="pointer-events: none;">
            <rect guid="29caee92-3443-41a7-9897-efc666d77842" fill="rgba(255,40,79,0)" stroke="rgba(255,40,79,1)" stroke-width="21.459227467811047"
                undefined="#ff284f" font-size="51.50214592274665" text-decoration="normal" font-style="normal" font-weight="normal"
                font-family="Helvetica Neue" transform="translate(-396.2804005722461, -22.019982508494266) rotate(0) scale(1, -1)"
                x="-257.51072961373393" y="-89.25889524096924" height="178.53339592274642" width="515.0214592274677" />
        </clipPath>
    </g>
</svg>
</textarea>


问:
Unable to get commits list deployed by ansible and jenkins
I want to get all the commits list which is deployed by ansible.I am using this code for getting list

```<code>- name: Print complete log list
      command: git log --pretty=oneline "{{ cloned.after }}..{{ cloned.before }}"
      register: commits_list
</code>```

But i am getting this error

```<code>fatal: [127.0.0.1]: FAILED! => {"changed": true, "cmd": ["git", "log", "--pretty=oneline", "192fe5aa6c1fb835297b235a19882a5ec67c7f16..c3c558b231d1591baf5e5fd76fdc5a311934a605"], "delta": "0:00:00.058074", "end": "2017-06-07 12:28:15.668605", "failed": true, "rc": 128, "start": "2017-06-07 12:28:15.610531", "stderr": "fatal: Not a git repository (or any of the parent directories): .git", "stderr_lines": ["fatal: Not a git repository (or any of the parent directories): .git"], "stdout": "", "stdout_lines": []}
</code>```

I register cloned to get the git information.

答:
You probably want to chdir into repo dir:</p>

```<code>- name: Print complete log list
  command: git log --pretty=oneline "{{ cloned.after }}..{{ cloned.before }}"
  args:
    chdir: /path/to/cloned/ropo
  register: commits_list
</code>```

Body:
I want to get all the commits list which is deployed by ansible.I am using this code for getting list

- name: Print complete log list
      command: git log --pretty=oneline "{{ cloned.after }}..{{ cloned.before }}"
      register: commits_list

But i am getting this error

fatal: [127.0.0.1]: FAILED! => {"changed": true, "cmd": ["git", "log", "--pretty=oneline", "192fe5aa6c1fb835297b235a19882a5ec67c7f16..c3c558b231d1591baf5e5fd76fdc5a311934a605"], "delta": "0:00:00.058074", "end": "2017-06-07 12:28:15.668605", "failed": true, "rc": 128, "start": "2017-06-07 12:28:15.610531", "stderr": "fatal: Not a git repository (or any of the parent directories): .git", "stderr_lines": ["fatal: Not a git repository (or any of the parent directories): .git"], "stdout": "", "stdout_lines": []}

I register cloned to get the git information.

Body:
You probably want to chdir into repo dir:

- name: Print complete log list
  command: git log --pretty=oneline "{{ cloned.after }}..{{ cloned.before }}"
  args:
    chdir: /path/to/cloned/ropo
  register: commits_list


问:
ERROR: In exporting mysqli query results into excel using php
I am trying to export MySQL query results into excel. Therefore I wrote the following PHP script:

```<code><?php
$conn = mysqli_connect('localhost','root','xyz','abc');
$select = "SELECT * FROM table_name";
$export = mysqli_query( $conn,$select) or die ( "Sql error : " .
mysqli_error($conn) );
$fields = mysqli_num_rows ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
//But this line giving error continuously
$header .= mysqli_fetch_field_direct($export,$i) . "\t";
 }
while( $row = mysqli_fetch_row( $export ) )
{
 $line = '';
 foreach( $row as $value )
 {
  if ( ( !isset( $value ) ) || ( $value == "" ) )
  {
    $value = "\t";
  }
  else
  {
     $value = str_replace( '"' , '""' , $value );
     $value = '"' . $value . '"' . "\t";
  }
  $line .= $value;
 }
$data .= trim( $line ) . "\n";
 }
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
  $data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=random.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
</code>```

But I am getting this error:

```<code>PHP Recoverable fatal error:
Object of class stdClass could not be converted to string in this line
$header .= mysqli_fetch_field_direct($export,$i) . "\t";
</code>```

and now I'm facing problem in debugging this code.

答:
I found the solution for my problem,instead of doing this $header .= mysqli_fetch_field_direct($export,$i) . "\t"; now i am using $header .= mysqli_fetch_field_direct($export,$i)->name . "\t";.

Now Its working fine.

Body:
I am trying to export MySQL query results into excel. Therefore I wrote the following PHP script:

<?php
$conn = mysqli_connect('localhost','root','xyz','abc');
$select = "SELECT * FROM table_name";
$export = mysqli_query( $conn,$select) or die ( "Sql error : " .
mysqli_error($conn) );
$fields = mysqli_num_rows ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
//But this line giving error continuously
$header .= mysqli_fetch_field_direct($export,$i) . "\t";
 }
while( $row = mysqli_fetch_row( $export ) )
{
 $line = '';
 foreach( $row as $value )
 {
  if ( ( !isset( $value ) ) || ( $value == "" ) )
  {
    $value = "\t";
  }
  else
  {
     $value = str_replace( '"' , '""' , $value );
     $value = '"' . $value . '"' . "\t";
  }
  $line .= $value;
 }
$data .= trim( $line ) . "\n";
 }
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
  $data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=random.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

But I am getting this error:

PHP Recoverable fatal error:
Object of class stdClass could not be converted to string in this line
$header .= mysqli_fetch_field_direct($export,$i) . "\t";

and now I'm facing problem in debugging this code.


问:
How to install gems from Gemfile?
I want to add code coverage to my project and sign up coveralls.io and create Gemfile with:

```<code>gem 'coveralls', require: false
</code>```

but how can I install the gem from Gemfile?

答:
First install bundler if you don't have it

gem install bundler or sudo gem install bundler if you don't have the required permissions. Bundler is a gem that manages gem dependencies.

then you can follow the above instruction for creating the gemfile, after which you can issue the command

bundle install

Title: How to install gems from Gemfile?

Body:
I want to add code coverage to my project and sign up coveralls.io and create Gemfile with:

gem 'coveralls', require: false

but how can I install the gem from Gemfile?


问:
How to use cURL in magento 1.9 module
I've developed a module, at the moment only some function and get/post from to Database , the front I have it already done.
I want to add a class (cURL) to call 3rd party api, but I don't know how can I to implement that. It should be in controllers(IndexController?) or Model folder as new file? and if I have to add some details in config.xml?</p>

答:
There is no restriction to use the curl in a particular file. It depends on your module functionality and parameters. The most effective effort to use curl in indexcontroller. Use can create a function and initiate them.

Example like:

```<code>  <?php

    $curl = new Varien_Http_Adapter_Curl();
    $curl->setConfig(array(
           'timeout'   => 15    //Timeout in no of seconds
    ));
    $feed_url = "http://feeds.feedburner.com/magento";
    $curl->write(Zend_Http_Client::GET, $feed_url, '1.0');
    $data = $curl->read();
    if ($data === false) {
       return false;
    }
    $data = preg_split('/^r?$/m', $data, 2);
    $data = trim($data[1]);
    $curl->close();

    try {
      $xml  = new SimpleXMLElement($data);
     //Parse the XML FEED and output the data
    }
    catch (Exception $e) {
       echo $e->getMessage();
    }

    ?>
</code>```

Title: How to use cURL in magento 1.9 module

Body:
There is no restriction to use the curl in a particular file. It depends on your module functionality and parameters. The most effective effort to use curl in indexcontroller. Use can create a function and initiate them.

Example like:

  <?php

    $curl = new Varien_Http_Adapter_Curl();
    $curl->setConfig(array(
           'timeout'   => 15    //Timeout in no of seconds
    ));
    $feed_url = "http://feeds.feedburner.com/magento";
    $curl->write(Zend_Http_Client::GET, $feed_url, '1.0');
    $data = $curl->read();
    if ($data === false) {
       return false;
    }
    $data = preg_split('/^r?$/m', $data, 2);
    $data = trim($data[1]);
    $curl->close();

    try {
      $xml  = new SimpleXMLElement($data);
     //Parse the XML FEED and output the data
    }
    catch (Exception $e) {
       echo $e->getMessage();
    }

    ?>


问:
How to send data from one window to another window?
Could you please tell me how to send data from one window to another window?
I have one button on my parent window. On click of that button I am moving to another page (There is success button present in another page). When I click success button on child or another window I am redirecting to parent window. I want to print "success" text on parent window.

http://plnkr.co/edit/6IRDD0DHxK6A7mExWOUP?p=preview

```<code>$(function() {
  $('#f').on('click', function() {
    // alert('ddd');
    window.open('a.html')
  })

   $('#succ').on('click', function() {
    // alert('succ');
    window.open('index.html')
  })
})
</code>```

答:
You can pass value to the html page through url parameter. just change your code in script.js file. Hope it will help you.

```<code>$(function() {
  $('#f').on('click', function() {
    window.open('a.html?id=' + 123)
 })
 $('#succ').on('click', function() {
   window.open('index.html?id=' + 1)
 })
})
</code>```

then you can fetch the id value form params.
Thank you

Body:
Could you please tell me how to send data from one window to another window?
I have one button on my parent window. On click of that button I am moving to another page (There is success button present in another page). When I click success button on child or another window I am redirecting to parent window. I want to print "success" text on parent window.

http://plnkr.co/edit/6IRDD0DHxK6A7mExWOUP?p=preview

$(function() {
  $('#f').on('click', function() {
    // alert('ddd');
    window.open('a.html')
  })

   $('#succ').on('click', function() {
    // alert('succ');
    window.open('index.html')
  })
})

Body:
You can pass value to the html page through url parameter. just change your code in script.js file. Hope it will help you.

$(function() {
  $('#f').on('click', function() {
    window.open('a.html?id=' + 123)
 })
 $('#succ').on('click', function() {
   window.open('index.html?id=' + 1)
 })
})

then you can fetch the id value form params.
Thank you


问:
Connecting Android with PHPMyAdmin
i'm having some trouble in connecting my android project to a database at phpmyadmin, can somebody help me how to connect my android project to phpmyadmin?

these are my java codes, it just need to fill the else at the bottom one:

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Activity_SignUp extends AppCompatActivity{

private Button btnSubmit;
private EditText name;
private EditText uname;
private EditText pass;
private EditText jabatan;
private EditText confirm;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);

    btnSubmit = (Button) findViewById(R.id.btnSubmit);
    name = (EditText) findViewById(R.id.Name);
    jabatan = (EditText) findViewById(R.id.Jabatan);
    uname = (EditText) findViewById(R.id.UName);
    pass = (EditText) findViewById(R.id.Pass);
    confirm = (EditText) findViewById(R.id.Confirm);

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onClick_SignUp(v);

        }
    });
}

public void onClick_SignUp(View v){

    if (name.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Name Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (jabatan.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Age Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (uname.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "UserName must Be Filled", Toast.LENGTH_SHORT).show();
    } else if (pass.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Password must be Filled", Toast.LENGTH_SHORT).show();
    } else if (confirm.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Confirm Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (!confirm.getText().toString().equals(pass.getText().toString())) {
        Toast.makeText(Activity_SignUp.this, "Confirm Doesn't match", Toast.LENGTH_SHORT).show();
    } else {

    }
}
}`
</code>```

this is my php file:

Service.php

```<code><?php

define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','account');

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

$Nama = $_POST['Nama'];
$Jabatan = $_POST['Jabatan'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];

$sql = "insert into account (Nama,Jabatan,Username,Password) values ('$Nama','$Jabatan','$Username','$Password')";
if(mysqli_query($con,$sql)){
  echo 'success';
}
else{
  echo 'failure';
}
mysqli_close($con);

?>
</code>```

dbConnect.php

```<code><?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','account');

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>
</code>```

insert.php

```<code><?php

if($_SERVER['REQUEST_METHOD']=='POST'){

$Nama = $_POST['Nama'];
$Jabatan = $_POST['Jabatan'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];

if($Nama == '' || $Jabatan == '' || $Username == '' || $Password == ''){

}else{

require_once('dbConnect.php');

$sql = "SELECT * FROM account WHERE Username='$Username'";

$check = mysqli_fetch_array(mysqli_query($con,$sql));

if(isset($check)){
echo 'Username already exist';
}else{
    $sql = "INSERT INTO account (Nama,Jabatan,Username,Password) VALUES('$Nama','$Jabatan','$Username','$Password')";

    if(mysqli_query($con,$sql)){
        echo 'successfully registered';
    }else{
        echo 'oops! Please try again!';
    }
}
    mysqli_close($con);
}
}else{
    echo 'error';
}
?>
</code>```

答:
You don't need to pass the v

```<code> btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onClick_SignUp();

        }
    });
</code>```

Remove the v in onClick_SignUp method.

Title: Connecting Android with PHPMyAdmin

Body:
i'm having some trouble in connecting my android project to a database at phpmyadmin, can somebody help me how to connect my android project to phpmyadmin?

these are my java codes, it just need to fill the else at the bottom one:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Activity_SignUp extends AppCompatActivity{

private Button btnSubmit;
private EditText name;
private EditText uname;
private EditText pass;
private EditText jabatan;
private EditText confirm;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);

    btnSubmit = (Button) findViewById(R.id.btnSubmit);
    name = (EditText) findViewById(R.id.Name);
    jabatan = (EditText) findViewById(R.id.Jabatan);
    uname = (EditText) findViewById(R.id.UName);
    pass = (EditText) findViewById(R.id.Pass);
    confirm = (EditText) findViewById(R.id.Confirm);

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onClick_SignUp(v);

        }
    });
}

public void onClick_SignUp(View v){

    if (name.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Name Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (jabatan.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Age Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (uname.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "UserName must Be Filled", Toast.LENGTH_SHORT).show();
    } else if (pass.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Password must be Filled", Toast.LENGTH_SHORT).show();
    } else if (confirm.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Confirm Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (!confirm.getText().toString().equals(pass.getText().toString())) {
        Toast.makeText(Activity_SignUp.this, "Confirm Doesn't match", Toast.LENGTH_SHORT).show();
    } else {

    }
}
}`

this is my php file:

Service.php

<?php

define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','account');

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

$Nama = $_POST['Nama'];
$Jabatan = $_POST['Jabatan'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];

$sql = "insert into account (Nama,Jabatan,Username,Password) values ('$Nama','$Jabatan','$Username','$Password')";
if(mysqli_query($con,$sql)){
  echo 'success';
}
else{
  echo 'failure';
}
mysqli_close($con);

?>

dbConnect.php

<?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','account');

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>

insert.php

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){

$Nama = $_POST['Nama'];
$Jabatan = $_POST['Jabatan'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];

if($Nama == '' || $Jabatan == '' || $Username == '' || $Password == ''){

}else{

require_once('dbConnect.php');

$sql = "SELECT * FROM account WHERE Username='$Username'";

$check = mysqli_fetch_array(mysqli_query($con,$sql));

if(isset($check)){
echo 'Username already exist';
}else{
    $sql = "INSERT INTO account (Nama,Jabatan,Username,Password) VALUES('$Nama','$Jabatan','$Username','$Password')";

    if(mysqli_query($con,$sql)){
        echo 'successfully registered';
    }else{
        echo 'oops! Please try again!';
    }
}
    mysqli_close($con);
}
}else{
    echo 'error';
}
?>

Body:
You don't need to pass the v

 btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onClick_SignUp();

        }
    });

Remove the v in onClick_SignUp method.


问:
IOS : containsObject Check for String
i have Array of String like:
Array = P123, P234, P543, P678

and i have string like P12300.(this can be same string inside array or without trailling zeros).

i was using containsObject

```<code>if(Array containsObject: P123)    ==> TRUE
if(Array containsObject: P23400)  ==> FALSE
if(Array containsObject: P1230)    ==> FALSE
</code>```

is there any better way to compare string so that above ALL case's will be true?

at present i am using containsObject, and i am not getting desired result as condition will be only true for exact same string.

Please let me know good way..

答:
NSPredicate is nice, another way is using containsString: method like

```<code>//assumes all objects in the array are NSStrings
- (NSArray *)array:(NSArray *)array containsSubstring:(NSString *)substring {
    NSMutableArray *newArray = [[NSMutableArray alloc] init];
    for (NSString *string in array) {
        if([string containsString:substring]) {
            [newArray addObject:string];
        }
    }
    return newArray;
}
</code>```

now you can call it like

```<code>NSArray *stringArray = @[@"P12300", @"P23400", @"P5430", @"P678"];
NSArray *subArray = [self array:stringArray containsSubstring:@"P23"];
NSLog(@"%@", subArray);
</code>```

Swift 3:

in Swift it's super easy using filter

```<code>let array: [String] = ["P12300", "P23400", "P5430", "P678"]
let newArray = array.filter {
    $0.contains("P123")
}
print(newArray)
</code>```

Title: IOS : containsObject Check for String

Body:
i have Array of String like:
Array = P123, P234, P543, P678

and i have string like P12300.(this can be same string inside array or without trailling zeros).

i was using containsObject

if(Array containsObject: P123)    ==> TRUE
if(Array containsObject: P23400)  ==> FALSE
if(Array containsObject: P1230)    ==> FALSE

is there any better way to compare string so that above ALL case's will be true?

at present i am using containsObject, and i am not getting desired result as condition will be only true for exact same string.

Please let me know good way..

Body:
NSPredicate is nice, another way is using containsString: method like

//assumes all objects in the array are NSStrings
- (NSArray *)array:(NSArray *)array containsSubstring:(NSString *)substring {
    NSMutableArray *newArray = [[NSMutableArray alloc] init];
    for (NSString *string in array) {
        if([string containsString:substring]) {
            [newArray addObject:string];
        }
    }
    return newArray;
}

now you can call it like

NSArray *stringArray = @[@"P12300", @"P23400", @"P5430", @"P678"];
NSArray *subArray = [self array:stringArray containsSubstring:@"P23"];
NSLog(@"%@", subArray);

Swift 3:

in Swift it's super easy using filter

let array: [String] = ["P12300", "P23400", "P5430", "P678"]
let newArray = array.filter {
    $0.contains("P123")
}
print(newArray)


问:
InvalidDataAccessApiUsageException: Executing an update/delete query Spring XML to Java config
I'm trying to convert spring xml configuration to java configuration. This works perfectly through XML configuration. However, it throws the following exception if I use java config initializer. This happens when it tries to run JQL. The application starts properly though (with all JPA mapping initialized).

```<code>org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:410) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:216) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslat
</code>```

Following is my persistence initializer class. Bit of reading suggested me this is related to transactions are not being started properly. I've put debug points to each of these methods but transactionManager method never gets executed during server startup or any later time. I'm not sure what am I doing wrong :(. Same code based works perfectly when persistence is initialized through persistence.xml.

```<code>@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "au.mypkg")
public class DatabaseConfig  {

    @Bean(name = "dataSource")
    @Primary
    public DataSource dataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup("java:jboss/datasources/mydb");
    }

    @PersistenceContext(unitName = "persistenceUnit")
    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception {
    ..........

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        final JtaTransactionManager transactionManager = new JtaTransactionManager();
        transactionManager.setTransactionManagerName(JBOSS_TRANSACTION_MANANGER);
        return transactionManager;
    }
</code>```

Error occurs when accessing this method on Dao

```<code>   public void updateById(final Long id) {

        final String sqlQuery = "UPDATE testtable w SET w.LAST_ACCESSED = :date WHERE w.testtable_ID = :testid";
        final Query query = dao.createNativeQuery(sqlQuery);
        query.setParameter("date", new Date());
        query.setParameter("testid", id);
        query.executeUpdate();
    }
</code>```

答:
Finally figured out what was going on with it. The reason this wasn't hitting the debug point was, EnableTransactionManagement imposes to auto-configure transactions for you. So if your transaction manager configured with default name which is in my case, it wouldn't try to call my method to configure transactions. The only way to get around with this is to use a different name for your transaction manager and pass that ref as a parameter on enableJPARepositories annotation.If you use one of the default names, it wouldn't make this call.   </p>

```<code>@Primary
@Bean(name = "myRealTransactionManager")
public PlatformTransactionManager transactionManager() {
    final JtaTransactionManager transactionManager = new JtaTransactionManager();
    transactionManager.setTransactionManagerName(JBOSS_TRANSACTION_MANANGER);
    return transactionManager;
}
</code>```

<p>.. and then </p>

```<code>@EnableJpaRepositories(basePackages = "au.mypkg", transactionManagerRef = "myRealTransactionManager"
</code>```

<p>The other problem was I have had used setdatasource as opposed to setJtaDataSource on LocalContainerEntityManagerFatoryBean.  </p>

Body:
I'm trying to convert spring xml configuration to java configuration. This works perfectly through XML configuration. However, it throws the following exception if I use java config initializer. This happens when it tries to run JQL. The application starts properly though (with all JPA mapping initialized).

org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:410) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:216) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417) [spring-orm-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslat

Following is my persistence initializer class. Bit of reading suggested me this is related to transactions are not being started properly. I've put debug points to each of these methods but transactionManager method never gets executed during server startup or any later time. I'm not sure what am I doing wrong :(. Same code based works perfectly when persistence is initialized through persistence.xml.

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "au.mypkg")
public class DatabaseConfig  {

    @Bean(name = "dataSource")
    @Primary
    public DataSource dataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup("java:jboss/datasources/mydb");
    }

    @PersistenceContext(unitName = "persistenceUnit")
    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception {
    ..........

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        final JtaTransactionManager transactionManager = new JtaTransactionManager();
        transactionManager.setTransactionManagerName(JBOSS_TRANSACTION_MANANGER);
        return transactionManager;
    }

Error occurs when accessing this method on Dao

   public void updateById(final Long id) {

        final String sqlQuery = "UPDATE testtable w SET w.LAST_ACCESSED = :date WHERE w.testtable_ID = :testid";
        final Query query = dao.createNativeQuery(sqlQuery);
        query.setParameter("date", new Date());
        query.setParameter("testid", id);
        query.executeUpdate();
    }

Body:
Finally figured out what was going on with it. The reason this wasn't hitting the debug point was, EnableTransactionManagement imposes to auto-configure transactions for you. So if your transaction manager configured with default name which is in my case, it wouldn't try to call my method to configure transactions. The only way to get around with this is to use a different name for your transaction manager and pass that ref as a parameter on enableJPARepositories annotation.If you use one of the default names, it wouldn't make this call.

@Primary
@Bean(name = "myRealTransactionManager")
public PlatformTransactionManager transactionManager() {
    final JtaTransactionManager transactionManager = new JtaTransactionManager();
    transactionManager.setTransactionManagerName(JBOSS_TRANSACTION_MANANGER);
    return transactionManager;
}

.. and then

@EnableJpaRepositories(basePackages = "au.mypkg", transactionManagerRef = "myRealTransactionManager"

The other problem was I have had used setdatasource as opposed to setJtaDataSource on LocalContainerEntityManagerFatoryBean.


问:
What versions of avro and parquet formats does Spark support?
Does Spark 2.0 support avro and parquet files? What versions?

I have downloaded spark-avro_2.10-0.1.jar and got this error during load:

```<code>Name: java.lang.IncompatibleClassChangeError
Message: org.apache.spark.sql.sources.TableScan
StackTrace:   at java.lang.ClassLoader.defineClassImpl(Native Method)
  at java.lang.ClassLoader.defineClass(ClassLoader.java:349)
  at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:154)
  at java.net.URLClassLoader.defineClass(URLClassLoader.java:727)
  at java.net.URLClassLoader.access$400(URLClassLoader.java:95)
  at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:1182)
  at java.security.AccessController.doPrivileged(AccessController.java:686)
  at java.net.URLClassLoader.findClass(URLClassLoader.java:602)
</code>```

答:
You are just using the wrong dependency. You should use the spark-avro dependency that is compiles with Scala 2.11. You can find it here.

As for parquet, it's supported without any dependency to add to your application.

Body:
Does Spark 2.0 support avro and parquet files? What versions?

I have downloaded spark-avro_2.10-0.1.jar and got this error during load:

Name: java.lang.IncompatibleClassChangeError
Message: org.apache.spark.sql.sources.TableScan
StackTrace:   at java.lang.ClassLoader.defineClassImpl(Native Method)
  at java.lang.ClassLoader.defineClass(ClassLoader.java:349)
  at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:154)
  at java.net.URLClassLoader.defineClass(URLClassLoader.java:727)
  at java.net.URLClassLoader.access$400(URLClassLoader.java:95)
  at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:1182)
  at java.security.AccessController.doPrivileged(AccessController.java:686)
  at java.net.URLClassLoader.findClass(URLClassLoader.java:602)


问:
Set Sender Name in email
I have this php code which I wrote for Joomla Contact form! Everything is working fine, except it is taking sender email instead of taking sender name, kindly suggest, below is my helper.php</p>

```<code>public static function sendEmailNotification($name, $email, $contact, $params){
        $app  = JFactory::getApplication();
        $menu = $app->getMenu()->getActive()->title;
        $mailer = JFactory::getMailer();
        $sender = array($params->get('sender_email'), $params->get('Busibells'));
        $mailer-> setSender($sender);
        $mailer-> addRecipient($params->get('receiver_email'));
        $mailer-> addCC($params->get('cc_email'));
        $mailer->setSubject('new mail submitted');
        $body = "<h3>A new user has contacted with the following information</h3> <br>";
        $body.="Name : $name<br>";
        $body.="Email : $email<br>";
        $body.="Contact : $contact<br>";
        $body.="Service Page: $menu";
        $mailer->setBody($body);
        $mailer->isHTML(true);
        $mailer->send();

    if($mailer->send()){
            $mailernew = JFactory::getMailer();
            $sendernew = array($params->get('sender_email'), $params->get('Busibells'));
            $mailernew-> setSender($sendernew);
            $mailernew-> addRecipient($email);
            $mailernew->setSubject('Welcome Mail');
            /*$body = body($params->get('welcome_message'));*/
            $body = '<!DOCTYPE html>
</code>```

答: i think there no problem in your code.you should check that what value is coming in $params->get('Busibells'). May be you taking wrong parameter filed</p>

Title: Set Sender Name in email

Body:
I have this php code which I wrote for Joomla Contact form! Everything is working fine, except it is taking sender email instead of taking sender name, kindly suggest, below is my helper.php

public static function sendEmailNotification($name, $email, $contact, $params){
        $app  = JFactory::getApplication();
        $menu = $app->getMenu()->getActive()->title;
        $mailer = JFactory::getMailer();
        $sender = array($params->get('sender_email'), $params->get('Busibells'));
        $mailer-> setSender($sender);
        $mailer-> addRecipient($params->get('receiver_email'));
        $mailer-> addCC($params->get('cc_email'));
        $mailer->setSubject('new mail submitted');
        $body = "
A new user has contacted with the following information

";
        $body.="Name : $name
";
        $body.="Email : $email
";
        $body.="Contact : $contact
";
        $body.="Service Page: $menu";
        $mailer->setBody($body);
        $mailer->isHTML(true);
        $mailer->send();

    if($mailer->send()){
            $mailernew = JFactory::getMailer();
            $sendernew = array($params->get('sender_email'), $params->get('Busibells'));
            $mailernew-> setSender($sendernew);
            $mailernew-> addRecipient($email);
            $mailernew->setSubject('Welcome Mail');
            /*$body = body($params->get('welcome_message'));*/
            $body = '<!DOCTYPE html>


问:
Method to return username and Id
Hi guys im trying to get Username And id, right now im just getting the id.

This is the Stored Procedure:

```<code> ALTER PROCEDURE [dbo].[spLogin]
    @username VARCHAR(MAX),
    @password VARCHAR(MAX)
    AS
        SELECT [dbo].[User].[Id],[dbo].[User].[Username] FROM [dbo].[User]
WHERE username=@username AND password=@password
</code>```

This is my method:

```<code> public class UserBL
    {
        string conexion = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        public int CheckUserLogin(UserL User)
        {
            using (SqlConnection con = new SqlConnection(conexion))
            {
                SqlCommand comObj = new SqlCommand("spLogin", con);
                comObj.CommandType = CommandType.StoredProcedure;
                comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
                comObj.Parameters.Add(new SqlParameter("@password", User.Password));
                con.Open();
                return Convert.ToInt32(comObj.ExecuteScalar());
            }
        }
    }
</code>```

This is my User class:

```<code> public class UserL
    {
        public int UserID { get; set; }
        [Required]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
    }
</code>```

And im checking if the user exited by id With Ajax but I need to create sessions, and in order to do that I need

答:
You can use a Dictionary to return the UserName and the Id, making the Id the key and UserName the value.

```<code>  public Dictionary<int, string> CheckUserLogin(UserL User)
        {
               var dict = new Dictionary<int, string>();
            using (SqlConnection con = new SqlConnection(conexion))
            {
                SqlCommand comObj = new SqlCommand("spLogin", con);
                comObj.CommandType = CommandType.StoredProcedure;
                comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
                comObj.Parameters.Add(new SqlParameter("@password", User.Password));
                con.Open();
               using (SqlDataReader reader = command.ExecuteReader())
               {
                    // Call Read before accessing data.
                    while (reader.Read())
                   {
                     dict.Add((int)reader["Id"],
                       reader["Username"]==DBNull.Value ?"":
                            (string)reader["Username"]);
                   }
               }
           }
           return dict;
       }
</code>```

Title: Method to return username and Id

Body:
Hi guys im trying to get Username And id, right now im just getting the id.

This is the Stored Procedure:

 ALTER PROCEDURE [dbo].[spLogin]
    @username VARCHAR(MAX),
    @password VARCHAR(MAX)
    AS
        SELECT [dbo].[User].[Id],[dbo].[User].[Username] FROM [dbo].[User]
WHERE username=@username AND password=@password

This is my method:

 public class UserBL
    {
        string conexion = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        public int CheckUserLogin(UserL User)
        {
            using (SqlConnection con = new SqlConnection(conexion))
            {
                SqlCommand comObj = new SqlCommand("spLogin", con);
                comObj.CommandType = CommandType.StoredProcedure;
                comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
                comObj.Parameters.Add(new SqlParameter("@password", User.Password));
                con.Open();
                return Convert.ToInt32(comObj.ExecuteScalar());
            }
        }
    }

This is my User class:

 public class UserL
    {
        public int UserID { get; set; }
        [Required]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
    }

And im checking if the user exited by id With Ajax but I need to create sessions, and in order to do that I need

Body:
You can use a Dictionary to return the UserName and the Id, making the Id the key and UserName the value.

  public Dictionary<int, string> CheckUserLogin(UserL User)
        {
               var dict = new Dictionary<int, string>();
            using (SqlConnection con = new SqlConnection(conexion))
            {
                SqlCommand comObj = new SqlCommand("spLogin", con);
                comObj.CommandType = CommandType.StoredProcedure;
                comObj.Parameters.Add(new SqlParameter("@username", User.UserName));
                comObj.Parameters.Add(new SqlParameter("@password", User.Password));
                con.Open();
               using (SqlDataReader reader = command.ExecuteReader())
               {
                    // Call Read before accessing data.
                    while (reader.Read())
                   {
                     dict.Add((int)reader["Id"],
                       reader["Username"]==DBNull.Value ?"":
                            (string)reader["Username"]);
                   }
               }
           }
           return dict;
       }


问:
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'templates/email/test.vm'
My code as follow.

```<code>VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
        ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        ve.init();
        Template tempalte = ve.getTemplate("templates/email/test.vm");
</code>```

I am getting following error.

org.apache.velocity.exception.ResourceNotFoundException: Unable to
  find resource 'templates/email/test.vm'   at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:452)
    at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:335)
    at
  org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1102).....

"template" folder is in my src folder.

If I directly put the velocity template file into src folder and
  update as "Template tempalte = ve.getTemplate("test.vm");" it works.

I am using Mac OS, Java 1.8, Eclipse Neon.

Please help me to solve this.

Thanks and Regards,
IsuruJ

答:
Few Issues may cause it

Templates folder is the root of velocity so removing it may work

ve.getTemplate("/email/test.vm");

File with uppercase which is ignored by windows as: folder Email or file Test.vm cannot be found

Permissions of new folder/file not allowing read if user not owner

Body:
My code as follow.

VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
        ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        ve.init();
        Template tempalte = ve.getTemplate("templates/email/test.vm");

I am getting following error.

org.apache.velocity.exception.ResourceNotFoundException: Unable to
  find resource 'templates/email/test.vm'   at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:452)
    at
  org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:335)
    at
  org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1102).....

"template" folder is in my src folder.

If I directly put the velocity template file into src folder and
  update as "Template tempalte = ve.getTemplate("test.vm");" it works.

I am using Mac OS, Java 1.8, Eclipse Neon.

Please help me to solve this.

Thanks and Regards,
IsuruJ


问:
Adding a varibale to the RouteDefination "from " in Apache camel
I am looking to amend the RouteDefination from in Apache Camel

I hav eproperties file as below
     test1=test
     queue1=queue

code as below

```<code>from( "activemq:queue:{{test1}}.{{queue1}}")
.transform()
.simple(" ${body} {{test1}}.{{queue1}}.hello ${date:now:yyyyMMdd}")
.to("stream:out");
</code>```

this will become for route as

```<code>from( "activemq:queue:test1.queue")
</code>```

i am looking to make it as

```<code>from( "activemq:queue:test1.queue_20170606")
</code>```

which is ${date:now:yyyyMMdd}

答:
This is not possible in Camel - the from endpoint is static.

However ActiveMQ supports queue wildcards which you can use to consume from multiple queues, and you can use JMS message selectors.

http://activemq.apache.org/wildcards.html

http://activemq.apache.org/selectors.html

The latter is not so performant as it needs to do a query on the queue.

If you want to do a route per yyyyMMdd, then you need to add/remove routes dynamic in Camel. See other questions on SO how to do that.

Body:
I am looking to amend the RouteDefination from in Apache Camel

I hav eproperties file as below
     test1=test
     queue1=queue

code as below

from( "activemq:queue:{{test1}}.{{queue1}}")
.transform()
.simple(" ${body} {{test1}}.{{queue1}}.hello ${date:now:yyyyMMdd}")
.to("stream:out");

this will become for route as

from( "activemq:queue:test1.queue")

i am looking to make it as

from( "activemq:queue:test1.queue_20170606")

which is ${date:now:yyyyMMdd}


问:
How to create buttons dynamicly based on file/folder structure in android
im new to android and im trying to make a "simple" app.
However i would like to know if, what i have planned, is possible in android.

Basicly it's a crude database reader/navigator.

I made a folder structure in the assets folder with a few directories and *.txt files.
Now the plan is to read/scan the folder structure on startup of the program and dynamicly create buttons labeld  based on the folder,- and file names.
The buttons have to link to the files and folders so the user can navigate the folder structure and open a *.txt file and read it. Also the idea is that the buttons reflect the folder structure as it is in the assets folder.

The idea is that the user can easly retrieve info from the app and i can add info to the app trough *.txt files  and adjust the structure just by adding/removing directories and files in the assets folder.

i am using android studio but like i already say'd: i am a beginner with programming and would like to know if this is even possible with android.
And if it is: could someone please tell me how i should start this project or link me to some example code on how this could be done?

Thanks in advance.

答:
It sounds like ListView is something that could be beneficial for you here. ListView allows you to dynamically create buttons, or whatever you need. ListView has the added advantage that you can use an XML file to inform the ListView of how to display the buttons, images or whatever you want to display for each element of the list. There are loads of videos demonstrating how to use ListView, but here is a link to its documentation: https://developer.android.com/guide/topics/ui/layout/listview.html

Also, if you'd like a structured way of learning how to develop apps, I'd recommend the Android courses on Udacity to help you out.

Best of luck!


问:
how to change the system default printer using Excel VBA?
is there any way in which I can use VBA to change the system default printer? As well as changing its settings? Or is it too much to ask from VBA T-T</p>

答:
Yes, it's possible. You need to execute a shell script from your VBA code:

```<code>Sub ChangePrinter()
    Shell "RUNDLL32 PRINTUI.DLL,PrintUIEntry /y /n ""HP LaserJet 3000"""
End Sub
</code>```

(change HP LaserJet 3000 to whatever your printer name is).

If your printer is on network location (e.g. HP LaserJet 3000 on 192.168.1.100) use this syntax:

```<code>Shell "RUNDLL32 PRINTUI.DLL,PrintUIEntry /y /n ""\\192.168.1.100\HP LaserJet 3000"""
</code>```

Also it's possible to change printer settings, but you will need a .dat file with necessary settings.

To get the current settings from printer:

```<code>Shell "RUNDLL32 PRINTUI.DLL,PrintUIEntry /Ss /n ""HP LaserJet 3000"" /a ""C:\your_settings.dat"" u"
</code>```

To feed the settings file to your printer's driver:

```<code>Shell "RUNDLL32 PRINTUI.DLL,PrintUIEntry /Sr /n ""HP LaserJet 3000"" /a ""C:\your_settings.dat"" u"
</code>```

Body:
Yes, it's possible. You need to execute a shell script from your VBA code:

Sub ChangePrinter()
    Shell "RUNDLL32 PRINTUI.DLL,PrintUIEntry /y /n ""HP LaserJet 3000"""
End Sub

(change HP LaserJet 3000 to whatever your printer name is).

If your printer is on network location (e.g. HP LaserJet 3000 on 192.168.1.100) use this syntax:

Shell "RUNDLL32 PRINTUI.DLL,PrintUIEntry /y /n ""\\192.168.1.100\HP LaserJet 3000"""

Also it's possible to change printer settings, but you will need a .dat file with necessary settings.

To get the current settings from printer:

Shell "RUNDLL32 PRINTUI.DLL,PrintUIEntry /Ss /n ""HP LaserJet 3000"" /a ""C:\your_settings.dat"" u"

To feed the settings file to your printer's driver:

Shell "RUNDLL32 PRINTUI.DLL,PrintUIEntry /Sr /n ""HP LaserJet 3000"" /a ""C:\your_settings.dat"" u"


问:
Extract metadata from multiple videos
I am faced with a challenge that requires multiple aspects of bash. I work in Linux (precisely Debian Stretch). Here is the situation (for all points/problem I write along the solution I considered for now, but I'm open to other ideas) :

I have videos of various types (and various upper-lower case), such as .mp4, .mov, .MOV, .MP4, .avi,... located in a directory (and spread across an almost un-structured tree of directories). To find all I tried to use the find command

For each video, I need to extract some metadata (i.e. the name of the file, duration of video, size of file and date of creation/last modification). The package mediainfo yields (among a lot of other things) the required fields.
The output of mediainfo is a long list of fields with format : <Tag>\t : <value>. I need to extract values for fields Complete name, Duration, File size and Encoded date.

So with all this information, I must filter the required fields value and put them in a CSV file. I considered using sed.

My goal is to achieve all these tasks either in a script or a small amount of separate commands.

The idea code (this code is hideously wrong, but you can get an idea) :

find . -type f -name "*.[mp4|MP4|mov|MOV|avi|AVI]" -exec mediainfo {} | sed '/Complete name|Duration|File size|Encoded date/p' > myfile.csv \;

Would you have any idea how to perform this task ? I feel terribly lost in combining find, exec and sed and outputting to a csv...

Thanks in advance for your help !

答:
So I finally managed to write a script doing that. Probably not the best way to do, but here it is :

```<code>resFile="myresult.csv"
dstDir="./destination/"
srcDir="./source/"

#first copy all files at same level in dstDir (with preserve and update)
#this is somehow necessary, relative name for MOV files and mediainfo
#do not seem to work together.
find $srcDir -type f \( -name "*.mp4" -o -name "*.mov" -o -name "*.MOV" -o -name "*.avi" \) -exec cp -up {} $dstDir \;

#then for each file, output mediainfo of file and keep only interesting tags. add ### between each file.
find $dstDir -type f \( -name "*.mp4" -o -name "*.mov" -o -name "*.MOV" -o -name "*.avi"\
    -exec sh -c " mediainfo --Output=XML {} | sed '1,15!d;/Duration\|Complete\|File_size\|Encoded_date/!d' >> $resFile && echo '########' >> $resFile" \;

#removes tags : <Duration>42s 15ms</Duration> -> 42s 15ms
sed -i 's/^<.*>\(.*\)<.*>/\1/I' $resFile

#Extract exact filename (and not relative)
sed -i 's/^\.\/.*\/\(.*\)\.[mp4|MOV|mov|avi|MP4]/\1/' $resFile

#Puts fields for a file on a unique line separated with commas
sed -i 'N;s/\n/,/;N;s/\n/,/;N;s/\n/,/;N;s/\n/,/' $resFile

#remove all trailing ###
sed -i 's/,#*$//' $resFile
</code>```

I would still be interested if anyone has idea to improve the code.
I "minimized" a little bit, my actual code is a bit more modular and performs a few checks

Title: Extract metadata from multiple videos

Body:
So I finally managed to write a script doing that. Probably not the best way to do, but here it is :

resFile="myresult.csv"
dstDir="./destination/"
srcDir="./source/"

#first copy all files at same level in dstDir (with preserve and update)
#this is somehow necessary, relative name for MOV files and mediainfo
#do not seem to work together.
find $srcDir -type f \( -name "*.mp4" -o -name "*.mov" -o -name "*.MOV" -o -name "*.avi" \) -exec cp -up {} $dstDir \;

#then for each file, output mediainfo of file and keep only interesting tags. add ### between each file.
find $dstDir -type f \( -name "*.mp4" -o -name "*.mov" -o -name "*.MOV" -o -name "*.avi"\
    -exec sh -c " mediainfo --Output=XML {} | sed '1,15!d;/Duration\|Complete\|File_size\|Encoded_date/!d' >> $resFile && echo '########' >> $resFile" \;

#removes tags : <Duration>42s 15ms</Duration> -> 42s 15ms
sed -i 's/^<.*>\(.*\)<.*>/\1/I' $resFile

#Extract exact filename (and not relative)
sed -i 's/^\.\/.*\/\(.*\)\.[mp4|MOV|mov|avi|MP4]/\1/' $resFile

#Puts fields for a file on a unique line separated with commas
sed -i 'N;s/\n/,/;N;s/\n/,/;N;s/\n/,/;N;s/\n/,/' $resFile

#remove all trailing ###
sed -i 's/,#*$//' $resFile

I would still be interested if anyone has idea to improve the code.
I "minimized" a little bit, my actual code is a bit more modular and performs a few checks


问:
How to update a string when contents of an IList<> are updated in wpf
I have an IList which is populated using the objects of the following class:

```<code>public class MenuCheckboxData
{
    public int Id { get; set; }
    public string Label { get; set; }
    public bool Checked { get; set; }
}
</code>```

This is the IList

```<code>public IList<MenuCheckboxData> MenuOptions
    {
        get;
        set;
    } = new List<MenuCheckboxData>();
</code>```

This IList is updated via a CheckBoxList from the View and gets updated as per the changes made to the view at runtime which is fine.
Now there is another string in the same class:

```<code>string strFinalOpts="";
</code>```

I want the strFinalOpts to be containing the Id of all the IList elements(separated by commas) where Checked=true.

How to get the strFinalOpts updated when the Checked property of any object in the IList is updated/changed from the View?

答:
A typical approach would be to have a some sort of base viewmodel class that provides support for INotifyPropertyChanged:

```<code>public abstract class BaseViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChangedEvent([CallerMemberName]string prop = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(prop));
    }

    protected bool SetProperty<T>(ref T store, T value, [CallerMemberName]string prop = null)
    {
        if (!object.Equals(store, value))
        {
            store = value;
            RaisePropertyChangedEvent(prop);
            return true;
        }
        return false;
    }
}
</code>```

And then implement each viewmodel property with change notifications:

```<code>public class MenuCheckboxData : BaseViewModel
{
    private int _Id;
    public int Id
    {
        get { return _Id; }
        set { SetProperty(ref _Id, value); }
    }

    private string _Label;
    public string Label
    {
        get { return _Label; }
        set { SetProperty(ref _Label, value); }
    }

    private bool _Checked;
    public bool Checked
    {
        get { return _Checked; }
        set { SetProperty(ref _Checked, value); }
    }
}
</code>```

For items collections where the actual items are not static, use an ObservableCollection<T> instead of IList<T>. Subscribe to CollectionChanged in order to manage the MenuCheckboxData.PropertyChanged event subscriptions for each item. Whenever a MenuCheckboxData.PropertyChanged event is raised for property Checked, re-compute the string with IDs.

```<code>public class Container : BaseViewModel
{
    public Container()
    {
        _MenuOptions = new ObservableCollection<MenuCheckboxData>();
        _MenuOptions.CollectionChanged += MenuOptions_CollectionChanged;
    }

    void MenuOptions_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.OldItems != null)
        {
            foreach (INotifyPropertyChanged item in e.OldItems)
            {
                item.PropertyChanged -= MenuCheckboxData_PropertyChanged;
            }
        }
        if (e.NewItems != null)
        {
            foreach (INotifyPropertyChanged item in e.NewItems)
            {
                item.PropertyChanged += MenuCheckboxData_PropertyChanged;
            }
        }
    }

    void MenuCheckboxData_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Checked")
        {
            // re-evaluate joined id list
            StrFinalOpts = string.Join(",", MenuOptions.Where(x => x.Checked).Select(x => x.Id.ToString()));
        }
    }

    private ObservableCollection<MenuCheckboxData> _MenuOptions;
    public ObservableCollection<MenuCheckboxData> MenuOptions
    {
        get { return _MenuOptions; }
    }

    private string _StrFinalOpts = "";
    public string StrFinalOpts
    {
        get { return _StrFinalOpts; }
        set { SetProperty(ref _StrFinalOpts, value); }
    }
}
</code>```

Body:
I have an IList which is populated using the objects of the following class:

public class MenuCheckboxData
{
    public int Id { get; set; }
    public string Label { get; set; }
    public bool Checked { get; set; }
}

This is the IList

public IList<MenuCheckboxData> MenuOptions
    {
        get;
        set;
    } = new List<MenuCheckboxData>();

This IList is updated via a CheckBoxList from the View and gets updated as per the changes made to the view at runtime which is fine.
Now there is another string in the same class:

string strFinalOpts="";

I want the strFinalOpts to be containing the Id of all the IList elements(separated by commas) where Checked=true.

How to get the strFinalOpts updated when the Checked property of any object in the IList is updated/changed from the View?

Body:
A typical approach would be to have a some sort of base viewmodel class that provides support for INotifyPropertyChanged:

public abstract class BaseViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChangedEvent([CallerMemberName]string prop = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(prop));
    }

    protected bool SetProperty<T>(ref T store, T value, [CallerMemberName]string prop = null)
    {
        if (!object.Equals(store, value))
        {
            store = value;
            RaisePropertyChangedEvent(prop);
            return true;
        }
        return false;
    }
}

And then implement each viewmodel property with change notifications:

public class MenuCheckboxData : BaseViewModel
{
    private int _Id;
    public int Id
    {
        get { return _Id; }
        set { SetProperty(ref _Id, value); }
    }

    private string _Label;
    public string Label
    {
        get { return _Label; }
        set { SetProperty(ref _Label, value); }
    }

    private bool _Checked;
    public bool Checked
    {
        get { return _Checked; }
        set { SetProperty(ref _Checked, value); }
    }
}

For items collections where the actual items are not static, use an ObservableCollection<T> instead of IList<T>. Subscribe to CollectionChanged in order to manage the MenuCheckboxData.PropertyChanged event subscriptions for each item. Whenever a MenuCheckboxData.PropertyChanged event is raised for property Checked, re-compute the string with IDs.

public class Container : BaseViewModel
{
    public Container()
    {
        _MenuOptions = new ObservableCollection<MenuCheckboxData>();
        _MenuOptions.CollectionChanged += MenuOptions_CollectionChanged;
    }

    void MenuOptions_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.OldItems != null)
        {
            foreach (INotifyPropertyChanged item in e.OldItems)
            {
                item.PropertyChanged -= MenuCheckboxData_PropertyChanged;
            }
        }
        if (e.NewItems != null)
        {
            foreach (INotifyPropertyChanged item in e.NewItems)
            {
                item.PropertyChanged += MenuCheckboxData_PropertyChanged;
            }
        }
    }

    void MenuCheckboxData_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Checked")
        {
            // re-evaluate joined id list
            StrFinalOpts = string.Join(",", MenuOptions.Where(x => x.Checked).Select(x => x.Id.ToString()));
        }
    }

    private ObservableCollection<MenuCheckboxData> _MenuOptions;
    public ObservableCollection<MenuCheckboxData> MenuOptions
    {
        get { return _MenuOptions; }
    }

    private string _StrFinalOpts = "";
    public string StrFinalOpts
    {
        get { return _StrFinalOpts; }
        set { SetProperty(ref _StrFinalOpts, value); }
    }
}


问:
"Freemodbus" protocol as master
is it possible to use" Freemodbus "as master side ?
i'm going to impelement it on stm32f4xx ARM pocessor

if not ,introduce me alternative protocol that works on RS485 physical layer...

答: You can try this it also include Modbus Master with GNU GENERAL PUBLIC LICENSE. I am also trying it. </p>

Title: "Freemodbus" protocol as master


问:
Koa.js route() is not a function
I just made simple koa app that returns rss xml by tag using parameter. and seems like middleware can't read router from router file. I have no idea why It doesn't work. I'm running this app.js with babel-node. and It keeps saying this error below

```<code>app.use((0, _koaLogger2.default)()).use((0, _routes2.default)());
                                                             ^
TypeError: (0 , _routes2.default) is not a function
</code>```

route/index.js

```<code>import Router from 'koa-router'
const router = new Router({ prefix: '/'})

router.get('/:tag', async (ctx, next) =>
    (ctx.body = await rssGenerator(this.param.tag)))

export default router
</code>```

app.js

```<code>import Koa from 'koa'
import logger from 'koa-logger'

import routes from './routes'

const app = new Koa()
const port = process.env.PORT || 3000

app
  .use(logger())
  .use(routes())

app.listen(port, () => console.log("[!] Server STARTED"))
</code>```

答:
I see 2 problems here in your code:

First: you are importing routes like this:

```<code>import routes from './routes'
</code>```

but in your code above the path is route/index.js and not routes

Second: in route/index.js you are exporting router

```<code>export default router
</code>```

but then you are trying to import routes

Title: Koa.js route() is not a function

Body:
I just made simple koa app that returns rss xml by tag using parameter. and seems like middleware can't read router from router file. I have no idea why It doesn't work. I'm running this app.js with babel-node. and It keeps saying this error below

app.use((0, _koaLogger2.default)()).use((0, _routes2.default)());
                                                             ^
TypeError: (0 , _routes2.default) is not a function

route/index.js

import Router from 'koa-router'
const router = new Router({ prefix: '/'})

router.get('/:tag', async (ctx, next) =>
    (ctx.body = await rssGenerator(this.param.tag)))

export default router

app.js

import Koa from 'koa'
import logger from 'koa-logger'

import routes from './routes'

const app = new Koa()
const port = process.env.PORT || 3000

app
  .use(logger())
  .use(routes())

app.listen(port, () => console.log("[!] Server STARTED"))

Body:
I see 2 problems here in your code:

First: you are importing routes like this:

import routes from './routes'

but in your code above the path is route/index.js and not routes

Second: in route/index.js you are exporting router

export default router

but then you are trying to import routes


问:
c# Windows Service Console.Writeln
I wrote, installed, and successfully started a Windows Service in c# that does nothing :)  Initially I just want echo stuff to the console, db queries the service makes etc.  I used the OnStart in my service, but from a cmd prompt when I do a     net start "My Service"  where do these messages show up?

I'm open to better ways.  I'm new to this and feeling my way through it step by step by echoing back to the console my progress.  Should I echo to the event log instead? How do I do that?(I know, I know, google it)

```<code> protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        Console.WriteLine("Sham-Wow!");
    }
</code>```

答:
The most common/accepted way of communicating the status of your service is to write to the Windows Event Log.

For easier debugging, I would recommend that you put all of your business code into a separate class from the service component.  You can then use that class from either your service, or from a console application.  While you are creating the service, you will use the console application to host your component, so that you can easily step-into the code.

ContentLicense: CC BY-SA 2.5

Title: c# Windows Service Console.Writeln

Body:
I wrote, installed, and successfully started a Windows Service in c# that does nothing :)  Initially I just want echo stuff to the console, db queries the service makes etc.  I used the OnStart in my service, but from a cmd prompt when I do a     net start "My Service"  where do these messages show up?

I'm open to better ways.  I'm new to this and feeling my way through it step by step by echoing back to the console my progress.  Should I echo to the event log instead? How do I do that?(I know, I know, google it)

 protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        Console.WriteLine("Sham-Wow!");
    }


问:
R - combining two columns of a data frame into a vector of the form c(x,y,z...)
I have a data frame containing two character columns which I want to combine such that the output will be a vector of characters, like so.

```<code>Var1    Var2     Var3

a1      a2       c(a1, a2)

b1      b2       c(b1, b2)
</code>```

Please note that I do not want to paste these values together but rather leave them as elements of a third vector specifically in the form c(, )

答:
We can use tidyverse

```<code>library(tidyverse)
df1 %>%
     mutate(Var3 = map2(Var1, Var2, c))
#  Var1 Var2   Var3
#1   a1   a2 a1, a2
#2   b1   b2 b1, b2
</code>```

Or using only base R

```<code>df1$Var3 <- do.call(Map, c(f = c, unname(df1)))
str(df1)
#'data.frame':   2 obs. of  3 variables:
# $ Var1: chr  "a1" "b1"
# $ Var2: chr  "a2" "b2"
#$ Var3:List of 2
#  ..$ a1: chr  "a1" "a2"
# ..$ b1: chr  "b1" "b2"

is.vector(df1$Var3[1])
#[1] TRUE
is.vector(df1$Var3[2])
#[1] TRUE
</code>```

data

```<code>df1 <- data.frame(Var1 = c("a1","b1"),Var2=c("a2","b2"), stringsAsFactors=FALSE)
</code>```

Body:
I have a data frame containing two character columns which I want to combine such that the output will be a vector of characters, like so.

Var1    Var2     Var3

a1      a2       c(a1, a2)

b1      b2       c(b1, b2)

Please note that I do not want to paste these values together but rather leave them as elements of a third vector specifically in the form c(, )

Body:
We can use tidyverse

library(tidyverse)
df1 %>%
     mutate(Var3 = map2(Var1, Var2, c))
#  Var1 Var2   Var3
#1   a1   a2 a1, a2
#2   b1   b2 b1, b2

Or using only base R

df1$Var3 <- do.call(Map, c(f = c, unname(df1)))
str(df1)
#'data.frame':   2 obs. of  3 variables:
# $ Var1: chr  "a1" "b1"
# $ Var2: chr  "a2" "b2"
#$ Var3:List of 2
#  ..$ a1: chr  "a1" "a2"
# ..$ b1: chr  "b1" "b2"

is.vector(df1$Var3[1])
#[1] TRUE
is.vector(df1$Var3[2])
#[1] TRUE

data

df1 <- data.frame(Var1 = c("a1","b1"),Var2=c("a2","b2"), stringsAsFactors=FALSE)


问:
Using static resources inside a jar library (to be used in Android)
I am developing a plain java library (jar), which contains some static files, which I put to src/main/resources. These static files are used to execute an algorithm and return processed data to the user.

```<code>public String getStringFromFile(String fileName) {
    String text = "";

    try {
        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource(fileName).getFile());
        Scanner scanner = new Scanner(file);

        text = scanner.useDelimiter("\\A").next();
        scanner.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return text;
}
</code>```

So far so good. However, when I try to use this library/method in an Android project I get:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.net.URL.getFile()' on a null object reference

I want my static resource files to be published with the library. Am I doing something wrong? Any thoughts?

答:
Ok. I think I have solved this. Following this article I created a res directory in the root of my jar module (on the same level as the src directory) and put my files there (helloworld.json). Then added this to build.gradle:

```<code>jar {
  into('resourcez') {
    from 'res'
  }
}
</code>```

Using this helper function (inside the jar lib) and getResourceAsStream() I get the contents of my resource files:

```<code>public String getModelFromStream(String fileName) {
    final String classpath = "resourcez/";
    ClassLoader classLoader = DexiModelLoader.class.getClassLoader();
    InputStream resourceAsStream = classLoader.getResourceAsStream(fileName);

    if (resourceAsStream == null)
        resourceAsStream = classLoader.getResourceAsStream(classpath + fileName);

    if (resourceAsStream == null)
        return "error";

    Scanner s = new Scanner(resourceAsStream).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}
</code>```

After this I simply call getStringFromStream("helloworld.json") or getStringFromStream("resourcez/helloworld.json") in my android app and voilà!

Body:
I am developing a plain java library (jar), which contains some static files, which I put to src/main/resources. These static files are used to execute an algorithm and return processed data to the user.

public String getStringFromFile(String fileName) {
    String text = "";

    try {
        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource(fileName).getFile());
        Scanner scanner = new Scanner(file);

        text = scanner.useDelimiter("\\A").next();
        scanner.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return text;
}

So far so good. However, when I try to use this library/method in an Android project I get:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.net.URL.getFile()' on a null object reference

I want my static resource files to be published with the library. Am I doing something wrong? Any thoughts?

Body:
Ok. I think I have solved this. Following this article I created a res directory in the root of my jar module (on the same level as the src directory) and put my files there (helloworld.json). Then added this to build.gradle:

jar {
  into('resourcez') {
    from 'res'
  }
}

Using this helper function (inside the jar lib) and getResourceAsStream() I get the contents of my resource files:

public String getModelFromStream(String fileName) {
    final String classpath = "resourcez/";
    ClassLoader classLoader = DexiModelLoader.class.getClassLoader();
    InputStream resourceAsStream = classLoader.getResourceAsStream(fileName);

    if (resourceAsStream == null)
        resourceAsStream = classLoader.getResourceAsStream(classpath + fileName);

    if (resourceAsStream == null)
        return "error";

    Scanner s = new Scanner(resourceAsStream).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

After this I simply call getStringFromStream("helloworld.json") or getStringFromStream("resourcez/helloworld.json") in my android app and voilà!