问:
In Laravel How to create subscriber in mailchimp using Guzzle HTTP
I am  using guzzle HTTP to send the request and I am getting this error
Client error: POST https://us17.api.mailchimp.com/3.0/batches resulted in a 401 Unauthorized response:
{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"API Key Missing","statu (truncated...)

```<code>        $userArray = [];
        $operations = [];
        //used to get the patient that need to sync mailchimp
        $getPatientToSync = Patient::select('NameFirst', 'NameLast' , 'Email')
        ->where([['flag_name' , '=', '1'], ['mailchimp_synced' ,'=' , '0']])->get();
        if($getPatientToSync->isEmpty()){
            return true;
        }
        foreach ($getPatientToSync as  $patient){
            $data = array(
                "apikey"        => config('mailchimp.api_key'),
                "email_address" => $patient->Email,
                "status"        => "subscribed",
                "merge_fields"  => array(
                    'FNAME' => $patient->NameFirst,
                    'LNAME' => $patient->NameLast,
                )
            );
            $userArray[] =  json_encode($data);
           }
        foreach ($userArray as $userArr){
            $temp = array(
                "method" => "POST",
                "path" => "/lists/".config('mailchimp.list_id')."/members/",
                "body" => $userArr
            );
            $operations['operations'][] =$temp;
        }
        $json_post = json_encode($operations);
        $auth = base64_encode( 'user:'.config('mailchimp.api_key') );
        //API URL
        $urll="https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
       $headers = array('Content-Type: application/json', 'Authorization: Basic
        '.$auth , $userlist);
        $client = new Client();
        $response =  $client->request('POST', $urll , $headers,json_post );
        dd($response);
</code>```

答:
First of all, you use Guzzle's request() method in a wrong way. The right way is:

```<code>$client->request('POST', $urll, [
    'headers' => $headers,
    'json' => $operations
]);
</code>```

Try it and then pay attention to the error message (it'a also useful).

Body:
I am  using guzzle HTTP to send the request and I am getting this error
Client error: POST https://us17.api.mailchimp.com/3.0/batches resulted in a 401 Unauthorized response:
{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"API Key Missing","statu (truncated...)

        $userArray = [];
        $operations = [];
        //used to get the patient that need to sync mailchimp
        $getPatientToSync = Patient::select('NameFirst', 'NameLast' , 'Email')
        ->where([['flag_name' , '=', '1'], ['mailchimp_synced' ,'=' , '0']])->get();
        if($getPatientToSync->isEmpty()){
            return true;
        }
        foreach ($getPatientToSync as  $patient){
            $data = array(
                "apikey"        => config('mailchimp.api_key'),
                "email_address" => $patient->Email,
                "status"        => "subscribed",
                "merge_fields"  => array(
                    'FNAME' => $patient->NameFirst,
                    'LNAME' => $patient->NameLast,
                )
            );
            $userArray[] =  json_encode($data);
           }
        foreach ($userArray as $userArr){
            $temp = array(
                "method" => "POST",
                "path" => "/lists/".config('mailchimp.list_id')."/members/",
                "body" => $userArr
            );
            $operations['operations'][] =$temp;
        }
        $json_post = json_encode($operations);
        $auth = base64_encode( 'user:'.config('mailchimp.api_key') );
        //API URL
        $urll="https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
       $headers = array('Content-Type: application/json', 'Authorization: Basic
        '.$auth , $userlist);
        $client = new Client();
        $response =  $client->request('POST', $urll , $headers,json_post );
        dd($response);

Body:
First of all, you use Guzzle's request() method in a wrong way. The right way is:

$client->request('POST', $urll, [
    'headers' => $headers,
    'json' => $operations
]);

Try it and then pay attention to the error message (it'a also useful).


来源: stackexchange

问:
Extract values only from an array to encode them in JSON using PHP
This has probably been asked many times but I can't find a solution for my case.

This is my array :

```<code>$request=Array (
        [0] => Array ( [staName] => Auditorium Stravinsky 2m2c )
        [1] => Array ( [staName] => Geneva Arena )
        [2] => Array ( [staName] => Les Docks )
        [3] => Array ( [staName] => Kheops )
    )
</code>```

And i need an output as follows as JSON:

```<code>"Auditorium Stravinsky 2m2c ","Geneva Arena","Les Docks","Kheops"
</code>```

My current code is as follows:

```<code>    foreach($request as $value)
    {
        $names[]=$value;
    }

    $jsonValue = json_encode(array_values($names));

    print_r($jsonValue);
</code>```

And my current output is as follows in JSON format:

```<code>[{"staName":"Auditorium Stravinsky 2m2c "},{"staName":"Geneva Arena"},{"staName":"Les Docks"},{"staName":"Kheops"}]
</code>```

How can i stop "staName " from being outputed?

Many thanks in advance and please be considerate of my post as this is only the second one I make on this site.

答:
You can achieve this from,

Code

```<code>$a = array();
foreach($request as $key =>$val){
  foreach($val as $k => $v){
   $a[] = $v;
  }
}
print_r(json_encode($a));
</code>```

Check this Demo link

Output

```<code>["Auditorium Stravinsky 2m2c","Geneva Arena","Les Docks","Kheops"]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This has probably been asked many times but I can't find a solution for my case.

This is my array :

$request=Array (
        [0] => Array ( [staName] => Auditorium Stravinsky 2m2c )
        [1] => Array ( [staName] => Geneva Arena )
        [2] => Array ( [staName] => Les Docks )
        [3] => Array ( [staName] => Kheops )
    )

And i need an output as follows as JSON:

"Auditorium Stravinsky 2m2c ","Geneva Arena","Les Docks","Kheops"

My current code is as follows:

    foreach($request as $value)
    {
        $names[]=$value;
    }

    $jsonValue = json_encode(array_values($names));

    print_r($jsonValue);

And my current output is as follows in JSON format:

[{"staName":"Auditorium Stravinsky 2m2c "},{"staName":"Geneva Arena"},{"staName":"Les Docks"},{"staName":"Kheops"}]

How can i stop "staName " from being outputed?

Many thanks in advance and please be considerate of my post as this is only the second one I make on this site.

Body:
You can achieve this from,

Code

$a = array();
foreach($request as $key =>$val){
  foreach($val as $k => $v){
   $a[] = $v;
  }
}
print_r(json_encode($a));

Check this Demo link

Output

["Auditorium Stravinsky 2m2c","Geneva Arena","Les Docks","Kheops"]


问:
Loading Batch Offline Data to DWH environment with Kafka as the "Entering door"
Some context to my question.

As you can see here:

https://medium.com/airbnb-engineering/data-infrastructure-at-airbnb-8adfb34f169c

There are 2 "doors" to load data into HDFS

Sqoop

Kafka

Using this topology as an example, what will be the best practice to load batch offline data which is hosted on an FTP server info HDFS?

Let's also assume that no changes are needed to perform on the file, we need to store it in HDFS in the same structure it is stored in the FTP server.

Thoughts?

答:
Kafka isn't exactly configured to transfer "file sized" data by default. At least, not entire files in one message. Maybe break the lines apart, but then you need to reorder them and put them back together in HDFS.

In my experience, I've seen a few options from an FTP server.

Vanilla Hadoop, no extra software required

Use an NFS Gateway,  WebHDFS or HttpFS to copy files directly to HDFS as if it were another filesystem

Additional Software required

Your own code with an FTP and HDFS client connection

Spark Streaming w/ an FTP Connector and HDFS write output

Kafka & Kafka Connect with an FTP Connector source and HDFS Sink

A Flume agent running on the FTP Server with an HDFS sink

Apache NiFi with a GetFTP and PutHDFS processor

Streamsets Data Collector doing something similar to NiFi (don't know the terms for this one)

we need to store it in HDFS in the same structure it is stored in the FTP server.

If these are small files, you're better off at least compressing the files into a Hadoop supported archive format before uploading to HDFS


问:
Dropdown list selected item always set to default value
I wish to pass values of the selected items into a database and however noticed that the selected item is not what is sent into the database you can see in the snap shot below.

during run time the following value is recorded.

Where did it all go wrong with the dropdown lists selected item?
Counting on your intelligence...thanks.

答:
I found the problem for the dropdownlist always selecting the first value. It appears the dropdown list is always rebinded anytime i click a button that requires a post pack as such the data tha was binded at page load re binds a gain before the selected item gets picked as such the default first value gets picked all the time. to solve my problem i first disabled enable auto postback on the dropdownlist and in the code behind that is my .cs file during the page load, where i first binded the data to the dropdown list, i used a condition like if(!ispostback) to bind my data. what this does is when the page loads first time the dropdownlist is binded and if i should select an item from the drop down list, the "auto post back" that i disabled earlier on keeps the selected item selected and when i click and button that requires a post to the server, the (!ispostback) prevents the dropdownlist to be binded again before selection. so in effect, the selection is done first and afterwards if the page should load anew, the drop down list is binded again.

i was in a bit of a rush while typing so please bare with my typo errors. do call in anytime for more clarification...peace

ContentLicense: CC BY-SA 2.5


问:
Why is this console log posting "undefined"?
i made an array that gets a variable to specify the value i want to display</p>

```<code>var antallSporsmal= 0;
var fasit = new Array();
fasit[1,3,1,2,3];
console.log(fasit[antallSporsmal]);
</code>```

答:
In your line :

```<code>fasit[1,3,1,2,3];
</code>```

You are not initializing your array, this does nothing. so fasit will be always empty, that's why fasit[0] will be undefined.

You need to change it:

```<code>fasit = [1,3,1,2,3];
</code>```

Body:
i made an array that gets a variable to specify the value i want to display

var antallSporsmal= 0;
var fasit = new Array();
fasit[1,3,1,2,3];
console.log(fasit[antallSporsmal]);

Body:
In your line :

fasit[1,3,1,2,3];

You are not initializing your array, this does nothing. so fasit will be always empty, that's why fasit[0] will be undefined.

You need to change it:

fasit = [1,3,1,2,3];


问:
SQL Select Sub Query
I have the following database tables

```<code>User          List
------        ------
userId (PK)   listId (PK)
fullName      description
              addedById (FK with userId in User table)
              modifiedById (FK with userId in User table)
</code>```

I need to pull out all data from the List table, but instead of showing the IDs for addedById and modifiedById, I need to pull the fullName from the User table.

This query works, and gives me the data I need. However, I'm not sure if there is a better way of constructing this query? I'm not keen on having multiple sub select queries within my main select query, mainly because of performance issues.

```<code>select t1.[description],
   t1.addedById,
   t1.modifiedById,
   (select fullName from dbo.User where userId = t1.addedById) as [AddedByUser],
   (select fullName from dbo.User where userId = t1.modifiedById) as [ModifiedByUser]

from dbo.List t1
</code>```

I'd really appreciate if anyone could suggest improvements to the query, or advise to keep as is.

Thanks.

答:
A more standard SQL method would be:

```<code>SELECT t1.description,
    t1.addedById,
    t1.modifiedById,
    add.fullName AS [AddedByUser],
    mod.fullName AS [ModifiedByUser]
FROM dbo.List t1
LEFT JOIN dbo.User add
    ON add.userId = t1.addedById
LEFT JOIN dbo.User mod
    ON mod.userID = t1.modifiedById
</code>```

However, I suspect this will perform identically to your query and probably has an identical execution plan.  The only real advantage to this method is that it's easier to expand.  For example, if you wanted to add new columns from the User table this would be easier.

As @Gordon notes, performance should be fine if there's an index on the fields you're joining with.

Title: SQL Select Sub Query

Body:
I have the following database tables

User          List
------        ------
userId (PK)   listId (PK)
fullName      description
              addedById (FK with userId in User table)
              modifiedById (FK with userId in User table)

I need to pull out all data from the List table, but instead of showing the IDs for addedById and modifiedById, I need to pull the fullName from the User table.

This query works, and gives me the data I need. However, I'm not sure if there is a better way of constructing this query? I'm not keen on having multiple sub select queries within my main select query, mainly because of performance issues.

select t1.[description],
   t1.addedById,
   t1.modifiedById,
   (select fullName from dbo.User where userId = t1.addedById) as [AddedByUser],
   (select fullName from dbo.User where userId = t1.modifiedById) as [ModifiedByUser]

from dbo.List t1

I'd really appreciate if anyone could suggest improvements to the query, or advise to keep as is.

Thanks.

Body:
A more standard SQL method would be:

SELECT t1.description,
    t1.addedById,
    t1.modifiedById,
    add.fullName AS [AddedByUser],
    mod.fullName AS [ModifiedByUser]
FROM dbo.List t1
LEFT JOIN dbo.User add
    ON add.userId = t1.addedById
LEFT JOIN dbo.User mod
    ON mod.userID = t1.modifiedById

However, I suspect this will perform identically to your query and probably has an identical execution plan.  The only real advantage to this method is that it's easier to expand.  For example, if you wanted to add new columns from the User table this would be easier.

As @Gordon notes, performance should be fine if there's an index on the fields you're joining with.


问:
Loading different Libraries with same Functions dynamically
I have a program which has a reference to an external DLL:

```<code>magic.externalFunctions.sql.dll
</code>```

depending on the target system I might need the following instead:

```<code>magic.externalFunctions.nosql.dll
</code>```

These DLLs are external libraries who offer the same functionality. Even the public methods and properties are the same. But they do not have a combined Interface or base class.

Now I need to chose between these two libraries depending on the target system. If they would have an Interface in common I would do something like:

```<code>public class DoDatabaseStuff() {
    private IMagic _magic
    public DoDatabaseStuff(bool useNoSql) {
       if (useNoSql) {
         _magic=new SqlMagic();
       } else {
         _magic=new NoSqlMagic();
       }
       myTable=_magic.Table.Create("CustomerTable");
       myTable.Columns.Add(typeof(int),"ID");
       myTable.Columns.Add(typeof(string),"Name");
   }
}
</code>```

Is there any way to solve this without using an excessive amount of reflection? I still want to use something like myTable.Columns.Add() instead of tableType.GetMethod("Add").Invoke()...

I also do not want to use conditions in the csproj using different build configurations. While this does work in theory, it gets distroyed every time the csproj changes automatically(e.g. a nuget-package updates)

答:
When you are confronted with bad design that you can not change, a good way to go is to keep that design out of your code. In this case that means that you should create the common interface that your external assemblies are lacking.

You can use adapters to provide a unified interface to keep the initial design flaw out of the core of your code.

You start with creating abstractions for the original classes you want to access:

```<code>public interface IMagic {
    ITable CreateTable(string name);
}

public interface ITable {
    void AddColumn(Type type, string name);
}
</code>```

Then you provide adapters:

```<code>class SqlMagicAdapter : IMagic {
    SqlMagic m_innerMagic = new SqlMagic();

    ITable CreateTable(string name) {
        return new SqlTableAdapter(m_innerMagic.Table.Create(name));
    }
}

class SqlTableAdapter : ITable {
    SqlTable m_innerTable;
    public SqlTableAdapter(SqlTable innerTable) {
        m_innerTable = innerTable;
    }
    void AddColumn(Type type, string name) {
        m_innerTable.Columns.Add(type, name);
    }
}

class NoSqlMagicAdapter : IMagic {
    NoSqlMagic m_innerMagic = new NoSqlMagic();

    ITable CreateTable(string name) {
        return new NoSqlTableAdapter(m_innerMagic.Table.Create(name));
    }
}

class NoSqlTableAdapter : ITable {
    NoSqlTable m_innerTable;
    public NoSqlTableAdapter(NoSqlTable innerTable) {
        m_innerTable = innerTable;
    }
    void AddColumn(Type type, string name) {
        m_innerTable.Columns.Add(type, name);
    }
</code>```

With a factory method you can return the respective adapter:

```<code>public static class MagicFactory {
    public static IMagic GetMagic(bool useNoSql) {
        if (useNoSql) {
            return new NoSqlMagic();
        }
        else {
            return new SqlMagic();
        }
    }
}
</code>```

Your core code can be kept clean by only using the abstractions returned by the factory:

```<code>public class DoDatabaseStuff() {
    private IMagic _magic
    public DoDatabaseStuff(bool useNoSql) {
       _magic = MagicFactory.GetMagic(useNoSql);
       ITable myTable = _magic.CreateTable("CustomerTable");
       myTable.AddColumn(typeof(int), "ID");
       myTable.AddColumn(typeof(string), "Name");
   }
}
</code>```

An added advantage is that you are also ready for any future changes, for example yet another updated external library that is not compatible to the previous ones. You can easily support these new functionalities without changing your core code.

Body:
I have a program which has a reference to an external DLL:

magic.externalFunctions.sql.dll

depending on the target system I might need the following instead:

magic.externalFunctions.nosql.dll

These DLLs are external libraries who offer the same functionality. Even the public methods and properties are the same. But they do not have a combined Interface or base class.

Now I need to chose between these two libraries depending on the target system. If they would have an Interface in common I would do something like:

public class DoDatabaseStuff() {
    private IMagic _magic
    public DoDatabaseStuff(bool useNoSql) {
       if (useNoSql) {
         _magic=new SqlMagic();
       } else {
         _magic=new NoSqlMagic();
       }
       myTable=_magic.Table.Create("CustomerTable");
       myTable.Columns.Add(typeof(int),"ID");
       myTable.Columns.Add(typeof(string),"Name");
   }
}

Is there any way to solve this without using an excessive amount of reflection? I still want to use something like myTable.Columns.Add() instead of tableType.GetMethod("Add").Invoke()...

I also do not want to use conditions in the csproj using different build configurations. While this does work in theory, it gets distroyed every time the csproj changes automatically(e.g. a nuget-package updates)

Body:
When you are confronted with bad design that you can not change, a good way to go is to keep that design out of your code. In this case that means that you should create the common interface that your external assemblies are lacking.

You can use adapters to provide a unified interface to keep the initial design flaw out of the core of your code.

You start with creating abstractions for the original classes you want to access:

public interface IMagic {
    ITable CreateTable(string name);
}

public interface ITable {
    void AddColumn(Type type, string name);
}

Then you provide adapters:

class SqlMagicAdapter : IMagic {
    SqlMagic m_innerMagic = new SqlMagic();

    ITable CreateTable(string name) {
        return new SqlTableAdapter(m_innerMagic.Table.Create(name));
    }
}

class SqlTableAdapter : ITable {
    SqlTable m_innerTable;
    public SqlTableAdapter(SqlTable innerTable) {
        m_innerTable = innerTable;
    }
    void AddColumn(Type type, string name) {
        m_innerTable.Columns.Add(type, name);
    }
}

class NoSqlMagicAdapter : IMagic {
    NoSqlMagic m_innerMagic = new NoSqlMagic();

    ITable CreateTable(string name) {
        return new NoSqlTableAdapter(m_innerMagic.Table.Create(name));
    }
}

class NoSqlTableAdapter : ITable {
    NoSqlTable m_innerTable;
    public NoSqlTableAdapter(NoSqlTable innerTable) {
        m_innerTable = innerTable;
    }
    void AddColumn(Type type, string name) {
        m_innerTable.Columns.Add(type, name);
    }

With a factory method you can return the respective adapter:

public static class MagicFactory {
    public static IMagic GetMagic(bool useNoSql) {
        if (useNoSql) {
            return new NoSqlMagic();
        }
        else {
            return new SqlMagic();
        }
    }
}

Your core code can be kept clean by only using the abstractions returned by the factory:

public class DoDatabaseStuff() {
    private IMagic _magic
    public DoDatabaseStuff(bool useNoSql) {
       _magic = MagicFactory.GetMagic(useNoSql);
       ITable myTable = _magic.CreateTable("CustomerTable");
       myTable.AddColumn(typeof(int), "ID");
       myTable.AddColumn(typeof(string), "Name");
   }
}

An added advantage is that you are also ready for any future changes, for example yet another updated external library that is not compatible to the previous ones. You can easily support these new functionalities without changing your core code.


问:
printf format based on data type
I have a templated buffer class with a simple printing function.

```<code>template <typename valueType, typename sumType, int N>
class IM_buffer
{
public:
    IM_buffer()
        : bufferValues(), numValues(-1), currentSum() { }

    void record(valueType sample)
    {
        // Set buffer index to be recorded
        numValues++;

        // Get memory location for oldest element in buffer
        valueType& oldest = bufferValues[modIdx(numValues)];

        // Add the input value to the current sum and take away the value being replaced
        currentSum += sample - oldest;

        // And now do the actual replacement in the same memory location
        oldest = sample;
    }

    valueType   getCurrent()            { return bufferValues[modIdx(numValues)];           }
    valueType   getNthPrev(int Nprev)   { return bufferValues[modIdx(numValues-Nprev)];     }
    sumType     getCurrentSum()         { return currentSum;                                }
    double      getAvg()                { return (double) currentSum / MIN(numValues+1, N); }
    int         getNumValues()          { return numValues+1;                               }
    int         getBufferSize()         { return N;                                         }

    void printBuff()
    {
        for (int ii=0; ii<N; ii++)
        {
            // if it's an integer type I need:
            printf("bufferValues[%2d]=%4d\n",ii,bufferValues[ii]);
            // but if it's a floating point type I need:
            printf("bufferValues[%2d]=%8g\n",ii,bufferValues[ii]);
        }
    }

    void clear()
    {
        for (int ii=0; ii<N; ii++)
            bufferValues[ii] = (valueType) 0.0;
        numValues = 0;
        currentSum = (sumType) 0.0;
    }

private:
    valueType bufferValues[N];
    int numValues;
    sumType currentSum;

    int modIdx(int a) { return (a % N + N) % N; }
};
</code>```

However, the format string of the printf should depend on what the data type is (e.g. int, vs. float, vs double). I've seen discussions like this but I don't really want to print out the data type, I just need to change the printf format string based on the data type. Can anyone point me in the right direction for how to implement some condition logic to select the right printf?

答:
As others mentioned in the comments, you should use std::cout that has overloads for all built in types. However, if you really insist on using printf, you can try the following hack:

```<code>#include <typeinfo>  // for typeid

std::string printfCmd("I wish to print this: ");
// int myVar = 69;  // uncomment to change var type to int
char myVar = 'd';
if (typeid(int) == typeid(myVar)) {
    printfCmd += "%d";
} else if (typeid(char) == typeid(myVar)) {
    printfCmd += "%c";
} else {
    // some warning/error
}

printf(printfCmd.c_str(), myVar);
</code>```

It is not a good solution, use it only if you really have to.

Title: printf format based on data type

Body:
I have a templated buffer class with a simple printing function.

template <typename valueType, typename sumType, int N>
class IM_buffer
{
public:
    IM_buffer()
        : bufferValues(), numValues(-1), currentSum() { }

    void record(valueType sample)
    {
        // Set buffer index to be recorded
        numValues++;

        // Get memory location for oldest element in buffer
        valueType& oldest = bufferValues[modIdx(numValues)];

        // Add the input value to the current sum and take away the value being replaced
        currentSum += sample - oldest;

        // And now do the actual replacement in the same memory location
        oldest = sample;
    }

    valueType   getCurrent()            { return bufferValues[modIdx(numValues)];           }
    valueType   getNthPrev(int Nprev)   { return bufferValues[modIdx(numValues-Nprev)];     }
    sumType     getCurrentSum()         { return currentSum;                                }
    double      getAvg()                { return (double) currentSum / MIN(numValues+1, N); }
    int         getNumValues()          { return numValues+1;                               }
    int         getBufferSize()         { return N;                                         }

    void printBuff()
    {
        for (int ii=0; ii<N; ii++)
        {
            // if it's an integer type I need:
            printf("bufferValues[%2d]=%4d\n",ii,bufferValues[ii]);
            // but if it's a floating point type I need:
            printf("bufferValues[%2d]=%8g\n",ii,bufferValues[ii]);
        }
    }

    void clear()
    {
        for (int ii=0; ii<N; ii++)
            bufferValues[ii] = (valueType) 0.0;
        numValues = 0;
        currentSum = (sumType) 0.0;
    }

private:
    valueType bufferValues[N];
    int numValues;
    sumType currentSum;

    int modIdx(int a) { return (a % N + N) % N; }
};

However, the format string of the printf should depend on what the data type is (e.g. int, vs. float, vs double). I've seen discussions like this but I don't really want to print out the data type, I just need to change the printf format string based on the data type. Can anyone point me in the right direction for how to implement some condition logic to select the right printf?

Body:
As others mentioned in the comments, you should use std::cout that has overloads for all built in types. However, if you really insist on using printf, you can try the following hack:

#include <typeinfo>  // for typeid

std::string printfCmd("I wish to print this: ");
// int myVar = 69;  // uncomment to change var type to int
char myVar = 'd';
if (typeid(int) == typeid(myVar)) {
    printfCmd += "%d";
} else if (typeid(char) == typeid(myVar)) {
    printfCmd += "%c";
} else {
    // some warning/error
}

printf(printfCmd.c_str(), myVar);

It is not a good solution, use it only if you really have to.


答:
Because your fasit array is empty. You're effectively calling fasit[0] but it doesn't exist due to the empty array.

If you want to add the 1,3,1,2,3 numbers to the array, might wanna change fasit[1,3,1,2,3]; to fasit.push(1,3,1,2,3);

Or just assign a new array to the fasit variable like this: fasit = [1,3,1,2,3];

Title: Why is this console log posting "undefined"?


问:
Calculate height of element when clicking on another - Angular 4
I am trying to do the following: when clicking on one element, I open another one. I need to calculate the height of that element I just opened.

I don't know how to do it because I have no event on the element I am opening, I will provide a small example code just so you get the idea what I want to do.

```<code><div class="parent">
  <div class="left">
    <div (click)="openRight = !openRight" class="click-element"></div>
  </div>
  <div *ngIf="openRight" class="right">

  </div>
</div>
</code>```

The goal is to dynamically set the height of left element based on the height of right element. Right element will have position absolute, that is the reason I need to get the height.

Thanks in advance!

答:
You can access the DOM element in angular using #. Then when you get the click event you can access the right element and get it's height.

HTML

```<code><div #rightElement class="right">
</div>
</code>```

TS

```<code>import { ElementRef, ViewChild } from '@angular/core';

@ViewChild('rightElement') rightElement: ElementRef;

// get the height
this.rightElement.nativeElement.offsetHeight;
</code>```

@EDIT

Why you have an undefined child is because you are using *ngIf condition. I think you are doing something like :

```<code>clickEventFunction($event) {
  ...

  this.openRight = true;

  ...

  // Use of the #rightElement
  this.rightElement.nativeElement.offsetHeight

  ...
}
</code>```

The problem is that angular will only see that you modified openRight after the execution of clickEventFunction, so #rightElement do not exist and ... UNDEFINED!

What you can do, is to say to angular that you did a change, so it will create the right element and then you could use of #rightElement.

Example :

```<code>import { ChangeDetectorRef } from 'angular2/core';

constructor(protected chRef: ChangeDetectorRef){
  ...
}

clickEventFunction($event) {
  ...

  this.openRight = true;

  // Tell angular to look at openRight
  this.chRef.detectChanges();

  ...

  // Use of the #rightElement
  this.rightElement.nativeElement.offsetHeight

  ...
}
</code>```

Body:
I am trying to do the following: when clicking on one element, I open another one. I need to calculate the height of that element I just opened.

I don't know how to do it because I have no event on the element I am opening, I will provide a small example code just so you get the idea what I want to do.

The goal is to dynamically set the height of left element based on the height of right element. Right element will have position absolute, that is the reason I need to get the height.

Thanks in advance!

Body:
You can access the DOM element in angular using #. Then when you get the click event you can access the right element and get it's height.

HTML

<div #rightElement class="right">
</div>

TS

import { ElementRef, ViewChild } from '@angular/core';

@ViewChild('rightElement') rightElement: ElementRef;

// get the height
this.rightElement.nativeElement.offsetHeight;

@EDIT

Why you have an undefined child is because you are using *ngIf condition. I think you are doing something like :

clickEventFunction($event) {
  ...

  this.openRight = true;

  ...

  // Use of the #rightElement
  this.rightElement.nativeElement.offsetHeight

  ...
}

The problem is that angular will only see that you modified openRight after the execution of clickEventFunction, so #rightElement do not exist and ... UNDEFINED!

What you can do, is to say to angular that you did a change, so it will create the right element and then you could use of #rightElement.

Example :

import { ChangeDetectorRef } from 'angular2/core';

constructor(protected chRef: ChangeDetectorRef){
  ...
}

clickEventFunction($event) {
  ...

  this.openRight = true;

  // Tell angular to look at openRight
  this.chRef.detectChanges();

  ...

  // Use of the #rightElement
  this.rightElement.nativeElement.offsetHeight

  ...
}


问:
How to print message in terminal with concat two strings in flutter?
I knows print() will useful but how to merge or concat two string variables.
like print(" "+str1+" "+str2)</p>

答:
In dart there are many string options.

For concatenation, you can do :

'hello $myVariable'

"hello ${myVariable.myProperty}"

'hello ' 'world' (only works with string literals)

'hello' + myVariable

So in your case, you can do a print(" $str1 $str2")

Use $var instead of ${var} here


问:
Inserting text to summernote from javascript function
So I've been trying to insert text into the summernote within a normal javascript function. I have a list of values that when clicked should append themselves into the actual text area. The functions are firing because I have messages being logged to the console when I click but for some reason nothing is still appending. Here is the function:

```<code>function appendListItem(ele){
    console.log("Clicked!");
    var id = $(ele).attr("id");
    console.log(typeof(id));
    console.log("ID:" + id);
    //var htmlStr = "<p>#"+id+"</p>";
    $(".summernote").summernote('code', id);
    console.log($("#summernote").summernote('code'));
}
</code>```

Everything is working except for the 7th line, $(".summernote").summernote('code', id);. I've tried using 'insertText' as well in the summernote function. The id is a string. And I've tried passing in an html string as evidenced by the commented out line (Line 6). Any help you can give me would be greatly appreciated!

EDIT 1:

Here is my html as requested:

```<code><body>
    <div><img src="./images/Logo.png" alt="Logo"  class="logo-center"></div>
    <div id="summernote"></div>
    <div class="checkList">
        <p id="checkTitle">CHECKLIST (<span id="fraction">0/5</span>)</p>
        <ul class="list-group" id="trigList">
            <li class='list-group-item'><a id='mood' onclick='appendListItem(this)'>Mood</a></li>
            <li class='list-group-item'><a id='phone' onclick='appendListItem(this)'>Phone</a></li>
            <li class='list-group-item'><a id='email' onclick='appendListItem(this)'>Email</a></li>
            <li class='list-group-item'><a id='lead' onclick='appendListItem(this)'>Lead</a></li>
        </ul>
    </div>
    <div><button type="button" class="btn btn-primary" onclick="logNote();">Log Note</button></div>
</body>
</code>```

答:
It looks like you have jQuery selectors mixed up. You have 1 Summernote so you can access it by using its ID id="summernote"

what you are currently doing, using this line $(".summernote").summernote('code', id);- is telling jQuery to get all elements that have a class of summernote due to the . selector in the beginning.

No elements in your html have a class of summernote so that is why its not working.

Change $(".summernote").summernote('code', id); to $("#summernote").summernote('code', id); and it should work. the # will get the element with id="summernote" which is your actual Summernote element.

Here is a full working example

```<code><body>
    <div><img src="./images/Logo.png" alt="Logo"  class="logo-center"></div>
    <div id="summernote"></div>
    <div class="checkList">
        <p id="checkTitle">CHECKLIST (<span id="fraction">0/5</span>)</p>
        <ul class="list-group" id="trigList">
            <li class='list-group-item'><a id='mood' onclick='appendListItem(this)'>Mood</a></li>
            <li class='list-group-item'><a id='phone' onclick='appendListItem(this)'>Phone</a></li>
            <li class='list-group-item'><a id='email' onclick='appendListItem(this)'>Email</a></li>
            <li class='list-group-item'><a id='lead' onclick='appendListItem(this)'>Lead</a></li>
        </ul>
    </div>
    <div><button type="button" class="btn btn-primary" onclick="logNote();">Log Note</button></div>
  <script>
    $(document).ready(function() {
      $('#summernote').summernote();
    });
    function appendListItem(elem) {
      //var htmlStr = "<p>#"+id+"</p>";
      var id = $(elem).attr("id");
      console.log(id);
      $("#summernote").summernote('code', id);
      // use 'insertText' instead of 'code' to append the id instead
    }
  </script>
</body>
</code>```

Body:
So I've been trying to insert text into the summernote within a normal javascript function. I have a list of values that when clicked should append themselves into the actual text area. The functions are firing because I have messages being logged to the console when I click but for some reason nothing is still appending. Here is the function:

function appendListItem(ele){
    console.log("Clicked!");
    var id = $(ele).attr("id");
    console.log(typeof(id));
    console.log("ID:" + id);
    //var htmlStr = "
#"+id+"
";
    $(".summernote").summernote('code', id);
    console.log($("#summernote").summernote('code'));
}

Everything is working except for the 7th line, $(".summernote").summernote('code', id);. I've tried using 'insertText' as well in the summernote function. The id is a string. And I've tried passing in an html string as evidenced by the commented out line (Line 6). Any help you can give me would be greatly appreciated!

EDIT 1:

Here is my html as requested:

CHECKLIST (0/5)

Mood

Phone

Email

Lead

<button type="button" class="btn btn-primary" onclick="logNote();">Log Note</button>

Body:
It looks like you have jQuery selectors mixed up. You have 1 Summernote so you can access it by using its ID id="summernote"

what you are currently doing, using this line $(".summernote").summernote('code', id);- is telling jQuery to get all elements that have a class of summernote due to the . selector in the beginning.

No elements in your html have a class of summernote so that is why its not working.

Change $(".summernote").summernote('code', id); to $("#summernote").summernote('code', id); and it should work. the # will get the element with id="summernote" which is your actual Summernote element.

Here is a full working example

<body>
    <div><img src="./images/Logo.png" alt="Logo"  class="logo-center"></div>
    <div id="summernote"></div>
    <div class="checkList">
        <p id="checkTitle">CHECKLIST (<span id="fraction">0/5</span>)</p>
        <ul class="list-group" id="trigList">
            <li class='list-group-item'><a id='mood' onclick='appendListItem(this)'>Mood</a></li>
            <li class='list-group-item'><a id='phone' onclick='appendListItem(this)'>Phone</a></li>
            <li class='list-group-item'><a id='email' onclick='appendListItem(this)'>Email</a></li>
            <li class='list-group-item'><a id='lead' onclick='appendListItem(this)'>Lead</a></li>
        </ul>
    </div>
    <div><button type="button" class="btn btn-primary" onclick="logNote();">Log Note</button></div>
  <script>
    $(document).ready(function() {
      $('#summernote').summernote();
    });
    function appendListItem(elem) {
      //var htmlStr = "<p>#"+id+"</p>";
      var id = $(elem).attr("id");
      console.log(id);
      $("#summernote").summernote('code', id);
      // use 'insertText' instead of 'code' to append the id instead
    }
  </script>
</body>


问:
How to debug Ansible issues?
Sometimes, ansible doesn't do what you want. And increasing verbosity doesn't help. For example, I'm now trying to start coturn server, which comes with init script on systemd OS (Debian Jessie). Ansible considers it running, but it's not. How do I look into what's happening under the hood? Which commands are executed, and what output/exit code?

答: There are multiple levels of debugging that you might need but the easiest one is to add ANSIBLE_STRATEGY=debug environment variable, which will enable the debugger on the first error.

Title: How to debug Ansible issues?


问:
Check for value definedness in C++
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

```<code>class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}
</code>```

Is it possible in C++?

Thanks

答:
You could try the Construct on first use idiom and write get_bar() this way:

```<code>double & get_bar()
{
    static double *bar = new double(something());
    return *bar;
}
</code>```

When you call get_bar() it will make bar for you if no one has asked for it yet.  Any subsequent calls will just return bar.  As the linked page says, this doesn't technically leak memory because the OS will reclaim it when the program exits.

UPDATE:

Changed the return value to double & to allow you to modify bar.

OwnerDisplayName: Tunnuz

Title: Check for value definedness in C++

Body:
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}

Is it possible in C++?

Thanks

Body:
You could try the Construct on first use idiom and write get_bar() this way:

double & get_bar()
{
    static double *bar = new double(something());
    return *bar;
}

When you call get_bar() it will make bar for you if no one has asked for it yet.  Any subsequent calls will just return bar.  As the linked page says, this doesn't technically leak memory because the OS will reclaim it when the program exits.

UPDATE:

Changed the return value to double & to allow you to modify bar.

OwnerDisplayName: Kristo

LastEditorDisplayName: Kristo


问:
MySQL Aurora DB Instance Turned read-only on by itself on AWS RDS
I've been working with MySQL and AuroraDB on AWS for a while now for a site I'm making. Up until a few minutes ago, I've been able to run any and all mutator functions on the instance through Lambda and MySQL workbench.

However, when I attempted to run an INSERT a few minutes ago, it gave me an error. I traced it back to Lambda saying that the --read-only flag is on my DB instance.

I was able to run these queries this morning, and now I cannot UPDATE, INSERT, or DELETE. I don't understand why it set itself to read-only randomly, besides maybe some sort of management or cleanup occurring on the AWS server, but under notifications there wasn't anything relating to any kind of maintenance.

Please let me know if there's any more information you need. I assumed that the code I was running is arbitrary, as I've tried running SQL commands directly through the workbench with the same results.

答: I found out the issue - the role of the slave instances of my Aurora cluster had swapped, probably during maintenance. I've since pointed all my Lambda functions to the cluster itself, which I actually didn't even know was something you could do, let alone the standard practice.</p>


问:
Pointers sent to function
I have following code in main():

```<code>msgs, err := ch.Consume(
        q.Name, // queue
        //..
    )

    cache := ttlru.New(100, ttlru.WithTTL(5 * time.Minute)) //Cache type

    //log.Println(reflect.TypeOf(msgs)) 'chan amqp.Delivery'

    go func() {
       //here I use `cache` and `msgs` as closures. And it works fine.
    }
</code>```

I decided to create separate function for instead of anonymous.

I declared it as func hitCache(cache *ttlru.Cache, msgs *chan amqp.Delivery) {

I get compile exception:

```<code>./go_server.go:61: cannot use cache (type ttlru.Cache) as type *ttlru.Cache in argument to hitCache:
    *ttlru.Cache is pointer to interface, not interface
./go_server.go:61: cannot use msgs (type <-chan amqp.Delivery) as type *chan amqp.Delivery in argument to hitCache
</code>```

Question: How should I pass msg and cache into the new function?

答:
You're using pointers in the function signature but not passing pointers - which is fine; as noted in the comments, there is no reason to use pointers for interface or channel values. Just change the function signature to:

```<code>hitCache(cache ttlru.Cache, msgs chan amqp.Delivery)
</code>```

And it should work fine.

Title: Pointers sent to function

Body:
I have following code in main():

msgs, err := ch.Consume(
        q.Name, // queue
        //..
    )

    cache := ttlru.New(100, ttlru.WithTTL(5 * time.Minute)) //Cache type

    //log.Println(reflect.TypeOf(msgs)) 'chan amqp.Delivery'

    go func() {
       //here I use `cache` and `msgs` as closures. And it works fine.
    }

I decided to create separate function for instead of anonymous.

I declared it as func hitCache(cache *ttlru.Cache, msgs *chan amqp.Delivery) {

I get compile exception:

./go_server.go:61: cannot use cache (type ttlru.Cache) as type *ttlru.Cache in argument to hitCache:
    *ttlru.Cache is pointer to interface, not interface
./go_server.go:61: cannot use msgs (type <-chan amqp.Delivery) as type *chan amqp.Delivery in argument to hitCache

Question: How should I pass msg and cache into the new function?

Body:
You're using pointers in the function signature but not passing pointers - which is fine; as noted in the comments, there is no reason to use pointers for interface or channel values. Just change the function signature to:

hitCache(cache ttlru.Cache, msgs chan amqp.Delivery)

And it should work fine.


问:
Bokeh Python conditional CheckboxGroup
Is there an easy way to create a conditional CheckboxGroup within the Bokeh-framework? Conditional in the sense that when another Bokeh-widget is triggered, the CheckboxGroup is populated based on the value within the triggering widget.

So for instance, if I am having a dropdown-menu in form of a Select-widget with options [a, b], and a separate Python-dict pointing at these "new" options {'a' : ['aa','bb','cc'], 'b' : ['dd','ee','ff']} - how do I create a checkbox based on the specific choice?

Pseudo code:

```<code>options_dict = {'a' : ['aa','bb','cc'], 'b' : ['dd','ee','ff']}
dropdown = Select(title="a dropdown menu:", options = ['a', 'b'], value='a')

# let all sub-options be the default option
checkbox = CheckboxGroup(labels=['aa','bb','cc','dd','ee','ff'], active=['aa','bb','cc','dd','ee','ff'])

# assume we have some function that is updating and fetching the value of the 'dropdown'

def select_something():
    selected_attribute = dropdown.value()
    return selected_attribute

def update():
    selected_attribute = select_something()
    # update the CheckBox contents - obviously Pseudo-code
    checkbox.labels = options_dict[selected_attribute]
    # and have all of them "pre-checked"
    checkbox.active = options_dict[selected_attribute]

dropdown.on_change('value', lambda attr, old, new: update())
</code>```

Thanks

答:
You can update the checkboxgroup by changing its active parameter.

It is a list of integers refering to each checkbox in order, if you have 3 checkboxes and you want only the last one to be checked you would change the active list to [2]; if you just want the first and last one to be checked you would change it to [0,2]

Title: Bokeh Python conditional CheckboxGroup

Body:
Is there an easy way to create a conditional CheckboxGroup within the Bokeh-framework? Conditional in the sense that when another Bokeh-widget is triggered, the CheckboxGroup is populated based on the value within the triggering widget.

So for instance, if I am having a dropdown-menu in form of a Select-widget with options [a, b], and a separate Python-dict pointing at these "new" options {'a' : ['aa','bb','cc'], 'b' : ['dd','ee','ff']} - how do I create a checkbox based on the specific choice?

Pseudo code:

options_dict = {'a' : ['aa','bb','cc'], 'b' : ['dd','ee','ff']}
dropdown = Select(title="a dropdown menu:", options = ['a', 'b'], value='a')

# let all sub-options be the default option
checkbox = CheckboxGroup(labels=['aa','bb','cc','dd','ee','ff'], active=['aa','bb','cc','dd','ee','ff'])

# assume we have some function that is updating and fetching the value of the 'dropdown'

def select_something():
    selected_attribute = dropdown.value()
    return selected_attribute

def update():
    selected_attribute = select_something()
    # update the CheckBox contents - obviously Pseudo-code
    checkbox.labels = options_dict[selected_attribute]
    # and have all of them "pre-checked"
    checkbox.active = options_dict[selected_attribute]

dropdown.on_change('value', lambda attr, old, new: update())

Thanks


问:
Postgresql Row Level Security Checking new data in WITH CHECK in Policy for INSERT
I've a Database with several tables.
A user has several objects and an object has several parts.

I want to write a policy that only the creator of the object is allowed to add parts to the object. Therefore I need to get the object a to be inserted part belongs to, but I've no idea how to check the data.

Is there a way to get the data to be inserted in the policy?

Thanks for your effort.

答:
Here is an example how to implement something like that with row level security. Adapt it to your need!

```<code>CREATE TABLE object(
   id integer PRIMARY KEY,
   name text NOT NULL,
   owner name NOT NULL DEFAULT current_user
);

CREATE TABLE part(
   id integer PRIMARY KEY,
   parent_id integer NOT NULL REFERENCES object(id),
   name text NOT NULL
);
</code>```

We have to give people some permissions:

```<code>GRANT SELECT, INSERT ON object TO PUBLIC;
GRANT SELECT, INSERT ON part TO PUBLIC;
</code>```

Now we enable row level security and allow only INSERTs in part when the owner in object matches:

```<code>ALTER TABLE part ENABLE ROW LEVEL SECURITY;

CREATE POLICY insert_only_owned ON part
   FOR INSERT TO PUBLIC
   WITH CHECK (EXISTS(
                  SELECT 1
                  FROM object o
                  WHERE o.id = parent_id
                    AND owner = current_user
              ));
</code>```

Body:
Here is an example how to implement something like that with row level security. Adapt it to your need!

CREATE TABLE object(
   id integer PRIMARY KEY,
   name text NOT NULL,
   owner name NOT NULL DEFAULT current_user
);

CREATE TABLE part(
   id integer PRIMARY KEY,
   parent_id integer NOT NULL REFERENCES object(id),
   name text NOT NULL
);

We have to give people some permissions:

GRANT SELECT, INSERT ON object TO PUBLIC;
GRANT SELECT, INSERT ON part TO PUBLIC;

Now we enable row level security and allow only INSERTs in part when the owner in object matches:

ALTER TABLE part ENABLE ROW LEVEL SECURITY;

CREATE POLICY insert_only_owned ON part
   FOR INSERT TO PUBLIC
   WITH CHECK (EXISTS(
                  SELECT 1
                  FROM object o
                  WHERE o.id = parent_id
                    AND owner = current_user
              ));


问:
Solving Error - "An item with the same key has already been added when returning 404"
I have my custom error page handler defined like this:

```<code>if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseBrowserLink();
}
else
{
    app.UseExceptionHandler("/Error");
}

app.UseStatusCodePagesWithReExecute("/Error/{0}");

app.UseMvc(routes =>
{
    ...
}
</code>```

Then in error controller:

```<code>public class ErrorController : Controller
{
    public IActionResult Index(int errorCode)
    {
        switch (errorCode)
        {
            case 404:
                return View($"~/Views/Error/{errorCode}.cshtml");
        }

        return View(errorCode);
    }
}
</code>```

When in production mode everything works fine, but when on develop, there are 2 scenarios:

I'm hitting 404 page "just like that" and it's showing my custom 404 page (which is correct)

I'm forcing 404 from action eg.

```<code>if(nothingFound)
{
    return NotFound();
}
</code>```

and then it's entering ErrorController action, and even the view (404.cshtml), but after that it prints whole debug titled:

ArgumentException: An item with the same key has already been added.
  Key: System.Object

Is it something normal when using app.UseDeveloperExceptionPage(), or do I have something miss-configured?

UPDATE

Stack trace:

```<code>System.ArgumentException: An item with the same key has already been added. Key: System.Object
   at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(Object key)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.StatusCodePagesExtensions.<>c__DisplayClass6_0.<<UseStatusCodePagesWithReExecute>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Web.BrowserLink.Runtime.BrowserLinkMiddleware.<ExecuteWithFilter>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()
</code>```

答:
I was having similar issue. I found the issue later that it was related to the order of using middleware. I was using middle ware to write response headers like X-Content-Type-Options and other headers. I just moved this above the app.UseStatusCodePagesWithReExecute and it start working correctly. So my current code is like:

```<code>app.Use(async (context, next) =>
        {
            context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
            context.Response.Headers.Add("X-Xss-Protection", "1");
            context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
            await next();
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
        }
</code>```

Hope this can help any one having similar issue like me.

Body:
I have my custom error page handler defined like this:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseBrowserLink();
}
else
{
    app.UseExceptionHandler("/Error");
}

app.UseStatusCodePagesWithReExecute("/Error/{0}");

app.UseMvc(routes =>
{
    ...
}

Then in error controller:

public class ErrorController : Controller
{
    public IActionResult Index(int errorCode)
    {
        switch (errorCode)
        {
            case 404:
                return View($"~/Views/Error/{errorCode}.cshtml");
        }

        return View(errorCode);
    }
}

When in production mode everything works fine, but when on develop, there are 2 scenarios:

I'm hitting 404 page "just like that" and it's showing my custom 404 page (which is correct)

I'm forcing 404 from action eg.

if(nothingFound)
{
    return NotFound();
}

and then it's entering ErrorController action, and even the view (404.cshtml), but after that it prints whole debug titled:

ArgumentException: An item with the same key has already been added.
  Key: System.Object

Is it something normal when using app.UseDeveloperExceptionPage(), or do I have something miss-configured?

UPDATE

Stack trace:

System.ArgumentException: An item with the same key has already been added. Key: System.Object
   at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(Object key)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.StatusCodePagesExtensions.<>c__DisplayClass6_0.<<UseStatusCodePagesWithReExecute>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Web.BrowserLink.Runtime.BrowserLinkMiddleware.<ExecuteWithFilter>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

Body:
I was having similar issue. I found the issue later that it was related to the order of using middleware. I was using middle ware to write response headers like X-Content-Type-Options and other headers. I just moved this above the app.UseStatusCodePagesWithReExecute and it start working correctly. So my current code is like:

app.Use(async (context, next) =>
        {
            context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
            context.Response.Headers.Add("X-Xss-Protection", "1");
            context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
            await next();
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
        }

Hope this can help any one having similar issue like me.

ContentLicense: CC BY-SA 4.0


问:
Wrap Sql query inside another Sql query using Peta Poco
How can you wrap a Sql query with arguments inside another query?

For instance:

```<code>var sqlCount = new Sql("COUNT(*) as Result").From("ArticleGroups");
sqlCount.LeftJoin("Articles").On("Articles.ArticleGroupId = ArticleGroups.Id");
sqlCount.Where("Articles.SupplierId = @supplier", new { supplier = supplier });
sqlCount.GroupBy("ArticleGroups.Id, ArticleGroups.Description");

var sqlCountWrap = new Sql();
sqlCountWrap.Select("COUNT(*)").From(string.Format("({0}) pt", sqlCount.ToString()));
</code>```

So my second Sql builder needs to wrap the first query into another one, but I get exception about the argument that is missing.

How can I fix this?

UPDATE

```<code>var sqlCountWrap = new Sql(sqlCount.ToString(), sqlCount.Arguments);
sqlCountWrap.Select("COUNT(*)").From(string.Format("({0}) pt", sqlCount.ToString()));
</code>```

Passing the sql and arguments into the new Sql instance doesn't help:

Exception:

base = {"Specified argument was out of the range of valid
  values.\r\nParameter name: Parameter '@0' specified but only 0
  parameters supplied (in `FROM (SELECT COUNT(*) as Result\nFROM
  ArticleGroups\nLEFT JOIN Articles\nON Articles.ArticleGroupId =
  ArticleGroups.Id...

答:
For everyone with the same issue as me, here is the solution:

```<code>var sqlCountWrap = new Sql();
sqlCountWrap.Select("COUNT(*)");
sqlCountWrap.Append("FROM (");
sqlCountWrap.Append(sqlCount.SQL, sqlCount.Arguments);
sqlCountWrap.Append(") pt");
</code>```

Using the append you can wrap the sql inside another sql and pass the arguments.

Body:
How can you wrap a Sql query with arguments inside another query?

For instance:

var sqlCount = new Sql("COUNT(*) as Result").From("ArticleGroups");
sqlCount.LeftJoin("Articles").On("Articles.ArticleGroupId = ArticleGroups.Id");
sqlCount.Where("Articles.SupplierId = @supplier", new { supplier = supplier });
sqlCount.GroupBy("ArticleGroups.Id, ArticleGroups.Description");

var sqlCountWrap = new Sql();
sqlCountWrap.Select("COUNT(*)").From(string.Format("({0}) pt", sqlCount.ToString()));

So my second Sql builder needs to wrap the first query into another one, but I get exception about the argument that is missing.

How can I fix this?

UPDATE

var sqlCountWrap = new Sql(sqlCount.ToString(), sqlCount.Arguments);
sqlCountWrap.Select("COUNT(*)").From(string.Format("({0}) pt", sqlCount.ToString()));

Passing the sql and arguments into the new Sql instance doesn't help:

Exception:

base = {"Specified argument was out of the range of valid
  values.\r\nParameter name: Parameter '@0' specified but only 0
  parameters supplied (in `FROM (SELECT COUNT(*) as Result\nFROM
  ArticleGroups\nLEFT JOIN Articles\nON Articles.ArticleGroupId =
  ArticleGroups.Id...

Body:
For everyone with the same issue as me, here is the solution:

var sqlCountWrap = new Sql();
sqlCountWrap.Select("COUNT(*)");
sqlCountWrap.Append("FROM (");
sqlCountWrap.Append(sqlCount.SQL, sqlCount.Arguments);
sqlCountWrap.Append(") pt");

Using the append you can wrap the sql inside another sql and pass the arguments.


问:
Android Layout: position element below lowest view
I've attached a picture to better illustrate what I'm going for.

I have two LinearLayouts positioned side by side. Both are able to expand vertically, using wrap_content. I would like to position another container (HorizontalScrollView) below whichever one has the greater height. It's currently set to go below the right-most column, as generally it is taller, but in some cases the ScrollView will cover up the content in the left-most column. Is there a way to set this in the .xml file or will I need to resort to setting this in my onCreate method?

答:
You can wrap together the two LinearLayouts in another Linear or Relative layout, something like that(just change the properties for the original 3 layouts as you have/need them) :</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/parent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<RelativeLayout
android:id="@+id/frame"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
>
<LinearLayout
android:id="@+id/linearLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/linearRight"
>
</LinearLayout>
<LinearLayout
android:id="@+id/linearRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
>
</LinearLayout>
</RelativeLayout>
<ScrollView
android:id="@+id/scroll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/frame"
android:layout_alignParentLeft="true"
>
</ScrollView>
</RelativeLayout>
</code>```

Body:
You can wrap together the two LinearLayouts in another Linear or Relative layout, something like that(just change the properties for the original 3 layouts as you have/need them) :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/parent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<RelativeLayout
android:id="@+id/frame"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
>
<LinearLayout
android:id="@+id/linearLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/linearRight"
>
</LinearLayout>
<LinearLayout
android:id="@+id/linearRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
>
</LinearLayout>
</RelativeLayout>
<ScrollView
android:id="@+id/scroll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/frame"
android:layout_alignParentLeft="true"
>
</ScrollView>
</RelativeLayout>


问:
What are common approaches to build custom API connectors?
I mostly have programming experience as a web developer, and now I'm tasked to build an integration between two rest services. The application is suppose to read from one REST service once every 5 minutes, and send the data to another service. I'll need to store a single checkSUM value somehow to be used on the next call.

At the moment I'm thinking about building it in Node and Express, hosted on heroku with a "Custom Clock Process". But I'm unsure what the best way to structure such an app is. It's quite foreign to me to work on an app without a view. Does MVC even make sense in such an app?

Can anyone point to resources explaining a good way to approach an app like this?

Does express make sense even without a view layer?

What is a good way to store a single value such as a checkSUM or SyncKey?
Is a DB overkill?

What would the folder structure look like for an app like this.

I'm aware that this is pretty broad question. I'm mostly looking for suggestions and resources, and ideas on how other people would approach this. What tech would you use?

答:
You can use request package to send request to your services. And cron package to schedule your task for every 5 min.

Here is simple code for this scenario

```<code>var request = require('request');
var CronJob = require('cron').CronJob;

var SOURCE_SERVICE_URL = "http://your.source.service/endpoint";
var DESTINATION_SERVICE_URL =  "http://your.destination.service/endpoint";

//initialize this value when you get checkSUM from request and use to compare next checkSUM
var lastCheckSUM = "";

var everyMinuteJob = new CronJob({
    cronTime: '*/5 * * * *',
    onTick: function () {
        console.log("Task started");
        task_1();
        //you can create and add tasks for other endpoints
    },
    start: true
});

var task_1 = function () {
    request(SOURCE_SERVICE_URL, function (error, response, body) {
        if (error) {
            console.log("Can not read data from source service.")
            return console.log(error);
        }
        console.log("Data read : " + body);
        //TODO - check the checkSUM value of response. Then set it to lastCheckSUM

        request
            .post(DESTINATION_SERVICE_URL, body, function (error, response, body) {
                if (error) {
                    console.log("Can not send data to destination service.")
                    return console.log(error);
                }
            })

    });
}
</code>```

Body:
You can use request package to send request to your services. And cron package to schedule your task for every 5 min.

Here is simple code for this scenario

var request = require('request');
var CronJob = require('cron').CronJob;

var SOURCE_SERVICE_URL = "http://your.source.service/endpoint";
var DESTINATION_SERVICE_URL =  "http://your.destination.service/endpoint";

//initialize this value when you get checkSUM from request and use to compare next checkSUM
var lastCheckSUM = "";

var everyMinuteJob = new CronJob({
    cronTime: '*/5 * * * *',
    onTick: function () {
        console.log("Task started");
        task_1();
        //you can create and add tasks for other endpoints
    },
    start: true
});

var task_1 = function () {
    request(SOURCE_SERVICE_URL, function (error, response, body) {
        if (error) {
            console.log("Can not read data from source service.")
            return console.log(error);
        }
        console.log("Data read : " + body);
        //TODO - check the checkSUM value of response. Then set it to lastCheckSUM

        request
            .post(DESTINATION_SERVICE_URL, body, function (error, response, body) {
                if (error) {
                    console.log("Can not send data to destination service.")
                    return console.log(error);
                }
            })

    });
}


问:
Is there any UI Console where I can query the Firebase Database?
Is there any UI Console where I can query the Firebase Database?? Basically I wish to query the data just like we can query other databases using UI</p>

答:
I found and have been using Firestation. Can be used on windows, mac, and linux. I would say to check it out. You can run sql queries against your firebase database.

You can view the source here.


问:
create a json from a soap response in java
I have a REST web service which in turn calls a Soap request. I want to convert the soap response into a json so that it can be returned as output to the REST service. What is the most efficient way to achieve this?

To elaborate the question, suppose I get a Soap xml response like given below.

```<code><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/" soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
    <soap:Body xmlns:m="http://www.example.org/stock">
        <m:GetStockPriceResponse>
            <m:Price>344.5</m:Price>
        </m:GetStockPriceResponse>
    </soap:Body>
</soap:Envelope>
</code>```

I want the json to be like this

{"price" : "344.5"}

I have tried the org.json.XML.toJSONObject() method. But it does not give the output I expect.

答:
If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.

It's available on Maven Central.

Example

```<code>import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ObjectNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance(namespaces()).create();
    Document document = parsing.xml().document(xml);

    Parser<ObjectNode> parser = parsing.obj("//m:GetStockPriceResponse")
        .attribute("price", "m:Price", parsing.number())
        .build();

    ObjectNode result = parser.apply(document);
    return result;
  }

  private Map<String, String> namespaces(){
    return new HashMap<String, String>(){{
        put("m", "http://www.example.org/stock");
    }};
  }
}
</code>```

It will return a Jackson ObjectNode, with the following json:

```<code>{"price":344.5}
</code>```

Body:
I have a REST web service which in turn calls a Soap request. I want to convert the soap response into a json so that it can be returned as output to the REST service. What is the most efficient way to achieve this?

To elaborate the question, suppose I get a Soap xml response like given below.

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/" soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
    <soap:Body xmlns:m="http://www.example.org/stock">
        <m:GetStockPriceResponse>
            <m:Price>344.5</m:Price>
        </m:GetStockPriceResponse>
    </soap:Body>
</soap:Envelope>

I want the json to be like this

{"price" : "344.5"}

I have tried the org.json.XML.toJSONObject() method. But it does not give the output I expect.

Body:
If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.

It's available on Maven Central.

Example

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ObjectNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance(namespaces()).create();
    Document document = parsing.xml().document(xml);

    Parser<ObjectNode> parser = parsing.obj("//m:GetStockPriceResponse")
        .attribute("price", "m:Price", parsing.number())
        .build();

    ObjectNode result = parser.apply(document);
    return result;
  }

  private Map<String, String> namespaces(){
    return new HashMap<String, String>(){{
        put("m", "http://www.example.org/stock");
    }};
  }
}

It will return a Jackson ObjectNode, with the following json:

{"price":344.5}


问:
Crystal Reports 2008 - Summary of Non-Additive Formula Field
My apologies if this has been answered already; it probably has, but I haven't found it in over an hour of Google and SO searching.

I have a non-additive formula field (Cost / Qty).  It works fine on detail rows, but when I add it to my group footers, it returns the values from the last detail row rather than a group-level calculation.  What do I need to do to get the formula evaluated upon all the rows in a group?  I'm surprised this isn't default behavior when adding a field to a group header or footer.

Here's what I'm getting:

```<code>Category    Cost Qty Avg Cost
Detail A-1  $100   1 $   100
Detail A-2  $200   3 $    67
Footer A    $300   4 $    67
</code>```

I expect to see an Avg Cost of $75 in the footer: $300 / 4.  If I used an aggregate I'd get an incorrect value (e.g., $167 for Sum, $83 for Avg).  In Cognos, I'd use "Expression" as my aggregation formula.

Can some experienced CR user please tell me what I need to do?

答:
You have to create a new formula field just for the Report Footer.

So if your detail formula is like this:

{Test.Cost} / {Test.Qty}

Then you need to create new formula with the following:

Sum ({Test.Cost}) / Sum ({Test.Qty})

and place it in the Report Footer. This will return the correct average ( 300 / 4 = 75 )

EDIT:

If you want to do this for a Group Footer a similar principle applies. You have to create a new formula field and add it to the Group Footer.

If you were grouping by the Category field for instance then your formula to calculate the average over the group would look like this:

Sum ({Test.Cost}, {Test.Category}) / Sum ({Test.Qty}, {Test.Category})

Body:
My apologies if this has been answered already; it probably has, but I haven't found it in over an hour of Google and SO searching.

I have a non-additive formula field (Cost / Qty).  It works fine on detail rows, but when I add it to my group footers, it returns the values from the last detail row rather than a group-level calculation.  What do I need to do to get the formula evaluated upon all the rows in a group?  I'm surprised this isn't default behavior when adding a field to a group header or footer.

Here's what I'm getting:

Category    Cost Qty Avg Cost
Detail A-1  $100   1 $   100
Detail A-2  $200   3 $    67
Footer A    $300   4 $    67

I expect to see an Avg Cost of $75 in the footer: $300 / 4.  If I used an aggregate I'd get an incorrect value (e.g., $167 for Sum, $83 for Avg).  In Cognos, I'd use "Expression" as my aggregation formula.

Can some experienced CR user please tell me what I need to do?


问:
Geb/Spock Error- No reports dir has been configured, you need to set in the config file or via the build adapter
I have trouble running my functional test from IntelliJ IDE. When I run the functional test, I got the following error message:

```<code>java.lang.IllegalStateException: No reports dir has been configured, you need to set in the config file or via the build adapter.

    at geb.Browser.getReportGroupDir(Browser.groovy:899)
    at geb.Browser.cleanReportGroupDir(Browser.groovy:932)
    at geb.spock.GebSpec.methodMissing(GebSpec.groovy:56)
    at geb.spock.GebReportingSpec.setupSpec(GebReportingSpec.groovy:37)
</code>```

Based on my research, all I need to do is to add the following code in GebConfig.groovy:
 reportsDir = new File("target/runtime_reports_dir")

I added the line to GebConfig.groovy and rebuild the project, but still running into the same issue. Is there any other fix to this error?

答:
I had this same issue, while having the reportsDir correctly configured in the GebConfig

Adding the resources folder (where my GebConfig is located) as "Test Sources Root" did the trick for me

To mark the folder as "Test Sources Root":

Right click in the folder

Mark Directory as

Test Sources Root

Happy testing!

Body:
I have trouble running my functional test from IntelliJ IDE. When I run the functional test, I got the following error message:

java.lang.IllegalStateException: No reports dir has been configured, you need to set in the config file or via the build adapter.

    at geb.Browser.getReportGroupDir(Browser.groovy:899)
    at geb.Browser.cleanReportGroupDir(Browser.groovy:932)
    at geb.spock.GebSpec.methodMissing(GebSpec.groovy:56)
    at geb.spock.GebReportingSpec.setupSpec(GebReportingSpec.groovy:37)

Based on my research, all I need to do is to add the following code in GebConfig.groovy:
 reportsDir = new File("target/runtime_reports_dir")

I added the line to GebConfig.groovy and rebuild the project, but still running into the same issue. Is there any other fix to this error?


问:
Excel VBA - Runtime error 438 : Object doesn't support this property or method
I'm new to VBA and I have the following code.
I want to sum in the variable SumDef the values of all the textboxes in a frame of a userform, if the textbox is not void.

But I get

runtime error 438 : Object doesn't support this property or method

```<code>Private Sub CommandButton2_Click()

'PROBLEEEEEM

Dim SumDef As Integer
Dim txt As Control

SumDef = 0

For Each txt In Me.Frame3.Controls

    If TypeName(txt) = "TextBox" And IsNumeric(txt.Value) = True Then

    SumDef = SumDef + CInt(txt.Text)

    End If

Next txt

If TextBox2.Value <> vbNullString And CInt(TextBox2.Text) <= SumDef Then

    cell2.Offset(, 7).Value = TextBox2.Text
    cell2.Offset(, 19).Value = TextBox3.Text
    cell2.Offset(, 8).Value = TextBox4.Text
    cell2.Offset(, 9).Value = TextBox5.Text
    cell2.Offset(, 10).Value = TextBox6.Text
    cell2.Offset(, 11).Value = TextBox7.Text
    cell2.Offset(, 12).Value = TextBox8.Text
    cell2.Offset(, 13).Value = TextBox9.Text
    cell2.Offset(, 14).Value = TextBox10.Text
    cell2.Offset(, 15).Value = TextBox11.Text
    cell2.Offset(, 16).Value = TextBox12.Text
    cell2.Offset(, 17).Value = TextBox13.Text
    cell2.Offset(, 18).Value = TextBox14.Text

    MsgBox "Bac enregistré avec succes", vbInformation, "ENR FAB 07"

    Me.CommandButton3.Enabled = True
    Me.CommandButton2.Enabled = False

Else
    MsgBox "Nombre de gants défauts est invalide", vbExclamation, "ENR FAB 07"
    TextBox2.Value = vbNullString
End If

End Sub
</code>```

答:
Nest your If statement like this instead as it's trying to evaluate the .Value on all controls otherwise, and not all controls have a .Value property:

```<code>If TypeName(txt) = "TextBox" Then
    If IsNumeric(txt.Value) = True Then
        SumDef = SumDef + CInt(txt.Text)
    End If
End If
</code>```

Body:
I'm new to VBA and I have the following code.
I want to sum in the variable SumDef the values of all the textboxes in a frame of a userform, if the textbox is not void.

But I get

runtime error 438 : Object doesn't support this property or method

Private Sub CommandButton2_Click()

'PROBLEEEEEM

Dim SumDef As Integer
Dim txt As Control

SumDef = 0

For Each txt In Me.Frame3.Controls

    If TypeName(txt) = "TextBox" And IsNumeric(txt.Value) = True Then

    SumDef = SumDef + CInt(txt.Text)

    End If

Next txt

If TextBox2.Value <> vbNullString And CInt(TextBox2.Text) <= SumDef Then

    cell2.Offset(, 7).Value = TextBox2.Text
    cell2.Offset(, 19).Value = TextBox3.Text
    cell2.Offset(, 8).Value = TextBox4.Text
    cell2.Offset(, 9).Value = TextBox5.Text
    cell2.Offset(, 10).Value = TextBox6.Text
    cell2.Offset(, 11).Value = TextBox7.Text
    cell2.Offset(, 12).Value = TextBox8.Text
    cell2.Offset(, 13).Value = TextBox9.Text
    cell2.Offset(, 14).Value = TextBox10.Text
    cell2.Offset(, 15).Value = TextBox11.Text
    cell2.Offset(, 16).Value = TextBox12.Text
    cell2.Offset(, 17).Value = TextBox13.Text
    cell2.Offset(, 18).Value = TextBox14.Text

    MsgBox "Bac enregistré avec succes", vbInformation, "ENR FAB 07"

    Me.CommandButton3.Enabled = True
    Me.CommandButton2.Enabled = False

Else
    MsgBox "Nombre de gants défauts est invalide", vbExclamation, "ENR FAB 07"
    TextBox2.Value = vbNullString
End If

End Sub

Body:
Nest your If statement like this instead as it's trying to evaluate the .Value on all controls otherwise, and not all controls have a .Value property:

If TypeName(txt) = "TextBox" Then
    If IsNumeric(txt.Value) = True Then
        SumDef = SumDef + CInt(txt.Text)
    End If
End If


问:
Calculate height of element when clicking on another - Angular 4
I am trying to do the following: when clicking on one element, I open another one. I need to calculate the height of that element I just opened.

I don't know how to do it because I have no event on the element I am opening, I will provide a small example code just so you get the idea what I want to do.

```<code><div class="parent">
  <div class="left">
    <div (click)="openRight = !openRight" class="click-element"></div>
  </div>
  <div *ngIf="openRight" class="right">

  </div>
</div>
</code>```

The goal is to dynamically set the height of left element based on the height of right element. Right element will have position absolute, that is the reason I need to get the height.

Thanks in advance!

答:
you can try below code :

```<code><div #mainScreen></div>
</code>```

in component file

```<code> import { ElementRef, ViewChild } from '@angular/core';

export class viewApp{

  @ViewChild('mainScreen') elementView: ElementRef;
  viewHeight: number;

clickMe(){
        this.viewHeight = this.elementView.nativeElement.offsetHeight;
          }
}
</code>```

or

```<code><div *ngFor="let item of items" (click)="clickMe($event.currentTarget)"></div>

clickMe(dom){
  let viewHeight=dom.clientHeight;
}
</code>```

Body:
I am trying to do the following: when clicking on one element, I open another one. I need to calculate the height of that element I just opened.

I don't know how to do it because I have no event on the element I am opening, I will provide a small example code just so you get the idea what I want to do.

The goal is to dynamically set the height of left element based on the height of right element. Right element will have position absolute, that is the reason I need to get the height.

Thanks in advance!

Body:
you can try below code :

<div #mainScreen></div>

in component file

 import { ElementRef, ViewChild } from '@angular/core';

export class viewApp{

  @ViewChild('mainScreen') elementView: ElementRef;
  viewHeight: number;

clickMe(){
        this.viewHeight = this.elementView.nativeElement.offsetHeight;
          }
}

or

<div *ngFor="let item of items" (click)="clickMe($event.currentTarget)"></div>

clickMe(dom){
  let viewHeight=dom.clientHeight;
}


问:
React native elements list width is too narrow
I am using react-native-elements list from here: https://react-native-training.github.io/react-native-elements/API/lists/

When I render it with flex: 1 it is very narrow.  When I render it with width: 400 it is OK.

Here are the styles:

```<code>container: {
        flex: 1,
        justifyContent: 'flex-start',
        alignItems: 'center',
    },
    half: {
        flex: 1,
        justifyContent: 'flex-start',
        alignItems: 'center',
        borderWidth: 2,
        borderColor: '#FF0000'
    },
</code>```

Here is the list code:

```<code>     <View style={styles.container}>
        { babyList.length === 0 ? null :
            <View style={styles.half}>
                <List containerStyle={{flex: 1}}>
                    <Text style={styles.welcome}>
                        Select Baby
                    </Text>
                    {babyList.map((baby, id) => {
                        return <ListItem key={"bbbtn" + id}
                                         onPress={ (event) => selectBaby(baby) } title={"Baby: " + baby.name}/>
                    })}
                </List>
            </View>
        }
      </View>
</code>```

Here is what it looks like with the above code:

Here is what it looks like if I set the containerStyle={{width: 400}}

I thought the flex: 1 would make it the max width?  What do I need to do to make it take up the whole parent container?

答:
This happens because you overwrite the default alignItems: 'stretch' with alignItems: 'center'. Remove it from your stylesheet and all elements will be stretched to fill all available space.

Here's your code on Snack: https://snack.expo.io/r121RGj1G

Body:
I am using react-native-elements list from here: https://react-native-training.github.io/react-native-elements/API/lists/

When I render it with flex: 1 it is very narrow.  When I render it with width: 400 it is OK.

Here are the styles:

container: {
        flex: 1,
        justifyContent: 'flex-start',
        alignItems: 'center',
    },
    half: {
        flex: 1,
        justifyContent: 'flex-start',
        alignItems: 'center',
        borderWidth: 2,
        borderColor: '#FF0000'
    },

Here is the list code:

     <View style={styles.container}>
        { babyList.length === 0 ? null :
            <View style={styles.half}>
                <List containerStyle={{flex: 1}}>
                    <Text style={styles.welcome}>
                        Select Baby
                    </Text>
                    {babyList.map((baby, id) => {
                        return <ListItem key={"bbbtn" + id}
                                         onPress={ (event) => selectBaby(baby) } title={"Baby: " + baby.name}/>
                    })}
                </List>
            </View>
        }
      </View>

Here is what it looks like with the above code:

Here is what it looks like if I set the containerStyle={{width: 400}}

I thought the flex: 1 would make it the max width?  What do I need to do to make it take up the whole parent container?


问:
Converting {integer} to f32 in Rust
I want to convert a value from {integer} to f32:

```<code>struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 { x: x, y: y, z: z };
            // do stuff with foo
        }
    }
}
</code>```

The compiler chokes on this with a type mismatch error (expecting f32 but getting {integer}). Unfortunately I can not simply change Vector3. I'm feeding a C-API with this.

Is there any easy and concise way I can convert x, y and z from {integer} to f32?

I guess there is no builtin conversion from i32 or {integer} to f32 because it could be lossy in certain situations. However, in my case the range I'm using is so small that this wouldn't be an issue. So I would like to tell the compiler to convert the value anyways.

Interestingly, the following works:

```<code>for x in -5..5 {
    let tmp: i32 = x;
    let foo: f32 = tmp as f32;
}
</code>```

I'm using a lot more that just one foo and one x so this turns hideous really fast.

Also, this works:

```<code>for x in -5i32..5i32 {
    let foo: f32 = x as f32;
    // do stuff with foo here
}
</code>```

But with my usecase this turns into:

```<code>for x in -5i32..5i32 {
    for y in -5i32..5i32 {
        for z in -5i32..5i32 {
            let foo: Vector3 = Vector3 {
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // do stuff with foo
        }
    }
}
</code>```

Which I think is pretty unreadable and an unreasonable amount of cruft for a simple conversion.

What am I missing here?

答:
Another solution this time using a function and traits. playground</p>

```<code>struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

impl Vector3 {
    pub fn new<T: Into<f32>>(a: T, b: T, c: T) -> Vector3 {
        Vector3 {
            x: a.into(),
            y: b.into(),
            z: c.into(),
        }
    }
}

fn main() {
    for x in -5..5i8 {
        for y in -5..5i8 {
            for z in -5..5i8 {
                let foo: Vector3 = Vector3::new(x, y, z);
                // do stuff with foo
            }
        }
    }
}
</code>```

Title: Converting {integer} to f32 in Rust

Body:
I want to convert a value from {integer} to f32:

struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 { x: x, y: y, z: z };
            // do stuff with foo
        }
    }
}

The compiler chokes on this with a type mismatch error (expecting f32 but getting {integer}). Unfortunately I can not simply change Vector3. I'm feeding a C-API with this.

Is there any easy and concise way I can convert x, y and z from {integer} to f32?

I guess there is no builtin conversion from i32 or {integer} to f32 because it could be lossy in certain situations. However, in my case the range I'm using is so small that this wouldn't be an issue. So I would like to tell the compiler to convert the value anyways.

Interestingly, the following works:

for x in -5..5 {
    let tmp: i32 = x;
    let foo: f32 = tmp as f32;
}

I'm using a lot more that just one foo and one x so this turns hideous really fast.

Also, this works:

for x in -5i32..5i32 {
    let foo: f32 = x as f32;
    // do stuff with foo here
}

But with my usecase this turns into:

for x in -5i32..5i32 {
    for y in -5i32..5i32 {
        for z in -5i32..5i32 {
            let foo: Vector3 = Vector3 {
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // do stuff with foo
        }
    }
}

Which I think is pretty unreadable and an unreasonable amount of cruft for a simple conversion.

What am I missing here?

Body:
Another solution this time using a function and traits. playground

struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

impl Vector3 {
    pub fn new<T: Into<f32>>(a: T, b: T, c: T) -> Vector3 {
        Vector3 {
            x: a.into(),
            y: b.into(),
            z: c.into(),
        }
    }
}

fn main() {
    for x in -5..5i8 {
        for y in -5..5i8 {
            for z in -5..5i8 {
                let foo: Vector3 = Vector3::new(x, y, z);
                // do stuff with foo
            }
        }
    }
}


问:
I want terraform commands in a directory without changing to directory
Say, I have mydir directory, I don't want to do a cd mydir and run terraform get/init/plan/apply. I want to pass it as a argument.

For eg:

terraform get -pwd mydir

答:
terraform get

E.g: terraform get mydir

Body:
terraform get

E.g: terraform get mydir


问:
Passing data through views context to javascript in Django
I'm trying to pass some data from the views.py to a template and using it in a javascript and I can't make it work. Does anyone know how can I solve this?

In the views.py

```<code>listaUsuarios = User.objects.values_list('username', flat=True)
context = {'listaUsuarios':listaUsuarios}

return render(request, redirect, context)
</code>```

This actually works and if I do a print(listaUsuarios[2])  it shows just the username number 2 in the database.

The javascript in the template

```<code>function checkForm(form)
{
 for (i = 0; i < listaUsuarioss.length; i++) {
     if(form.username.value==listaUsuarioss[i]){
 alert("Error: El nombre de usuario ya está en uso");
       form.username.focus();
 return false;
 }
}
}
</code>```

The invocation to the script

```<code><form method="post" action="{% url 'register' %}" onsubmit="return checkForm(this,{{listaUsuarios}});">
</code>```

I know I should have used Django forms for the registration but I didn't and I'm trying to make this work for checking before the registration of a new user if that username is already in use.

Thank you to everyone!

答:
Your JavaScript doesn't have any access to Django template variables. You need to send the list as JSON, parse it in the JS and assign the result to a local variable there.

```<code>context = {'listaUsuarios': json.dumps(list(listaUsuarios))}
</code>```

...

```<code>function checkForm(form) {
    var listaUsuarios = JSON.parse({{ listaUsarios|safe }});
    ...
</code>```

Body:
I'm trying to pass some data from the views.py to a template and using it in a javascript and I can't make it work. Does anyone know how can I solve this?

In the views.py

listaUsuarios = User.objects.values_list('username', flat=True)
context = {'listaUsuarios':listaUsuarios}

return render(request, redirect, context)

This actually works and if I do a print(listaUsuarios[2])  it shows just the username number 2 in the database.

The javascript in the template

function checkForm(form)
{
 for (i = 0; i < listaUsuarioss.length; i++) {
     if(form.username.value==listaUsuarioss[i]){
 alert("Error: El nombre de usuario ya está en uso");
       form.username.focus();
 return false;
 }
}
}

The invocation to the script

<form method="post" action="{% url 'register' %}" onsubmit="return checkForm(this,{{listaUsuarios}});">

I know I should have used Django forms for the registration but I didn't and I'm trying to make this work for checking before the registration of a new user if that username is already in use.

Thank you to everyone!

Body:
Your JavaScript doesn't have any access to Django template variables. You need to send the list as JSON, parse it in the JS and assign the result to a local variable there.

context = {'listaUsuarios': json.dumps(list(listaUsuarios))}

...

function checkForm(form) {
    var listaUsuarios = JSON.parse({{ listaUsarios|safe }});
    ...