问:
Bootstrap Collapse not working properly (Hide Not working)
I am using bootstrap collapse functionality is not working properly in our IBM web portal.
It working fine on “show” functionality but not working in  “Hide” functionality.

```<code><a href="#demo" data-toggle="collapse"><span class=”icon”>Collapsible</span></a>

<div id="demo" class="collapse">
Sample Code
</div>
</code>```

I see in console window the “area-expanded” value did not change in our collapse and also did not change class name like “collapsed” and collapse in”.

How to fix it .

答:
in

```<code><head>
    <script type="text/javascript" src="jquery-3.1.1.js"></script>
    <script src="js/bootstrap.js"></script>
</head>
</code>```

and in the end of body, you add:

```<code><body>
..............
    <script src="js/jquery-1.11.3.min.js"></script>
</body>
</code>```

That code is solve for your problem

Body:
I am using bootstrap collapse functionality is not working properly in our IBM web portal.
It working fine on “show” functionality but not working in  “Hide” functionality.

Collapsible

Sample Code

I see in console window the “area-expanded” value did not change in our collapse and also did not change class name like “collapsed” and collapse in”.

How to fix it .

Body:
in

<head>
    <script type="text/javascript" src="jquery-3.1.1.js"></script>
    <script src="js/bootstrap.js"></script>
</head>

and in the end of body, you add:

<body>
..............
    <script src="js/jquery-1.11.3.min.js"></script>
</body>

That code is solve for your problem


来源: stackexchange

问:
Using for update with bulk collect pl sql
I have function in which I have to add for update clause.

```<code>    FUNCTION FUNC_NAME(
    strValues IN arrayofstrings)
    RETURN arrayofnumbers IS
    ids arrayofnumbers := arrayofnumbers();
BEGIN
    SELECT myId BULK COLLECT INTO ids
    FROM table_1
    WHERE table_1.rownum1 IN (select column_value from table(strValues))
    GROUP BY myId
    HAVING count(*) = (select count(*) from table(strValues))
    --for update of myId
    ;
    RETURN ids;
END FUNC_NAME;
</code>```

but if delete comment, the error

```<code>Error(26,7): PL/SQL: ORA-01786: FOR UPDATE of this query expression is not allowed
</code>```

how can I rebuild my query?

答:
You cannot simply locked rows from a table using for update where you are using group by clause. A group by clause will give a wholistic view of table data by grouping the records on the specified columns hence it doesnot make sense as well,if you lock rows for any DML. You can use as below and lock rows.

Either:

Here in example i use an Oracle inbuilt collection sys.odcinumberlist.

```<code>CREATE OR REPLACE FUNCTION FUNC_NAME (strValues IN SYS.odcinumberlist)
   RETURN SYS.odcinumberlist
IS
   ids   SYS.odcinumberlist;

   CURSOR fall_jobs_cur (strValues IN SYS.odcinumberlist)
   IS
          SELECT myId
            FROM table_1
           WHERE table_1.rownum1 IN (SELECT COLUMN_VALUE
                                       FROM TABLE (strValues))
      FOR UPDATE OF myId;
BEGIN
   OPEN fall_jobs_cur (strValues);

   FETCH fall_jobs_cur BULK COLLECT INTO ids;

   RETURN ids;
END FUNC_NAME;
</code>```

Or

```<code>CREATE OR REPLACE FUNCTION FUNC_NAME (strValues IN SYS.odcinumberlist)
   RETURN SYS.odcinumberlist
IS
   ids   SYS.odcinumberlist;
BEGIN
       SELECT myId
         BULK COLLECT INTO ids
         FROM table_1
        WHERE table_1.rownum1 IN (SELECT COLUMN_VALUE
                                    FROM TABLE (strValues));
      FOR UPDATE OF myId;

   RETURN ids;
END FUNC_NAME;
</code>```

The above two codes will compile but when you will execute it, you will again face issue.

Like :

```<code>SQL> SELECT FUNC_NAME(sys.odcinumberlist(1,2,3)) col1 from dual;
SELECT FUNC_NAME(sys.odcinumberlist(1,2,3)) col1 from dual
       *
ERROR at line 1:
ORA-14551: cannot perform a DML operation inside a query
ORA-06512: at "FUNC_NAME", line 8
ORA-06512: at "FUNC_NAME", line 14
</code>```

So my question is what do you really wanted to achieve.

ContentLicense: CC BY-SA 3.0

Body:
I have function in which I have to add for update clause.

    FUNCTION FUNC_NAME(
    strValues IN arrayofstrings)
    RETURN arrayofnumbers IS
    ids arrayofnumbers := arrayofnumbers();
BEGIN
    SELECT myId BULK COLLECT INTO ids
    FROM table_1
    WHERE table_1.rownum1 IN (select column_value from table(strValues))
    GROUP BY myId
    HAVING count(*) = (select count(*) from table(strValues))
    --for update of myId
    ;
    RETURN ids;
END FUNC_NAME;

but if delete comment, the error

Error(26,7): PL/SQL: ORA-01786: FOR UPDATE of this query expression is not allowed

how can I rebuild my query?

Body:
You cannot simply locked rows from a table using for update where you are using group by clause. A group by clause will give a wholistic view of table data by grouping the records on the specified columns hence it doesnot make sense as well,if you lock rows for any DML. You can use as below and lock rows.

Either:

Here in example i use an Oracle inbuilt collection sys.odcinumberlist.

CREATE OR REPLACE FUNCTION FUNC_NAME (strValues IN SYS.odcinumberlist)
   RETURN SYS.odcinumberlist
IS
   ids   SYS.odcinumberlist;

   CURSOR fall_jobs_cur (strValues IN SYS.odcinumberlist)
   IS
          SELECT myId
            FROM table_1
           WHERE table_1.rownum1 IN (SELECT COLUMN_VALUE
                                       FROM TABLE (strValues))
      FOR UPDATE OF myId;
BEGIN
   OPEN fall_jobs_cur (strValues);

   FETCH fall_jobs_cur BULK COLLECT INTO ids;

   RETURN ids;
END FUNC_NAME;

Or

CREATE OR REPLACE FUNCTION FUNC_NAME (strValues IN SYS.odcinumberlist)
   RETURN SYS.odcinumberlist
IS
   ids   SYS.odcinumberlist;
BEGIN
       SELECT myId
         BULK COLLECT INTO ids
         FROM table_1
        WHERE table_1.rownum1 IN (SELECT COLUMN_VALUE
                                    FROM TABLE (strValues));
      FOR UPDATE OF myId;

   RETURN ids;
END FUNC_NAME;

The above two codes will compile but when you will execute it, you will again face issue.

Like :

SQL> SELECT FUNC_NAME(sys.odcinumberlist(1,2,3)) col1 from dual;
SELECT FUNC_NAME(sys.odcinumberlist(1,2,3)) col1 from dual
       *
ERROR at line 1:
ORA-14551: cannot perform a DML operation inside a query
ORA-06512: at "FUNC_NAME", line 8
ORA-06512: at "FUNC_NAME", line 14

So my question is what do you really wanted to achieve.


问:
Does anyone use template metaprogramming in real life?
I discovered template metaprogramming more than 5 years ago and got a huge kick out of reading Modern C++ Design but I never found an opertunity to use it in real life.

Have you ever used this technique in real code?

Contributors to Boost need not apply ;o)

答:
For those familiar with Oracle Template Library (OTL), boost::any and Loki library (the one described in Modern C++ Design) here's the proof of concept TMP code that enables you to store one row of otl_stream in vector<boost::any> container and access data by column number. And 'Yes', I'm going to incorporate it in production code.

```<code>#include <iostream>
#include <vector>
#include <string>
#include <Loki/Typelist.h>
#include <Loki/TypeTraits.h>
#include <Loki/TypeManip.h>
#include <boost/any.hpp>
#define OTL_ORA10G_R2
#define OTL_ORA_UTF8
#include <otlv4.h>

using namespace Loki;

/* Auxiliary structs */
template <int T1, int T2>
struct IsIntTemplateEqualsTo{
    static const int value = ( T1 == T2 );
};

template <int T1>
struct ZeroIntTemplateWorkaround{
    static const int value = ( 0 == T1? 1 : T1 );
};

/* Wrapper class for data row */
template <class TList>
class T_DataRow;

template <>
class T_DataRow<NullType>{
protected:
    std::vector<boost::any> _data;
public:
    void Populate( otl_stream& ){};
};

/* Note the inheritance trick that enables to traverse Typelist */
template <class T, class U>
class T_DataRow< Typelist<T, U> >:public T_DataRow<U>{
public:
    void Populate( otl_stream& aInputStream ){
        T value;
        aInputStream >> value;
        boost::any anyValue = value;
        _data.push_back( anyValue );

        T_DataRow<U>::Populate( aInputStream );
    }

    template <int TIdx>
    /* return type */
    Select<
        IsIntTemplateEqualsTo<TIdx, 0>::value,
        typename T,
        typename TL::TypeAt<
            U,
            ZeroIntTemplateWorkaround<TIdx>::value - 1
        >::Result
    >::Result
    /* sig */
    GetValue(){
    /* body */
        return boost::any_cast<
            Select<
                IsIntTemplateEqualsTo<TIdx, 0>::value,
                typename T,
                typename TL::TypeAt<
                    U,
                    ZeroIntTemplateWorkaround<TIdx>::value - 1
                >::Result
            >::Result
        >( _data[ TIdx ] );
    }
};

int main(int argc, char* argv[])
{
    db.rlogon( "AMONRAWMS/WMS@amohpadb.world" ); // connect to Oracle
    std::cout<<"Connected to oracle DB"<<std::endl;
    otl_stream o( 1, "select * from blockstatuslist", db );

    T_DataRow< TYPELIST_3( int, int, std::string )> c;
    c.Populate( o );
    typedef enum{ rcnum, id, name } e_fields;
    /* After declaring enum you can actually acess columns by name */
    std::cout << c.GetValue<rcnum>() << std::endl;
    std::cout << c.GetValue<id>() << std::endl;
    std::cout << c.GetValue<name>() << std::endl;
    return 0;
};
</code>```

For those not familiar with mentioned libraries.

The problem with OTL's otl_stream container is that one can access columns data only in sequential order by declaring variables of appropriate type and applying the operator >> to otl_stream object in the following way:

```<code>otl_stream o( 1, "select * from blockstatuslist", db );
int rcnum;
int id;
std::string name;
o >> rcnum >> id >> name;
</code>```

It's not always convenient. The workaround is to write some wrapper class and to populate it with data from otl_stream. The desire is to be able to declare the list of column types and then:

take the type T of the column

declare variable of that type

apply olt_stream::operator >>(T&)

store the result (in the vector of boost::any)

take the type of the next column and repeat until all columns are processed

You can do all this with the help of Loki's Typelist struct, template specialization and inheritance.

With the help of Loki's library constructs you can also generate bunch of GetValue functions that return values of appropriate type deducing it from column's number (actually number of type in Typelist).

OwnerDisplayName: Motti

ContentLicense: CC BY-SA 2.5

Body:
For those familiar with Oracle Template Library (OTL), boost::any and Loki library (the one described in Modern C++ Design) here's the proof of concept TMP code that enables you to store one row of otl_stream in vector<boost::any> container and access data by column number. And 'Yes', I'm going to incorporate it in production code.

#include <iostream>
#include <vector>
#include <string>
#include <Loki/Typelist.h>
#include <Loki/TypeTraits.h>
#include <Loki/TypeManip.h>
#include <boost/any.hpp>
#define OTL_ORA10G_R2
#define OTL_ORA_UTF8
#include <otlv4.h>

using namespace Loki;

/* Auxiliary structs */
template <int T1, int T2>
struct IsIntTemplateEqualsTo{
    static const int value = ( T1 == T2 );
};

template <int T1>
struct ZeroIntTemplateWorkaround{
    static const int value = ( 0 == T1? 1 : T1 );
};

/* Wrapper class for data row */
template <class TList>
class T_DataRow;

template <>
class T_DataRow<NullType>{
protected:
    std::vector<boost::any> _data;
public:
    void Populate( otl_stream& ){};
};

/* Note the inheritance trick that enables to traverse Typelist */
template <class T, class U>
class T_DataRow< Typelist<T, U> >:public T_DataRow<U>{
public:
    void Populate( otl_stream& aInputStream ){
        T value;
        aInputStream >> value;
        boost::any anyValue = value;
        _data.push_back( anyValue );

        T_DataRow<U>::Populate( aInputStream );
    }

    template <int TIdx>
    /* return type */
    Select<
        IsIntTemplateEqualsTo<TIdx, 0>::value,
        typename T,
        typename TL::TypeAt<
            U,
            ZeroIntTemplateWorkaround<TIdx>::value - 1
        >::Result
    >::Result
    /* sig */
    GetValue(){
    /* body */
        return boost::any_cast<
            Select<
                IsIntTemplateEqualsTo<TIdx, 0>::value,
                typename T,
                typename TL::TypeAt<
                    U,
                    ZeroIntTemplateWorkaround<TIdx>::value - 1
                >::Result
            >::Result
        >( _data[ TIdx ] );
    }
};

int main(int argc, char* argv[])
{
    db.rlogon( "AMONRAWMS/WMS@amohpadb.world" ); // connect to Oracle
    std::cout<<"Connected to oracle DB"<<std::endl;
    otl_stream o( 1, "select * from blockstatuslist", db );

    T_DataRow< TYPELIST_3( int, int, std::string )> c;
    c.Populate( o );
    typedef enum{ rcnum, id, name } e_fields;
    /* After declaring enum you can actually acess columns by name */
    std::cout << c.GetValue<rcnum>() << std::endl;
    std::cout << c.GetValue<id>() << std::endl;
    std::cout << c.GetValue<name>() << std::endl;
    return 0;
};

For those not familiar with mentioned libraries.

The problem with OTL's otl_stream container is that one can access columns data only in sequential order by declaring variables of appropriate type and applying the operator >> to otl_stream object in the following way:

otl_stream o( 1, "select * from blockstatuslist", db );
int rcnum;
int id;
std::string name;
o >> rcnum >> id >> name;

It's not always convenient. The workaround is to write some wrapper class and to populate it with data from otl_stream. The desire is to be able to declare the list of column types and then:

take the type T of the column

declare variable of that type

apply olt_stream::operator >>(T&)

store the result (in the vector of boost::any)

take the type of the next column and repeat until all columns are processed

You can do all this with the help of Loki's Typelist struct, template specialization and inheritance.

With the help of Loki's library constructs you can also generate bunch of GetValue functions that return values of appropriate type deducing it from column's number (actually number of type in Typelist).

ContentLicense: CC BY-SA 4.0


问:
How do I overwrite the value of a specific index/column in a DataFrame?
I have a dataframe Exposure with zeros constructed as follows:

```<code>Exposure = pd.DataFrame(0, index=dates, columns=tickers)
</code>```

and a DataFrame df with data.

I want to fill some of the data from df to Exposure:

```<code>    for index, column in df.iterrows():
        # value of df(index,column) to be filled at Exposure(index,column)
</code>```

How do I overwrite the value of at (index,column) of Exposure with the value of df(index,column)?

答:
You can try this:

```<code>for index, column in df.iterrows():
    Exposure.loc[index, column.index] = column.values
</code>```

This will make new index and columns in Exposure if they don't exist, if you want to avoid this, construct the common index and columns firstly, then do the assignment in a vectorized way(avoiding the for loop):

```<code>common_index = Exposure.index.intersection(df.index)
common_columns = Exposure.columns.intersection(df.columns)
Exposure.loc[common_index, common_columns] = df.loc[common_index, common_columns]
</code>```

Body:
I have a dataframe Exposure with zeros constructed as follows:

Exposure = pd.DataFrame(0, index=dates, columns=tickers)

and a DataFrame df with data.

I want to fill some of the data from df to Exposure:

    for index, column in df.iterrows():
        # value of df(index,column) to be filled at Exposure(index,column)

How do I overwrite the value of at (index,column) of Exposure with the value of df(index,column)?

Body:
You can try this:

for index, column in df.iterrows():
    Exposure.loc[index, column.index] = column.values

This will make new index and columns in Exposure if they don't exist, if you want to avoid this, construct the common index and columns firstly, then do the assignment in a vectorized way(avoiding the for loop):

common_index = Exposure.index.intersection(df.index)
common_columns = Exposure.columns.intersection(df.columns)
Exposure.loc[common_index, common_columns] = df.loc[common_index, common_columns]


问:
SSRS - Show data based on user option Report by:(hour/day/month/year/daypeak)
I have the DB table that stores customername, hourly values (0-23) and reading dates  all meters. I created a SSRS report that gets the hourly data from the table based on the date range (start & enddate)

Report Design has the following parameters:

```<code>Start Date:
End Date:
Customer: Dropdown list that show all our active customers
Report By: Dropdown list that show (Hour/Day/Month/Day Peak/Month Peak/Year Peak)
</code>```

End user selects date range (start & end), customername and Reportby:Month. I should be able to show the report based on user selected option (report by:).

I created a dataset under query have this query:

```<code>SELECT CustomerName, ReadingDate, IntegratedHour, IntegratedUsage, IntegratedGeneration
FROM         DB.dbo.TableName
WHERE     (DATEADD(HOUR, IntegratedHour, ReadingDate) BETWEEN DATEADD(HOUR, 0, @StartDate) AND DATEADD(HOUR, 23, @EndDate)) AND
                      (CustomerName = @FacilityName)
ORDER BY ReadingDate, IntegratedHour
</code>```

This query results me the hourly values.

How do i filter or bring this to show report by Day/month/Year based on end-user selection. I am not sure where to set the filter or how to query.

Could someone help me on this. Appreciate your help/advises. Thanks

答:
I don't know what your Day Peak/Month Peak/Year Peak definitions are but hopefully this can help.</p>

```<code>DECLARE @StartDate DATETIME = '2017-01-01'
      , @EndDate DATETIME = '2017-12-02'
      , @FacilityName VARCHAR(50) = 'Peter'
      , @ReportBY VARCHAR(20) = 'Month'

DECLARE @TestData TABLE (CustomerName VARCHAR(50),ReadingDate DATETIME,IntegratedHour INT,IntegratedUsage DECIMAL(15,2),IntegratedGeneration  DECIMAL(15,2))
INSERT INTO @TestData
SELECT 'Peter','2017-01-01',1,20,33
INSERT INTO @TestData
SELECT 'Peter','2017-01-01',2,21,33
INSERT INTO @TestData
SELECT 'Peter','2017-01-01',3,22,33
INSERT INTO @TestData
SELECT 'Peter','2017-02-01',3,22,33

SELECT CustomerName
     , CASE WHEN @ReportBY = 'Hour' THEN IntegratedHour
              WHEN @ReportBY = 'Day' THEN ReadingDate
              WHEN @ReportBY = 'Month' THEN MONTH(ReadingDate)
              WHEN @ReportBY = 'Day Peak' THEN ReadingDate
              WHEN @ReportBY = 'Month Peak' THEN ReadingDate
              WHEN @ReportBY = 'Year Peak' THEN ReadingDate
              ELSE  ReadingDate END As DateType
     , SUM(IntegratedUsage)
     , SUM(IntegratedGeneration)
FROM  @TestData
WHERE (DATEADD(hh, IntegratedHour, ReadingDate) BETWEEN DATEADD(hh, 0, @StartDate) AND DATEADD(hh, 23, @EndDate))
    AND (CustomerName = @FacilityName)
GROUP BY CustomerName
       , CASE WHEN @ReportBY = 'Hour' THEN IntegratedHour
              WHEN @ReportBY = 'Day' THEN ReadingDate
              WHEN @ReportBY = 'Month' THEN MONTH(ReadingDate)
              WHEN @ReportBY = 'Day Peak' THEN ReadingDate
              WHEN @ReportBY = 'Month Peak' THEN ReadingDate
              WHEN @ReportBY = 'Year Peak' THEN ReadingDate
              ELSE  ReadingDate END
</code>```

Body:
I have the DB table that stores customername, hourly values (0-23) and reading dates  all meters. I created a SSRS report that gets the hourly data from the table based on the date range (start & enddate)

Report Design has the following parameters:

Start Date:
End Date:
Customer: Dropdown list that show all our active customers
Report By: Dropdown list that show (Hour/Day/Month/Day Peak/Month Peak/Year Peak)

End user selects date range (start & end), customername and Reportby:Month. I should be able to show the report based on user selected option (report by:).

I created a dataset under query have this query:

SELECT CustomerName, ReadingDate, IntegratedHour, IntegratedUsage, IntegratedGeneration
FROM         DB.dbo.TableName
WHERE     (DATEADD(HOUR, IntegratedHour, ReadingDate) BETWEEN DATEADD(HOUR, 0, @StartDate) AND DATEADD(HOUR, 23, @EndDate)) AND
                      (CustomerName = @FacilityName)
ORDER BY ReadingDate, IntegratedHour

This query results me the hourly values.

How do i filter or bring this to show report by Day/month/Year based on end-user selection. I am not sure where to set the filter or how to query.

Could someone help me on this. Appreciate your help/advises. Thanks

Body:
I don't know what your Day Peak/Month Peak/Year Peak definitions are but hopefully this can help.

DECLARE @StartDate DATETIME = '2017-01-01'
      , @EndDate DATETIME = '2017-12-02'
      , @FacilityName VARCHAR(50) = 'Peter'
      , @ReportBY VARCHAR(20) = 'Month'

DECLARE @TestData TABLE (CustomerName VARCHAR(50),ReadingDate DATETIME,IntegratedHour INT,IntegratedUsage DECIMAL(15,2),IntegratedGeneration  DECIMAL(15,2))
INSERT INTO @TestData
SELECT 'Peter','2017-01-01',1,20,33
INSERT INTO @TestData
SELECT 'Peter','2017-01-01',2,21,33
INSERT INTO @TestData
SELECT 'Peter','2017-01-01',3,22,33
INSERT INTO @TestData
SELECT 'Peter','2017-02-01',3,22,33

SELECT CustomerName
     , CASE WHEN @ReportBY = 'Hour' THEN IntegratedHour
              WHEN @ReportBY = 'Day' THEN ReadingDate
              WHEN @ReportBY = 'Month' THEN MONTH(ReadingDate)
              WHEN @ReportBY = 'Day Peak' THEN ReadingDate
              WHEN @ReportBY = 'Month Peak' THEN ReadingDate
              WHEN @ReportBY = 'Year Peak' THEN ReadingDate
              ELSE  ReadingDate END As DateType
     , SUM(IntegratedUsage)
     , SUM(IntegratedGeneration)
FROM  @TestData
WHERE (DATEADD(hh, IntegratedHour, ReadingDate) BETWEEN DATEADD(hh, 0, @StartDate) AND DATEADD(hh, 23, @EndDate))
    AND (CustomerName = @FacilityName)
GROUP BY CustomerName
       , CASE WHEN @ReportBY = 'Hour' THEN IntegratedHour
              WHEN @ReportBY = 'Day' THEN ReadingDate
              WHEN @ReportBY = 'Month' THEN MONTH(ReadingDate)
              WHEN @ReportBY = 'Day Peak' THEN ReadingDate
              WHEN @ReportBY = 'Month Peak' THEN ReadingDate
              WHEN @ReportBY = 'Year Peak' THEN ReadingDate
              ELSE  ReadingDate END


问:
Creating multiple column dimension from csv
I'm trying to make a pie chart using multiple columns from a csv file, I can produce a pie chart but it only use the last value d.gre. What am I doing wrong?

Code is below

```<code>d3.csv("elecVotes.csv", function (data) {

var ndx = crossfilter(data);
var partysDim = ndx.dimension(function(d) { return +d.rep, +d.dem, +d.lib, +d.ind, +d.gre;})
var partys = partysDim.group();

var pie = dc.pieChart('#chart-pie');

pie
    .width(180)
    .height(180)
    .radius(80)
    .dimension(partysDim)
    .group(partys)
    .renderLabel(true)
    .innerRadius(10)
    .transitionDuration(500)
    .colorAccessor(function (d, i) { return d.value; });

    dc.renderAll();
});
</code>```

electVotes.csv

state, rep,dem,lib,ind,gre
Alabama,1314431,725704,44211,20276,9341
New York,5655,54444,65666,2355,12225
Texas,4355,543234,12321,12331,45644

答:
Gordon's suggestion should work, but I would also urge you to consider getting the data into a more appropriate format up front. It will make your life easier in a lot of ways and when using a lot of different tools. Specifically, you would need to transform your file to having only three columns: State, Party, and Votes. If you are maintaining this data in Excel, do it there. Or you can run this on the file you load:

```<code>var newData = []
data.forEach(function(d) {
  newData.push({state: d.state, party: 'rep', votes: d.rep})
  newData.push({state: d.state, party: 'dem', votes: d.dem})
  newData.push({state: d.state, party: 'lib', votes: d.lib})
  newData.push({state: d.state, party: 'ind', votes: d.ind})
  newData.push({state: d.state, party: 'gre', votes: d.gre})
})
data = newData
</code>```

Then your Crossfilter dimension and group creation will look like this:

```<code>var ndx = crossfilter(data);
var partysDim = ndx.dimension(function(d) { return d.party;})
var partys = partysDim.group().reduceSum(function(d) { return d.votes;});
</code>```

Again, this is another way of handling the same problem. I think there are big payoffs from organizing your data the right way up front so I usually recommend doing that work and then keeping the Crossfilter/dc.js code nice and simple.

Body:
I'm trying to make a pie chart using multiple columns from a csv file, I can produce a pie chart but it only use the last value d.gre. What am I doing wrong?

Code is below

d3.csv("elecVotes.csv", function (data) {

var ndx = crossfilter(data);
var partysDim = ndx.dimension(function(d) { return +d.rep, +d.dem, +d.lib, +d.ind, +d.gre;})
var partys = partysDim.group();

var pie = dc.pieChart('#chart-pie');

pie
    .width(180)
    .height(180)
    .radius(80)
    .dimension(partysDim)
    .group(partys)
    .renderLabel(true)
    .innerRadius(10)
    .transitionDuration(500)
    .colorAccessor(function (d, i) { return d.value; });

    dc.renderAll();
});

electVotes.csv

state, rep,dem,lib,ind,gre
Alabama,1314431,725704,44211,20276,9341
New York,5655,54444,65666,2355,12225
Texas,4355,543234,12321,12331,45644

Body:
Gordon's suggestion should work, but I would also urge you to consider getting the data into a more appropriate format up front. It will make your life easier in a lot of ways and when using a lot of different tools. Specifically, you would need to transform your file to having only three columns: State, Party, and Votes. If you are maintaining this data in Excel, do it there. Or you can run this on the file you load:

var newData = []
data.forEach(function(d) {
  newData.push({state: d.state, party: 'rep', votes: d.rep})
  newData.push({state: d.state, party: 'dem', votes: d.dem})
  newData.push({state: d.state, party: 'lib', votes: d.lib})
  newData.push({state: d.state, party: 'ind', votes: d.ind})
  newData.push({state: d.state, party: 'gre', votes: d.gre})
})
data = newData

Then your Crossfilter dimension and group creation will look like this:

var ndx = crossfilter(data);
var partysDim = ndx.dimension(function(d) { return d.party;})
var partys = partysDim.group().reduceSum(function(d) { return d.votes;});

Again, this is another way of handling the same problem. I think there are big payoffs from organizing your data the right way up front so I usually recommend doing that work and then keeping the Crossfilter/dc.js code nice and simple.


问:
Purpose of "with" methods in class
I'm looking at class called Product which includes the following:

```<code>@JsonProperty("name")
public void setName(String name) {
    this.name = name;
}

public Product withName(String name) {
    this.name = name;
    return this;
}
</code>```

what is the purpose of the withName method and how is it used? Why not just do:

```<code>Product p = new Product();
p.setName("foo");
</code>```

答:
You could do either way, but the first is trying to provide a "fluent" api so you can chain together a number of calls... something like:

```<code>Product p = new Product().withName("blah").price(1234).quantityOnHand(35);
</code>```

It is similar to a builder where you may have another object that presents the api and then ends the chain with a "build()" call that produces the instance of the class you're building:

```<code>Product p = ProductBuilder.newBuilder().withName("blah").price(1234).quantityOnHand(35).build();
</code>```

Title: Purpose of "with" methods in class

Body:
I'm looking at class called Product which includes the following:

@JsonProperty("name")
public void setName(String name) {
    this.name = name;
}

public Product withName(String name) {
    this.name = name;
    return this;
}

what is the purpose of the withName method and how is it used? Why not just do:

Product p = new Product();
p.setName("foo");

Body:
You could do either way, but the first is trying to provide a "fluent" api so you can chain together a number of calls... something like:

Product p = new Product().withName("blah").price(1234).quantityOnHand(35);

It is similar to a builder where you may have another object that presents the api and then ends the chain with a "build()" call that produces the instance of the class you're building:

Product p = ProductBuilder.newBuilder().withName("blah").price(1234).quantityOnHand(35).build();


问:
schedule cron job executed twice in different time (AWS Beanstalk)
I use AWS Beanstealk php worker environment.

I managed my cron jobs in cron.yaml

```<code>version: 1
cron:
 - name: "prepare-technical"
   url: "/workers/cron/event/prepare/technical"
   schedule: "45 0 * * *"
</code>```

And I didn't understand why but, this cron is executed twice times and in differents hours :

```<code>127.0.0.1 (-) - - [24/Mar/2017:00:44:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [24/Mar/2017:00:52:43 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [25/Mar/2017:00:44:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [25/Mar/2017:00:49:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [26/Mar/2017:00:44:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [26/Mar/2017:00:53:23 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [27/Mar/2017:00:44:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [27/Mar/2017:00:50:35 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [28/Mar/2017:00:45:00 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [28/Mar/2017:00:50:00 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [29/Mar/2017:00:44:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [29/Mar/2017:00:50:16 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [30/Mar/2017:00:45:00 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [30/Mar/2017:00:50:21 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
</code>```

Do you have an idea how can I fix that ?
Thanks

答:
By default, jobs will be re-posted if your web server doesn't respond within five minutes. There are a few possible approaches:

1) Increase the "Inactivity Timeout" under Configuration/Worker Configuration/Advanced Options. The maximum value is 1800 (30 minutes.)

2) Make your jobs run more quickly by adding processing power or splitting them into smaller chunks.

3) When you receive a job, execute it in a background thread and return from the main thread immediately.

Body:
I use AWS Beanstealk php worker environment.

I managed my cron jobs in cron.yaml

version: 1
cron:
 - name: "prepare-technical"
   url: "/workers/cron/event/prepare/technical"
   schedule: "45 0 * * *"

And I didn't understand why but, this cron is executed twice times and in differents hours :

127.0.0.1 (-) - - [24/Mar/2017:00:44:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [24/Mar/2017:00:52:43 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [25/Mar/2017:00:44:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [25/Mar/2017:00:49:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [26/Mar/2017:00:44:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [26/Mar/2017:00:53:23 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [27/Mar/2017:00:44:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [27/Mar/2017:00:50:35 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [28/Mar/2017:00:45:00 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [28/Mar/2017:00:50:00 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [29/Mar/2017:00:44:59 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [29/Mar/2017:00:50:16 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

127.0.0.1 (-) - - [30/Mar/2017:00:45:00 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"
127.0.0.1 (-) - - [30/Mar/2017:00:50:21 +0000] "POST /workers/cron/event/prepare/technical HTTP/1.1" 200 - "-" "aws-sqsd/2.3"

Do you have an idea how can I fix that ?
Thanks


问:
how to get from Linux command inside shell a string or value to JAVA?
it's possible to get the output of a command inside linux shell to a JAVA app? if it's possible how? I see the chance to  execute from JAVA a shell command i wish the opposite result : SHELL COMMANDS OUTPUT  --->to---> Java VARIABLE or STRING.  thanks for reply</p>

答:
You can use jcraft  and then execute command which returns the output

Example

```<code>host = //your hostIP;

String user = "username";
String password = "pwd";

String command = "the command you want to execute";
try {

  java.util.Properties config = new java.util.Properties();
  config.put("StrictHostKeyChecking", "no");
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host, 22);
  session.setPassword(password);
  session.setConfig(config);
  session.connect();
  System.out.println("Connected");

  Channel channel = session.openChannel("exec");
  ((ChannelExec) channel).setCommand(command);
  channel.setInputStream(null);
  ((ChannelExec) channel).setErrStream(System.err);

  InputStream in = channel.getInputStream();
  channel.connect();
  byte[] tmp = new byte[1024];
  while (true) {
    while (in.available() > 0) {
      int i = in.read(tmp, 0, 1024);
      if (i < 0)
        break;
      area.append(new String(tmp, 0, i));
      //System.out.print(new String(tmp, 0, i)); //command output
    }
    if (channel.isClosed()) {
      System.out.println("exit-status: " + channel.getExitStatus());
      break;
    }
    try {
      Thread.sleep(1000);
    } catch (Exception ee) {
    }
  }
  channel.disconnect();
  session.disconnect();
  System.out.println("DONE");
} catch (Exception e) {
  e.printStackTrace();
  return false;
}
</code>```

Body:
You can use jcraft  and then execute command which returns the output

Example

host = //your hostIP;

String user = "username";
String password = "pwd";

String command = "the command you want to execute";
try {

  java.util.Properties config = new java.util.Properties();
  config.put("StrictHostKeyChecking", "no");
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host, 22);
  session.setPassword(password);
  session.setConfig(config);
  session.connect();
  System.out.println("Connected");

  Channel channel = session.openChannel("exec");
  ((ChannelExec) channel).setCommand(command);
  channel.setInputStream(null);
  ((ChannelExec) channel).setErrStream(System.err);

  InputStream in = channel.getInputStream();
  channel.connect();
  byte[] tmp = new byte[1024];
  while (true) {
    while (in.available() > 0) {
      int i = in.read(tmp, 0, 1024);
      if (i < 0)
        break;
      area.append(new String(tmp, 0, i));
      //System.out.print(new String(tmp, 0, i)); //command output
    }
    if (channel.isClosed()) {
      System.out.println("exit-status: " + channel.getExitStatus());
      break;
    }
    try {
      Thread.sleep(1000);
    } catch (Exception ee) {
    }
  }
  channel.disconnect();
  session.disconnect();
  System.out.println("DONE");
} catch (Exception e) {
  e.printStackTrace();
  return false;
}


问:
How to implement Facebook and Twitter into an iPhone app
Hey guys! I'm making my own Facebook app (or Twitter) and I would like to know how to implement it into your iPHone app.
If anyone could help me, send me a link or something
Thanks!</p>

答:
http://developers.facebook.com/blog/post/213
You can take a look for Facebook API.</p>


问:
PHP how do I get a formated result table of prepared statement as strings
I'm currently working on a small University project and I have to get into PHP. I have a score table where I want to get a ranked list back in PHP. The query works in phpmyadmin, but I just can't get my head around the prepared statement and how to get the results out of it. Here my code:

```<code>    $con = getConnection ();

if (!$con) {
    exit();
}

$stmt = $con -> prepare("SELECT NICKNAME, HIGHSCORE, @curRank := @curRank + 1 AS RANK FROM scores p, (SELECT @curRank := 0) r ORDER BY HIGHSCORE DESC;");

$stmt->execute();
$result = $stmt->get_result(); //$result is of type mysqli_result
$num_rows = $result->num_rows;  //count number of rows in the result

// the '=' in the if statement is intentional, it will return true on success or false if it fails.
if (!$result_array = $result->fetch_assoc()) {
}

for ($j=0; $j<=$num_rows ;$j++){
        $rows[$j]=$result->fetch_row();
        print_r($rows[$j]);
}
mysqli_close($con);
</code>```

}

and this is how the print_r looks like:

Array ( [0] => guvtg [1] => 234 [2] => 2 ) Array ( [0] => guvtgloa [1]
  => 228 [2] => 3 ) Array ( [0] => guvtgloakkschmua [1] => 226 [2] => 4 ) Array ( [0] => guvtgloakk [1] => 182 [2] => 5 )

As you can see I'm getting the whole array, but I just want and output like this:

guvtg , 234 , 2
guvtgloa , 228 , 3
etc..

Does anybody know how to get a proper result? Thank you

答:
If you want to use fetch_assoc() it will give you an associative array with each item corresponding to a row field; will return FALSE when you are beyond the last row.

```<code>while ( $row = $result->fetch_assoc() ) {
        echo $row[ 'NICKNAME' ] . "," . $row['HIGHSCORE'] . "," . $row['RANK'];
        // maybe echo something at the end of the line (another comma or a line break....)
}
</code>```

You don't have to get the row count but you shoud check that $result is not FALSE.

Similarly if you don't care about column names you may use fetch_row

```<code>while ( $row = $result->fetch_row() ) {
        echo implode( ',', $row );
        // maybe echo something at the end of the line (another comma or a line break....)
}
</code>```

This way you can use implode to pack the data in comma separated values.

(But you have to handle what character to put between each row in outout)

Ex. if you want rows separated by line breaks (that will produce a CSV file) put echo "\n"; as the last statement inside the loop.

If you want a stream of comma separated values (no line breaks) then one solution is this:

```<code>$first = true;
while ( $row = $result->fetch_WOR() ) {
        if( $first ) { $first = false; } else { echo ","; }
        echo implode( ',', $row );
        // maybe echo something at the end of the line (another comma or a line break....)
}
</code>```

Body:
I'm currently working on a small University project and I have to get into PHP. I have a score table where I want to get a ranked list back in PHP. The query works in phpmyadmin, but I just can't get my head around the prepared statement and how to get the results out of it. Here my code:

    $con = getConnection ();

if (!$con) {
    exit();
}

$stmt = $con -> prepare("SELECT NICKNAME, HIGHSCORE, @curRank := @curRank + 1 AS RANK FROM scores p, (SELECT @curRank := 0) r ORDER BY HIGHSCORE DESC;");

$stmt->execute();
$result = $stmt->get_result(); //$result is of type mysqli_result
$num_rows = $result->num_rows;  //count number of rows in the result

// the '=' in the if statement is intentional, it will return true on success or false if it fails.
if (!$result_array = $result->fetch_assoc()) {
}

for ($j=0; $j<=$num_rows ;$j++){
        $rows[$j]=$result->fetch_row();
        print_r($rows[$j]);
}
mysqli_close($con);

}

and this is how the print_r looks like:

Array ( [0] => guvtg [1] => 234 [2] => 2 ) Array ( [0] => guvtgloa [1]
  => 228 [2] => 3 ) Array ( [0] => guvtgloakkschmua [1] => 226 [2] => 4 ) Array ( [0] => guvtgloakk [1] => 182 [2] => 5 )

As you can see I'm getting the whole array, but I just want and output like this:

guvtg , 234 , 2
guvtgloa , 228 , 3
etc..

Does anybody know how to get a proper result? Thank you

Body:
If you want to use fetch_assoc() it will give you an associative array with each item corresponding to a row field; will return FALSE when you are beyond the last row.

while ( $row = $result->fetch_assoc() ) {
        echo $row[ 'NICKNAME' ] . "," . $row['HIGHSCORE'] . "," . $row['RANK'];
        // maybe echo something at the end of the line (another comma or a line break....)
}

You don't have to get the row count but you shoud check that $result is not FALSE.

Similarly if you don't care about column names you may use fetch_row

while ( $row = $result->fetch_row() ) {
        echo implode( ',', $row );
        // maybe echo something at the end of the line (another comma or a line break....)
}

This way you can use implode to pack the data in comma separated values.

(But you have to handle what character to put between each row in outout)

Ex. if you want rows separated by line breaks (that will produce a CSV file) put echo "\n"; as the last statement inside the loop.

If you want a stream of comma separated values (no line breaks) then one solution is this:

$first = true;
while ( $row = $result->fetch_WOR() ) {
        if( $first ) { $first = false; } else { echo ","; }
        echo implode( ',', $row );
        // maybe echo something at the end of the line (another comma or a line break....)
}


问:
Array multiplying the answer and returning it
This is what I am trying to do. I would like my code to return the following:

"The volume of the small box is: 300"

But I cannot seem to figure out what to do:

```<code><?php
    $box = array(
       "Small box" => array("length" => 12, "width" => 10, "depth" => 2.5),
       "Medium box" => array("length" => 30, "width" => 20, "depth" => 4),
       "Large box" => array("length" => 60, "width" => 40, "depth" => 11.5)

    );
    foreach ($box as $number => $boxes)
    {
        echo "The volume of the "."$number"." is: \t";
        foreach ($boxes as $value)
        {
            if (is_numeric($value))
            {
               $sum = array_product($boxes);
               echo "$sum";
            }
        }
        echo "<br />";
    }
    ?>
</code>```

答:
You are looping through the $value, calculating and displaying the $sum multiple (3) times.  Just calculate the product:

```<code>foreach ($box as $number => $boxes)
{
    echo "The volume of the "."$number"." is: \t";
    echo array_product($boxes);

    echo "<br />";
}
</code>```

If you don't have a predictable array with length, width and depth then there is little point in doing this at all, but you could also do:

```<code>    echo $boxes['length'] * $boxes['width'] * $boxes['depth'];
</code>```

Body:
This is what I am trying to do. I would like my code to return the following:

"The volume of the small box is: 300"

But I cannot seem to figure out what to do:

<?php
    $box = array(
       "Small box" => array("length" => 12, "width" => 10, "depth" => 2.5),
       "Medium box" => array("length" => 30, "width" => 20, "depth" => 4),
       "Large box" => array("length" => 60, "width" => 40, "depth" => 11.5)

    );
    foreach ($box as $number => $boxes)
    {
        echo "The volume of the "."$number"." is: \t";
        foreach ($boxes as $value)
        {
            if (is_numeric($value))
            {
               $sum = array_product($boxes);
               echo "$sum";
            }
        }
        echo "
";
    }
    ?>

Body:
You are looping through the $value, calculating and displaying the $sum multiple (3) times.  Just calculate the product:

foreach ($box as $number => $boxes)
{
    echo "The volume of the "."$number"." is: \t";
    echo array_product($boxes);

    echo "<br />";
}

If you don't have a predictable array with length, width and depth then there is little point in doing this at all, but you could also do:

    echo $boxes['length'] * $boxes['width'] * $boxes['depth'];


问:
How to add extras to an intent created by Linkify?
I have created a content provider (a word and its definition database). I also have an activity that will display a word and its definition, this activity requires two things: a custom Parcelable extra, and of course the word.

The goal is that in big texts in my app, Linkify will match some words, and when the user clicks on it it will display an activity with the word and its definition. The words are stored in a database, hence the content provider. The activity requires the word to be displayed, and an additional Parcelable. However Linkify does not provide access to the Intent. Currently the intent only contains the word to be defined.

What whould I do to be able to add the custom Parcelable to the Intent created implicitly by Linkify.addLinks?

答:
After looking in the source I have located where the Intent is created:
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/text/style/URLSpan.java

Thanks to open source, I created my own Linkify class (copied from Linkify) which uses also its own URLSpan copy, that takes into account the Parcelable I wanted to use.


问:
azure documentdb create document duplicates Id property
I want to store the following object in azure documentdb

```<code>public class MyDocument
{
    public string Id { get; set; }
    public SomeOtherClass SomeOtherClass { get; set; }
}
</code>```

the property Id is a timestamp (yyyyMMddHHmmss) followed by a guid. As a side-effect, this allows me to sort on Id.
I used this call to store it:

```<code> await docDbClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(db, coll), myDoc);
</code>```

When the document is stored, it has my documents properties (Id and SomeOtherClass) and an additional "id" property (note the lowercase "i"). (and some other technical properties used by documentdb). This is filled with a guid.

As far as I understood, by storing an object which already has an Id property, documentdb would use this and not generate it's own (but it did!).

Now I have two problems: I can't check with

```<code> await docDbClient.ReadDocumentAsync(UriFactory.CreateDocumentCollectionUri(db, coll), myDoc.Id);
</code>```

to see if a document already exists, and I can't use the Id property to sort and compare documents in a query like this:

```<code>IQueryable<MyDocument> query = _client.CreateDocumentQuery<MyDocument>(
            UriFactory.CreateDocumentCollectionUri(_account.Database, _account.Collection), queryOptions);
 query = query.Where(x => x.Id.CompareTo(inputValue) >= 0);
</code>```

where inputValue is another key of the same form, to be used for paging. Because when deserializing the object out of documentdb, the id property replaces my Id property and I never see it's original value.

Am I using this wrong?
Did I make the wrong assumption that my Id property would be used instead of an auto-generated one with lowercase?

EDIT: I can confirm that this is solved when using [JsonProperty("id")] on the Id property. But any document already insertedI can't retrieve my original value of Id

答:
DocumentDB's id property is what has to be unique. Your own Id property (with upper-case I) is not a special property - it's just... a property that you created.

And you've seen the guids auto-generated in the id property. Note that you can put your own value in id, as long as it's unique. You don't have to accept the default value (guid).

Body:
I want to store the following object in azure documentdb

public class MyDocument
{
    public string Id { get; set; }
    public SomeOtherClass SomeOtherClass { get; set; }
}

the property Id is a timestamp (yyyyMMddHHmmss) followed by a guid. As a side-effect, this allows me to sort on Id.
I used this call to store it:

 await docDbClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(db, coll), myDoc);

When the document is stored, it has my documents properties (Id and SomeOtherClass) and an additional "id" property (note the lowercase "i"). (and some other technical properties used by documentdb). This is filled with a guid.

As far as I understood, by storing an object which already has an Id property, documentdb would use this and not generate it's own (but it did!).

Now I have two problems: I can't check with

 await docDbClient.ReadDocumentAsync(UriFactory.CreateDocumentCollectionUri(db, coll), myDoc.Id);

to see if a document already exists, and I can't use the Id property to sort and compare documents in a query like this:

IQueryable<MyDocument> query = _client.CreateDocumentQuery<MyDocument>(
            UriFactory.CreateDocumentCollectionUri(_account.Database, _account.Collection), queryOptions);
 query = query.Where(x => x.Id.CompareTo(inputValue) >= 0);

where inputValue is another key of the same form, to be used for paging. Because when deserializing the object out of documentdb, the id property replaces my Id property and I never see it's original value.

Am I using this wrong?
Did I make the wrong assumption that my Id property would be used instead of an auto-generated one with lowercase?

EDIT: I can confirm that this is solved when using [JsonProperty("id")] on the Id property. But any document already insertedI can't retrieve my original value of Id


问:
Line break in xsl fop
I use an xslt and fop to generate a PDF out of the xml.
in the PDF I want to have all
 replaced by a line break.

In the first SalesOrderItem, the line break is in ShortDescription and this one works fine but in the second SalesOrderItem the
 is in OrderText and the brackets are escaped. As you can see there is
 instead of
. Here the line break is not working.
I tried replacing but that did not work.

My xml looks like this:

```<code>     <SalesOrderItem>
    <ReceivingPerson>...</ReceivingPerson>
    <Building />
    <Department>...</Department>
    <Floor />
    <Room />
    <DeliveryAddress>
    </DeliveryAddress>
    <IsFreetext>false</IsFreetext>
    <OrderItemNo>1</OrderItemNo>
    <ProductId>800100</ProductId>
    <ExtProductId />
    <ProductDescShort>Text1  <br/><b>text2</b></ProductDescShort>
    <Quantity>1,00</Quantity>
    <PriceUnit>1</PriceUnit>
    <NetPrice>20,00</NetPrice>
    <TotalNetPrice>20,00</TotalNetPrice>
    <GLAccount>
      <GLAccountId>123</GLAccountId>
      <DescShort />
      <CustomerId>customer1</CustomerId>
    </GLAccount>
    <DeliveryDate>06.04.2017</DeliveryDate>
    <OrderText />
    <UnitOfMeasure id='PCE'>
      <Description>Stück</Description>
    </UnitOfMeasure>
    <Status id='090'>
      <StatusDesc>offen</StatusDesc>
    </Status>
    <Tax id='BB'>
      <Description>19%</Description>
    </Tax>
    <CostDistribution>
      <CostDistributionPositions>
        <CostDistributionPos>
          <CostObject>
            <CostObjectId>1006901</CostObjectId>
            <CostObjectType>COSTCENTER</CostObjectType>
            <CustomerId>customer1</CustomerId>
            <MasterCostObjectId>NP-RNS</MasterCostObjectId>
          </CostObject>
          <Percentage>100,00</Percentage>
        </CostDistributionPos>
      </CostDistributionPositions>
    </CostDistribution>
    <DocumentAttachments />
    <Attributes />
    <ExtGLAccountId />
    <Comment />
    <Supplier supplierId='90025370'>
      <SupplierName>WORDSHOP</SupplierName>
      <SupplierLanguage>de</SupplierLanguage>
      <AddressAssociation type='default' default='true'>
        <Address id='90025370'>
        </Address>
      </AddressAssociation>
      <TermsOfDelivery>
        <Description />
        <LongDescription />
      </TermsOfDelivery>
      <TermsOfPayment>
        <Description>30 Tage netto</Description>
        <LongDescription>30 Tage netto</LongDescription>
        <DiscountDays1>30</DiscountDays1>
        <DiscountDays2>0</DiscountDays2>
        <NetDays />
        <DiscountPerc1>0</DiscountPerc1>
        <DiscountPerc2>0</DiscountPerc2>
      </TermsOfPayment>
    </Supplier>
  </SalesOrderItem>
  <SalesOrderItem>
    <ReceivingPerson>fdf</ReceivingPerson>
    <Building />
    <Department/>
    <Floor />
    <Room />
    <DeliveryAddress>
    </DeliveryAddress>
    <IsFreetext>false</IsFreetext>
    <OrderItemNo>2</OrderItemNo>
    <ProductId>50049411</ProductId>
    <ExtProductId />
    <ProductDescShort>Product desc</ProductDescShort>
    <Quantity>1.670,00</Quantity>
    <PriceUnit>1</PriceUnit>
    <NetPrice>0,01</NetPrice>
    <TotalNetPrice>16,70</TotalNetPrice>
    <GLAccount>
      <GLAccountId>9764955002</GLAccountId>
      <DescShort />
      <CustomerId>customer1</CustomerId>
    </GLAccount>
    <DeliveryDate>30.03.2017</DeliveryDate>
    <OrderText>7090070589<br/>17<br/>13.02.2017<br/>name 1<br/>12345<br/>Musterstadt<br/>Strasse 25<br/>D</OrderText>
    <UnitOfMeasure id='PCE'>
      <Description>Stück</Description>
    </UnitOfMeasure>
    <Status id='090'>
      <StatusDesc>offen</StatusDesc>
    </Status>
    <Tax id='N8'>
      <Description>7%</Description>
    </Tax>
    <CostDistribution>
      <CostDistributionPositions>
        <CostDistributionPos>
          <CostObject>
            <CostObjectId>1006901</CostObjectId>
            <CostObjectType>COSTCENTER</CostObjectType>
            <CustomerId>customer1</CustomerId>
            <MasterCostObjectId>c1</MasterCostObjectId>
          </CostObject>
          <Percentage>100,00</Percentage>
        </CostDistributionPos>
      </CostDistributionPositions>
    </CostDistribution>
    <DocumentAttachments />
    <Attributes />
    <ExtGLAccountId />
    <Comment />
    <Supplier supplierId='90004996'>
      <SupplierName>supplier1</SupplierName>
      <SupplierLanguage>de</SupplierLanguage>
      <AddressAssociation type='default' default='true'>
        <Address id='90004996'>
        </Address>
      </AddressAssociation>
      <TermsOfDelivery>
        <Description />
        <LongDescription />
      </TermsOfDelivery>
      <TermsOfPayment>
        <Description>innerhalb von 14 Tagen ohne Abzug</Description>
        <LongDescription>innerhalb von 14 Tagen ohne Abzug</LongDescription>
        <DiscountDays1>14</DiscountDays1>
        <DiscountDays2>0</DiscountDays2>
        <NetDays />
        <DiscountPerc1>0</DiscountPerc1>
        <DiscountPerc2>0</DiscountPerc2>
      </TermsOfPayment>
    </Supplier>
  </SalesOrderItem>
</code>```

My XSLT looks like this:

```<code><xsl:template match="br">
<fo:block><xsl:apply-templates/></fo:block>
</xsl:template>
...
<xsl:for-each select="SalesOrder/SalesOrderItems/SalesOrderItem">
...
<xsl:if test="ProductDescShort">
<fo:block><xsl:apply-templates select="ProductDescShort"/></fo:block>
</xsl:if>
...
<xsl:if test="OrderText!=''">
<fo:table-row keep-with-next.within-line="always" keep-with-previous.within-line="always" keep-with-previous.within-column="always" keep-with-previous.within-page="always">
<fo:table-cell/><fo:table-cell number-columns-spanned="3" display-align="before">
  <fo:block position="relative" white-space-collapse="false"  linefeed-treatment="preserve"  start-indent="2.0pt" display-align="before" text-align="start" color="#000000" font-family="Arial" font-size="10.0pt">
    <xsl:apply-templates select="OrderText"/>
  </fo:block>
</fo:table-cell>
...
</xsl:for-each>
</code>```

EDIT:

I changed it to replace like this, but it won't replace. I guess my replace search string is wrong, but I couldn't figure out what I need to insert to make it match.

```<code><xsl:if test="OrderText!=''">
<fo:table-row keep-with-next.within-line="always" keep-with-previous.within-line="always" keep-with-previous.within-column="always" keep-with-previous.within-page="always">
<fo:table-cell/><fo:table-cell number-columns-spanned="3" display-align="before">
<fo:block position="relative" white-space-collapse="false"  linefeed-treatment="preserve"  start-indent="2.0pt" display-align="before" text-align="start" color="#000000" font-family="Arial" font-size="10.0pt">
<xsl:variable name="newtext">
 <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="OrderText" />
         <xsl:with-param name="replace" select="'<br/>'" />
        <xsl:with-param name="by" select="20" />
    </xsl:call-template>
</xsl:variable>
 <xsl:value-of select="$newtext"/>
</fo:block>
</fo:table-cell>
...
<!-- Replace Template -->
<xsl:template name="string-replace-all">
    <xsl:param name="text" />
    <xsl:param name="replace" />
    <xsl:param name="by" />
    <xsl:choose>
        <xsl:when test="$text = '' or $replace = ''or not($replace)" >
            <!-- Prevent this routine from hanging -->
            <xsl:value-of select="$text" />
        </xsl:when>
        <xsl:when test="contains($text, $replace)">
            <xsl:value-of select="substring-before($text,$replace)" />
            <xsl:value-of select="$by" />
            <xsl:call-template name="string-replace-all">
                <xsl:with-param name="text" select="substring-after($text,$replace)" />
                <xsl:with-param name="replace" select="$replace" />
                <xsl:with-param name="by" select="$by" />
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text" />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</code>```

答:
The params in 'replace' and 'by' where wrong. This is working:

```<code><fo:block position="relative" white-space-collapse="false"  linefeed-treatment="preserve"  start-indent="2.0pt" display-align="before" text-align="start" color="#000000" font-family="Arial" font-size="10.0pt">
<xsl:variable name="newtext">
 <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="OrderText" />
        <xsl:with-param name="replace" select="'<br/>'" />
        <xsl:with-param name="by" select="'
'" />
    </xsl:call-template>
</xsl:variable>
 <xsl:value-of select="$newtext"/>
    </fo:block>
</code>```

In Oxygen Developer I couldn't get this to work but on the system this is running on, there must be a different XSLT processor and with that one it's working.

Title: Line break in xsl fop

Body:
I use an xslt and fop to generate a PDF out of the xml.
in the PDF I want to have all
 replaced by a line break.

In the first SalesOrderItem, the line break is in ShortDescription and this one works fine but in the second SalesOrderItem the
 is in OrderText and the brackets are escaped. As you can see there is
 instead of
. Here the line break is not working.
I tried replacing but that did not work.

My xml looks like this:

     <SalesOrderItem>
    <ReceivingPerson>...</ReceivingPerson>
    <Building />
    <Department>...</Department>
    <Floor />
    <Room />
    <DeliveryAddress>
    </DeliveryAddress>
    <IsFreetext>false</IsFreetext>
    <OrderItemNo>1</OrderItemNo>
    <ProductId>800100</ProductId>
    <ExtProductId />
    <ProductDescShort>Text1
text2</ProductDescShort>
    <Quantity>1,00</Quantity>
    <PriceUnit>1</PriceUnit>
    <NetPrice>20,00</NetPrice>
    <TotalNetPrice>20,00</TotalNetPrice>
    <GLAccount>
      <GLAccountId>123</GLAccountId>
      <DescShort />
      <CustomerId>customer1</CustomerId>
    </GLAccount>
    <DeliveryDate>06.04.2017</DeliveryDate>
    <OrderText />
    <UnitOfMeasure id='PCE'>
      <Description>Stück</Description>
    </UnitOfMeasure>
    <Status id='090'>
      <StatusDesc>offen</StatusDesc>
    </Status>
    <Tax id='BB'>
      <Description>19%</Description>
    </Tax>
    <CostDistribution>
      <CostDistributionPositions>
        <CostDistributionPos>
          <CostObject>
            <CostObjectId>1006901</CostObjectId>
            <CostObjectType>COSTCENTER</CostObjectType>
            <CustomerId>customer1</CustomerId>
            <MasterCostObjectId>NP-RNS</MasterCostObjectId>
          </CostObject>
          <Percentage>100,00</Percentage>
        </CostDistributionPos>
      </CostDistributionPositions>
    </CostDistribution>
    <DocumentAttachments />
    <Attributes />
    <ExtGLAccountId />
    <Comment />
    <Supplier supplierId='90025370'>
      <SupplierName>WORDSHOP</SupplierName>
      <SupplierLanguage>de</SupplierLanguage>
      <AddressAssociation type='default' default='true'>
        <Address id='90025370'>
        </Address>
      </AddressAssociation>
      <TermsOfDelivery>
        <Description />
        <LongDescription />
      </TermsOfDelivery>
      <TermsOfPayment>
        <Description>30 Tage netto</Description>
        <LongDescription>30 Tage netto</LongDescription>
        <DiscountDays1>30</DiscountDays1>
        <DiscountDays2>0</DiscountDays2>
        <NetDays />
        <DiscountPerc1>0</DiscountPerc1>
        <DiscountPerc2>0</DiscountPerc2>
      </TermsOfPayment>
    </Supplier>
  </SalesOrderItem>
  <SalesOrderItem>
    <ReceivingPerson>fdf</ReceivingPerson>
    <Building />
    <Department/>
    <Floor />
    <Room />
    <DeliveryAddress>
    </DeliveryAddress>
    <IsFreetext>false</IsFreetext>
    <OrderItemNo>2</OrderItemNo>
    <ProductId>50049411</ProductId>
    <ExtProductId />
    <ProductDescShort>Product desc</ProductDescShort>
    <Quantity>1.670,00</Quantity>
    <PriceUnit>1</PriceUnit>
    <NetPrice>0,01</NetPrice>
    <TotalNetPrice>16,70</TotalNetPrice>
    <GLAccount>
      <GLAccountId>9764955002</GLAccountId>
      <DescShort />
      <CustomerId>customer1</CustomerId>
    </GLAccount>
    <DeliveryDate>30.03.2017</DeliveryDate>
    <OrderText>7090070589
17
13.02.2017
name 1
12345
Musterstadt
Strasse 25
D</OrderText>
    <UnitOfMeasure id='PCE'>
      <Description>Stück</Description>
    </UnitOfMeasure>
    <Status id='090'>
      <StatusDesc>offen</StatusDesc>
    </Status>
    <Tax id='N8'>
      <Description>7%</Description>
    </Tax>
    <CostDistribution>
      <CostDistributionPositions>
        <CostDistributionPos>
          <CostObject>
            <CostObjectId>1006901</CostObjectId>
            <CostObjectType>COSTCENTER</CostObjectType>
            <CustomerId>customer1</CustomerId>
            <MasterCostObjectId>c1</MasterCostObjectId>
          </CostObject>
          <Percentage>100,00</Percentage>
        </CostDistributionPos>
      </CostDistributionPositions>
    </CostDistribution>
    <DocumentAttachments />
    <Attributes />
    <ExtGLAccountId />
    <Comment />
    <Supplier supplierId='90004996'>
      <SupplierName>supplier1</SupplierName>
      <SupplierLanguage>de</SupplierLanguage>
      <AddressAssociation type='default' default='true'>
        <Address id='90004996'>
        </Address>
      </AddressAssociation>
      <TermsOfDelivery>
        <Description />
        <LongDescription />
      </TermsOfDelivery>
      <TermsOfPayment>
        <Description>innerhalb von 14 Tagen ohne Abzug</Description>
        <LongDescription>innerhalb von 14 Tagen ohne Abzug</LongDescription>
        <DiscountDays1>14</DiscountDays1>
        <DiscountDays2>0</DiscountDays2>
        <NetDays />
        <DiscountPerc1>0</DiscountPerc1>
        <DiscountPerc2>0</DiscountPerc2>
      </TermsOfPayment>
    </Supplier>
  </SalesOrderItem>

My XSLT looks like this:

<xsl:template match="br">
<fo:block><xsl:apply-templates/></fo:block>
</xsl:template>
...
<xsl:for-each select="SalesOrder/SalesOrderItems/SalesOrderItem">
...
<xsl:if test="ProductDescShort">
<fo:block><xsl:apply-templates select="ProductDescShort"/></fo:block>
</xsl:if>
...
<xsl:if test="OrderText!=''">
<fo:table-row keep-with-next.within-line="always" keep-with-previous.within-line="always" keep-with-previous.within-column="always" keep-with-previous.within-page="always">
<fo:table-cell/><fo:table-cell number-columns-spanned="3" display-align="before">
  <fo:block position="relative" white-space-collapse="false"  linefeed-treatment="preserve"  start-indent="2.0pt" display-align="before" text-align="start" color="#000000" font-family="Arial" font-size="10.0pt">
    <xsl:apply-templates select="OrderText"/>
  </fo:block>
</fo:table-cell>
...
</xsl:for-each>

EDIT:

I changed it to replace like this, but it won't replace. I guess my replace search string is wrong, but I couldn't figure out what I need to insert to make it match.

<xsl:if test="OrderText!=''">
<fo:table-row keep-with-next.within-line="always" keep-with-previous.within-line="always" keep-with-previous.within-column="always" keep-with-previous.within-page="always">
<fo:table-cell/><fo:table-cell number-columns-spanned="3" display-align="before">
<fo:block position="relative" white-space-collapse="false"  linefeed-treatment="preserve"  start-indent="2.0pt" display-align="before" text-align="start" color="#000000" font-family="Arial" font-size="10.0pt">
<xsl:variable name="newtext">
 <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="OrderText" />
         <xsl:with-param name="replace" select="'&lt;br/&gt;'" />
        <xsl:with-param name="by" select="20" />
    </xsl:call-template>
</xsl:variable>
 <xsl:value-of select="$newtext"/>
</fo:block>
</fo:table-cell>
...

<xsl:template name="string-replace-all">
    <xsl:param name="text" />
    <xsl:param name="replace" />
    <xsl:param name="by" />
    <xsl:choose>
        <xsl:when test="$text = '' or $replace = ''or not($replace)" >

            <xsl:value-of select="$text" />
        </xsl:when>
        <xsl:when test="contains($text, $replace)">
            <xsl:value-of select="substring-before($text,$replace)" />
            <xsl:value-of select="$by" />
            <xsl:call-template name="string-replace-all">
                <xsl:with-param name="text" select="substring-after($text,$replace)" />
                <xsl:with-param name="replace" select="$replace" />
                <xsl:with-param name="by" select="$by" />
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text" />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

Body:
The params in 'replace' and 'by' where wrong. This is working:

<fo:block position="relative" white-space-collapse="false"  linefeed-treatment="preserve"  start-indent="2.0pt" display-align="before" text-align="start" color="#000000" font-family="Arial" font-size="10.0pt">
<xsl:variable name="newtext">
 <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="OrderText" />
        <xsl:with-param name="replace" select="'&lt;br/&gt;'" />
        <xsl:with-param name="by" select="'&#xa;'" />
    </xsl:call-template>
</xsl:variable>
 <xsl:value-of select="$newtext"/>
    </fo:block>

In Oxygen Developer I couldn't get this to work but on the system this is running on, there must be a different XSLT processor and with that one it's working.


问:
Why doesnt this xPath (c#) work?
Got this xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>
</code>```

And this xpath:

```<code>videoToAdd.Title = doc.SelectSingleNode(@"/video/title").InnerXml;
</code>```

And im getting an 'object reference not set to an instance of an object'.  Any ideas why this is a valid xpath from what I can see and it used to work...

答:
Try this:

```<code>videoToAdd.Title = doc.SelectSingleNode(@"//xmlns:video/xmlns:title").InnerXml;
</code>```

Your XML document has an XML namespace and to find the elements you must prefix them with xmlns:.

Title: Why doesnt this xPath (c#) work?

Body:
Got this xml:

<?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>

And this xpath:

videoToAdd.Title = doc.SelectSingleNode(@"/video/title").InnerXml;

And im getting an 'object reference not set to an instance of an object'.  Any ideas why this is a valid xpath from what I can see and it used to work...

Body:
Try this:

videoToAdd.Title = doc.SelectSingleNode(@"//xmlns:video/xmlns:title").InnerXml;

Your XML document has an XML namespace and to find the elements you must prefix them with xmlns:.


问:
Different class or type of a variable after using $ in R
I have a small dataframe:

```<code>teams <- c("PHI","NYM","FLA","ATL","WSN")
wins <- c(92, 89, 94, 72, 59)
defeats <- c(70, 73, 77, 90, 102)

df <- data.frame(teams, wins, defeats)
</code>```

And I would like to know the type and class of any value inside a dataframe.

When I use the class and typeof methods and reference the variable name using the dollar sign I get same result for nleast$teams: a factor.
Why is teams a factor and not a character type?

```<code>class(nleast$teams)
# factor
typeof(nleast$teams)
# factor
</code>```

When I use just the name of the variable without a dollar sign I get character type and class for nleast$teams.

```<code>typeof(teams)
# character
 class(teams)
# "character"
</code>```

I would like to know why I get different results when I use $ or just the name of the variable?

Thank you

答:
The data.frame function for making a new variable has an argument stringsAsFactors, which by default is TRUE. This means you'll convert character type variables to factor variables by default when creating a new data frame.

To correct this, simply change the call:

```<code>df <- data.frame(teams, wins, defeats)
</code>```

to

```<code>df <- data.frame(teams, wins, defeats, stringsAsFactors=FALSE)
</code>```

Body:
I have a small dataframe:

teams <- c("PHI","NYM","FLA","ATL","WSN")
wins <- c(92, 89, 94, 72, 59)
defeats <- c(70, 73, 77, 90, 102)

df <- data.frame(teams, wins, defeats)

And I would like to know the type and class of any value inside a dataframe.

When I use the class and typeof methods and reference the variable name using the dollar sign I get same result for nleast$teams: a factor.
Why is teams a factor and not a character type?

class(nleast$teams)
# factor
typeof(nleast$teams)
# factor

When I use just the name of the variable without a dollar sign I get character type and class for nleast$teams.

typeof(teams)
# character
 class(teams)
# "character"

I would like to know why I get different results when I use $ or just the name of the variable?

Thank you

Body:
The data.frame function for making a new variable has an argument stringsAsFactors, which by default is TRUE. This means you'll convert character type variables to factor variables by default when creating a new data frame.

To correct this, simply change the call:

df <- data.frame(teams, wins, defeats)

to

df <- data.frame(teams, wins, defeats, stringsAsFactors=FALSE)


问:
Netbeans persistence.xml - definition of path for persistence unit
I have an application that connects to a Derby database using the Derby Network Server that has been started as a standalone process outside of the Netbeans IDE.

When I run my application within the IDE (I don't start the Network Server from the Services tab as it is already running) the following is observed:-

The application connects successfully to the server.

Subsequent database accesses fail with error Internal Exception: java.sql.SQLNonTransientConnectionException: The connection was refused because the database MyAppDB was not found.
Error Code: 40000

The persistence.xml in Netbeans shows the following for the JDBC connection:-
jdbc:derby://localhost:1527//Users/David/Desktop/DerbyDatabases/MyAppDB
[david on TEST]

However the xml source in Netbeans shows the following:-
jdbc:derby://localhost:1527/MyAppDB

I can fix this problem by changing the persistence.xml source (in Netbeans) to show the following for JDBC connection:-

jdbc:derby://localhost:1527//Users/David/Desktop/DerbyDatabases/MyAppDB

Everything now works and the application runs fine :-)

HOWEVER!!!

As soon as I tell Netbeans to do a Clean and Build Project, it reverts the JDBC connection back to:-

jdbc:derby://localhost:1527/MyAppDB

On running the Application it can no longer access the Db with the same error as above.

Note that none of these problems occur if I run the Network Server from with Netbeans by opening the connection via the Services tab. This is no good for me as I want to deploy the application.

Do any of you guys know what is going on here? - I'm sure it's a simple mistake on my part.

Thank you.

答: This problem was eventually solved by deleting the persistence unit (using NetBeans) and re-creating it with the same name but with the JDBC connection containing the correct path. Is this a NetBeans problem?</p>


问:
Powershell - calling unmanaged Function CreateProfile crashes Powershell.exe
When calling a unmanaged piece of code with pinvoke -- createprofile.  The Powershell.exe process crashes after the call to the method in the unmanaged code. The profile is created successfully.

Why this would happen?  My code is below:

```<code>    function CreateProfile
    {
        param([String]$UserSid, [String]$UserName,  [system.uint32]$ProfilePath)
        Add-Type -TypeDefinition '
            using System;
            using System.Runtime.InteropServices;
            public static class PInvoke {
                [DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
                public static extern int CreateProfile( [MarshalAs(UnmanagedType.LPWStr)] String pszUserSid, [MarshalAs(UnmanagedType.LPWStr)] String pszUserName, [Out][MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszProfilePath, uint cchProfilePath);
            }
        '
       $pszProfilePath = new-object -typename System.Text.StringBuilder
    [int]$results = [PInvoke]::CreateProfile($UserSid, $UserName, $pszProfilePath, $ProfilePath)
    }
$stringbuff = new-object system.text.stringbuilder(260)
[system.uint32]$a =$stringbuff.capacity
$sid = ((get-aduser -id 'brtestlocaluser').sid.value)
CreateProfile -usersid $sid -username 'brtestlocaluser' -ProfilePath $a
</code>```

答:
Finally was able to figure this out. Calling it in another means seemed to fix this issue.  </p>

```<code>function Register-NativeMethod
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$dll,

        # Param2 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [string]
        $methodSignature
    )

    $script:nativeMethods += [PSCustomObject]@{ Dll = $dll; Signature = $methodSignature; }
}
function Add-NativeMethods
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param($typeName = 'NativeMethods')

    $nativeMethodsCode = $script:nativeMethods | ForEach-Object { "
        [DllImport(`"$($_.Dll)`")]
        public static extern $($_.Signature);
    " }

    Add-Type @"
        using System;
        using System.Text;
        using System.Runtime.InteropServices;
        public static class $typeName {
            $nativeMethodsCode
        }
"@
}
function New-ProfileFromSID {

[CmdletBinding()]
[Alias()]
[OutputType([int])]
Param
(
    # Param1 help description
    [Parameter(Mandatory=$true,
               ValueFromPipelineByPropertyName=$true,
               Position=0)]
    [string]$UserName,
    [string]$domain = ''
)
$methodname = 'UserEnvCP2'
$script:nativeMethods = @();

if (-not ([System.Management.Automation.PSTypeName]$methodname).Type)
{
    Register-NativeMethod "userenv.dll" "int CreateProfile([MarshalAs(UnmanagedType.LPWStr)] string pszUserSid,`
     [MarshalAs(UnmanagedType.LPWStr)] string pszUserName,`
     [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszProfilePath, uint cchProfilePath)";

    Add-NativeMethods -typeName $methodname;
}

$sb = new-object System.Text.StringBuilder(260);
$pathLen = $sb.Capacity;

Write-Verbose "Creating user profile for $Username";
#$SID= ((get-aduser -id $UserName -ErrorAction Stop).sid.value)
if($domain)
{
    $objUser = New-Object System.Security.Principal.NTAccount($domain, $UserName)
    $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
    $SID = $strSID.Value
}
else
{
   $objUser = New-Object System.Security.Principal.NTAccount($UserName)
   $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
   $SID = $strSID.Value
}
Write-Verbose "$UserName SID: $SID"
try
{
   $result = [UserEnvCP2]::CreateProfile($SID, $Username, $sb, $pathLen)
   if($result -eq '-2147024713')
   {
       $status = "$userName already exists"
       write-verbose "$username Creation Result: $result"
    }
    elseif($result -eq '-2147024809')
    {
        $status = "$username Not Found"
        write-verbose "$username creation result: $result"
    }
   elseif($result -eq 0)
   {
       $status = "$username Profile has been created"
       write-verbose "$username Creation Result: $result"
   }
   else
   {
      $status = "$UserName unknown return result: $result"
   }
}
catch
{
    Write-Error $_.Exception.Message;
    break;
}
$status
}
</code>```

Body:
When calling a unmanaged piece of code with pinvoke -- createprofile.  The Powershell.exe process crashes after the call to the method in the unmanaged code. The profile is created successfully.

Why this would happen?  My code is below:

    function CreateProfile
    {
        param([String]$UserSid, [String]$UserName,  [system.uint32]$ProfilePath)
        Add-Type -TypeDefinition '
            using System;
            using System.Runtime.InteropServices;
            public static class PInvoke {
                [DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
                public static extern int CreateProfile( [MarshalAs(UnmanagedType.LPWStr)] String pszUserSid, [MarshalAs(UnmanagedType.LPWStr)] String pszUserName, [Out][MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszProfilePath, uint cchProfilePath);
            }
        '
       $pszProfilePath = new-object -typename System.Text.StringBuilder
    [int]$results = [PInvoke]::CreateProfile($UserSid, $UserName, $pszProfilePath, $ProfilePath)
    }
$stringbuff = new-object system.text.stringbuilder(260)
[system.uint32]$a =$stringbuff.capacity
$sid = ((get-aduser -id 'brtestlocaluser').sid.value)
CreateProfile -usersid $sid -username 'brtestlocaluser' -ProfilePath $a

Body:
Finally was able to figure this out. Calling it in another means seemed to fix this issue.

function Register-NativeMethod
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$dll,

        # Param2 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [string]
        $methodSignature
    )

    $script:nativeMethods += [PSCustomObject]@{ Dll = $dll; Signature = $methodSignature; }
}
function Add-NativeMethods
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param($typeName = 'NativeMethods')

    $nativeMethodsCode = $script:nativeMethods | ForEach-Object { "
        [DllImport(`"$($_.Dll)`")]
        public static extern $($_.Signature);
    " }

    Add-Type @"
        using System;
        using System.Text;
        using System.Runtime.InteropServices;
        public static class $typeName {
            $nativeMethodsCode
        }
"@
}
function New-ProfileFromSID {

[CmdletBinding()]
[Alias()]
[OutputType([int])]
Param
(
    # Param1 help description
    [Parameter(Mandatory=$true,
               ValueFromPipelineByPropertyName=$true,
               Position=0)]
    [string]$UserName,
    [string]$domain = ''
)
$methodname = 'UserEnvCP2'
$script:nativeMethods = @();

if (-not ([System.Management.Automation.PSTypeName]$methodname).Type)
{
    Register-NativeMethod "userenv.dll" "int CreateProfile([MarshalAs(UnmanagedType.LPWStr)] string pszUserSid,`
     [MarshalAs(UnmanagedType.LPWStr)] string pszUserName,`
     [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszProfilePath, uint cchProfilePath)";

    Add-NativeMethods -typeName $methodname;
}

$sb = new-object System.Text.StringBuilder(260);
$pathLen = $sb.Capacity;

Write-Verbose "Creating user profile for $Username";
#$SID= ((get-aduser -id $UserName -ErrorAction Stop).sid.value)
if($domain)
{
    $objUser = New-Object System.Security.Principal.NTAccount($domain, $UserName)
    $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
    $SID = $strSID.Value
}
else
{
   $objUser = New-Object System.Security.Principal.NTAccount($UserName)
   $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
   $SID = $strSID.Value
}
Write-Verbose "$UserName SID: $SID"
try
{
   $result = [UserEnvCP2]::CreateProfile($SID, $Username, $sb, $pathLen)
   if($result -eq '-2147024713')
   {
       $status = "$userName already exists"
       write-verbose "$username Creation Result: $result"
    }
    elseif($result -eq '-2147024809')
    {
        $status = "$username Not Found"
        write-verbose "$username creation result: $result"
    }
   elseif($result -eq 0)
   {
       $status = "$username Profile has been created"
       write-verbose "$username Creation Result: $result"
   }
   else
   {
      $status = "$UserName unknown return result: $result"
   }
}
catch
{
    Write-Error $_.Exception.Message;
    break;
}
$status
}


问:
How does message attachments work in Outlook REST API
this is what i'm trying to accomplish:

First i'm using the beta version of the API.

So i'm using
/api/beta/me/messages/{message_id}/replyall
and
/api/beta/me/messages/{message_id}/forward
endpoints.
The Comment of the reply/forward message is not set.
A new message is sent in the request.
This message contains the exact attachments i want for the message to have. And the message body contains the whole message text (we construct our own message history).

The result from this request is that the created reply/forward message contains the attachments that i have send AND the attachments that are part of the message i reply to/forward.

Under attachments i mean both inline files and attached files.

The message body is constructed correctly.

I also tried creating a draft and then updating the attachments for this draft using:
PATCH /api/v2.0/me/messages/{message_id}
for which in the documentation is said that i can specify "one or more writable message properties in the request body", but for some reason it does not work with message attachments. But i guess even if it does work with attachments, it will just add the attachments that i send and won't delete the old ones.

So is there some parameter that i can set, so i can accomplish this behavior?

I tried to make a request to https://outlook.office.com/api/beta/me/messages/{message_id}/createreply
and then delete the unwanted attachments from the returned draft message. The problem here is that this endpoint doesn't return the attachments. I also tried adding the $expand=attachments query, but still no attachments returned.

答: I had the same issue with attachments when forward/reply/replyAll and I figured the best way of doing this, is to construct your new message with all the attachments that you want (like the way you are doing it) and then simply use the send api call, i.e., 'https://outlook.office365.com/api/v2.0/me/sendmail' with your new message. I hope it works for you!</p>


答:
```<code>$box = array(
    "Small box" => array("length" => 12, "width" => 10, "depth" => 2.5),
    "Medium box" => array("length" => 30, "width" => 20, "depth" => 4),
    "Large box" => array("length" => 60, "width" => 40, "depth" => 11.5)
);

foreach ($box as $key => $boxes) {
    $volume = array_product($boxes);
    echo "The volume of the $key is: $volume\n";
}
</code>```

Title: Array multiplying the answer and returning it


问:
AngularJS Promise Resolved but cannot reach data
```<code>var promise = GetQuestions.quote.get();
console.log(promise);
promise.$promise.then(function(quote) {
  $scope.quotes = quote;
  console.log($scope.quotes);
  for( quote in $scope.quotes){
     console.log(quote.cite);
  }
});
</code>```

factory

```<code>.factory('GetQuestions', ['$resource', function($resource){
   return {
      quote: $resource('**Resource Link**', {}, { get: { method: 'GET', isArray: true }})
   };
}])
</code>```

Here is console.log(promise):

```<code>[$promise: Promise, $resolved: false]
</code>```

Here is console.log($scope.quotes):

And console.log(quote.cite) logs undefined

The Issue:

My issue is that I can't access the "cites", the promise is supposedly resolved however I can't seem to access the data correctly. I have tried doing promise.then() (instead of promise.$promise.then()), however I get an error telling me promise.then() is not a function. I am not sure why this is. Any help?

答:
Instead of the  for var in list syntax, try

```<code>$scope.quotes.forEach(function(quote) {
    console.log(quote.cite);
});
</code>```

The for var in list should not be used to iterate over arrays. It's intended purpose is to iterate over object properties. When you use it to iterate over an array, you will often get weird behavior.

See this SO question.

Body:
var promise = GetQuestions.quote.get();
console.log(promise);
promise.$promise.then(function(quote) {
  $scope.quotes = quote;
  console.log($scope.quotes);
  for( quote in $scope.quotes){
     console.log(quote.cite);
  }
});

factory

.factory('GetQuestions', ['$resource', function($resource){
   return {
      quote: $resource('**Resource Link**', {}, { get: { method: 'GET', isArray: true }})
   };
}])

Here is console.log(promise):

[$promise: Promise, $resolved: false]

Here is console.log($scope.quotes):

And console.log(quote.cite) logs undefined

The Issue:

My issue is that I can't access the "cites", the promise is supposedly resolved however I can't seem to access the data correctly. I have tried doing promise.then() (instead of promise.$promise.then()), however I get an error telling me promise.then() is not a function. I am not sure why this is. Any help?

Body:
Instead of the  for var in list syntax, try

$scope.quotes.forEach(function(quote) {
    console.log(quote.cite);
});

The for var in list should not be used to iterate over arrays. It's intended purpose is to iterate over object properties. When you use it to iterate over an array, you will often get weird behavior.

See this SO question.


问:
Specflow Contextual Assertions
We use Specflow and currently, most of our assertions are done using Fluent Assertions, ie look something like:

myval.Should().NotBe(null)

All is working well, however there are some cases in which we want the same code to sometimes Assert Inconclusive, and sometimes not.

For example, let us assume we have a step which calls a method to install the AUT.

The test which asserts that the AUT can be installed correctly will use this method as part of a WHEN/THEN step.

In this instance, if installation fails, we want to proceed as normal and fail the test.

GIVEN The AUT is NOT installed
WHEN I install the AUT

However, for all other tests, the same method may be called as part of a GIVEN step or as part of a BeforeScenario / BeforeFeature hook, and in that instance, if the installation fails, the test should be failed as inconclusive, because it was not the test itself that failed, but the Setup stage.

GIVEN the AUT is installed
WHEN I perform function X of the AUT

So in this example, let us assume that the step definitions for WHEN I install the AUT in the first test, and GIVEN the AUT is installed in the second test simply call a helper method with something like AppFacade.Install()

Of course we can litter AppFacade.Install() and all our other helper methods with conditionals etc, but I was wondering if anyone out there has a more elegant solution - ie way to extend an assertion engine so that it automatically applies this logic - I see no barriers on the Specflow side to achieving this insofar as you can examine the Specflow context objects to detect what kind of step you are on.

Ideally we would like to stick with Fluent Assertions, but if this overly complicates things, we would be willing to reconsider.

答:
Not sure if this will help but you can inherit the TechTalk.SpecFlow.Steps class on your steps class like so;

```<code>public sealed class MyFeatureSteps : Steps
</code>```

What does this allow you to do? Well you can do something like this;

```<code>[Given(@"Everything is installed")]
public void GivenEverythingIsInstalled()
{
  // Perform Installation with no assertion
  // You can use this step just to do the setup
  // No assertions literally just perform all the actions required to install
}

[Then(@"its all installed correctly")]
public void ThenItsAllInstalledCorrectly()
{
  // Because you have inherited the TechTalk.SpecFlow.Steps class
  Given("Everything is installed");
  Assert.IsTrue(CorrectInstallCheckMehtod(), "It should have installed");
}
</code>```

Basically you can make steps as granular as you want now and just put assertions where you need them, and you can reference other steps within each other.

Take note while you can reference a GIVEN step within a WHEN (or THEN) step, if the last thing you do within the step is call another and it is different to its parent I.e a WHEN step references a GIVEN step if you try to use an AND in your feature file its going to be a GIVEN AND. I hope that makes sense

I hope this will help you. I think you should avoid not failing tests even if that's not what you are specifically testing because it still highlights some broken functionality. Alternatively put an assert after the install that checks its installed this will cause the test to fail before it even starts, again this really is not a bad thing.

Title: Specflow Contextual Assertions

Body:
Not sure if this will help but you can inherit the TechTalk.SpecFlow.Steps class on your steps class like so;

public sealed class MyFeatureSteps : Steps

What does this allow you to do? Well you can do something like this;

[Given(@"Everything is installed")]
public void GivenEverythingIsInstalled()
{
  // Perform Installation with no assertion
  // You can use this step just to do the setup
  // No assertions literally just perform all the actions required to install
}

[Then(@"its all installed correctly")]
public void ThenItsAllInstalledCorrectly()
{
  // Because you have inherited the TechTalk.SpecFlow.Steps class
  Given("Everything is installed");
  Assert.IsTrue(CorrectInstallCheckMehtod(), "It should have installed");
}

Basically you can make steps as granular as you want now and just put assertions where you need them, and you can reference other steps within each other.

Take note while you can reference a GIVEN step within a WHEN (or THEN) step, if the last thing you do within the step is call another and it is different to its parent I.e a WHEN step references a GIVEN step if you try to use an AND in your feature file its going to be a GIVEN AND. I hope that makes sense

I hope this will help you. I think you should avoid not failing tests even if that's not what you are specifically testing because it still highlights some broken functionality. Alternatively put an assert after the install that checks its installed this will cause the test to fail before it even starts, again this really is not a bad thing.


问:
Scheme Language - Background running application - Error Analysis after crash
Do I have any chance to get a stack backtrace or similar
of a running scheme background process. Or to dump an Image
on any exception or error of the running system which I can
examine later ?

EDITED
to be more precise
On Unix I have been running a web application (started in background from shell via &). Now I want to get some debuggable stuff in case of any error. for example stack backtrace, Image Dump (core dump), or such.

this probably is easy to get in Common Lisp, Java or Smalltalk, but I don't have any clue how to achieve this with Scheme.

thanks for any suggestions

答:
I answer my own question here.

I have found a portable Debugger for Scheme Language:

seems a bit dated
http://www.cs.cmu.edu/Groups/AI/lang/scheme/code/debug/psd/

seems to be more recent:
https://bitbucket.org/certainty/psd

PSD is instrumenting the original source program, so this should be an attractive DIY solution.


问:
Reading specific column from file when last few rows are not equivalent in python
I have a problem during the reading of a text file in python. Basically what I need is to get the 4th column in a list.

With this small function I achieve it without any great issues:

```<code>def load_file(filename):

    f = open(filename, 'r')

   # skip the first useless row
   line = list(f.readlines()[1:])

   total_sp = []

    for i in line:
        t = i.strip().split()
        total_sp.append(int(t[4]))

    return total_sp
</code>```

but now I have to manage files, that in the last row(s) have any random number that don't respect the text format. An example of the not working text file is:

```<code>#generated file
well10_1         3        18         6         1         2  -0.01158   0.01842       142
well5_1         1        14         6         1         2  0.009474   0.01842       141
well4_1         1        13         4         1         2  -0.01842  -0.03737       125
well7_1         3        10         1         1         2 -0.002632  0.009005       101
well3_1         1        10         9         1         2  -0.03579  -0.06368       157
well8_1         3        10        10         1         2  -0.06895   -0.1021       158
well9_1         3        10        18         1         2   0.03053   0.02158       176
well2_1         1         4         4         1         2  -0.03737  -0.03737       128
well6_1         3         4         5         1         2  -0.07053   -0.1421       127
well1_1        -2         3         1         1         2  0.006663  -0.02415       128
         1    0.9259
         2   0.07407
</code>```

where 1    0.9259 and 2   0.07407 have to be dumped.

In fact, using the function of above with this text file, I get the following error because of the 2 additional last rows:

```<code>Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/tmp/tmpqi8Ktw.py", line 21, in load_obh
    total_sp.append(int(t[4]))
IndexError: list index out of range
</code>```

How can I get rid of the last lines in the line variable?

Thanks to all

答:
Also there is a "your case-specific" solution:</p>

```<code>for i in line:
    if not i.startswith(' '):
        t = i.strip().split()
        total_sp.append(int(t[4]))
</code>```

Body:
I have a problem during the reading of a text file in python. Basically what I need is to get the 4th column in a list.

With this small function I achieve it without any great issues:

def load_file(filename):

    f = open(filename, 'r')

   # skip the first useless row
   line = list(f.readlines()[1:])

   total_sp = []

    for i in line:
        t = i.strip().split()
        total_sp.append(int(t[4]))

    return total_sp

but now I have to manage files, that in the last row(s) have any random number that don't respect the text format. An example of the not working text file is:

#generated file
well10_1         3        18         6         1         2  -0.01158   0.01842       142
well5_1         1        14         6         1         2  0.009474   0.01842       141
well4_1         1        13         4         1         2  -0.01842  -0.03737       125
well7_1         3        10         1         1         2 -0.002632  0.009005       101
well3_1         1        10         9         1         2  -0.03579  -0.06368       157
well8_1         3        10        10         1         2  -0.06895   -0.1021       158
well9_1         3        10        18         1         2   0.03053   0.02158       176
well2_1         1         4         4         1         2  -0.03737  -0.03737       128
well6_1         3         4         5         1         2  -0.07053   -0.1421       127
well1_1        -2         3         1         1         2  0.006663  -0.02415       128
         1    0.9259
         2   0.07407

where 1    0.9259 and 2   0.07407 have to be dumped.

In fact, using the function of above with this text file, I get the following error because of the 2 additional last rows:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/tmp/tmpqi8Ktw.py", line 21, in load_obh
    total_sp.append(int(t[4]))
IndexError: list index out of range

How can I get rid of the last lines in the line variable?

Thanks to all

Body:
Also there is a "your case-specific" solution:

for i in line:
    if not i.startswith(' '):
        t = i.strip().split()
        total_sp.append(int(t[4]))