问:
Dynamically display an image url with javascript
I am using tag manager to dynamically place information from the website into an html element using custom javascript. My code at the moment is this. PS I can't figure out how to post properly. This actually starts with

```<code>function(){
    console.log("Start image variable");
    var element = document.getElementsByClassName("MagicZoomPlus")[0];
    console.log(element);
    var image = element.getAttribute("img src").innerHTML;
    console.log(image);
    return image;
}
</code>```

This returns the following debug information

```<code>unreachable code after return statement[Learn More]  trustlogo.js:28:123
Start image variable  gtm.js:1:42
<a id="ZoomGallery" href="/uploads/products/892_3521-05 .jpg" class="MagicZoomPlus" title="Franklin Paradigm Grey Sofa">  gtm.js:1:136
undefined  gtm.js:1:186
</code>```

The html on the site I am trying to reach is

```<code><a id="ZoomGallery" href="/uploads/products/892_3521-05 .jpg" class="MagicZoomPlus"   title="Franklin Paradigm Grey Sofa"><img src="/uploads/products/892_3521-05 .jpg" alt="FranklinParadigm Grey Sofa" /></a>
</code>```

答:
This is what I ended up coming up with, which works.</p>

```<code>function myFunc() {
  var img = document.querySelector(".MagicZoomPlus img");

  return img.src
}
</code>```

Body:
I am using tag manager to dynamically place information from the website into an html element using custom javascript. My code at the moment is this. PS I can't figure out how to post properly. This actually starts with

function(){
    console.log("Start image variable");
    var element = document.getElementsByClassName("MagicZoomPlus")[0];
    console.log(element);
    var image = element.getAttribute("img src").innerHTML;
    console.log(image);
    return image;
}

This returns the following debug information

unreachable code after return statement[Learn More]  trustlogo.js:28:123
Start image variable  gtm.js:1:42
  gtm.js:1:136
undefined  gtm.js:1:186

The html on the site I am trying to reach is

Body:
This is what I ended up coming up with, which works.

function myFunc() {
  var img = document.querySelector(".MagicZoomPlus img");

  return img.src
}


来源: stackexchange

问:
Converting a Boost Spirit Lex semantic action to Phoenix - How to access _val?
I wrote a semantic action for my Boost Spirit Lexer to convert escape sequences in strings to what they stand for. It works perfectly and I want to convert it to a Boost Phoenix expression, but can't get that one to compile.

Here is what works:

```<code>// the semantic action
struct ConvertEscapes
{
    template <typename ItT, typename IdT, typename CtxT>
    void operator () (ItT& start, ItT& end, lex::pass_flags& matched, IdT& id, CtxT& ctx)
    {
        static boost::wregex escapeRgx(L"(\\\\r)|(\\\\n)|(\\\\t)|(\\\\\\\\)|(\\\\\")");
        static std::wstring escapeRepl = L"(?1\r)(?2\n)(?3\t)(?4\\\\)(?5\")";
        static std::wstring wval; // static b/c set_value doesn't seem to copy

        auto const& val = ctx.get_value();
        wval.assign(val.begin(), val.end());
        wval = boost::regex_replace(wval,
                                    escapeRgx,
                                    escapeRepl,
                                    boost::match_default | boost::format_all);
        ctx.set_value(wval);
    }
};

// the token declaration
lex::token_def<std::wstring, wchar_t> literal_str;

// the token definition
literal_str  = L"\\\"([^\\\\\"]|(\\\\.))*\\\""; // string with escapes

// adding it to the lexer
this->self += literal_str [ ConvertEscapes() ];
</code>```

This is what I tried to convert it:

```<code>this->self += literal_str
[
    lex::_val = boost::regex_replace(lex::_val /* this is the place I can't figure out */,
                                     boost::wregex(L"(\\\\r)|(\\\\n)|
                                     (\\\\t)|(\\\\\\\\)|(\\\\\")"),
                                     L"(?1\r)(?2\n)(?3\t)(?4\\\\)(?5\")",
                                     boost::match_default | boost::format_all)
];
</code>```

A wstring can't be constructed from _val. _val also doesn't have begin() or end(), how is it supposed to be used anyway?

This std::wstring(lex::_start, lex::_end) fails, too, because those arguments aren't recognized as iterators.

In this question, I found phoenix::construct<std::wstring>(lex::_start, lex::_end), but this also doesn't really result in a wstring.

How do I get either a string or a pair of wchar_t iterators for the current token?

答:
I'm going to chant the oft-heard "Why"?

This time, for good reason.

In general, avoid semantic actions: Boost Spirit: "Semantic actions are evil"?.

Phoenix Actors are needlessly more complex than the dedicated functor. They have a sweet point (mainly simple assignment or builtin operations). But if the actor is any kind of non-trivial you'll see the complexity ramp up quickly, not just for the human but also for the compiler. This leads to

slow compilation

sub-optimal emitted code

harder to maintain source

new classes of error (e.g. when the expression templates hold references to locals/temporaries, something that Boost Proto (and hence Phoenix) does not prevent or signal. In fact, it encourages it by assuming all template expressions are ephemeral, but I digress).

Interestingly: Spirit X3 dropped Phoenix altogether, even though Phoenix was once the brain child of Spirit³.

The new style uses c++14 polymorphic lambdas, that look 90% like the helper function object in the original code, but inline as a lambda.

This specific case

Can't work. At all.

The problem is that you're mixing lazy/deferred actors with direct invocations. That can never work. The type of phoenix::construct<std::wstring>(lex::_start, lex::_end) isn't supposed to be std::wstring. Of course. It is supposed to be a lazy actor¹ that can be used at some later time to create a std::wstring.

Now that we know that (and why) phoenix::construct<std::wstring>(lex::_start, lex::_end) is an actor type, it should become clear why it is completely bogus to call boost::regex_replace on it. You might as well say

```<code>struct implementation_defined {} bogus;
boost::regex_replace(bogus, re, fmt, boost::match_default | boost::format_all);
</code>```

And wonder why it would not compile.

Summary:

You should probably just have the dedicated functor. You can of course Phoenix-adapt the regex functions you require, but all it does is shift the complexity tax for some syntactic sugar.

I'd always opt for the more naive approach that is going to be more understandable to a seasoned c++ programmer, and avoids pitfalls that come with high-wire acts².

Nevertheless, here's a pointer should you be curious:

http://www.boost.org/doc/libs/1_63_0/libs/phoenix/doc/html/phoenix/modules/function.html

Live On Coliru

```<code>#include <iostream>
#include <boost/regex.hpp>
#include <boost/phoenix.hpp>
#include <boost/spirit/include/lex_lexer.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/lex.hpp>

namespace lex = boost::spirit::lex;

BOOST_PHOENIX_ADAPT_FUNCTION(std::wstring, regex_replace_, boost::regex_replace, 4)

template <typename... T>
struct Lexer : lex::lexer<T...> {
    Lexer() {
        // the token definition
        literal_str  = L"\\\"([^\\\\\"]|(\\\\.))*\\\""; // string with escapes

        // adding it to the lexer
        this->self += literal_str [
            lex::_val = regex_replace_(lex::_val,
                 boost::wregex(L"(\\\\r)|(\\\\n)|(\\\\t)|(\\\\\\\\)|(\\\\\")"),
                 L"(?1\r)(?2\n)(?3\t)(?4\\\\)(?5\")",
                 boost::match_default | boost::format_all)

        ];
    }

    // the token declaration
    lex::token_def<std::wstring, wchar_t> literal_str;
};

int main() {
    typedef lex::lexertl::token<std::wstring::const_iterator, boost::mpl::vector<std::wstring, wchar_t>> token_type;
    typedef Lexer<lex::lexertl::actor_lexer<token_type>> lexer_type;
    typedef lexer_type::iterator_type lexer_iterator_type;
}
</code>```

¹ think composed function object that can be invoked at a later time

² the balance might tip if you were designing this as an EDSL for further configuration by non-experts, but then you will have the added responsibility of documenting your EDSL and the constraints in which it can be used

³ should we say, spirit-child of a brain?

ContentLicense: CC BY-SA 3.0

Body:
I wrote a semantic action for my Boost Spirit Lexer to convert escape sequences in strings to what they stand for. It works perfectly and I want to convert it to a Boost Phoenix expression, but can't get that one to compile.

Here is what works:

// the semantic action
struct ConvertEscapes
{
    template <typename ItT, typename IdT, typename CtxT>
    void operator () (ItT& start, ItT& end, lex::pass_flags& matched, IdT& id, CtxT& ctx)
    {
        static boost::wregex escapeRgx(L"(\\\\r)|(\\\\n)|(\\\\t)|(\\\\\\\\)|(\\\\\")");
        static std::wstring escapeRepl = L"(?1\r)(?2\n)(?3\t)(?4\\\\)(?5\")";
        static std::wstring wval; // static b/c set_value doesn't seem to copy

        auto const& val = ctx.get_value();
        wval.assign(val.begin(), val.end());
        wval = boost::regex_replace(wval,
                                    escapeRgx,
                                    escapeRepl,
                                    boost::match_default | boost::format_all);
        ctx.set_value(wval);
    }
};

// the token declaration
lex::token_def<std::wstring, wchar_t> literal_str;

// the token definition
literal_str  = L"\\\"([^\\\\\"]|(\\\\.))*\\\""; // string with escapes

// adding it to the lexer
this->self += literal_str [ ConvertEscapes() ];

This is what I tried to convert it:

this->self += literal_str
[
    lex::_val = boost::regex_replace(lex::_val /* this is the place I can't figure out */,
                                     boost::wregex(L"(\\\\r)|(\\\\n)|
                                     (\\\\t)|(\\\\\\\\)|(\\\\\")"),
                                     L"(?1\r)(?2\n)(?3\t)(?4\\\\)(?5\")",
                                     boost::match_default | boost::format_all)
];

A wstring can't be constructed from _val. _val also doesn't have begin() or end(), how is it supposed to be used anyway?

This std::wstring(lex::_start, lex::_end) fails, too, because those arguments aren't recognized as iterators.

In this question, I found phoenix::construct<std::wstring>(lex::_start, lex::_end), but this also doesn't really result in a wstring.

How do I get either a string or a pair of wchar_t iterators for the current token?

Body:
I'm going to chant the oft-heard "Why"?

This time, for good reason.

In general, avoid semantic actions: Boost Spirit: "Semantic actions are evil"?.

Phoenix Actors are needlessly more complex than the dedicated functor. They have a sweet point (mainly simple assignment or builtin operations). But if the actor is any kind of non-trivial you'll see the complexity ramp up quickly, not just for the human but also for the compiler. This leads to

slow compilation

sub-optimal emitted code

harder to maintain source

new classes of error (e.g. when the expression templates hold references to locals/temporaries, something that Boost Proto (and hence Phoenix) does not prevent or signal. In fact, it encourages it by assuming all template expressions are ephemeral, but I digress).

Interestingly: Spirit X3 dropped Phoenix altogether, even though Phoenix was once the brain child of Spirit³.

The new style uses c++14 polymorphic lambdas, that look 90% like the helper function object in the original code, but inline as a lambda.

This specific case

Can't work. At all.

The problem is that you're mixing lazy/deferred actors with direct invocations. That can never work. The type of phoenix::construct<std::wstring>(lex::_start, lex::_end) isn't supposed to be std::wstring. Of course. It is supposed to be a lazy actor¹ that can be used at some later time to create a std::wstring.

Now that we know that (and why) phoenix::construct<std::wstring>(lex::_start, lex::_end) is an actor type, it should become clear why it is completely bogus to call boost::regex_replace on it. You might as well say

struct implementation_defined {} bogus;
boost::regex_replace(bogus, re, fmt, boost::match_default | boost::format_all);

And wonder why it would not compile.

Summary:

You should probably just have the dedicated functor. You can of course Phoenix-adapt the regex functions you require, but all it does is shift the complexity tax for some syntactic sugar.

I'd always opt for the more naive approach that is going to be more understandable to a seasoned c++ programmer, and avoids pitfalls that come with high-wire acts².

Nevertheless, here's a pointer should you be curious:

http://www.boost.org/doc/libs/1_63_0/libs/phoenix/doc/html/phoenix/modules/function.html

Live On Coliru

#include <iostream>
#include <boost/regex.hpp>
#include <boost/phoenix.hpp>
#include <boost/spirit/include/lex_lexer.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/lex.hpp>

namespace lex = boost::spirit::lex;

BOOST_PHOENIX_ADAPT_FUNCTION(std::wstring, regex_replace_, boost::regex_replace, 4)

template <typename... T>
struct Lexer : lex::lexer<T...> {
    Lexer() {
        // the token definition
        literal_str  = L"\\\"([^\\\\\"]|(\\\\.))*\\\""; // string with escapes

        // adding it to the lexer
        this->self += literal_str [
            lex::_val = regex_replace_(lex::_val,
                 boost::wregex(L"(\\\\r)|(\\\\n)|(\\\\t)|(\\\\\\\\)|(\\\\\")"),
                 L"(?1\r)(?2\n)(?3\t)(?4\\\\)(?5\")",
                 boost::match_default | boost::format_all)

        ];
    }

    // the token declaration
    lex::token_def<std::wstring, wchar_t> literal_str;
};

int main() {
    typedef lex::lexertl::token<std::wstring::const_iterator, boost::mpl::vector<std::wstring, wchar_t>> token_type;
    typedef Lexer<lex::lexertl::actor_lexer<token_type>> lexer_type;
    typedef lexer_type::iterator_type lexer_iterator_type;
}

¹ think composed function object that can be invoked at a later time

² the balance might tip if you were designing this as an EDSL for further configuration by non-experts, but then you will have the added responsibility of documenting your EDSL and the constraints in which it can be used

³ should we say, spirit-child of a brain?


问:
How to search (using regex) for a regex literal in text?
I just stumbled on a case where I had to remove quotes surrounding a specific regex pattern in a file, and the immediate conclusion I came to was to use vim's search and replace util and just escape each special character in the original and replacement patterns.

This worked (after a little tinkering), but it left me wondering if there is a better way to do these sorts of things.

The original regex (quoted): '/^\//' to be replaced with /^\//

And the search/replace pattern I used:

s/'\/\^\\\/\/'/\/\^\\\/\//g

Thanks!

答: Could you avoid using regex entirely by using a nice simple string search and replace?</p>

ContentLicense: CC BY-SA 2.5


问:
Laravel dusk not working .env.dusk.local
I have an application and I want to use Laravel Dusk.

I created a file named .env.dusk.local with a database for tests and a file named .env with my default database.

I ran the php artisan command and created a user by /register.

After I created a login test with the same email but with a different password, this would not be a problem because in .env.dusk.local it would be a different bank and would not have any users registered.

But when I run the php artisan dusk command it takes the information from the original .env and ends up erasing all records from my default database.

I would like to know how to load the information from my .env.dusk.local and use my test database.

.env default

```<code>APP_ENV=local
APP_KEY=base64:K8otIkxJk0rFsZYSEq1hwBuaxQX3QI3Bb7ZmemJRIWg=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost:8000

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_dusk
DB_USERNAME=root
DB_PASSWORD=123456
</code>```

.env.dusk.local

```<code>APP_ENV=local
APP_KEY=base64:K8otIkxJk0rFsZYSEq1hwBuaxQX3QI3Bb7ZmemJRIWg=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost:8000

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_dusk_test
DB_USERNAME=root
DB_PASSWORD=123456
</code>```

Mu function for testLogin

```<code>namespace Tests\Browser;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\App;
use Tests\DuskTestCase;

class LoginTest extends DuskTestCase
{

    use DatabaseMigrations;
    /**
     * A Dusk test example.
     *
     * @return void
     */
    public function testLogin()
    {
        $user = factory(\App\User::class)->create(['email' => 'lucas@example.com']);

        $this->browse(function ($browser) use ($user) {
            $browser->visit('/login')
                    ->type('email', $user->email)
                    ->type('password', 'secret')
                    ->press('Login')
                    ->assertPathIs('/home');
        });
    }
}
</code>```

Here is this project in github

答:
Instead of .env.dusk.local try .env.dusk

Also instead of using your mysql database I would recommend using a temporary sqlite db since it gets created and destroyed during tests.

you will have to have a sqilte config in your database.php that points at an actual .sqlite file that you have in your installation

so copy the sqlite config in database.php and then paste it, name it sqlite_dusk maybe, then for the location of the db put it as storage_path('dusk.sqlite') or something like that. Then create a blank dusk.sqlite file in the root of your storage folder.

Then in your .env.dusk set:

```<code>DB_CONNECTION=sqlite_dusk
</code>```

Hope that helps!

Body:
I have an application and I want to use Laravel Dusk.

I created a file named .env.dusk.local with a database for tests and a file named .env with my default database.

I ran the php artisan command and created a user by /register.

After I created a login test with the same email but with a different password, this would not be a problem because in .env.dusk.local it would be a different bank and would not have any users registered.

But when I run the php artisan dusk command it takes the information from the original .env and ends up erasing all records from my default database.

I would like to know how to load the information from my .env.dusk.local and use my test database.

.env default

APP_ENV=local
APP_KEY=base64:K8otIkxJk0rFsZYSEq1hwBuaxQX3QI3Bb7ZmemJRIWg=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost:8000

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_dusk
DB_USERNAME=root
DB_PASSWORD=123456

.env.dusk.local

APP_ENV=local
APP_KEY=base64:K8otIkxJk0rFsZYSEq1hwBuaxQX3QI3Bb7ZmemJRIWg=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost:8000

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_dusk_test
DB_USERNAME=root
DB_PASSWORD=123456

Mu function for testLogin

namespace Tests\Browser;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\App;
use Tests\DuskTestCase;

class LoginTest extends DuskTestCase
{

    use DatabaseMigrations;
    /**
     * A Dusk test example.
     *
     * @return void
     */
    public function testLogin()
    {
        $user = factory(\App\User::class)->create(['email' => 'lucas@example.com']);

        $this->browse(function ($browser) use ($user) {
            $browser->visit('/login')
                    ->type('email', $user->email)
                    ->type('password', 'secret')
                    ->press('Login')
                    ->assertPathIs('/home');
        });
    }
}

Here is this project in github

Body:
Instead of .env.dusk.local try .env.dusk

Also instead of using your mysql database I would recommend using a temporary sqlite db since it gets created and destroyed during tests.

you will have to have a sqilte config in your database.php that points at an actual .sqlite file that you have in your installation

so copy the sqlite config in database.php and then paste it, name it sqlite_dusk maybe, then for the location of the db put it as storage_path('dusk.sqlite') or something like that. Then create a blank dusk.sqlite file in the root of your storage folder.

Then in your .env.dusk set:

DB_CONNECTION=sqlite_dusk

Hope that helps!


问:
Passing argument makes a pointer without cast?
I'm having an issue with compling the code.
I keep getting these errors.

"C: 194 warning passing argument 3 of 'matrix_column_subtract' makes pointer from integer without a cast"

"C: 12 note: expected 'double**' but argument is type 'int'

"C: 194 error too few arguments to function 'matrix_column_subtract'

I think I know what is going on I'm calling matrix_column_multiply is a void and I need to be calling it a pointer pointer I think and I don't know how to chage that. If anyone has some idea on how I can get this to compile that would be highly appreciated!!

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define DEBUG 0
#define MAX_ITER 10000

double *eigen (int n, double **A);
void qr_decomp (int n, double **A, double **Q, double **R);

void matrix_copy_column(double **msrc, int col1, double **mdst,int col2, int rows);
void matrix_column_subtract(double **m1, int c1, double **m2, int c2, int rows);
void matrix_column_multiply(double **m, int c, double k, int rows);

int main() {

    int i, n = 126;
    double *eig, **Am;
    FILE *BinInp, *TxtOut;

    /* Input Code: Reads bv, Am in binary form from CGrad.bin */
    if ( (BinInp = fopen("CGrad.bin","r")) == NULL ) {
        fprintf(stderr, "Cannot open matrix binary file INPUT... exiting\n");
        exit(-1);
    }

    Am = (double**)malloc (n*sizeof(double*));
    Am[0] = (double*)malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        Am[i] = Am[0] + i*n;
    }
    for (i = 0; i < n; i++) {
        if (i==0) { /* Read one extra line that is discarded (bv is still in bin       file) */
            if (!fread(Am[i], sizeof(double), n, BinInp)) {
                fprintf(stderr, "Cannot read row Am[%03d] of matrix...      exiting\n", i+1);
                exit(1);
            }
        }
        if (!fread(Am[i], sizeof(double), n, BinInp)) {
            fprintf(stderr, "Cannot read row Am[%03d] of matrix... exiting\n",  i+1);
            exit(1);
        }
    }

    if (fclose(BinInp) == EOF) {
        fprintf(stderr, "Cannot close matrix binary file INPUT... exiting\n");
        exit(-1);
    }

    /* COMPUTE EIGENVALUES HERE USING FUNCTIONS. RETURN EIGENVALUES (AS 1D    VECTOR) TO eig. */
    if (DEBUG) printf ("Calling eigen\n");
    eig = eigen (n, Am);

    /* Output Code: Writes eig in text form to Eigs.txt */

    if ( (TxtOut = fopen("Eigs.txt", "w")) == NULL ) {
        fprintf(stderr, "Cannot open matrix text file OUTPUT... exiting\n");
        exit(-1);
    }
    for (i = 0; i < n; i++) {
        fprintf (TxtOut, "%18.14e ", eig[i]);
    }

    if (fclose(TxtOut) == EOF) {
        fprintf(stderr, "Cannot close matrix text file INPUT... exiting\n");
        exit(-1);
    }

    return 0;
}

double* eigen (int n, double **Acur)
{
    double err = 1, eps = 1e-2;
    double ndenom, nnumer, temp;
    double *eig, **Anex, **Qsub, **Rsub;
    int i, j, k, iters = 1;

    /* Malloc memory for the three matricies */
    Anex = malloc (n*sizeof(double*));
    Anex[0] = malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        Anex[i] = Anex[0] + i*n;
    }
    Qsub = malloc (n*sizeof(double*));
    Qsub[0] = malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        Qsub[i] = Qsub[0] + i*n;
    }
    Rsub = malloc (n*sizeof(double*));
    Rsub[0] = malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        Rsub[i] = Rsub[0] + i*n;
    }

    /* Malloc memory for the return eig vector */
    eig  = malloc (n*sizeof(double));
    for (i = 0; i < n; i++) {
        eig[i] = 0;
    }

    /* Enter main iteration loop for eigenvalues */
    while (err > eps && iters < MAX_ITER) {

        /* QR Decompose Acur then find next iterate value in Anex */
        qr_decomp (n, Acur, Qsub, Rsub);
        // FIND NEXT ITERATE VALUE, PUT IN Anex.

        /* Determine relative error change, reset "old" iterate value. */
        ndenom = 0;
        nnumer = 0;
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                temp = Anex[i][j]-Acur[i][j];
                ndenom += temp*temp;
                nnumer += Anex[i][j]*Anex[i][j];

                Acur[i][j] = Anex[i][j];
            }
        }
        err = sqrt(ndenom)/sqrt(nnumer);

        /* Increment the iteration count and report error */
        if (iters % 25 == 0) {
            printf ("Error at end of iteration %05d = %14.10f %%\n", iters,   100*err);
        }
        ++iters;
    }
    printf ("Error at end of iteration %05d = %14.10f\nCONVERGED.\n", iters-1, err);

    if (iters == MAX_ITER) {
        printf ("WARNING: MAX_ITER iterations reached!...\n");
    }

    /* Copy diagonal entries of Acur into eig for return to main */
    for (i=0; i<n; i++) {
        eig[i] = Acur[i][i];
    }
    return eig;
}

void qr_decomp (int n, double **Adec, double **myQ, double **myR)
{
    int i, j, k; /* Loop Variables: this is all you should need! */
    double **T, **S;
    double r;

    T = malloc (n*sizeof(double*));
    T[0] = malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        T[i] = T[0] + i*n;
    }

    S = malloc (n*sizeof(double*));
    S[0] = malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        S[i] = S[0] + i*n;
    }

    /* Main loop for decomposition */
    for (i=0; i<n; i++) {
        /* Column i of Q is initially column i of A */

        matrix_copy_column(Adec,i,myQ,i,n);

        /* For j < i-1, Perform the dot product between the j row of Q and the
        i row of A to determine the R(j,i) value, then insure the Q i column
        is orthogonal to all other Q columns by subtracting existing Q columns
        from it. */

        for (j = 0; j < i; j++) {

            //r[j,i] = Qj^T * Ui
            matrix_copy_column(myQ,j,T,0,n);
            matrix_copy_column(Adec,i,S,0,n);

            for (k=0; k<n; k++) {
                r += T[k][0] * S[k][0];
            }
            /* Determine the R diagonal as the magnitude of the Q column, then
            normalize the Q column (make it a unit vector). */

            //Qi = Ui

            myR[j][i] = r;

            // Something wrong here.
            // There is one parameter missing, as matrix_column_subtract needs 5 parameters and
            // only 4 are given.
            // Also, matrix_column_multiply is defined as returning a void, whereas the   3rd parameter
            // of matrix_column_subtract should be a double **

            matrix_column_subtract(myQ,i,matrix_column_multiply(T,0,r,n),j);

        }
    }
}

/* Copies a matrix column from msrc at column col1 to mdst at column col2 */
void matrix_copy_column(double **msrc, int col1, double **mdst,int col2, int rows) {
    int i = 0;
    for (i=0; i<rows; i++) {
        mdst[i][col2] = msrc[i][col1];
    }
}

/* Subtracts m2's column c2 from m1's column c1 */
void matrix_column_subtract(double **m1, int c1, double **m2, int c2, int rows) {
    int i = 0;
    for (i=0; i<rows; i++) {
        m1[i][c1] -= m2[i][c2];
    }
    /*return m1;*/
}

void matrix_column_multiply(double **m, int c, double k, int rows) {
    int i = 0;
    for (i=0; i<rows; i++) {
        m[i][c] *= k;
    }
    /*return m;*/
}
</code>```

答:
A problem is here.

```<code>matrix_column_subtract(myQ,i,matrix_column_multiply(T,0,r,n),j);
</code>```

The relevant function signatures are:

```<code>void matrix_column_subtract(double **m1, int c1, double **m2, int c2, int rows);
void matrix_column_multiply(double **m, int c, double k, int rows);
</code>```

Note that matrix_column_multiply returns void, but you're passing it in as if it were double **. I'm guessing the compiler is desperately trying to make it work and returned some sort of garbage integer.

These functions return void because they do their work directly on the matrix in question. matrix_column_multiply alters m. matrix_column_subtract alters m1.

To make it work, call matrix_column_multiply on T then pass T (now modified by the multiplication) into matrix_column_subtract.

```<code>matrix_column_multiply(T, 0, r, n);
matrix_column_subtract(myQ, i, T, j, ...rows...);
</code>```

You're still missing the fifth argument, rows. I'm going to guess that's n, same as has been used for the rows in every other matrix_column_blah call.

Body:
I'm having an issue with compling the code.
I keep getting these errors.

"C: 194 warning passing argument 3 of 'matrix_column_subtract' makes pointer from integer without a cast"

"C: 12 note: expected 'double**' but argument is type 'int'

"C: 194 error too few arguments to function 'matrix_column_subtract'

I think I know what is going on I'm calling matrix_column_multiply is a void and I need to be calling it a pointer pointer I think and I don't know how to chage that. If anyone has some idea on how I can get this to compile that would be highly appreciated!!

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define DEBUG 0
#define MAX_ITER 10000

double *eigen (int n, double **A);
void qr_decomp (int n, double **A, double **Q, double **R);

void matrix_copy_column(double **msrc, int col1, double **mdst,int col2, int rows);
void matrix_column_subtract(double **m1, int c1, double **m2, int c2, int rows);
void matrix_column_multiply(double **m, int c, double k, int rows);

int main() {

    int i, n = 126;
    double *eig, **Am;
    FILE *BinInp, *TxtOut;

    /* Input Code: Reads bv, Am in binary form from CGrad.bin */
    if ( (BinInp = fopen("CGrad.bin","r")) == NULL ) {
        fprintf(stderr, "Cannot open matrix binary file INPUT... exiting\n");
        exit(-1);
    }

    Am = (double**)malloc (n*sizeof(double*));
    Am[0] = (double*)malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        Am[i] = Am[0] + i*n;
    }
    for (i = 0; i < n; i++) {
        if (i==0) { /* Read one extra line that is discarded (bv is still in bin       file) */
            if (!fread(Am[i], sizeof(double), n, BinInp)) {
                fprintf(stderr, "Cannot read row Am[%03d] of matrix...      exiting\n", i+1);
                exit(1);
            }
        }
        if (!fread(Am[i], sizeof(double), n, BinInp)) {
            fprintf(stderr, "Cannot read row Am[%03d] of matrix... exiting\n",  i+1);
            exit(1);
        }
    }

    if (fclose(BinInp) == EOF) {
        fprintf(stderr, "Cannot close matrix binary file INPUT... exiting\n");
        exit(-1);
    }

    /* COMPUTE EIGENVALUES HERE USING FUNCTIONS. RETURN EIGENVALUES (AS 1D    VECTOR) TO eig. */
    if (DEBUG) printf ("Calling eigen\n");
    eig = eigen (n, Am);

    /* Output Code: Writes eig in text form to Eigs.txt */

    if ( (TxtOut = fopen("Eigs.txt", "w")) == NULL ) {
        fprintf(stderr, "Cannot open matrix text file OUTPUT... exiting\n");
        exit(-1);
    }
    for (i = 0; i < n; i++) {
        fprintf (TxtOut, "%18.14e ", eig[i]);
    }

    if (fclose(TxtOut) == EOF) {
        fprintf(stderr, "Cannot close matrix text file INPUT... exiting\n");
        exit(-1);
    }

    return 0;
}

double* eigen (int n, double **Acur)
{
    double err = 1, eps = 1e-2;
    double ndenom, nnumer, temp;
    double *eig, **Anex, **Qsub, **Rsub;
    int i, j, k, iters = 1;

    /* Malloc memory for the three matricies */
    Anex = malloc (n*sizeof(double*));
    Anex[0] = malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        Anex[i] = Anex[0] + i*n;
    }
    Qsub = malloc (n*sizeof(double*));
    Qsub[0] = malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        Qsub[i] = Qsub[0] + i*n;
    }
    Rsub = malloc (n*sizeof(double*));
    Rsub[0] = malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        Rsub[i] = Rsub[0] + i*n;
    }

    /* Malloc memory for the return eig vector */
    eig  = malloc (n*sizeof(double));
    for (i = 0; i < n; i++) {
        eig[i] = 0;
    }

    /* Enter main iteration loop for eigenvalues */
    while (err > eps && iters < MAX_ITER) {

        /* QR Decompose Acur then find next iterate value in Anex */
        qr_decomp (n, Acur, Qsub, Rsub);
        // FIND NEXT ITERATE VALUE, PUT IN Anex.

        /* Determine relative error change, reset "old" iterate value. */
        ndenom = 0;
        nnumer = 0;
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                temp = Anex[i][j]-Acur[i][j];
                ndenom += temp*temp;
                nnumer += Anex[i][j]*Anex[i][j];

                Acur[i][j] = Anex[i][j];
            }
        }
        err = sqrt(ndenom)/sqrt(nnumer);

        /* Increment the iteration count and report error */
        if (iters % 25 == 0) {
            printf ("Error at end of iteration %05d = %14.10f %%\n", iters,   100*err);
        }
        ++iters;
    }
    printf ("Error at end of iteration %05d = %14.10f\nCONVERGED.\n", iters-1, err);

    if (iters == MAX_ITER) {
        printf ("WARNING: MAX_ITER iterations reached!...\n");
    }

    /* Copy diagonal entries of Acur into eig for return to main */
    for (i=0; i<n; i++) {
        eig[i] = Acur[i][i];
    }
    return eig;
}

void qr_decomp (int n, double **Adec, double **myQ, double **myR)
{
    int i, j, k; /* Loop Variables: this is all you should need! */
    double **T, **S;
    double r;

    T = malloc (n*sizeof(double*));
    T[0] = malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        T[i] = T[0] + i*n;
    }

    S = malloc (n*sizeof(double*));
    S[0] = malloc (n*n*sizeof(double));
    for (i = 1; i < n; ++i) {
        S[i] = S[0] + i*n;
    }

    /* Main loop for decomposition */
    for (i=0; i<n; i++) {
        /* Column i of Q is initially column i of A */

        matrix_copy_column(Adec,i,myQ,i,n);

        /* For j < i-1, Perform the dot product between the j row of Q and the
        i row of A to determine the R(j,i) value, then insure the Q i column
        is orthogonal to all other Q columns by subtracting existing Q columns
        from it. */

        for (j = 0; j < i; j++) {

            //r[j,i] = Qj^T * Ui
            matrix_copy_column(myQ,j,T,0,n);
            matrix_copy_column(Adec,i,S,0,n);

            for (k=0; k<n; k++) {
                r += T[k][0] * S[k][0];
            }
            /* Determine the R diagonal as the magnitude of the Q column, then
            normalize the Q column (make it a unit vector). */

            //Qi = Ui

            myR[j][i] = r;

            // Something wrong here.
            // There is one parameter missing, as matrix_column_subtract needs 5 parameters and
            // only 4 are given.
            // Also, matrix_column_multiply is defined as returning a void, whereas the   3rd parameter
            // of matrix_column_subtract should be a double **

            matrix_column_subtract(myQ,i,matrix_column_multiply(T,0,r,n),j);

        }
    }
}

/* Copies a matrix column from msrc at column col1 to mdst at column col2 */
void matrix_copy_column(double **msrc, int col1, double **mdst,int col2, int rows) {
    int i = 0;
    for (i=0; i<rows; i++) {
        mdst[i][col2] = msrc[i][col1];
    }
}

/* Subtracts m2's column c2 from m1's column c1 */
void matrix_column_subtract(double **m1, int c1, double **m2, int c2, int rows) {
    int i = 0;
    for (i=0; i<rows; i++) {
        m1[i][c1] -= m2[i][c2];
    }
    /*return m1;*/
}

void matrix_column_multiply(double **m, int c, double k, int rows) {
    int i = 0;
    for (i=0; i<rows; i++) {
        m[i][c] *= k;
    }
    /*return m;*/
}

Body:
A problem is here.

matrix_column_subtract(myQ,i,matrix_column_multiply(T,0,r,n),j);

The relevant function signatures are:

void matrix_column_subtract(double **m1, int c1, double **m2, int c2, int rows);
void matrix_column_multiply(double **m, int c, double k, int rows);

Note that matrix_column_multiply returns void, but you're passing it in as if it were double **. I'm guessing the compiler is desperately trying to make it work and returned some sort of garbage integer.

These functions return void because they do their work directly on the matrix in question. matrix_column_multiply alters m. matrix_column_subtract alters m1.

To make it work, call matrix_column_multiply on T then pass T (now modified by the multiplication) into matrix_column_subtract.

matrix_column_multiply(T, 0, r, n);
matrix_column_subtract(myQ, i, T, j, ...rows...);

You're still missing the fifth argument, rows. I'm going to guess that's n, same as has been used for the rows in every other matrix_column_blah call.


问:
Java repeat part of a program with if and boolean operators
Hello I'm fairly new to java and I had troubles in a little test game.
So this is just a part of the code, I want that the user can repeat the part as often as he like with an while operater.

The code is here:

```<code>else if (a == 6){
        boolean InGame = true;
        while ( InGame );

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = scan.nextLine();
        if  (PlayAgain == "nein");
        boolean inGame = false;
</code>```

Well I have never worked alot with booleans due to me being new in java.
Would nice if you could help me out.

答:
```<code>else if (a == 6){
Scanner scan=new Scanner(System.in);
            boolean InGame = true;
            do{

            System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
            System.out.println("Spieler Eins");
            double playerOne = scan.nextDouble();
            System.out.println("Spieler Zwei");
            double playerTwo = scan.nextDouble();

            double randomValue = Math.random() * 100.0;

            // Math.abs
            double spacingOne = Math.abs(playerOne - randomValue);
            double spacingTwo = Math.abs(playerTwo - randomValue);
            System.out.println("Die Random Zahl war " + randomValue);

            if (spacingOne < spacingTwo) {
                System.out.println("Spieler Eins hat gewonnen!");
            }

            if (spacingOne > spacingTwo) {
                System.out.println("Spieler Zwei hat gewonnen!");
            }

            if (spacingOne == spacingTwo) {
                System.out.println("Unentschieden!");
            }
            System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
            String PlayAgain = scan.nextLine();
            if  (PlayAgain == "nein"){
            boolean inGame = false;
            }
            }
            while ( InGame );
</code>```

Body:
Hello I'm fairly new to java and I had troubles in a little test game.
So this is just a part of the code, I want that the user can repeat the part as often as he like with an while operater.

The code is here:

else if (a == 6){
        boolean InGame = true;
        while ( InGame );

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = scan.nextLine();
        if  (PlayAgain == "nein");
        boolean inGame = false;

Well I have never worked alot with booleans due to me being new in java.
Would nice if you could help me out.


问:
Apache Storm vs Apache Samza vs Apache Spark
I have worked on Storm and Spark but Samza is quite new.

I do not understand why Samza was introduced when Storm is already there for real time processing. Spark provides in memory near real time processing and has other very useful components as graphx and mllib.

What are improvements that Samza brings and what further improvements are possible?

答:
This is a good summary of the differences and pros and cons.

I would just add that Samza, which actually isn't that new, brings a certain simplicity since it is opinionated on the use of Kafka as its backend, while others try to be more generic at the cost of simplicity. Samza is pioneered by the same people who created Kafka, who are also the same people behind the Kappa Architecture--primarily Jay Kreps formerly of LinkedIn. That's pretty cool.

Also, the programming models are totally different between realtime streams with Samza, microbatches in Spark Streaming (which isn't exactly the same as Spark), and spouts and bolts with tuples in Storm.

None of these are "better." It all depends on your use cases, the strengths of your team, how the APIs match up with your mental models, quality of support, etc.

You also forgot Apache Flink and Twitter's Heron, which they made because Storm started to fail them. Then again, very few need to operate at the scale of Twitter.


问:
Laravel database connections
I'm using Laravel 5. I see Laravel uses .env to connect databases for example DB_USERNAME and DB_PASSWORD, but i want to log in and use my username and password from my form to connect with those values from withim my oracle database with a table name "dba_users" which has the user and password and some others fields

i want to do that becauses each user has their own granted permissions(roles) to certain tables, thus Oracle would managed the user login permissions and not the .env DB_USERNAME.

Any ideas?

Thanks

答: The real term or question title for this would be "Dynamic Laravel Database Connections" on multi-tenant application. If you google about it you will find a lot of code like this: https://laracasts.com/discuss/channels/tips/set-up-dynamic-database-connection-globally</p>

Title: Laravel database connections


问:
making a loop to display buttons
I am trying to make a loop that will display some images and add an event listener to each image which, when clicked will assign the appropriate value to humanGoal. I have:

```<code>var humanGoal;

function displayPicker(round){
    for(var i = 0; i <= round; i++){
        document.write('<img src=img/die' + i + '.png id="' + 'picker' + i + '">');
        document.getElementById('picker'+i).addEventListener("click", function () {
            humanGoal = i;
            document.write('you picked ' + humanGoal );
        });
    }
}
</code>```

why does humanGoal always === round+1, instead of the variable i from the for loop?

答:
See answer to your question is simple, when you were trying to assign human goal with value of i, the loop is already been iterated over "rounds" value that why you always getting i === round inside click function.

See the below code snippet,

```

for getting the correct result you can follow the approach provided by @Kind user

Title: making a loop to display buttons

Body:
I am trying to make a loop that will display some images and add an event listener to each image which, when clicked will assign the appropriate value to humanGoal. I have:

var humanGoal;

function displayPicker(round){
    for(var i = 0; i <= round; i++){
        document.write('');
        document.getElementById('picker'+i).addEventListener("click", function () {
            humanGoal = i;
            document.write('you picked ' + humanGoal );
        });
    }
}

why does humanGoal always === round+1, instead of the variable i from the for loop?

Body:
See answer to your question is simple, when you were trying to assign human goal with value of i, the loop is already been iterated over "rounds" value that why you always getting i === round inside click function.

See the below code snippet,

<html>
 <script>
 var humanGoal;

  function displayPicker(round){
   for(var i = 0; i <= round; i++){
    document.write('<img src=img/die' + i + '.png id="' + 'picker' + i + '">');
    document.getElementById('picker'+i).addEventListener("click", function () {
     console.log("me getting called second");
     humanGoal = i;
     document.body.append('you picked ' + humanGoal );
    });
    console.log("me getting called first");
   }
  }

 </script>
 <body onload="displayPicker(4)">
 </body>
</html>

for getting the correct result you can follow the approach provided by @Kind user


问:
How do you set the UserState in the RunWorkerCompletedEventArgs object?
HI all.
I have an array of BackgroundWorker objects running instances of a Worker class.  When I call the Worker class the object instance does it's thing and then runs out of code (the loop finishes).  I'm able to listen to the RunWorkerCompleted() event but when it calls the delegate that I've set up I need to know which of my Worker objects just completed.

I see a UserState property in the RunWorkerCompletedEventArgs that comes to my delegate but I have no idea how to set this in my Worker object as it's finishing.

Any ideas?

snippet from my WorkManager.cs class

```<code>public Worker AddWorker()
{
    Worker w = new Worker();

    _workers.Add(w.WorkerID,w);

    BackgroundWorker bg = new BackgroundWorker();
    _bgworkers.Add(bg);

    bg.DoWork += w.Start;
    bg.WorkerReportsProgress = true;
    bg.WorkerSupportsCancellation = true;
    bg.ProgressChanged += ProcessWorkerMessage;
    bg.RunWorkerCompleted += WorkerFinished;

    w.WorkManager = this;
    w.BackgroundWorker = bg;

    bg.RunWorkerAsync(w);

    return w;

}

public void WorkerFinished(object sender, RunWorkerCompletedEventArgs e)
{
    if (_onManagerEvent != null)
        _onManagerEvent(new ManagerEvent { EventDate = DateTime.Now, Message = "Worker ??? successfully ended." });
}
</code>```

So when my Worker object finishes the loop in its Start() method, what do I do to fill the userState property of the RunWorkerCompleteEventArgs object "e" that is passed to my WorkerFinished method()?

Thanks

答:
Your Start method on the Worker class can set the Result property of the DoWorkEventArgs argument.   Here's an example:

```<code>void Start(object sender, DoWorkEventArgs e)
{
   //Do your loop and other work.
   e.Result = this;
}
</code>```

Then in the finish event handler, you can retrieve e.Result:

```<code>public void WorkerFinished(object sender, RunWorkerCompletedEventArgs e)
{
    //You should always check e.Cancelled and e.Error before checking e.Result!
    // ... even though I'm skipping that here

    Worker w = e.Result as Worker;
    if( w != null)
    {
        if (_onManagerEvent != null)
            _onManagerEvent(new ManagerEvent
                    {
                      EventDate = DateTime.Now,
                      Message = String.Format("Worker {0} successfully ended."
                                              , w.ToString())
                    });
    }
}
</code>```

Body:
HI all.
I have an array of BackgroundWorker objects running instances of a Worker class.  When I call the Worker class the object instance does it's thing and then runs out of code (the loop finishes).  I'm able to listen to the RunWorkerCompleted() event but when it calls the delegate that I've set up I need to know which of my Worker objects just completed.

I see a UserState property in the RunWorkerCompletedEventArgs that comes to my delegate but I have no idea how to set this in my Worker object as it's finishing.

Any ideas?

snippet from my WorkManager.cs class

public Worker AddWorker()
{
    Worker w = new Worker();

    _workers.Add(w.WorkerID,w);

    BackgroundWorker bg = new BackgroundWorker();
    _bgworkers.Add(bg);

    bg.DoWork += w.Start;
    bg.WorkerReportsProgress = true;
    bg.WorkerSupportsCancellation = true;
    bg.ProgressChanged += ProcessWorkerMessage;
    bg.RunWorkerCompleted += WorkerFinished;

    w.WorkManager = this;
    w.BackgroundWorker = bg;

    bg.RunWorkerAsync(w);

    return w;

}

public void WorkerFinished(object sender, RunWorkerCompletedEventArgs e)
{
    if (_onManagerEvent != null)
        _onManagerEvent(new ManagerEvent { EventDate = DateTime.Now, Message = "Worker ??? successfully ended." });
}

So when my Worker object finishes the loop in its Start() method, what do I do to fill the userState property of the RunWorkerCompleteEventArgs object "e" that is passed to my WorkerFinished method()?

Thanks

Body:
Your Start method on the Worker class can set the Result property of the DoWorkEventArgs argument.   Here's an example:

void Start(object sender, DoWorkEventArgs e)
{
   //Do your loop and other work.
   e.Result = this;
}

Then in the finish event handler, you can retrieve e.Result:

public void WorkerFinished(object sender, RunWorkerCompletedEventArgs e)
{
    //You should always check e.Cancelled and e.Error before checking e.Result!
    // ... even though I'm skipping that here

    Worker w = e.Result as Worker;
    if( w != null)
    {
        if (_onManagerEvent != null)
            _onManagerEvent(new ManagerEvent
                    {
                      EventDate = DateTime.Now,
                      Message = String.Format("Worker {0} successfully ended."
                                              , w.ToString())
                    });
    }
}


问:
SSRS 2008 - How to link 2 or more year parameters into 1
After some research, I see that blending parameters is a popular topic but I haven't found a solution to this specific situation. Shortly said, I have 3 parameters from various datasets all stating the same year and I want to blend them (visually) into 1 so to eliminate this redundancy for my report's end-user.

In the "Available values" from "Parameter properties", all the values are taken from a dataset (hidden) and the "value field" is [Measures].[ParameterValue] from their corresponding hidden dataset.

When I "show hidden datasets" and go into "text mode" of each of these hiden datasets are these are the 3 MEMBER [Measures].[ParameterValue] AS :

```<code>[Time].[Financial Year].CURRENTMEMBER.UNIQUENAME
[Financial Period].[FP - Year].CURRENTMEMBER.UNIQUENAME
[Time exit].[Financial Year Exit].CURRENTMEMBER.UNIQUENAME
</code>```

When you look at what value this gives, they have the following output (accordingly):

```<code>[Time].[Financial Year].&[2017]
[Financial Period].[FP - Year].[FP - Year].&[2017]
[Time exit].[Financial Year Exit].Financial Year Exit].&[2017]
</code>```

A. So, in my opinion, since the "roots" of each [Year] parameter value are different I need to create a dataset or a member within each of these hidden datasets that replaces this [2017]. Is that "doable" and, if yes, any guidance on how?

B. If not, another outcome would be acceptable as well: the end user would need to generate mostly current year and current year-1. To tackle this I made a Template "Year" DS with the same content as in FP - Year and added the following members:

```<code>Member [Measures].[Last Year] as 'YEAR(NOW())-1'
Member [Measures].[Current Year] as 'YEAR(NOW())'
</code>```

I inserted them into SELECT and previewed, it displays 2 new columns with 2017 and 2016. Then I went and changed in that PF-Year parameter's DS, value and label and I get an error. Any suggestions?

Any suggestions on this?

EDIT1: I have tackled B. and found a solution to it, I simply created the following 2 Default values for each parameter:

Current year: ="[Time].[Financial Year].&[" + CStr(Year(Now())) + "]"

Last year: ="[Time].[Financial Year].&[" + CStr(Year(Now())-1) + "]"

However, even though with this result I presume it will minimize the number of actions for the end-user, I would still prefer having 1 parameter showing instead of 3...

EDIT2 & partial solution I found another solution for A., it's not exactly what I wanted but it kind of gets the job done.

Created a new Year parameter with 2 available values: [CurrentYear] and [LastYear]

For each of the default values of each other parameter, I swaped the 2017 and 2016 values for CStr(Parameters!Year.Value(0)) and for CStr(Parameters!Year.Value(1)) accordingly. Example: ="[Year exit].[Financial Year exit].&[" + CStr(Parameters!Year.Value(0)) + "]".

In the options of each parameter, I set them as "Hidden" expect for my new Year parameter.

Now, I have 1 Year parameter with a dropdown list displaying Current Year and Last Year.

Even though this alleviates the issue, is there anyway to have a similar outcome but with the drop down menu displaying the actual years? i.e. it would be dynamic so in years to come, there would be 2018, 2019, etc. that would pop up? This way the end user would be able to compare not only current and past year but any 2 years?

Thanks to all!

EDIT3 Here is a screen shot of where I am at, at this point:

EDIT4

I have arrived to a fix: since I know that the end-users will only be comparing 2 years at a time (so 2 default values per parameter), I left hidden 2 parameters out of 3 and for the 2 hidden, I changed their default values.
So, I kept @[Financial Year] as my main parameter and the others have the following default values:

@[FP - Year]:

="[Financial Period].[FP - Year].[FP - Year].&[" + CStr(Parameters!Financial Year(0)) + "]"
="[Financial Period].[FP - Year].[FP - Year].&[" + CStr(Parameters!Financial Year(1)) + "]"

@[Financial Year exit]:

="[Year exit].[Financial Year exit].&[" + CStr(Parameters!Financial Year(0)) + "]"
="[Year exit].[Financial Year exit].&[" + CStr(Parameters!Financial Year(1)) + "]"

And voilà the result:

答:
I'd suggest two ways:

1: SSRS: add an invisible parameter (i.e. CurrentYear) and run in your MDX query the following:

```<code>StrToMember('[Time].[Financial Year].&[' +@CurrentYear + ']')
</code>```

2: MDX: add a dynamic calculated members for each hierarchy:

```<code>member [Time].[Financial Year].[Current Year] as
StrToMember('[Time].[Financial Year].&[' + Format(Now(),'yyyy') + ']')
</code>```

See my blog post for more details.

Body:
After some research, I see that blending parameters is a popular topic but I haven't found a solution to this specific situation. Shortly said, I have 3 parameters from various datasets all stating the same year and I want to blend them (visually) into 1 so to eliminate this redundancy for my report's end-user.

In the "Available values" from "Parameter properties", all the values are taken from a dataset (hidden) and the "value field" is [Measures].[ParameterValue] from their corresponding hidden dataset.

When I "show hidden datasets" and go into "text mode" of each of these hiden datasets are these are the 3 MEMBER [Measures].[ParameterValue] AS :

[Time].[Financial Year].CURRENTMEMBER.UNIQUENAME
[Financial Period].[FP - Year].CURRENTMEMBER.UNIQUENAME
[Time exit].[Financial Year Exit].CURRENTMEMBER.UNIQUENAME

When you look at what value this gives, they have the following output (accordingly):

[Time].[Financial Year].&[2017]
[Financial Period].[FP - Year].[FP - Year].&[2017]
[Time exit].[Financial Year Exit].Financial Year Exit].&[2017]

A. So, in my opinion, since the "roots" of each [Year] parameter value are different I need to create a dataset or a member within each of these hidden datasets that replaces this [2017]. Is that "doable" and, if yes, any guidance on how?

B. If not, another outcome would be acceptable as well: the end user would need to generate mostly current year and current year-1. To tackle this I made a Template "Year" DS with the same content as in FP - Year and added the following members:

Member [Measures].[Last Year] as 'YEAR(NOW())-1'
Member [Measures].[Current Year] as 'YEAR(NOW())'

I inserted them into SELECT and previewed, it displays 2 new columns with 2017 and 2016. Then I went and changed in that PF-Year parameter's DS, value and label and I get an error. Any suggestions?

Any suggestions on this?

EDIT1: I have tackled B. and found a solution to it, I simply created the following 2 Default values for each parameter:

Current year: ="[Time].[Financial Year].&[" + CStr(Year(Now())) + "]"

Last year: ="[Time].[Financial Year].&[" + CStr(Year(Now())-1) + "]"

However, even though with this result I presume it will minimize the number of actions for the end-user, I would still prefer having 1 parameter showing instead of 3...

EDIT2 & partial solution I found another solution for A., it's not exactly what I wanted but it kind of gets the job done.

Created a new Year parameter with 2 available values: [CurrentYear] and [LastYear]

For each of the default values of each other parameter, I swaped the 2017 and 2016 values for CStr(Parameters!Year.Value(0)) and for CStr(Parameters!Year.Value(1)) accordingly. Example: ="[Year exit].[Financial Year exit].&[" + CStr(Parameters!Year.Value(0)) + "]".

In the options of each parameter, I set them as "Hidden" expect for my new Year parameter.

Now, I have 1 Year parameter with a dropdown list displaying Current Year and Last Year.

Even though this alleviates the issue, is there anyway to have a similar outcome but with the drop down menu displaying the actual years? i.e. it would be dynamic so in years to come, there would be 2018, 2019, etc. that would pop up? This way the end user would be able to compare not only current and past year but any 2 years?

Thanks to all!

EDIT3 Here is a screen shot of where I am at, at this point:

EDIT4

I have arrived to a fix: since I know that the end-users will only be comparing 2 years at a time (so 2 default values per parameter), I left hidden 2 parameters out of 3 and for the 2 hidden, I changed their default values.
So, I kept @[Financial Year] as my main parameter and the others have the following default values:

@[FP - Year]:

="[Financial Period].[FP - Year].[FP - Year].&[" + CStr(Parameters!Financial Year(0)) + "]"
="[Financial Period].[FP - Year].[FP - Year].&[" + CStr(Parameters!Financial Year(1)) + "]"

@[Financial Year exit]:

="[Year exit].[Financial Year exit].&[" + CStr(Parameters!Financial Year(0)) + "]"
="[Year exit].[Financial Year exit].&[" + CStr(Parameters!Financial Year(1)) + "]"

And voilà the result:

Body:
I'd suggest two ways:

1: SSRS: add an invisible parameter (i.e. CurrentYear) and run in your MDX query the following:

StrToMember('[Time].[Financial Year].&[' +@CurrentYear + ']')

2: MDX: add a dynamic calculated members for each hierarchy:

member [Time].[Financial Year].[Current Year] as
StrToMember('[Time].[Financial Year].&[' + Format(Now(),'yyyy') + ']')

See my blog post for more details.


问:
Why isn't my .innerHTML working in sublime text 3?
I am trying to learn Javascript but for some reason my .innerHTML isnt working. It doesnt even look like its registering within Sublime Text (not changing colors). Any help would be great.

```<code><body>

    <div id="container">

        <h1>Internal & External Javascript</h1>
        <p id="output"></p>

    </div> <!-- #Container -->

    <script type="text/javascript">

        document.getElementbyId("output").innerHTML = "This text was created with internal Javascript";

    </script>

</body>
</code>```

答: I figured it out! I didn't make the B in by uppercase. Sorry for the easy question, remember, I am new to this.</p>

Body:
I am trying to learn Javascript but for some reason my .innerHTML isnt working. It doesnt even look like its registering within Sublime Text (not changing colors). Any help would be great.

Internal & External Javascript


问:
on the Y/N I would like a lowercase y to be able to respond exactly how an uppercase Y would
When it asks the user if they would like to "run the coin toss simulation(Y/N)" I want the user to be able to input a lowercase y as well as an uppercase Y and having them both do the same thing. What is happening when I put a lowercase y is that it gives me the goodbye message as if the user inputted N

the areas that deal with this are on lines 7-9 and 32-34 any help is greatly appreciated, thanks all

```<code>import random
def main():
    name = input("Hello user, please enter your name: ")
    print("Hello", name , "This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N): ")
    if yn != 'Y':
        print("Ok have a nice day!")
        return

    while True:
        heads = tails = 0
        while True:
            count = int(input("Enter the amount of times you would like the coin to flip: "))
            if count <= 0:
                print("Silly rabbit, that won't work")
            else:
                break

        while tails + heads < count:
            coin = random.randint(1, 2)
            if coin ==1:
                heads = heads + 1
            else:
                tails = tails + 1

        print("you flipped", count , "time(s)")
        print("you flipped heads", heads , "time(s)")
        print("you flipped tails", tails , "time(s)")

        yn = input("Would you like to run another coin toss simulation?(Y/N): ")
        if yn != 'Y':
            print("Ok have a nice day!")
            return
</code>```

main()

答:
Give them a few options</p>

```<code>if yn.lower() not in ('y', 'yes'):
    ...
</code>```

Body:
When it asks the user if they would like to "run the coin toss simulation(Y/N)" I want the user to be able to input a lowercase y as well as an uppercase Y and having them both do the same thing. What is happening when I put a lowercase y is that it gives me the goodbye message as if the user inputted N

the areas that deal with this are on lines 7-9 and 32-34 any help is greatly appreciated, thanks all

import random
def main():
    name = input("Hello user, please enter your name: ")
    print("Hello", name , "This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N): ")
    if yn != 'Y':
        print("Ok have a nice day!")
        return

    while True:
        heads = tails = 0
        while True:
            count = int(input("Enter the amount of times you would like the coin to flip: "))
            if count <= 0:
                print("Silly rabbit, that won't work")
            else:
                break

        while tails + heads < count:
            coin = random.randint(1, 2)
            if coin ==1:
                heads = heads + 1
            else:
                tails = tails + 1

        print("you flipped", count , "time(s)")
        print("you flipped heads", heads , "time(s)")
        print("you flipped tails", tails , "time(s)")

        yn = input("Would you like to run another coin toss simulation?(Y/N): ")
        if yn != 'Y':
            print("Ok have a nice day!")
            return

main()

Body:
Give them a few options

if yn.lower() not in ('y', 'yes'):
    ...


问:
Filtering arrays by strings
I have a situation where I have an array of path names, e.g

```<code>[0]: /var/www/mysite/fred.md
[1]: /var/www/mysite/george.md
[2]: /var/www/mysite/arthur.md
[3]: /var/www/mysite/.htaccess
</code>```

I have another array of strings

```<code>[0]: fred
[1]: art
</code>```

I want to filter the array of path names so that I end up with an array of items where any part of the path name matches the string - so I should get

```<code>[0]: /var/www/mysite/fred.md
[1]: /var/www/mysite/arthur.md
</code>```

What's the most efficient way of doing this in PHP?

答:
Maybe not more efficient than a loop but an alternate. As pointed out in the comments, a benefit is that you can use the strings as regular expressions:

```<code>$result = preg_grep('/'.implode('|', $strings).'/i', $pathnames);
</code>```

To avoid characters in the strings being interpreted as a regular expression, escape them:

```<code>$pattern = implode("|", array_map(function($v){ return preg_quote($v, "/"); }, $strings));
$result  = preg_grep("/$pattern/i", $pathnames);
</code>```

Title: Filtering arrays by strings

Body:
I have a situation where I have an array of path names, e.g

[0]: /var/www/mysite/fred.md
[1]: /var/www/mysite/george.md
[2]: /var/www/mysite/arthur.md
[3]: /var/www/mysite/.htaccess

I have another array of strings

[0]: fred
[1]: art

I want to filter the array of path names so that I end up with an array of items where any part of the path name matches the string - so I should get

[0]: /var/www/mysite/fred.md
[1]: /var/www/mysite/arthur.md

What's the most efficient way of doing this in PHP?

Body:
Maybe not more efficient than a loop but an alternate. As pointed out in the comments, a benefit is that you can use the strings as regular expressions:

$result = preg_grep('/'.implode('|', $strings).'/i', $pathnames);

To avoid characters in the strings being interpreted as a regular expression, escape them:

$pattern = implode("|", array_map(function($v){ return preg_quote($v, "/"); }, $strings));
$result  = preg_grep("/$pattern/i", $pathnames);


问:
Parsing XML using the xpath.js in Node JS
My XML looks like this:

```<code><ns2:OrderList>
  <order order_id="123" item_name="123"/>
  <order order_id="234" item_name="1233"/>
  <order order_id="2357" item_name="1234"/>
  ......
</ns2:OrderList>
</code>```

I am wanting to use the XPath.js from npjms.

How can I get array with "order_id" values ????

答:
```<code>var select = require('xpath.js')
    , dom = require('xmldom').DOMParser

var xml = `<ns2:OrderList>
            <order order_id="123" item_name="123"/>
            <order order_id="234" item_name="1233"/>
            <order order_id="2357" item_name="1234"/>
           </ns2:OrderList>`;

var doc = new dom().parseFromString(xml);
var nodes = select(doc, "//order/@order_id");
var orderIds = [];
nodes.forEach(function(node) {
    orderIds.push(node.nodeValue);
});

console.log(orderIds);
</code>```

Body:
My XML looks like this:

<ns2:OrderList>
  <order order_id="123" item_name="123"/>
  <order order_id="234" item_name="1233"/>
  <order order_id="2357" item_name="1234"/>
  ......
</ns2:OrderList>

I am wanting to use the XPath.js from npjms.

How can I get array with "order_id" values ????


问:
Java closing statements
Okay so my code works, however if the user correctly guesses "blue", the line prints "you got the right color!". Then the code should end. However, it brings up another a k.next(); line. How can I prevent this?
If you do not understand, here is the code.

import java.util.Scanner;

public class BEassignment11
{
  public static void main (String [] args)
  {
    Scanner k = new Scanner (System.in);
    String color;
    String again;

    do
    {

      System.out.println ("Try to guess my favorite color!");
      color = k.next();

      if  (color.equalsIgnoreCase ("blue"))
      {
        System.out.println ("You got the right color!");

      }

      else

        System.out.println ("That is not the right color. Would you like to try again? Yes/No");
        again = k.next();
    }
    while (again.equalsIgnoreCase ("yes"));

  }
}```

答:
System.out.println.... is part of the else clause. You seem to be surprised that the line

```<code>again = k.next();
</code>```

still gets executed even when the user gets the color correct. I suggest you change the else code to the following:

```<code>if  (color.equalsIgnoreCase ("blue"))
      {
        System.out.println ("You got the right color!");
        again = "No";
      }
    else
    {
        System.out.println ("That is not the right color. Would you like to try again? Yes/No");
        again = k.next();
    }
</code>```

That will automatically tell the program not to run again if the user guesses correctly and will only read the user's answer for trying again if they answer incorrectly.

Title: Java closing statements

Body:
System.out.println.... is part of the else clause. You seem to be surprised that the line

again = k.next();

still gets executed even when the user gets the color correct. I suggest you change the else code to the following:

if  (color.equalsIgnoreCase ("blue"))
      {
        System.out.println ("You got the right color!");
        again = "No";
      }
    else
    {
        System.out.println ("That is not the right color. Would you like to try again? Yes/No");
        again = k.next();
    }

That will automatically tell the program not to run again if the user guesses correctly and will only read the user's answer for trying again if they answer incorrectly.


问:
Math.pow(x,2) area of square
i am running a code, but i dont seem to be able to get the scanner working, anyone got an idea how?

```<code>public class verk34 {

public static void main(String[] args) {

 System.out.println(Math.pow(x,2));
 }
}
</code>```

the thing is inserting a number on your own without altering the code.

答:
As per my understanding, you need to add Scanner for taking input from end users and importing the java.util.Scanner statement.

```<code>Scanner in = new Scanner(System.in);
int x = in.nextInt();
</code>```

Title: Math.pow(x,2) area of square

Body:
i am running a code, but i dont seem to be able to get the scanner working, anyone got an idea how?

public class verk34 {

public static void main(String[] args) {

 System.out.println(Math.pow(x,2));
 }
}

the thing is inserting a number on your own without altering the code.

Body:
As per my understanding, you need to add Scanner for taking input from end users and importing the java.util.Scanner statement.

Scanner in = new Scanner(System.in);
int x = in.nextInt();


问:
Check if a number is prime or not in mysql
I am wondering what's the best way to check whether a number is prime or not using sql. I was able to generate the sequence of numbers from 1 to 1000 but I would like to identify which number is a prime. Can somebody share your thoughts on this.Thanks.</p>

```<code>SELECT i
  FROM
(
select
     i0.i
    +i1.i*2
    +i2.i*4
    +i3.i*8
    +i4.i*16
    +i5.i*32
    +i6.i*64
    +i7.i*128
    +i8.i*256
    +i9.i*512
    as i
from
               (select 0 as i union select 1) as i0
    cross join (select 0 as i union select 1) as i1
    cross join (select 0 as i union select 1) as i2
    cross join (select 0 as i union select 1) as i3
    cross join (select 0 as i union select 1) as i4
    cross join (select 0 as i union select 1) as i5
    cross join (select 0 as i union select 1) as i6
    cross join (select 0 as i union select 1) as i7
    cross join (select 0 as i union select 1) as i8
    cross join (select 0 as i union select 1) as i9
) Z
WHERE i>=1 AND i<=1000;
</code>```

答:
You can use a self join to check for primes from the table of generated numbers. Primes have 2 factors, a conditional check would be sufficient.

```<code>select val
from (select x.val,x1.val as divisor,mod(x.val,x1.val) as remaindr
      from x
      join x x1 on x1.val <= x.val
     ) t
group by val
having sum(case when remaindr = 0 then 1 else 0 end) = 2
</code>```

Sample Demo

An optimization for the above is to check for divisors in the range of 1 to sqrt(number). In that case the only factor for a prime number would be 1, and the conditional check can be changed accordingly.

```<code>select val
from (select x.val,x1.val as divisor,mod(x.val,x1.val) as remaindr
      from x
      join x x1 on x.val >= pow(x1.val,2)
      where x.val > 1 --excluding 1 as it is neither prime nor composite
     ) t
group by val
having sum(case when remaindr = 0 then 1 else 0 end) = 1
</code>```

Body:
I am wondering what's the best way to check whether a number is prime or not using sql. I was able to generate the sequence of numbers from 1 to 1000 but I would like to identify which number is a prime. Can somebody share your thoughts on this.Thanks.

SELECT i
  FROM
(
select
     i0.i
    +i1.i*2
    +i2.i*4
    +i3.i*8
    +i4.i*16
    +i5.i*32
    +i6.i*64
    +i7.i*128
    +i8.i*256
    +i9.i*512
    as i
from
               (select 0 as i union select 1) as i0
    cross join (select 0 as i union select 1) as i1
    cross join (select 0 as i union select 1) as i2
    cross join (select 0 as i union select 1) as i3
    cross join (select 0 as i union select 1) as i4
    cross join (select 0 as i union select 1) as i5
    cross join (select 0 as i union select 1) as i6
    cross join (select 0 as i union select 1) as i7
    cross join (select 0 as i union select 1) as i8
    cross join (select 0 as i union select 1) as i9
) Z
WHERE i>=1 AND i<=1000;

Body:
You can use a self join to check for primes from the table of generated numbers. Primes have 2 factors, a conditional check would be sufficient.

select val
from (select x.val,x1.val as divisor,mod(x.val,x1.val) as remaindr
      from x
      join x x1 on x1.val <= x.val
     ) t
group by val
having sum(case when remaindr = 0 then 1 else 0 end) = 2

Sample Demo

An optimization for the above is to check for divisors in the range of 1 to sqrt(number). In that case the only factor for a prime number would be 1, and the conditional check can be changed accordingly.

select val
from (select x.val,x1.val as divisor,mod(x.val,x1.val) as remaindr
      from x
      join x x1 on x.val >= pow(x1.val,2)
      where x.val > 1 --excluding 1 as it is neither prime nor composite
     ) t
group by val
having sum(case when remaindr = 0 then 1 else 0 end) = 1


问:
PyClips clips.BatchStar() and Clips (batch ...) do not work together
I have three files:

1.) A python filetest.py:

```<code>import clips
PATH_TO_CLP_FILE = r'd:\temp\batch_bug.clp'
clips.BatchStar(PATH_TO_CLP_FILE)
clips.PrintFacts()
</code>```

2.) A file batch_bug.clp:

```<code>(assert (asdf0))
(batch "D:\\temp\\batchbug2.clp")
(assert (asdf1))
(printout t (facts))
</code>```

And finally a file batchbug2.clp:

```<code>(assert (fdsa))
</code>```

Running python test.py results in the following output:

```<code>f-0     (initial-fact)
f-1     (asdf0)
f-2     (asdf1)
For a total of 3 facts.

[ENVRNMNT8] Environment data not fully deallocated.

[ENVRNMNT8] MemoryAmount = 22.

[ENVRNMNT8] MemoryCalls = 1.
</code>```

This is not what I expected because there is no (fdsa) fact, i.e. calling (batch "D:\\temp\\batchbug2.clp") did not work. In addition, there are the [ENVRNMNT8] messages. What is going on here?

EDIT:

I found out about the CLIPS batch*(...) command. And using this instead of the batch(...) works as expected. Why is that?

答:
The batch command opens a file and uses its contents when requests are made for characters from standard input (the keyboard). When you're using CLIPS interactively, character requests are made from standard input by the read/evaluate/print loop (the CLIPS> command prompt) as well as any read or readline function calls in your code.

When you embed CLIPS as in done in this PyCLIPS example, there is no read/evaluate/print loop so the only requests for characters from standard input are going to come from the read and readline functions. Since this example doesn't make any character requests from standard input, the contents of the batch file is never processed.

The batch* command opens a file, directly parses its contents for commands, and then immediately executes them--No requests for characters from standard input need to be made for the commands to execute.

The batch command is useful for running test cases from the command prompt because you can simulate all keyboard input. The batch* command is useful for running command scripts when you don't have immediate access to the command prompt (either because you're embedding CLIPS or CLIPS is currently executing) or you don't want the executed commands and their return values echoed to standard output.

The ENVRNMNT8 error message occurs when CLIPS exits and it determines that all allocated memory has not been properly freed. In this case, there's a bug in the deallocation code for an unprocessed batch file that doesn't free a string containing the batch file name (for CLIPS 6.30). A fix has been checked into the CLIPS SVN repository at SourceForge.

Body:
I have three files:

1.) A python filetest.py:

import clips
PATH_TO_CLP_FILE = r'd:\temp\batch_bug.clp'
clips.BatchStar(PATH_TO_CLP_FILE)
clips.PrintFacts()

2.) A file batch_bug.clp:

(assert (asdf0))
(batch "D:\\temp\\batchbug2.clp")
(assert (asdf1))
(printout t (facts))

And finally a file batchbug2.clp:

(assert (fdsa))

Running python test.py results in the following output:

f-0     (initial-fact)
f-1     (asdf0)
f-2     (asdf1)
For a total of 3 facts.

[ENVRNMNT8] Environment data not fully deallocated.

[ENVRNMNT8] MemoryAmount = 22.

[ENVRNMNT8] MemoryCalls = 1.

This is not what I expected because there is no (fdsa) fact, i.e. calling (batch "D:\\temp\\batchbug2.clp") did not work. In addition, there are the [ENVRNMNT8] messages. What is going on here?

EDIT:

I found out about the CLIPS batch*(...) command. And using this instead of the batch(...) works as expected. Why is that?


问:
Python PIL/numpy conversion
I'm having problems converting between python PIL images and numpy arrays. I already checked existing Stackoverflow posts on this, but it didn't solve the problem:

```<code>import matplotlib.pyplot as plt
import numpy as np
import PIL

rgb_img = plt.imread('some-image.png')
PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img))

plt.imshow(PIL_rgb_img)
</code>```

I get a black screen. I tried with and without converting to uint8, and I also tried only keeping the RGB channels out of the entire RGBA data. Nothing worked.

答:
I may not give you a full explanation , (for that, you may read matplotlib's functions docs) but clearly with some tests the following is happening:

when you call:

```<code>rgb_img = plt.imread('img.png')
</code>```

it gives a numpy float array, which will read colors between [0 - 1] as white and black ( and for RGB also )

when you call:

```<code>PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img))
</code>```

which convert it to uint8 values, it just take what supposed to be 255 and make it 1 which is completely wrong,

you know in uint8 the values should be between [0 - 255]

and when you put :

```<code>plt.imshow(PIL_rgb_img)
</code>```

it just show a 255 times 'faded' image , which is very close to black..

P. S.:

That's only happen with '.png' files,
something with plt.imread ..

to solve just put :

```<code>img = 'some_img.png'
rgb_img = plt.imread(img)
if img.split('.')[-1]=='png':
    PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img*255))
else:
    PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img))

plt.imshow(PIL_rgb_img)
</code>```

That's should fix it.

Title: Python PIL/numpy conversion

Body:
I'm having problems converting between python PIL images and numpy arrays. I already checked existing Stackoverflow posts on this, but it didn't solve the problem:

import matplotlib.pyplot as plt
import numpy as np
import PIL

rgb_img = plt.imread('some-image.png')
PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img))

plt.imshow(PIL_rgb_img)

I get a black screen. I tried with and without converting to uint8, and I also tried only keeping the RGB channels out of the entire RGBA data. Nothing worked.

Body:
I may not give you a full explanation , (for that, you may read matplotlib's functions docs) but clearly with some tests the following is happening:

when you call:

rgb_img = plt.imread('img.png')

it gives a numpy float array, which will read colors between [0 - 1] as white and black ( and for RGB also )

when you call:

PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img))

which convert it to uint8 values, it just take what supposed to be 255 and make it 1 which is completely wrong,

you know in uint8 the values should be between [0 - 255]

and when you put :

plt.imshow(PIL_rgb_img)

it just show a 255 times 'faded' image , which is very close to black..

P. S.:

That's only happen with '.png' files,
something with plt.imread ..

to solve just put :

img = 'some_img.png'
rgb_img = plt.imread(img)
if img.split('.')[-1]=='png':
    PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img*255))
else:
    PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img))

plt.imshow(PIL_rgb_img)

That's should fix it.


问:
Use getters/setters in Svelte Custom methods
I am not able to compile my svelte component when using a get/set pair in custom methods. Is this not supported? Or am I doing something wrong?

Example:

Say I wanted to have a component that displays a name and I want to set the name using.

com.name = 'The new name';

However I only want the component to use the name if it has no spaces in the name.

```<code><h1>Hello {{name}}!</h1>

<script>
    export default {
        data () {
            return {
                name: 'The Name',
            }
        },
        methods: {
            get displayName() {
                return this.get('name');
            },
            set displayName(val) {
                if (val.indexOf(' ') < 0) {
                    this.set('name', val);
                }
            }
        }
    }
</script>
</code>```

The Issue is that when I try to compile this, it says there is a duplicate key.

```<code>    Duplicate property 'displayName'

    49:             return this.get('name');
    50:         },
    51:         set displayName(val) {
</code>```

Here is a REPL - https://svelte.technology/repl?version=1.13.2&gist=0eeab5717526694139ba73eae766bb30

I don't see anything in the documentation about this. I can just not use setters, but I would like to be able to.

答:
tl;dr this is possible with a wrapper object

The error message here is a bit confusing — it's not the duplicate property that's a problem, is that you can't have getters and setters in methods, which in any case is separate from the data object that populates a component's internal state (along with data supplied at instantiation and any computed values there might be). I've opened an issue for that here.

The data itself also can't have getters and setters — or rather it can, but they won't be used, because the object returned from your data function isn't the same as the internal state object (otherwise we'd all probably run into mutation-related bugs).

But it's actually fairly easy to create a wrapper object that allows you to get and set a component's data:

function wrap (component) {
  var wrapper = {};
  var data = component.get();

  Object.keys(data).forEach(key => {
    Object.defineProperty(wrapper, key, {
      get() {
        return component.get()[key];
      },
      set(value) {
        component.set({ obj[key]: value });
      }
    })
  });

  return wrapper;
}

var component = new Component({...});
var wrapper = wrap(component);

wrapper.name = 'Rich';
```

You could even do component.data = wrap(component) if you were so inclined — then you could manipulate component.data.name and so on.

I've put together a small repo demoing that approach — see it in action here.

Body:
I am not able to compile my svelte component when using a get/set pair in custom methods. Is this not supported? Or am I doing something wrong?

Example:

Say I wanted to have a component that displays a name and I want to set the name using.

com.name = 'The new name';

However I only want the component to use the name if it has no spaces in the name.

Hello {{name}}!

The Issue is that when I try to compile this, it says there is a duplicate key.

    Duplicate property 'displayName'

    49:             return this.get('name');
    50:         },
    51:         set displayName(val) {

Here is a REPL - https://svelte.technology/repl?version=1.13.2&gist=0eeab5717526694139ba73eae766bb30

I don't see anything in the documentation about this. I can just not use setters, but I would like to be able to.

Body:
tl;dr this is possible with a wrapper object

The error message here is a bit confusing — it's not the duplicate property that's a problem, is that you can't have getters and setters in methods, which in any case is separate from the data object that populates a component's internal state (along with data supplied at instantiation and any computed values there might be). I've opened an issue for that here.

The data itself also can't have getters and setters — or rather it can, but they won't be used, because the object returned from your data function isn't the same as the internal state object (otherwise we'd all probably run into mutation-related bugs).

But it's actually fairly easy to create a wrapper object that allows you to get and set a component's data:

function wrap (component) {
  var wrapper = {};
  var data = component.get();

  Object.keys(data).forEach(key => {
    Object.defineProperty(wrapper, key, {
      get() {
        return component.get()[key];
      },
      set(value) {
        component.set({ obj[key]: value });
      }
    })
  });

  return wrapper;
}

var component = new Component({...});
var wrapper = wrap(component);

wrapper.name = 'Rich';

You could even do component.data = wrap(component) if you were so inclined — then you could manipulate component.data.name and so on.

I've put together a small repo demoing that approach — see it in action here.

ContentLicense: CC BY-SA 4.0


问:
How to unquote header without unquote other data?
I have data that looks like the following:

```<code>Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741
</code>```

It's a huge file with 100k observations. I read it in R and trim it down to 10k and then write it to csv. However, I couldn't find how to unquote only the header without losing the quotes within the data. If I keep quote = TRUE, this is what the final data looks like but I want to get rid of the quotes in the header.

```<code>"Scenario","ScenName","Step","Date","GBP_fx","EUR_fx"
0,"assets",0,"30/09/2016",1,0.865126741
</code>```

Any suggestions?

答:
You can write the header then append the rows, e.g. :

```<code># input sample
testDF <- read.csv(text=
'Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741')

# custom write.csv function
write.csv.noheaderquote <- function(x,file){
  # write header
  write.table(head(x,0),file=file,sep=',',quote=FALSE,row.names = FALSE)
  # append the rest of the rows
  write.table(x,file=file,sep=',',row.names=FALSE,append=TRUE,col.names=FALSE)
}

# use the new function to write your csv
write.csv.noheaderquote(testDF,"destfile.csv")
</code>```

Resulting destfile.csv :

```<code>Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741
</code>```

Body:
I have data that looks like the following:

Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741

It's a huge file with 100k observations. I read it in R and trim it down to 10k and then write it to csv. However, I couldn't find how to unquote only the header without losing the quotes within the data. If I keep quote = TRUE, this is what the final data looks like but I want to get rid of the quotes in the header.

"Scenario","ScenName","Step","Date","GBP_fx","EUR_fx"
0,"assets",0,"30/09/2016",1,0.865126741

Any suggestions?

Body:
You can write the header then append the rows, e.g. :

# input sample
testDF <- read.csv(text=
'Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741')

# custom write.csv function
write.csv.noheaderquote <- function(x,file){
  # write header
  write.table(head(x,0),file=file,sep=',',quote=FALSE,row.names = FALSE)
  # append the rest of the rows
  write.table(x,file=file,sep=',',row.names=FALSE,append=TRUE,col.names=FALSE)
}

# use the new function to write your csv
write.csv.noheaderquote(testDF,"destfile.csv")

Resulting destfile.csv :

Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741


问:
Avro Java API Timestamp Logical Type?
With the Avro Java API, I can make a simple record schema like:

```<code>    Schema schemaWithTimestamp = SchemaBuilder
            .record("MyRecord").namespace("org.demo")
            .fields()
            .name("timestamp").type().longType().noDefault()
            .endRecord();
</code>```

How do I tag a schema field with a logical type, specifically:
https://avro.apache.org/docs/1.8.1/api/java/org/apache/avro/LogicalTypes.TimestampMillis.html

答:
Thanks to DontPanic:

```<code>    Schema timestampMilliType = LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG));

    Schema schemaWithTimestamp = SchemaBuilder
            .record("MyRecord").namespace("org.demo")
            .fields()
            .name("timestamp_with_logical_type").type(timestampMilliType).noDefault()
            .name("timestamp_no_logical_type").type().longType().noDefault()
            .endRecord();

    System.out.println(schemaWithTimestamp.toString(true));
</code>```

This results in:

```<code>{
  "type" : "record",
  "name" : "MyRecord",
  "namespace" : "org.demo",
  "fields" : [ {
    "name" : "timestamp_with_logical_type",
    "type" : {
      "type" : "long",
      "logicalType" : "timestamp-millis"
    }
  }, {
    "name" : "timestamp_no_logical_type",
    "type" : "long"
  } ]
}
</code>```

Title: Avro Java API Timestamp Logical Type?

Body:
With the Avro Java API, I can make a simple record schema like:

    Schema schemaWithTimestamp = SchemaBuilder
            .record("MyRecord").namespace("org.demo")
            .fields()
            .name("timestamp").type().longType().noDefault()
            .endRecord();

How do I tag a schema field with a logical type, specifically:
https://avro.apache.org/docs/1.8.1/api/java/org/apache/avro/LogicalTypes.TimestampMillis.html

Body:
Thanks to DontPanic:

    Schema timestampMilliType = LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG));

    Schema schemaWithTimestamp = SchemaBuilder
            .record("MyRecord").namespace("org.demo")
            .fields()
            .name("timestamp_with_logical_type").type(timestampMilliType).noDefault()
            .name("timestamp_no_logical_type").type().longType().noDefault()
            .endRecord();

    System.out.println(schemaWithTimestamp.toString(true));

This results in:

{
  "type" : "record",
  "name" : "MyRecord",
  "namespace" : "org.demo",
  "fields" : [ {
    "name" : "timestamp_with_logical_type",
    "type" : {
      "type" : "long",
      "logicalType" : "timestamp-millis"
    }
  }, {
    "name" : "timestamp_no_logical_type",
    "type" : "long"
  } ]
}


问:
How to deserialize a pseudo-json array into c#
I might be silly, but I'm stuck on this one.

I'm coding in c# and attempting to parse a JSON string into an object.
The problem is that the string contains a data-field which I call a pseudo-array. It isn't a real array, because it is missing the []'s....

I really don't want to create an object with 500 properties just to cater for what I assume to be a bug in the API's JSON response - but how on earth do I deserialize this into c# objects?

Below is the sample JSON from the API's documentation page.
(I don't own the API - so I can't change the JSON)

Any advice will be appreciated.
Thanks
k

`

```<code>{
    "data": {
        "71489": { <---- This is supposed to be an item in an array - but it isn't
            "air_by_date": 0,
            "cache": {
                "banner": 1,
                "poster": 1
            },
            "language": "en",
            "network": "USA Network",
            "next_ep_airdate": "",
            "paused": 0,
            "quality": "HD720p",
            "show_name": "Law & Order: Criminal Intent",
            "status": "Ended",
            "tvdbid": 71489,
            "tvrage_id": 4203,
            "tvrage_name": "Law & Order: Criminal Intent"
        },
        "140141": {
            "air_by_date": 0,
            "cache": {
                "banner": 0,
                "poster": 0
            },
            "language": "fr",
            "network": "CBS",
            "next_ep_airdate": "2012-01-15",
            "paused": 0,
            "quality": "Any",
            "show_name": "Undercover Boss (US)",
            "status": "Continuing",
            "tvdbid": 140141,
            "tvrage_id": 22657,
            "tvrage_name": "Undercover Boss"
        },
...
        "194751": {
            "air_by_date": 1,
            "cache": {
                "banner": 1,
                "poster": 1
            },
            "language": "en",
            "network": "TBS Superstation",
            "next_ep_airdate": 2011-11-28",
            "paused": 0,
            "quality": "Custom",
            "show_name": "Conan (2010)",
            "status": "Continuing",
            "tvdbid": 194751,
            "tvrage_id": 0,
            "tvrage_name": ""
        },
        "248261": {
            "air_by_date": 0,
            "cache": {
                "banner": 1,
                "poster": 1
            },
            "language": "en",
            "network": "Cartoon Network",
            "next_ep_airdate": "",
            "paused": 1,
            "quality": "HD",
            "show_name": "NTSF:SD:SUV::",
            "status": "Continuing",
            "tvdbid": 248261,
            "tvrage_id": 28439,
            "tvrage_name": "NTSF:SD:SUV"
        }
    },
    "message": "",
    "result": "success"
}
`
</code>```

答:
The data property of your JSON object is an associative array.  You need to access each element by the appropriate key (in this case a numeric string)

```<code>// convert from a String into a JObject
var data = JObject.Parse(json);

// access single property
Response.Write(data["data"]["71489"]);
Response.Write(data["data"]["140141"]);

// iterate all properties
foreach (JProperty prop in data["data"])
{
    Response.Write(prop.Name + ": " + prop.Value);

    // Also possible to access things like:
    // - prop.Value["air_by_date"]
    // - prop.Value["cache"]["banner"]
    // - prop.Value["cache"]["poster"]
    // - prop.Value["language"]
}
</code>```

Body:
I might be silly, but I'm stuck on this one.

I'm coding in c# and attempting to parse a JSON string into an object.
The problem is that the string contains a data-field which I call a pseudo-array. It isn't a real array, because it is missing the []'s....

I really don't want to create an object with 500 properties just to cater for what I assume to be a bug in the API's JSON response - but how on earth do I deserialize this into c# objects?

Below is the sample JSON from the API's documentation page.
(I don't own the API - so I can't change the JSON)

Any advice will be appreciated.
Thanks
k

`

{
    "data": {
        "71489": { <---- This is supposed to be an item in an array - but it isn't
            "air_by_date": 0,
            "cache": {
                "banner": 1,
                "poster": 1
            },
            "language": "en",
            "network": "USA Network",
            "next_ep_airdate": "",
            "paused": 0,
            "quality": "HD720p",
            "show_name": "Law & Order: Criminal Intent",
            "status": "Ended",
            "tvdbid": 71489,
            "tvrage_id": 4203,
            "tvrage_name": "Law & Order: Criminal Intent"
        },
        "140141": {
            "air_by_date": 0,
            "cache": {
                "banner": 0,
                "poster": 0
            },
            "language": "fr",
            "network": "CBS",
            "next_ep_airdate": "2012-01-15",
            "paused": 0,
            "quality": "Any",
            "show_name": "Undercover Boss (US)",
            "status": "Continuing",
            "tvdbid": 140141,
            "tvrage_id": 22657,
            "tvrage_name": "Undercover Boss"
        },
...
        "194751": {
            "air_by_date": 1,
            "cache": {
                "banner": 1,
                "poster": 1
            },
            "language": "en",
            "network": "TBS Superstation",
            "next_ep_airdate": 2011-11-28",
            "paused": 0,
            "quality": "Custom",
            "show_name": "Conan (2010)",
            "status": "Continuing",
            "tvdbid": 194751,
            "tvrage_id": 0,
            "tvrage_name": ""
        },
        "248261": {
            "air_by_date": 0,
            "cache": {
                "banner": 1,
                "poster": 1
            },
            "language": "en",
            "network": "Cartoon Network",
            "next_ep_airdate": "",
            "paused": 1,
            "quality": "HD",
            "show_name": "NTSF:SD:SUV::",
            "status": "Continuing",
            "tvdbid": 248261,
            "tvrage_id": 28439,
            "tvrage_name": "NTSF:SD:SUV"
        }
    },
    "message": "",
    "result": "success"
}
`

Body:
The data property of your JSON object is an associative array.  You need to access each element by the appropriate key (in this case a numeric string)

// convert from a String into a JObject
var data = JObject.Parse(json);

// access single property
Response.Write(data["data"]["71489"]);
Response.Write(data["data"]["140141"]);

// iterate all properties
foreach (JProperty prop in data["data"])
{
    Response.Write(prop.Name + ": " + prop.Value);

    // Also possible to access things like:
    // - prop.Value["air_by_date"]
    // - prop.Value["cache"]["banner"]
    // - prop.Value["cache"]["poster"]
    // - prop.Value["language"]
}