问:
Heterogeneous initializer list
I have a QueryField and Select helper classes used to construct SQL statements:

```<code>class QueryField
{
public:
    QueryField(std::string_view column)
        : m_column{ column }
    {
    }
    QueryField(std::string_view column, std::string_view alias)
        : m_column{ column }
        , m_alias{ alias }
    {
    }

private:
    std::string m_column;
    std::string m_alias;
};

class Select
{
public:

    Select(std::initializer_list<QueryField> fields)
    {
        for (auto & field : fields)
        {
            m_fields.emplace_back(std::move(field));
        }
    }

private:

    std::vector<QueryField> m_fields;
};
</code>```

as seen from the code above Select is a collection of QueryField objects that can initialized like this:

```<code>Select{ QueryField{ "up.audit_option" "option" }, QueryField("uep.success"), QueryField("uep.failure") };
</code>```

is it possible to eliminate the need of specifying QueryField explicitly and initialize Select object as follows?

```<code>Select{ { "up.audit_option" "option" }, "uep.success", "uep.failure" };
</code>```

答:
With your solution, you can indeed drop the types, but you have to keep the braces:

```<code>Select{ { "up.audit_option" "option" }, {"uep.success"}, {"uep.failure"} }
</code>```

Also be careful with initialized list: all the elements inside will be copied. Even if you move:

```<code>Select(std::initializer_list<QueryField> fields)
{
    for (auto & field : fields)
    {
        // Actually copy. No move is done.
        m_fields.emplace_back(std::move(field));
    }
}
</code>```

No move is allowed since every elements in the initializer list are constant.

My preferred solution would be to drop std::initializer_list and be simple with simple case and more explicit with complex cases.

To allow true heterogenous parameters, I'll go with variadic templates:

```<code>template<typename... Args>
Select(Args&&... fields) :
    m_fields{QueryField{std::forward<Args>(args)}...} {}
</code>```

If you want to keep the copy/move constructor, you must filter out some parameter types:

```<code>template<typename T, typename = void typename... Args>
struct is_not_copy_impl : std::false_type {};

template<typename T, typename Arg>
struct is_not_copy_impl<T, std::enable_if_t<std::is_base_of_v<T, std::decay_t<Arg>>>, Arg> : std::true_type {};

template<typename T, typename... Args>
using is_not_copy = is_not_copy_impl<T, void, Args...>;

template<typename... Args, std::enable_if_t<!is_not_copy<Select, Args...>::value>* = nullptr>
Select(Args&&... fields) :
    m_fields{QueryField{std::forward<Args>(args)}...} {}
</code>```

This code will move when a QueryField is passed, and construct a new one when a value of other type is passed.

The usage is this:

```<code>Select{
    QueryField{"up.audit_option" "option"},
    "uep.success",
    "uep.failure"
};
</code>```

Title: Heterogeneous initializer list

Body:
I have a QueryField and Select helper classes used to construct SQL statements:

class QueryField
{
public:
    QueryField(std::string_view column)
        : m_column{ column }
    {
    }
    QueryField(std::string_view column, std::string_view alias)
        : m_column{ column }
        , m_alias{ alias }
    {
    }

private:
    std::string m_column;
    std::string m_alias;
};

class Select
{
public:

    Select(std::initializer_list<QueryField> fields)
    {
        for (auto & field : fields)
        {
            m_fields.emplace_back(std::move(field));
        }
    }

private:

    std::vector<QueryField> m_fields;
};

as seen from the code above Select is a collection of QueryField objects that can initialized like this:

Select{ QueryField{ "up.audit_option" "option" }, QueryField("uep.success"), QueryField("uep.failure") };

is it possible to eliminate the need of specifying QueryField explicitly and initialize Select object as follows?

Select{ { "up.audit_option" "option" }, "uep.success", "uep.failure" };

Body:
With your solution, you can indeed drop the types, but you have to keep the braces:

Select{ { "up.audit_option" "option" }, {"uep.success"}, {"uep.failure"} }

Also be careful with initialized list: all the elements inside will be copied. Even if you move:

Select(std::initializer_list<QueryField> fields)
{
    for (auto & field : fields)
    {
        // Actually copy. No move is done.
        m_fields.emplace_back(std::move(field));
    }
}

No move is allowed since every elements in the initializer list are constant.

My preferred solution would be to drop std::initializer_list and be simple with simple case and more explicit with complex cases.

To allow true heterogenous parameters, I'll go with variadic templates:

template<typename... Args>
Select(Args&&... fields) :
    m_fields{QueryField{std::forward<Args>(args)}...} {}

If you want to keep the copy/move constructor, you must filter out some parameter types:

template<typename T, typename = void typename... Args>
struct is_not_copy_impl : std::false_type {};

template<typename T, typename Arg>
struct is_not_copy_impl<T, std::enable_if_t<std::is_base_of_v<T, std::decay_t<Arg>>>, Arg> : std::true_type {};

template<typename T, typename... Args>
using is_not_copy = is_not_copy_impl<T, void, Args...>;

template<typename... Args, std::enable_if_t<!is_not_copy<Select, Args...>::value>* = nullptr>
Select(Args&&... fields) :
    m_fields{QueryField{std::forward<Args>(args)}...} {}

This code will move when a QueryField is passed, and construct a new one when a value of other type is passed.

The usage is this:

Select{
    QueryField{"up.audit_option" "option"},
    "uep.success",
    "uep.failure"
};


来源: stackexchange

问:
abort trap - something is wrong with my code
I am developing linked list in C++. I have issue while using delete.

I read number of elements from program arguments. I can create them. I can list them. When I use delete, code doesn't work.

Do I have to use delete at all?

```<code>#include <iostream>
#include <sstream>

struct element {
  int value;
  element *next;
};

int main(int argc, char **argv) {

  int num;
  std::stringstream ss;

  if (argc >= 2) {
    std::cout << argv[0] << std::endl;
    ss << argv[1];
    ss >> num;
    std::cout << "You want: " << num << " numbers" << std::endl;
  } else {
    std::cout << "Error" << std::endl;
  }

  element *first = NULL;
  element *current = NULL;

  // creating
  for(int i=0; i<num; i++) {
    element *elem = new element();
    if( first == NULL ) {
      first = elem;
    }

    elem -> value = i;
    elem -> next = NULL;

    if( current == NULL ) {
      current = elem;
    } else {
      current -> next = elem;
      current = elem;
    }
  }

  // printing
  current = first;
  while( current ) {
    std::cout << "value: " << current -> value << std::endl;
    current = current -> next;
  }

  // removing
  current = first;
  while( current ) {
    delete current;
    current = current -> next;
  }

  delete first;

}
</code>```

What I want is to print all elements. I know that each new should be accompanied by delete, but something is wrong in my code.

答:
I have fixed my code based on @Yksisarvinen comment. It works now. Thanks!</p>

```<code>#include <iostream>
#include <sstream>

struct element {
  int value;
  element *next;
};

int main(int argc, char **argv) {

  int num;
  std::stringstream ss;

  if (argc >= 2) {
    std::cout << argv[0] << std::endl;
    ss << argv[1];
    ss >> num;
    std::cout << "You want: " << num << " numbers" << std::endl;
  } else {
    std::cout << "Error" << std::endl;
  }

  element *first = NULL;
  element *current = NULL;

  // creating
  for(int i=0; i<num; i++) {
    element *elem = new element();
    elem -> value = i;
    elem -> next = NULL;

    if( current == NULL ) {
      first = elem;
      current = elem;
    } else {
      current -> next = elem;
      current = elem;
    }
  }

  // printing
  current = first;
  while( current ) {
    std::cout << "value: " << current -> value << std::endl;
    current = current -> next;
  }

  // removing
  current = first;
  while( current ) {
    element *to_remove = current;
    current = current -> next;
    delete to_remove;
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am developing linked list in C++. I have issue while using delete.

I read number of elements from program arguments. I can create them. I can list them. When I use delete, code doesn't work.

Do I have to use delete at all?

#include <iostream>
#include <sstream>

struct element {
  int value;
  element *next;
};

int main(int argc, char **argv) {

  int num;
  std::stringstream ss;

  if (argc >= 2) {
    std::cout << argv[0] << std::endl;
    ss << argv[1];
    ss >> num;
    std::cout << "You want: " << num << " numbers" << std::endl;
  } else {
    std::cout << "Error" << std::endl;
  }

  element *first = NULL;
  element *current = NULL;

  // creating
  for(int i=0; i<num; i++) {
    element *elem = new element();
    if( first == NULL ) {
      first = elem;
    }

    elem -> value = i;
    elem -> next = NULL;

    if( current == NULL ) {
      current = elem;
    } else {
      current -> next = elem;
      current = elem;
    }
  }

  // printing
  current = first;
  while( current ) {
    std::cout << "value: " << current -> value << std::endl;
    current = current -> next;
  }

  // removing
  current = first;
  while( current ) {
    delete current;
    current = current -> next;
  }

  delete first;

}

What I want is to print all elements. I know that each new should be accompanied by delete, but something is wrong in my code.

Body:
I have fixed my code based on @Yksisarvinen comment. It works now. Thanks!

#include <iostream>
#include <sstream>

struct element {
  int value;
  element *next;
};

int main(int argc, char **argv) {

  int num;
  std::stringstream ss;

  if (argc >= 2) {
    std::cout << argv[0] << std::endl;
    ss << argv[1];
    ss >> num;
    std::cout << "You want: " << num << " numbers" << std::endl;
  } else {
    std::cout << "Error" << std::endl;
  }

  element *first = NULL;
  element *current = NULL;

  // creating
  for(int i=0; i<num; i++) {
    element *elem = new element();
    elem -> value = i;
    elem -> next = NULL;

    if( current == NULL ) {
      first = elem;
      current = elem;
    } else {
      current -> next = elem;
      current = elem;
    }
  }

  // printing
  current = first;
  while( current ) {
    std::cout << "value: " << current -> value << std::endl;
    current = current -> next;
  }

  // removing
  current = first;
  while( current ) {
    element *to_remove = current;
    current = current -> next;
    delete to_remove;
  }
}


问:
Aggregate values based on multiple dimension members to create a Profit & Loss report via SCOPE statement
I am relatively new to SSAS MDX and am facing the problem to create aggregates over all measures of different dimension members.
The following picture best describes what I'm trying to achieve:
Problem and What the solution should be

This is a draft and a simplification of a more complex scenario, so don't bother ;-).
After running a series of experiments I figured out to use a simple dimension without connection to other dimensions to be able to use the SCOPE statement to override the produced results in the report.
The simple dimension "Kurz PuL" contains the preceding members (Umsatz .. Periodenergebnis) and shall produce the Profits + Loss report.

Kurz PuL Dimension

What currently works is to show results of single members (like Umsatz, Wareneinsatz, SbA, Personal).
But I am not able to aggregate values of more than one member to obtain an aggregate, e.g.: of Umsatz + Wareneinsatz = Rohertrag. I tried different approaches but none worked.
See the following SCOPE statements which are used to "override" the resulting values that are displayed in Excel (first image ^^):

SCOPE Statements:

```<code>    /*
The CALCULATE command controls the aggregation of leaf cells in the cube.
If the CALCULATE command is deleted or modified, the data within the cube is affected.
You should edit this command only if you manually specify how the cube is aggregated.
*/
CALCULATE;

SCOPE ([Kurz PuL].[Calculated].[Umsatz]);
    THIS = AGGREGATE([EinfacheBwaZeile].[Hierarchy].&[U]);
END SCOPE;

SCOPE ([Kurz PuL].[Calculated].[Wareneinsatz]);
    THIS = AGGREGATE([EinfacheBwaZeile].[Hierarchy].&[W]);
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[Rohertrag]);
    THIS = AGGREGATE(FILTER([EinfacheBwaZeile].[Hierarchy].CurrentMember, { [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W] }));
END SCOPE;

SCOPE ([Kurz PuL].[Calculated].[Personal]);
    THIS = AGGREGATE( { [EinfacheBwaZeile].[Hierarchy].&[P] });
END SCOPE;

SCOPE ([Kurz PuL].[Calculated].[Marketing]);
    THIS = AGGREGATE( { [EinfacheBwaZeile].[Hierarchy].&[M] });
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[Deckungsbeitrag]);
    THIS = AGGREGATE( {   [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W], [EinfacheBwaZeile].[Hierarchy].&[R], [EinfacheBwaZeile].[Hierarchy].&[P]
                        , [EinfacheBwaZeile].[Hierarchy].&[M], [EinfacheBwaZeile].[Hierarchy].&[D] });
END SCOPE;

SCOPE ([Kurz PuL].[Calculated].[SbA]);
    THIS = AGGREGATE( { [EinfacheBwaZeile].[Hierarchy].&[S] });
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[EBITDA]);
    THIS = AGGREGATE( {   [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W], [EinfacheBwaZeile].[Hierarchy].&[R], [EinfacheBwaZeile].[Hierarchy].&[P]
                        , [EinfacheBwaZeile].[Hierarchy].&[M], [EinfacheBwaZeile].[Hierarchy].&[D]
                        , [EinfacheBwaZeile].[Hierarchy].&[S], [EinfacheBwaZeile].[Hierarchy].&[A] });
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[EBIT]);
    THIS = AGGREGATE( {   [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W], [EinfacheBwaZeile].[Hierarchy].&[R], [EinfacheBwaZeile].[Hierarchy].&[P]
                        , [EinfacheBwaZeile].[Hierarchy].&[M], [EinfacheBwaZeile].[Hierarchy].&[D]
                        , [EinfacheBwaZeile].[Hierarchy].&[S], [EinfacheBwaZeile].[Hierarchy].&[A]
                        , [EinfacheBwaZeile].[Hierarchy].&[I] });
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[EBT]);
    THIS = AGGREGATE( {   [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W], [EinfacheBwaZeile].[Hierarchy].&[R], [EinfacheBwaZeile].[Hierarchy].&[P]
                        , [EinfacheBwaZeile].[Hierarchy].&[M], [EinfacheBwaZeile].[Hierarchy].&[D]
                        , [EinfacheBwaZeile].[Hierarchy].&[S], [EinfacheBwaZeile].[Hierarchy].&[A]
                        , [EinfacheBwaZeile].[Hierarchy].&[I]
                        , [EinfacheBwaZeile].[Hierarchy].&[T] });
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[Periodenergebnis]);
    THIS = AGGREGATE( {   [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W], [EinfacheBwaZeile].[Hierarchy].&[R], [EinfacheBwaZeile].[Hierarchy].&[P]
                        , [EinfacheBwaZeile].[Hierarchy].&[M], [EinfacheBwaZeile].[Hierarchy].&[D]
                        , [EinfacheBwaZeile].[Hierarchy].&[S], [EinfacheBwaZeile].[Hierarchy].&[A]
                        , [EinfacheBwaZeile].[Hierarchy].&[I]
                        , [EinfacheBwaZeile].[Hierarchy].&[T]
                        , [EinfacheBwaZeile].[Hierarchy].&[E] });
END SCOPE;
</code>```

I've been trying to find a resource that explains how to aggregate on more than one member but didn't find a solution.
How can I use the AGGREGATE() function to combine/sum values that are related to multiple dimension members of [EinfacheBwaZeile].[Hierarchy].A, … .B, … .C ?

I really appreciate your answers!
Thanks in advance,
Cordt

-- UPDATE 2019-05-28 as reply to Moaz as of 2019-05-27: --
Hi Moaz,
thank you for your suggestion.
Sadly, that solution does not meet my needs.
First thing to notice is, that I need a SCOPE-Statement, not a SELECT-MDX.
Second, I need all the measures of specific members of another dimension to be "summarized". That looks at first sight like a "running total" but it depends on the values of "previous" members where some may be skipped.
In words of the Adventure Works sample, the following shows what I need:

```<code>SCOPE (MountainBikeSales);
    THIS = AGGREGATE(Product.&[Bikes]);
END SCOPE;
SCOPE (BikesAndAccessories);
    THIS = AGGREGATE({ Product.&[Bikes], Product.&[Accessories] });
END SCOPE;
SCOPE (BikesAccsClothing);
    THIS = AGGREGATE({ Product.&[Bikes], Product.&[Accessories], Product.&[Clothing] });
END SCOPE;
</code>```

Is that more clear?
You could even think of a SCOPE that skips Accessories by summarizing Bikes and Clothing instead of Accessories.
Problem to me is, that the first statement would succeed (that summarizes a single member) but the others won't.

Thank you for your advice!
Cordt

答:
I am not sure that i understand your problem exactly. But I think you want to know how to calculate running totals. It that is the case take a look at the below example

```<code>with
member
[Measures].[Internet Sales AmountRunningtotal]
as
case when [Measures].[Internet Sales Amount] = null then null
else
sum({[Product].[Subcategory].firstchild:[Product].[Subcategory].currentmember},[Measures].[Internet Sales Amount])
end
select {[Measures].[Internet Sales Amount],
[Measures].[Internet Sales AmountRunningtotal]
} on columns,

non empty
([Date].[Calendar Year].[Calendar Year],[Date].[Calendar Quarter of Year].[Calendar Quarter of Year],
[Product].[Category].[Category],[Product].[Subcategory].[Subcategory])
on
rows
from
[Adventure Works]
</code>```

Result

Edit:Based on your edit

```<code>select
{
[Measures].[Internet Sales Amount],
[Measures].[Internet Order Quantity],
[Measures].[Internet Tax Amount],
[Measures].[Internet Gross Profit Margin]
}on 0 ,
[Product].[Category].[Category]
on 1
from
[Adventure Works]
</code>```

Results

Notice that all measures for Components have null values. Now Lets equate Components with Bikes & Accessories

```<code>Scope  ([Product].[Category].&[2]) ;
this = (aggregate({[Product].[Category].&[1],[Product].[Category].&[4]},[Measures].[Measures].currentmember));
end scope;

select
{
[Measures].[Internet Sales Amount],
[Measures].[Internet Order Quantity],
[Measures].[Internet Tax Amount],
[Measures].[Internet Gross Profit Margin]
}on 0 ,
[Product].[Category].[Category]
on 1
from
[Adventure Works]
</code>```

Results

Body:
I am relatively new to SSAS MDX and am facing the problem to create aggregates over all measures of different dimension members.
The following picture best describes what I'm trying to achieve:
Problem and What the solution should be

This is a draft and a simplification of a more complex scenario, so don't bother ;-).
After running a series of experiments I figured out to use a simple dimension without connection to other dimensions to be able to use the SCOPE statement to override the produced results in the report.
The simple dimension "Kurz PuL" contains the preceding members (Umsatz .. Periodenergebnis) and shall produce the Profits + Loss report.

Kurz PuL Dimension

What currently works is to show results of single members (like Umsatz, Wareneinsatz, SbA, Personal).
But I am not able to aggregate values of more than one member to obtain an aggregate, e.g.: of Umsatz + Wareneinsatz = Rohertrag. I tried different approaches but none worked.
See the following SCOPE statements which are used to "override" the resulting values that are displayed in Excel (first image ^^):

SCOPE Statements:

    /*
The CALCULATE command controls the aggregation of leaf cells in the cube.
If the CALCULATE command is deleted or modified, the data within the cube is affected.
You should edit this command only if you manually specify how the cube is aggregated.
*/
CALCULATE;

SCOPE ([Kurz PuL].[Calculated].[Umsatz]);
    THIS = AGGREGATE([EinfacheBwaZeile].[Hierarchy].&[U]);
END SCOPE;

SCOPE ([Kurz PuL].[Calculated].[Wareneinsatz]);
    THIS = AGGREGATE([EinfacheBwaZeile].[Hierarchy].&[W]);
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[Rohertrag]);
    THIS = AGGREGATE(FILTER([EinfacheBwaZeile].[Hierarchy].CurrentMember, { [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W] }));
END SCOPE;

SCOPE ([Kurz PuL].[Calculated].[Personal]);
    THIS = AGGREGATE( { [EinfacheBwaZeile].[Hierarchy].&[P] });
END SCOPE;

SCOPE ([Kurz PuL].[Calculated].[Marketing]);
    THIS = AGGREGATE( { [EinfacheBwaZeile].[Hierarchy].&[M] });
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[Deckungsbeitrag]);
    THIS = AGGREGATE( {   [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W], [EinfacheBwaZeile].[Hierarchy].&[R], [EinfacheBwaZeile].[Hierarchy].&[P]
                        , [EinfacheBwaZeile].[Hierarchy].&[M], [EinfacheBwaZeile].[Hierarchy].&[D] });
END SCOPE;

SCOPE ([Kurz PuL].[Calculated].[SbA]);
    THIS = AGGREGATE( { [EinfacheBwaZeile].[Hierarchy].&[S] });
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[EBITDA]);
    THIS = AGGREGATE( {   [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W], [EinfacheBwaZeile].[Hierarchy].&[R], [EinfacheBwaZeile].[Hierarchy].&[P]
                        , [EinfacheBwaZeile].[Hierarchy].&[M], [EinfacheBwaZeile].[Hierarchy].&[D]
                        , [EinfacheBwaZeile].[Hierarchy].&[S], [EinfacheBwaZeile].[Hierarchy].&[A] });
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[EBIT]);
    THIS = AGGREGATE( {   [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W], [EinfacheBwaZeile].[Hierarchy].&[R], [EinfacheBwaZeile].[Hierarchy].&[P]
                        , [EinfacheBwaZeile].[Hierarchy].&[M], [EinfacheBwaZeile].[Hierarchy].&[D]
                        , [EinfacheBwaZeile].[Hierarchy].&[S], [EinfacheBwaZeile].[Hierarchy].&[A]
                        , [EinfacheBwaZeile].[Hierarchy].&[I] });
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[EBT]);
    THIS = AGGREGATE( {   [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W], [EinfacheBwaZeile].[Hierarchy].&[R], [EinfacheBwaZeile].[Hierarchy].&[P]
                        , [EinfacheBwaZeile].[Hierarchy].&[M], [EinfacheBwaZeile].[Hierarchy].&[D]
                        , [EinfacheBwaZeile].[Hierarchy].&[S], [EinfacheBwaZeile].[Hierarchy].&[A]
                        , [EinfacheBwaZeile].[Hierarchy].&[I]
                        , [EinfacheBwaZeile].[Hierarchy].&[T] });
END SCOPE;

/* DOES NOT WORK: */
SCOPE ([Kurz PuL].[Calculated].[Periodenergebnis]);
    THIS = AGGREGATE( {   [EinfacheBwaZeile].[Hierarchy].&[U], [EinfacheBwaZeile].[Hierarchy].&[W], [EinfacheBwaZeile].[Hierarchy].&[R], [EinfacheBwaZeile].[Hierarchy].&[P]
                        , [EinfacheBwaZeile].[Hierarchy].&[M], [EinfacheBwaZeile].[Hierarchy].&[D]
                        , [EinfacheBwaZeile].[Hierarchy].&[S], [EinfacheBwaZeile].[Hierarchy].&[A]
                        , [EinfacheBwaZeile].[Hierarchy].&[I]
                        , [EinfacheBwaZeile].[Hierarchy].&[T]
                        , [EinfacheBwaZeile].[Hierarchy].&[E] });
END SCOPE;

I've been trying to find a resource that explains how to aggregate on more than one member but didn't find a solution.
How can I use the AGGREGATE() function to combine/sum values that are related to multiple dimension members of [EinfacheBwaZeile].[Hierarchy].A, … .B, … .C ?

I really appreciate your answers!
Thanks in advance,
Cordt

-- UPDATE 2019-05-28 as reply to Moaz as of 2019-05-27: --
Hi Moaz,
thank you for your suggestion.
Sadly, that solution does not meet my needs.
First thing to notice is, that I need a SCOPE-Statement, not a SELECT-MDX.
Second, I need all the measures of specific members of another dimension to be "summarized". That looks at first sight like a "running total" but it depends on the values of "previous" members where some may be skipped.
In words of the Adventure Works sample, the following shows what I need:

SCOPE (MountainBikeSales);
    THIS = AGGREGATE(Product.&[Bikes]);
END SCOPE;
SCOPE (BikesAndAccessories);
    THIS = AGGREGATE({ Product.&[Bikes], Product.&[Accessories] });
END SCOPE;
SCOPE (BikesAccsClothing);
    THIS = AGGREGATE({ Product.&[Bikes], Product.&[Accessories], Product.&[Clothing] });
END SCOPE;

Is that more clear?
You could even think of a SCOPE that skips Accessories by summarizing Bikes and Clothing instead of Accessories.
Problem to me is, that the first statement would succeed (that summarizes a single member) but the others won't.

Thank you for your advice!
Cordt

Body:
I am not sure that i understand your problem exactly. But I think you want to know how to calculate running totals. It that is the case take a look at the below example

with
member
[Measures].[Internet Sales AmountRunningtotal]
as
case when [Measures].[Internet Sales Amount] = null then null
else
sum({[Product].[Subcategory].firstchild:[Product].[Subcategory].currentmember},[Measures].[Internet Sales Amount])
end
select {[Measures].[Internet Sales Amount],
[Measures].[Internet Sales AmountRunningtotal]
} on columns,

non empty
([Date].[Calendar Year].[Calendar Year],[Date].[Calendar Quarter of Year].[Calendar Quarter of Year],
[Product].[Category].[Category],[Product].[Subcategory].[Subcategory])
on
rows
from
[Adventure Works]

Result

Edit:Based on your edit

select
{
[Measures].[Internet Sales Amount],
[Measures].[Internet Order Quantity],
[Measures].[Internet Tax Amount],
[Measures].[Internet Gross Profit Margin]
}on 0 ,
[Product].[Category].[Category]
on 1
from
[Adventure Works]

Results

Notice that all measures for Components have null values. Now Lets equate Components with Bikes & Accessories

Scope  ([Product].[Category].&[2]) ;
this = (aggregate({[Product].[Category].&[1],[Product].[Category].&[4]},[Measures].[Measures].currentmember));
end scope;

select
{
[Measures].[Internet Sales Amount],
[Measures].[Internet Order Quantity],
[Measures].[Internet Tax Amount],
[Measures].[Internet Gross Profit Margin]
}on 0 ,
[Product].[Category].[Category]
on 1
from
[Adventure Works]

Results


问:
Replace javascript array with item inside of object
I want to show some data depending on which month it is. I have an array from 0 to 11. I'm confused on how to do this because there are multiple arrays inside of the object and it's scaring me lol

```<code>[
  {
    l: false,
    u: 'AU',
    n: 'Adelaide',
    rain: [
      22.4091,
      18,
      26.0909,
      42.875,
      56.9205,
      68.0568,
      75.4205,
      66.3636,
      58.8977,
      48.75,
      28.2159,
      27.9545,
    ],
  },
  {
    l: false,
    u: 'AU',
    n: 'A Different Place',
    rain: [
      22.4091,
      18,
      26.0909,
      42.875,
      56.9205,
      68.0568,
      75.4205,
      66.3636,
      58.8977,
      48.75,
      28.2159,
      27.9545,
    ],
  },
];
</code>```

I have a variable that I can reference like this: getMonth(new Date(this.props.startDate))

0

Can I do something like this?

forEach(data[x].rain[getMonth(new Date(this.props.startDate))])

I'd like to replace the existing rain array with the data of the corresponding month. So for example if it was January (0) I'd like data[1].rain = 22.4091

expected output if (getMonth = 0):

```<code>[
  {
    l: false,
    u: 'AU',
    n: 'Adelaide',
    rain: 22.4091
  },
  {
    l: false,
    u: 'AU',
    n: 'A Different Place',
    rain: 22.4091
    ],
  },
];
</code>```

Body:
I want to show some data depending on which month it is. I have an array from 0 to 11. I'm confused on how to do this because there are multiple arrays inside of the object and it's scaring me lol

[
  {
    l: false,
    u: 'AU',
    n: 'Adelaide',
    rain: [
      22.4091,
      18,
      26.0909,
      42.875,
      56.9205,
      68.0568,
      75.4205,
      66.3636,
      58.8977,
      48.75,
      28.2159,
      27.9545,
    ],
  },
  {
    l: false,
    u: 'AU',
    n: 'A Different Place',
    rain: [
      22.4091,
      18,
      26.0909,
      42.875,
      56.9205,
      68.0568,
      75.4205,
      66.3636,
      58.8977,
      48.75,
      28.2159,
      27.9545,
    ],
  },
];

I have a variable that I can reference like this: getMonth(new Date(this.props.startDate))

0

Can I do something like this?

forEach(data[x].rain[getMonth(new Date(this.props.startDate))])

I'd like to replace the existing rain array with the data of the corresponding month. So for example if it was January (0) I'd like data[1].rain = 22.4091

expected output if (getMonth = 0):

[
  {
    l: false,
    u: 'AU',
    n: 'Adelaide',
    rain: 22.4091
  },
  {
    l: false,
    u: 'AU',
    n: 'A Different Place',
    rain: 22.4091
    ],
  },
];

Body:
you can do this

let data = [ { l: false, u: 'AU', n: 'Adelaide', rain: [ 22.4091, 18, 26.0909, 42.875, 56.9205, 68.0568, 75.4205, 66.3636, 58.8977, 48.75, 28.2159, 27.9545, ], }, { l: false, u: 'AU', n: 'A Different Place', rain: [ 22.4091, 18, 26.0909, 42.875, 56.9205, 68.0568, 75.4205, 66.3636, 58.8977, 48.75, 28.2159, 27.9545, ], }, ];

const res = data.map(x => ({...x,rain:x.rain[ (new Date(this.props.startDate).getMonth()) ]}))
console.log(res)

if this is already date then this.props.startDate.getMonth() else convert as above


问:
Saving timestamp in mysql table using php
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

```<code>INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')
</code>```

答:
Check field type in table just save time stamp value in datatype like  bigint etc.

Not datetime type

ContentLicense: CC BY-SA 3.0

Body:
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')


问:
update query corrupts characters
my sql update works correctly but it changes the turkish characters. update query changes turkish characters like ı to i etc. here is my query:

```<code>set @updstatement = 'UPDATE ' + @table_name + ' SET ' + @text_col + '= ''' + @newText + ''' WHERE ' + @id_col + '= ''' + @cur_Id + '''';
                PRINT @updstatement
                exec sp_executesql @updstatement
                PRINT 'Updated: ' + @cur_Id;
</code>```

I have tried COLLATE DATABASE_DEFAULT and COLLATE TURKISH_CI_AS options but nothing changed. Datatype of column is ntext. Collate setting of table's database is Latin1_General_CI_AS. Collate setting of table is Latin1_General_CI_AS. Collate setting of column is Latin1_General_CI_AS. Before update I can see that turkish characters are stored correctly in the table's column. After update query data of column is corrupted. Do you have any idea?

答:
Like I said in my comment, don't inject raw values into your dynamic SQL statements. It's a big SQL injection issue and there is no excuse to ever do it.

I suspect you're using a varchar and the combination of using a non-parametrised statement is causing the problem. If this doesn't solve the issue, you need to provide an example that replicates the problem (note the guessed data types):

```<code>DECLARE @table_name sysname,
        @textcol sysname,
        @newtext nvarchar(50), --Guessed datatype
        @id_col sysname,
        @cur_id int; --Guessed dataytpe

DECLARE @updstatement nvarchar(MAX);
SET @updstatement = 'UPDATE ' + QUOTENAME(@table_name) + N' SET ' + QUOTENAME(@text_col) + N' = @newtext WHERE ' + QUOTENAME(@id_col) + N' = @cur_id;';
PRINT @updstatement; --Your debugging friend
EXEC sp_executesql @SQL, N'@newtext nvarchar(50), @cur_id int', @newtext = @newtext, @cur_id = @cur_id;
</code>```

Title: update query corrupts characters

Body:
my sql update works correctly but it changes the turkish characters. update query changes turkish characters like ı to i etc. here is my query:

set @updstatement = 'UPDATE ' + @table_name + ' SET ' + @text_col + '= ''' + @newText + ''' WHERE ' + @id_col + '= ''' + @cur_Id + '''';
                PRINT @updstatement
                exec sp_executesql @updstatement
                PRINT 'Updated: ' + @cur_Id;

I have tried COLLATE DATABASE_DEFAULT and COLLATE TURKISH_CI_AS options but nothing changed. Datatype of column is ntext. Collate setting of table's database is Latin1_General_CI_AS. Collate setting of table is Latin1_General_CI_AS. Collate setting of column is Latin1_General_CI_AS. Before update I can see that turkish characters are stored correctly in the table's column. After update query data of column is corrupted. Do you have any idea?

Body:
Like I said in my comment, don't inject raw values into your dynamic SQL statements. It's a big SQL injection issue and there is no excuse to ever do it.

I suspect you're using a varchar and the combination of using a non-parametrised statement is causing the problem. If this doesn't solve the issue, you need to provide an example that replicates the problem (note the guessed data types):

DECLARE @table_name sysname,
        @textcol sysname,
        @newtext nvarchar(50), --Guessed datatype
        @id_col sysname,
        @cur_id int; --Guessed dataytpe

DECLARE @updstatement nvarchar(MAX);
SET @updstatement = 'UPDATE ' + QUOTENAME(@table_name) + N' SET ' + QUOTENAME(@text_col) + N' = @newtext WHERE ' + QUOTENAME(@id_col) + N' = @cur_id;';
PRINT @updstatement; --Your debugging friend
EXEC sp_executesql @SQL, N'@newtext nvarchar(50), @cur_id int', @newtext = @newtext, @cur_id = @cur_id;


问:
Using purrr::walk() and ifelse to produce ggplots
I have a dataframe with one row per individual. The columns are an outcome variable and then a bunch of potential predictors of that outcome. As a preliminary step of my data analysis I want to visualize each predictor variable and its association with the outcome using ggplot. I'd like a histogram for continuous variables and a bar plot for categorical.

My attempt is

```<code>numeric <- c(0,1.1,2.4,3.1,4.0,5.9,4.2,3.3,2.2,1.1)
categorical <- as.factor(c("yes","no","no","yes","yes","no","no","yes","no","no"))
outcome <- as.factor(c("alive","dead","alive","dead","alive","dead","alive","dead","alive","dead"))
df <- data.frame(num = numeric, cat = categorical, outcome = outcome)
predictors <- c("num", "cat")
predictors %>%
    walk(print(ggplot(df, aes(x=., fill=outcome)) +
    {ifelse(class(.) == "factor", geom_bar(position="fill"), geom_histogram(position="fill", bins=10))}))
</code>```

But I get the error

```<code>Error in rep(no, length.out = length(ans)): attempt to replicate an object of type 'environment'
Traceback:

1. predictors %>% walk(print(ggplot(df, aes(x = ., fill = outcome)) +
 .     {
 .         ifelse(class(.) == "factor", geom_bar(position = "fill"),
 .             geom_histogram(position = "fill", bins = 10))
 .     }))
2. withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
3. eval(quote(`_fseq`(`_lhs`)), env, env)
4. eval(quote(`_fseq`(`_lhs`)), env, env)
5. `_fseq`(`_lhs`)
6. freduce(value, `_function_list`)
7. withVisible(function_list[[k]](value))
8. function_list[[k]](value)
9. walk(., print(ggplot(df, aes(x = ., fill = outcome)) + {
 .     ifelse(class(.) == "factor", geom_bar(position = "fill"),
 .         geom_histogram(position = "fill", bins = 10))
 . }))
10. map(.x, .f, ...)
11. as_mapper(.f, ...)
12. print(ggplot(df, aes(x = ., fill = outcome)) + {
  .     ifelse(class(.) == "factor", geom_bar(position = "fill"),
  .         geom_histogram(position = "fill", bins = 10))
  . })
13. ifelse(class(.) == "factor", geom_bar(position = "fill"), geom_histogram(position = "fill",
  .     bins = 10))   # at line 9 of file <text>
</code>```

I expect this code two produce two plots

My actual dataset has >20 predictors, so I'd like a nice way to produce 20+ ggplots and ideally keep it in a pipeline format like this so I can add additional steps once I get the plots working.

答:
Here is one way passing predictors columns to map and create a list of plots based on the class of the column.

```<code>library(tidyverse)
library(rlang)

p1 <- map(predictors, function(p) if (class(df[[p]]) == "factor")
      ggplot(df, aes(x = !!sym(p), fill=outcome)) + geom_bar(position="fill")
      else
      ggplot(df, aes(x = !!sym(p), fill=outcome)) +
                 geom_histogram(position="fill", bins=10))

p1[[1]]
</code>```

```<code>p1[[2]]
</code>```

Body:
I have a dataframe with one row per individual. The columns are an outcome variable and then a bunch of potential predictors of that outcome. As a preliminary step of my data analysis I want to visualize each predictor variable and its association with the outcome using ggplot. I'd like a histogram for continuous variables and a bar plot for categorical.

My attempt is

numeric <- c(0,1.1,2.4,3.1,4.0,5.9,4.2,3.3,2.2,1.1)
categorical <- as.factor(c("yes","no","no","yes","yes","no","no","yes","no","no"))
outcome <- as.factor(c("alive","dead","alive","dead","alive","dead","alive","dead","alive","dead"))
df <- data.frame(num = numeric, cat = categorical, outcome = outcome)
predictors <- c("num", "cat")
predictors %>%
    walk(print(ggplot(df, aes(x=., fill=outcome)) +
    {ifelse(class(.) == "factor", geom_bar(position="fill"), geom_histogram(position="fill", bins=10))}))

But I get the error

Error in rep(no, length.out = length(ans)): attempt to replicate an object of type 'environment'
Traceback:

1. predictors %>% walk(print(ggplot(df, aes(x = ., fill = outcome)) +
 .     {
 .         ifelse(class(.) == "factor", geom_bar(position = "fill"),
 .             geom_histogram(position = "fill", bins = 10))
 .     }))
2. withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
3. eval(quote(`_fseq`(`_lhs`)), env, env)
4. eval(quote(`_fseq`(`_lhs`)), env, env)
5. `_fseq`(`_lhs`)
6. freduce(value, `_function_list`)
7. withVisible(function_list[[k]](value))
8. function_list[[k]](value)
9. walk(., print(ggplot(df, aes(x = ., fill = outcome)) + {
 .     ifelse(class(.) == "factor", geom_bar(position = "fill"),
 .         geom_histogram(position = "fill", bins = 10))
 . }))
10. map(.x, .f, ...)
11. as_mapper(.f, ...)
12. print(ggplot(df, aes(x = ., fill = outcome)) + {
  .     ifelse(class(.) == "factor", geom_bar(position = "fill"),
  .         geom_histogram(position = "fill", bins = 10))
  . })
13. ifelse(class(.) == "factor", geom_bar(position = "fill"), geom_histogram(position = "fill",
  .     bins = 10))   # at line 9 of file <text>

I expect this code two produce two plots

My actual dataset has >20 predictors, so I'd like a nice way to produce 20+ ggplots and ideally keep it in a pipeline format like this so I can add additional steps once I get the plots working.

Body:
Here is one way passing predictors columns to map and create a list of plots based on the class of the column.

library(tidyverse)
library(rlang)

p1 <- map(predictors, function(p) if (class(df[[p]]) == "factor")
      ggplot(df, aes(x = !!sym(p), fill=outcome)) + geom_bar(position="fill")
      else
      ggplot(df, aes(x = !!sym(p), fill=outcome)) +
                 geom_histogram(position="fill", bins=10))

p1[[1]]

p1[[2]]


问:
Laravel get object attribute if object id is known
How do I get the value from a object if the ID is known?

So, I got the house id, in the house model there is an user_id for every house like:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use stdClass;
use App\Service\ChangesetService;

class HouseProfile extends Model
{
    protected $guarded = ['id', 'user_id'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
</code>```

Every user got an address (string)

I need the address and I got the house id and I'm working in a blade file in Laravel 5.5

答:
You should never run queries of put too much logic in you Blade files. Instead you should pass variables to them.

In your controller

```<code>$house = HouseProfile::findOrFail($houseId);
return view('your.view.name', [
    'house' => $house
]);
</code>```

In your blade file you can use @IndianCoding response, so

```<code>@if($house->user)
 {{ $house->user->address }}
@endif
</code>```

Body:
How do I get the value from a object if the ID is known?

So, I got the house id, in the house model there is an user_id for every house like:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use stdClass;
use App\Service\ChangesetService;

class HouseProfile extends Model
{
    protected $guarded = ['id', 'user_id'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Every user got an address (string)

I need the address and I got the house id and I'm working in a blade file in Laravel 5.5

Body:
You should never run queries of put too much logic in you Blade files. Instead you should pass variables to them.

In your controller

$house = HouseProfile::findOrFail($houseId);
return view('your.view.name', [
    'house' => $house
]);

In your blade file you can use @IndianCoding response, so

@if($house->user)
 {{ $house->user->address }}
@endif


问:
How to convert array of string to simple string in JavaScript?
I have the following JavaScript array of strings:

```<code>arrayOfString = ['a', 'b,c', 'd,e', 'f'];
</code>```

And I would like to convert this array to an array similar to this:

```<code>myString = ["a", "b", "c", "d", "e", "f"];
</code>```

How I can accomplish that?

答:
you can use spread operator, map and split

let arr = [];
let input =  ['a', 'b,c', 'd,e', 'f'];
input.map(obj => arr = [...arr,...obj.split(",")])

console.log(arr);```

Body:
I have the following JavaScript array of strings:

arrayOfString = ['a', 'b,c', 'd,e', 'f'];

And I would like to convert this array to an array similar to this:

myString = ["a", "b", "c", "d", "e", "f"];

How I can accomplish that?


问:
how to reduce the size of file....in java

Possible Duplicate:

  Resize an image in Java - Any Open Source Library ?

```<code>InputStream is = new FileInputStream(file);
    long length = file.length();
    // if (length > Integer.MAX_VALUE) {
    // File is too large
    // }
    byte[] bytes = new byte[(int) length];
</code>```

if i enter large image....it should accept but size should be reduced

答:
Image resize in Java

Java Image Manupulation

Body:
Possible Duplicate:

  Resize an image in Java - Any Open Source Library ?

InputStream is = new FileInputStream(file);
    long length = file.length();
    // if (length > Integer.MAX_VALUE) {
    // File is too large
    // }
    byte[] bytes = new byte[(int) length];

if i enter large image....it should accept but size should be reduced


问:
How do I terminate a thread in C++11?
I don't need to terminate the thread correctly, or make it respond to a "terminate" command. I am interested in terminating the thread forcefully using pure C++11.</p>

答:
I guess the thread that needs to be killed is either in any kind of waiting mode, or doing some heavy job.
I would suggest using a "naive" way.

Define some global boolean:

```<code>std::atomic_bool stop_thread_1 = false;
</code>```

Put the following code (or similar) in several key points, in a way that it will cause all functions in the call stack to return until the thread naturally ends:

```<code>if (stop_thread_1)
    return;
</code>```

Then to stop the thread from another (main) thread:

```<code>stop_thread_1 = true;
thread1.join ();
stop_thread_1 = false; //(for next time. this can be when starting the thread instead)
</code>```

Title: How do I terminate a thread in C++11?

Body:
I guess the thread that needs to be killed is either in any kind of waiting mode, or doing some heavy job.
I would suggest using a "naive" way.

Define some global boolean:

std::atomic_bool stop_thread_1 = false;

Put the following code (or similar) in several key points, in a way that it will cause all functions in the call stack to return until the thread naturally ends:

if (stop_thread_1)
    return;

Then to stop the thread from another (main) thread:

stop_thread_1 = true;
thread1.join ();
stop_thread_1 = false; //(for next time. this can be when starting the thread instead)


问:
Standard/Correct way to create a singleton object with generic types
I am trying to make a singleton object with generic types.

The object does not take generic types, so the following does not compile.

```<code>object SomeObj {
  val dataStore = mutable.HashMap.empty[K, V]

  def setPair[K, V](key: K, value: V): Option[V] = dataStore.set(key, value)

  def getValue[K, V](key: K): Option[V] = dataStore.get(key)
}
</code>```

What would be the correct(standard way) to represent some sort of data store that is supposed to be only a single store shared by other program components?

答:
Just a thought, maybe it helps

import scala.collection.concurrent.TrieMap

```<code>object Main {

  class Dict[K, V] {
    lazy val dictionary = Dictionary(new TrieMap[K, V]())

    def getDictionary(): TrieMap[K, V] = this.dictionary.values
  }

  case class Dictionary[K, V](val values: TrieMap[K, V])

  def main(args: Array[String]): Unit = {
    val dictionary = new Dict[String, String]()
    dictionary.getDictionary().put("one", "word")
    dictionary.getDictionary().foreach(println)
  }
}
</code>```

Body:
I am trying to make a singleton object with generic types.

The object does not take generic types, so the following does not compile.

object SomeObj {
  val dataStore = mutable.HashMap.empty[K, V]

  def setPair[K, V](key: K, value: V): Option[V] = dataStore.set(key, value)

  def getValue[K, V](key: K): Option[V] = dataStore.get(key)
}

What would be the correct(standard way) to represent some sort of data store that is supposed to be only a single store shared by other program components?

Body:
Just a thought, maybe it helps

import scala.collection.concurrent.TrieMap

object Main {

  class Dict[K, V] {
    lazy val dictionary = Dictionary(new TrieMap[K, V]())

    def getDictionary(): TrieMap[K, V] = this.dictionary.values
  }

  case class Dictionary[K, V](val values: TrieMap[K, V])

  def main(args: Array[String]): Unit = {
    val dictionary = new Dict[String, String]()
    dictionary.getDictionary().put("one", "word")
    dictionary.getDictionary().foreach(println)
  }
}


问:
Yahoo Weather API by Lat and Lon
I'm writing a weather app in Xamarin.Form. I am using the Yahoo API. I have no problem getting the weather by the city name parameter. However, when I change the code to use longitude and latitude, the weather does not appear.

To download the weather I use the example from the page: https://developer.yahoo.com/weather/documentation.html#oauth-csharp

I processed it in the following way:

```<code>lSign = string.Format(
                "format={0}&" +
                "lat={1}&" +
                "lon={2}&" +
                "oauth_consumer_key={3}&" +
                "oauth_nonce={4}&" +
                "oauth_signature_method={5}&" +
                "oauth_timestamp={6}&" +
                "oauth_version={7}&" +
                "u={8}",
                cFormat,
                szerokosc,
                dlugosc,
                cConsumerKey,
                lNonce,
                cOAuthSignMethod,
                lTimes,
                cOAuthVersion,
                jednostka.ToString().ToLower()
</code>```

(...)

```<code>url = cURL + "?lat=" + szerokosc + "&lon=" + dlugosc + "&u=" + jednostka.ToString().ToLower() + "&format=" + cFormat;
</code>```

答:
Unfortunately, the simple removal of " lat = {1} & " + " lon = {2} & " from variable lSign does not solve the problem.

For example, to get weather data by the city name I use:

```<code>lSign = string.Format(
                "format={0}&" +
                "location={1}&" +
                "oauth_consumer_key={2}&" +
                "oauth_nonce={3}&" +
                "oauth_signature_method={4}&" +
                "oauth_timestamp={5}&" +
                "oauth_version={6}&" +
                "u={7}",
                cFormat,
                miasto,
                cConsumerKey,
                lNonce,
                cOAuthSignMethod,
                lTimes,
                cOAuthVersion,
                jednostka.ToString().ToLower()
</code>```

and

```<code>url = cURL + "?location=" + Uri.EscapeDataString(miasto) + "&u=" + jednostka.ToString().ToLower() + "&format=" + cFormat;
</code>```

and

```<code>string headerString = _get_auth();

                    WebClient webClient = new WebClient();
                    webClient.Headers[HttpRequestHeader.ContentType] = "application/" + cFormat;
                    webClient.Headers[HttpRequestHeader.Authorization] = headerString;
                    webClient.Headers.Add("X-Yahoo-App-Id", cAppID);
                    byte[] reponse = webClient.DownloadData(url);
                    string lOut = Encoding.ASCII.GetString(reponse);
</code>```

Title: Yahoo Weather API by Lat and Lon

Body:
I'm writing a weather app in Xamarin.Form. I am using the Yahoo API. I have no problem getting the weather by the city name parameter. However, when I change the code to use longitude and latitude, the weather does not appear.

To download the weather I use the example from the page: https://developer.yahoo.com/weather/documentation.html#oauth-csharp

I processed it in the following way:

lSign = string.Format(
                "format={0}&" +
                "lat={1}&" +
                "lon={2}&" +
                "oauth_consumer_key={3}&" +
                "oauth_nonce={4}&" +
                "oauth_signature_method={5}&" +
                "oauth_timestamp={6}&" +
                "oauth_version={7}&" +
                "u={8}",
                cFormat,
                szerokosc,
                dlugosc,
                cConsumerKey,
                lNonce,
                cOAuthSignMethod,
                lTimes,
                cOAuthVersion,
                jednostka.ToString().ToLower()

(...)

url = cURL + "?lat=" + szerokosc + "&lon=" + dlugosc + "&u=" + jednostka.ToString().ToLower() + "&format=" + cFormat;

Body:
Unfortunately, the simple removal of " lat = {1} & " + " lon = {2} & " from variable lSign does not solve the problem.

For example, to get weather data by the city name I use:

lSign = string.Format(
                "format={0}&" +
                "location={1}&" +
                "oauth_consumer_key={2}&" +
                "oauth_nonce={3}&" +
                "oauth_signature_method={4}&" +
                "oauth_timestamp={5}&" +
                "oauth_version={6}&" +
                "u={7}",
                cFormat,
                miasto,
                cConsumerKey,
                lNonce,
                cOAuthSignMethod,
                lTimes,
                cOAuthVersion,
                jednostka.ToString().ToLower()

and

url = cURL + "?location=" + Uri.EscapeDataString(miasto) + "&u=" + jednostka.ToString().ToLower() + "&format=" + cFormat;

and

string headerString = _get_auth();

                    WebClient webClient = new WebClient();
                    webClient.Headers[HttpRequestHeader.ContentType] = "application/" + cFormat;
                    webClient.Headers[HttpRequestHeader.Authorization] = headerString;
                    webClient.Headers.Add("X-Yahoo-App-Id", cAppID);
                    byte[] reponse = webClient.DownloadData(url);
                    string lOut = Encoding.ASCII.GetString(reponse);


问:
Robust solution to plot large datasets with custom line formats using loops
I am attempting to graph population and country data by year from the Comparative Political Data Set. Ex:

```<code>year    country   pop15_64
1960  Australia    6296.50
1961  Australia    6428.60
1962  Australia    6571.50
1960        USA  107919.4
1961        USA  109048.6
1962        USA  111177.3
</code>```

The problem comes in attempting to see what line corresponds to what country. I have tried a number of different methods, and the easiest to differentiate seems to be plotting lines as dashes. Ex (snippet, not full):

```<code>df2.loc[df2['country'] == 'Cyprus'].plot(x='year', y='pop15_64', ax=ax, color='k')
df2.loc[df2['country'] == 'Czech Republic'].plot(x='year', y='pop15_64', ax=ax, color='g', dashes=[3, 3])
</code>```

Resulting graph:

But the above is not robust. Adding to the dataset requires hard coding another line, as does removing a country. This loops robustly over the data:

```<code>fig, ax = plt.subplots()
plt.xlabel('Year')
plt.ylabel('Population')
for countries in df2['country'].unique():
     df2[df2['country']==countries].plot.line(x='year',
                                              y='pop15_64',
                                              ax=ax,
                                              label=countries,
                                              title='Country Population by Year')

ax.legend(handlelength=5)
plt.show()
</code>```

Resulting graph:

...but I see no way of customizing lines within those loops without breaking it. For example, this:

```<code>for countries, x in df2['country'].unique():
     df2[df2['country']==countries].plot.line(x='year',
                                              y='pop15_64',
                                              ax=ax,
                                              dashes=[x+2, x],
                                              label=countries,
                                              title='Country Population by Year')
</code>```

...results in a "ValueError: too many values to unpack (expected 2)"

What else I tried:

 .groupby - couldn't get groupby and iterables to work together in one plot

 iterables - had difficulty getting unique countries without losing the underlying data, still had line customization issues.

I admit that while I have experience in C, C++, and C#, I am a novice at python and more so with pandas. It requires a restructuring in how one thinks about problems. As a result, applying the many vaguely similar StackOverflow Q&A about custom lines and legends has not resulted in solutions like it might for someone with more experience. I hope someone knows an answer, and that this might help more than just me.

Update: after Peter Leimbigler's answer I modified the above for this tentative solution:

```<code>for i, countries in enumerate(df2['country'].unique()):
     df2[df2['country']==countries].plot.line(x='year',
                                              y='pop15_64',
                                              ax=ax,
                                              dashes=[3+i, i/2, abs(i-2), i/2],
                                              label=countries)
</code>```

答:
I would suggest the following change to your attempt at changing dash properties within a loop:

```<code>for i, countries in enumerate(df2['country'].unique()):
</code>```

This will need further stylistic adjustment, but should be a good starting point.

More broadly, to echo Quang Hoang's comment, it's very difficult to present this many lines on one plot without visual confusion. Two possible workarounds:

Group the dataset by greater region (North & South America, SE Asia, etc.) and build several plots.

Build an interactive line plot with zooming, panning, and toggling of countries, in something like Bokeh, Plotly Dash, or Holoviews.

Body:
I am attempting to graph population and country data by year from the Comparative Political Data Set. Ex:

year    country   pop15_64
1960  Australia    6296.50
1961  Australia    6428.60
1962  Australia    6571.50
1960        USA  107919.4
1961        USA  109048.6
1962        USA  111177.3

The problem comes in attempting to see what line corresponds to what country. I have tried a number of different methods, and the easiest to differentiate seems to be plotting lines as dashes. Ex (snippet, not full):

df2.loc[df2['country'] == 'Cyprus'].plot(x='year', y='pop15_64', ax=ax, color='k')
df2.loc[df2['country'] == 'Czech Republic'].plot(x='year', y='pop15_64', ax=ax, color='g', dashes=[3, 3])

Resulting graph:

But the above is not robust. Adding to the dataset requires hard coding another line, as does removing a country. This loops robustly over the data:

fig, ax = plt.subplots()
plt.xlabel('Year')
plt.ylabel('Population')
for countries in df2['country'].unique():
     df2[df2['country']==countries].plot.line(x='year',
                                              y='pop15_64',
                                              ax=ax,
                                              label=countries,
                                              title='Country Population by Year')

ax.legend(handlelength=5)
plt.show()

Resulting graph:

...but I see no way of customizing lines within those loops without breaking it. For example, this:

for countries, x in df2['country'].unique():
     df2[df2['country']==countries].plot.line(x='year',
                                              y='pop15_64',
                                              ax=ax,
                                              dashes=[x+2, x],
                                              label=countries,
                                              title='Country Population by Year')

...results in a "ValueError: too many values to unpack (expected 2)"

What else I tried:

 .groupby - couldn't get groupby and iterables to work together in one plot

 iterables - had difficulty getting unique countries without losing the underlying data, still had line customization issues.

I admit that while I have experience in C, C++, and C#, I am a novice at python and more so with pandas. It requires a restructuring in how one thinks about problems. As a result, applying the many vaguely similar StackOverflow Q&A about custom lines and legends has not resulted in solutions like it might for someone with more experience. I hope someone knows an answer, and that this might help more than just me.

Update: after Peter Leimbigler's answer I modified the above for this tentative solution:

for i, countries in enumerate(df2['country'].unique()):
     df2[df2['country']==countries].plot.line(x='year',
                                              y='pop15_64',
                                              ax=ax,
                                              dashes=[3+i, i/2, abs(i-2), i/2],
                                              label=countries)

Body:
I would suggest the following change to your attempt at changing dash properties within a loop:

for i, countries in enumerate(df2['country'].unique()):

This will need further stylistic adjustment, but should be a good starting point.

More broadly, to echo Quang Hoang's comment, it's very difficult to present this many lines on one plot without visual confusion. Two possible workarounds:

Group the dataset by greater region (North & South America, SE Asia, etc.) and build several plots.

Build an interactive line plot with zooming, panning, and toggling of countries, in something like Bokeh, Plotly Dash, or Holoviews.


问:
How to disable JavaScript build error in Visual Studio 2017?
I just updated Visual Studio 2017 from RC to final. I didn’t get the following error but recently I get this error. In building the project, I get the following error and it prevents the web project to start:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   eqeqeq  (ESLint) Expected '===' and instead saw '=='.   VistaBest.Shop.Web  C:\***\Request.js   21
</code>```

How can I disable JavaScript building error in Visual Studio 2017?

答:
For Visual Studio 2019.

Open Tools > Options

Navigate to Text Editor > JavaScript/TypeScript

=> Linting > General.

Then unchecked ESLint check box.
Please The bellow Image for reference.

Body:
I just updated Visual Studio 2017 from RC to final. I didn’t get the following error but recently I get this error. In building the project, I get the following error and it prevents the web project to start:

Severity    Code    Description Project File    Line    Suppression State
Error   eqeqeq  (ESLint) Expected '===' and instead saw '=='.   VistaBest.Shop.Web  C:\***\Request.js   21

How can I disable JavaScript building error in Visual Studio 2017?


问:
play framework inter-app communication
Since Play currently supports using only one database per application, what's the best way for one Play application to access the data of another?  Are there any better methods than simply fetching data in JSON format?</p>

答:
Be patient for a few days IMO because the multidb support is incoming very soon.

Apparently Morten Kjetland has implemented it and gonna commit it after some verifications...

http://groups.google.com/group/play-framework/browse_thread/thread/598e70249c56e17e?pli=1

Title: play framework inter-app communication


问:
Is there a better way in writing a where clause in access vba
Here is a little brain teaser!

I have a query that has at least 3 different where clauses. Instead of writing an elaborate if statement to test every single possible outcome, I am wondering if there is a simpler way of doing it!

These 3 clauses are chosen from drop down menus that have at least 3 x different values including an "ALL" option.

I hope you guys are starting to se my issue...

so if I have:

```<code>SELECT * FROM tabe1 WHERE col1 = combo1Value AND col2 = combo2Value AND col3 = combo3Value
</code>```

USER decides to select the following:

combo1: All

combo2: item (an option that is not all)

combo3: item (an option that is not all)

so now is there a way to re-write my query:

```<code>WHERE col1 = * AND col2 = combo2value AND col3 = combo3value
</code>```

or I have no choice but to write a big if-statement???

答:
You can use something like this:</p>

```<code>WHERE
    col1 = IIf([combo1value] = "*", [col1], [combo1value]) AND
    col2 = IIf([combo2value] = "*", [col2], [combo2value]) AND
    col3 = IIf([combo3value] = "*", [col3], [combo3value])
</code>```

Body:
Here is a little brain teaser!

I have a query that has at least 3 different where clauses. Instead of writing an elaborate if statement to test every single possible outcome, I am wondering if there is a simpler way of doing it!

These 3 clauses are chosen from drop down menus that have at least 3 x different values including an "ALL" option.

I hope you guys are starting to se my issue...

so if I have:

SELECT * FROM tabe1 WHERE col1 = combo1Value AND col2 = combo2Value AND col3 = combo3Value

USER decides to select the following:

combo1: All

combo2: item (an option that is not all)

combo3: item (an option that is not all)

so now is there a way to re-write my query:

WHERE col1 = * AND col2 = combo2value AND col3 = combo3value

or I have no choice but to write a big if-statement???

Body:
You can use something like this:

WHERE
    col1 = IIf([combo1value] = "*", [col1], [combo1value]) AND
    col2 = IIf([combo2value] = "*", [col2], [combo2value]) AND
    col3 = IIf([combo3value] = "*", [col3], [combo3value])


问:
How to add or remove an item from state array in react
I have state array and when user click on an item , item should be added to state array. I use type script, interface for data model.

This is the code I used

```<code>this.setState(prevState => ({
  this.state.activeItemList: [...prevState.activeItemList, newItem]
}))
</code>```

Interface

```<code>interface IState {     activeItemList?: IItem[] | null;  }
</code>```

Is this the correct way?

答:
That's certainly a correct way, yes, and I'd say it's probably the idiomatic way today. You're doing both of the important things:

You're using the callback version of setState, and

You're creating a new array, not modifying an existing on on the state.

Perfect!

You can also use concat rather than spread:

```<code>this.setState(prevState => ({
  this.state.activeItemList: prevState.activeItemList.concat(newItem)
}))
</code>```

but again, your way is probably the idiomatic way in today's world. Also, if newItem were an array (e.g., activeItemList was intended as an array of arrays), concat would spread it, which wouldn't be good.

Body:
I have state array and when user click on an item , item should be added to state array. I use type script, interface for data model.

This is the code I used

this.setState(prevState => ({
  this.state.activeItemList: [...prevState.activeItemList, newItem]
}))

Interface

interface IState {     activeItemList?: IItem[] | null;  }

Is this the correct way?

Body:
That's certainly a correct way, yes, and I'd say it's probably the idiomatic way today. You're doing both of the important things:

You're using the callback version of setState, and

You're creating a new array, not modifying an existing on on the state.

Perfect!

You can also use concat rather than spread:

this.setState(prevState => ({
  this.state.activeItemList: prevState.activeItemList.concat(newItem)
}))

but again, your way is probably the idiomatic way in today's world. Also, if newItem were an array (e.g., activeItemList was intended as an array of arrays), concat would spread it, which wouldn't be good.


问:
Custom Expandable RecyclerView Crashing on notifyItemRangeRemoved and notifyItemRangeInserted
I have created expandable recylerview following is my adapter code

```<code>public class FoodMenuRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    List<Object> objects;
    FoodMenuParentListener foodMenuParentListener;
    boolean isAddAllowed;

    boolean isVegOnly;
    static final int TYPE_FOOD = 0;
    static final int TYPE_MENU_ITEM = 1;

    public FoodMenuRecyclerAdapter(List<Object> objects, FoodMenuParentListener foodMenuParentListener, boolean isVegOnly, boolean isAddAllowed) {
        this.foodMenuParentListener = foodMenuParentListener;
        this.isVegOnly = isVegOnly;
        this.isAddAllowed = isAddAllowed;
        this.objects = objects;
    }

    @Override
    public int getItemViewType(int position) {
        Object object = objects.get(position);
        if (object instanceof FoodMenuItem) {
            return TYPE_FOOD;
        } else if(this.objects.get(position) == null) {
            throw new IllegalStateException("Null object added");
        }else {
            return TYPE_MENU_ITEM;
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view;
        switch (getItemViewType(i)) {
            case TYPE_FOOD:
                view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_food_parent, viewGroup, false);
                return new MenuViewHolder(view);
            case TYPE_MENU_ITEM:
                view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_food_child, viewGroup, false);
                return new ChildMenuHolder(view);
            default:
                throw new IllegalArgumentException("Invalid viewType");

        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        Object object = objects.get(i);
        Context context = viewHolder.itemView.getContext();
        Log.d("myAdapter","position"+ i + ":"+ ((getItemViewType(i) == TYPE_MENU_ITEM) ? "TYPE_MENU_ITEM" : "TYPE_FOOD"));
         if (getItemViewType(i) == TYPE_MENU_ITEM) {
            ChildMenuHolder childMenuHolder = (ChildMenuHolder) viewHolder;

            Item item = (Item) object;

            childMenuHolder.tvTitle.setText(item.getTitle());
            childMenuHolder.txtQty.setText(String.valueOf(item.getQuatity()));
            childMenuHolder.txtCartInc.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.txtQty.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.txtCartDec.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.btnAdd.setVisibility(!item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.btnAdd.setBackgroundResource(isAddAllowed ? R.drawable.rounded_bottom_edge_shape_food : R.drawable.rounded_bottom_edge_shape_disable);
            childMenuHolder.btnAdd.setTextColor(isAddAllowed ? ContextCompat.getColor(context, R.color.button_green) : ContextCompat.getColor(context, R.color.gray_a1));
            childMenuHolder.ivType.setColorFilter(item.getType().equalsIgnoreCase(Item.FOOD_TYPE_VEG) ? ContextCompat.getColor(context, R.color.selected_green) : ContextCompat.getColor(context, R.color.app_red));
        } else {
            FoodMenuItem foodMenuItem = (FoodMenuItem) object;
            MenuViewHolder menuViewHolder = (MenuViewHolder) viewHolder;
            if (isVegOnly) {
                List<Item> items = new ArrayList<>();
                for (Item item : foodMenuItem.getItems()) {
                    if (item.getType().equalsIgnoreCase(Item.FOOD_TYPE_VEG)) {
                        items.add(item);
                    }
                }
                menuViewHolder.tvNumItems.setText("(" + items.size() + " items)");

            } else {
                menuViewHolder.tvNumItems.setText("(" + foodMenuItem.getItems().size() + " items)");

            }
            menuViewHolder.ivArrow.setImageResource(foodMenuItem.isExpanded() ? R.drawable.chev_up : R.drawable.chev_down);
            menuViewHolder.tvTitle.setText(foodMenuItem.getCategoryName());
        }

    }

    @Override
    public int getItemCount() {
        return objects.size();
    }

    public class MenuViewHolder extends RecyclerView.ViewHolder {
        TextView tvTitle;
        TextView tvNumItems;
        ImageView ivArrow;
        // RecyclerView rvMenu;
        View rlArrow;

        public MenuViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
            tvNumItems = (TextView) itemView.findViewById(R.id.tvNumItems);
            ivArrow = (ImageView) itemView.findViewById(R.id.ivArrow);
            // rvMenu.setNestedScrollingEnabled(false);
            rlArrow = itemView.findViewById(R.id.rlArrow);
            rlArrow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (foodMenuParentListener != null) {
                        Object object = objects.get(getAdapterPosition());
                        if (object instanceof FoodMenuItem) {
                            FoodMenuItem foodMenuItem = (FoodMenuItem) object;
                            foodMenuParentListener.OnExpandClick(foodMenuItem, getAdapterPosition());

                        }
                    }
                }
            });
            tvTitle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (foodMenuParentListener != null) {
                        Object object = objects.get(getAdapterPosition());
                        if (object instanceof FoodMenuItem) {
                            FoodMenuItem foodMenuItem = (FoodMenuItem) object;
                            foodMenuParentListener.OnExpandClick(foodMenuItem, getAdapterPosition());

                        }
                    }
                }
            });
        }
    }

    public boolean isVegOnly() {
        return isVegOnly;
    }

    public void setVegOnly(boolean vegOnly) {
        isVegOnly = vegOnly;
    }

    public interface FoodMenuParentListener extends AddItemListener {
        public void OnExpandClick(FoodMenuItem foodMenuItem, int position);

        public void OnVegOnlyClicked();
    }

    public class ChildMenuHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        ImageView ivType;
        TextView tvTitle;
        TextView tvPrice;
        TextView txtCartDec;
        TextView txtQty;
        TextView txtCartInc;

        Button btnAdd;

        public ChildMenuHolder(@NonNull View itemView) {
            super(itemView);
            ivType = (ImageView) itemView.findViewById(R.id.ivType);
            tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
            tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
            txtCartDec = (TextView) itemView.findViewById(R.id.txtCartDec);
            txtQty = (TextView) itemView.findViewById(R.id.txtQty);
            txtCartInc = (TextView) itemView.findViewById(R.id.txtCartInc);
            btnAdd = (Button) itemView.findViewById(R.id.btnAdd);
            btnAdd.setOnClickListener(this);
            txtCartInc.setOnClickListener(this);
            txtCartDec.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {

        }
    }

    public void setExpandIndex(int expandIndex) {
    }

    public boolean isItemExpanded(int position) {
        return true;
    }

    public class VegOnlyViewHolder extends RecyclerView.ViewHolder {
        Switch wtVeg;

        public VegOnlyViewHolder(@NonNull View itemView) {
            super(itemView);
            wtVeg = (Switch) itemView.findViewById(R.id.wtVeg);
            wtVeg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (foodMenuParentListener != null) {
                        foodMenuParentListener.OnVegOnlyClicked();
                    }
                }
            });
        }
    }

    public interface AddItemListener {
        public void onAddClicked(Item item, int parentIndex);

        public void increaseItemCount(Item item, int parentIndex);

        public void decreaseItemCount(Item item, int parentIndex);
    }

    public void addAll(int position, List<Item> objectsToAdd) {
        this.objects.addAll(position, objectsToAdd);
    }

    public void addItem(int position, Item object) {
        this.objects.add(position, object);
    }
    public void removeItem(Object object) {
        this.objects.remove(object);
    }

    public void removeAll(List<Item> objectsToRemove) {
        objects.removeAll(objectsToRemove);
        Log.d("myAdapter","item at first position after remove" + ":"+objects.get(0));
        Log.d("myAdapter","item at second position after remove" + ":"+objects.get(1));
    }

    public Object isItemInList(Item item) {
        for (Object object : objects) {
            if (object instanceof Item && ((Item) object).getId().equals(item.getId())) {
                return object;
            }
        }
        return null;
    }
    }
</code>```

Following is code in my Fragment to expand collapse RecyclerView

```<code> @Override
        public void OnExpandClick(FoodMenuItem foodMenuItem, int position) {
            if (recyclerViewMenu != null && recyclerViewMenu.getAdapter() != null) {
                recyclerViewMenu.getRecycledViewPool().clear();
                FoodMenuRecyclerAdapter foodMenuRecyclerAdapter = (FoodMenuRecyclerAdapter) recyclerViewMenu.getAdapter();
                foodMenuItem.setExpanded(!foodMenuItem.isExpanded());
                if (foodMenuItem.isExpanded()) {
                    foodMenuRecyclerAdapter.addAll(position + 1, foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeInserted(position, foodMenuItem.getItems().size());

                } else {
                    foodMenuRecyclerAdapter.removeAll(foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeRemoved(position + 1, foodMenuItem.getItems().size());

                }

            }

        }
</code>```

Following is listener code inside fragment to expand and collapse

```<code>public void OnExpandClick(FoodMenuItem foodMenuItem, int position) {
            if (recyclerViewMenu != null && recyclerViewMenu.getAdapter() != null) {
                FoodMenuRecyclerAdapter foodMenuRecyclerAdapter = (FoodMenuRecyclerAdapter) recyclerViewMenu.getAdapter();
                foodMenuItem.setExpanded(!foodMenuItem.isExpanded());
                if (foodMenuItem.isExpanded()) {
                    foodMenuRecyclerAdapter.addAll(position + 1, foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeInserted(position, foodMenuItem.getItems().size());

                } else {
                    foodMenuRecyclerAdapter.removeAll(foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeRemoved(position +1 , foodMenuItem.getItems().size());

                }

            }

        }
</code>```

Above code is throwing exception following is exception stack trace

```<code> java.lang.ClassCastException: com.myapp.android.pojoentities.Item cannot be cast to com.myapp.android.pojoentities.FoodMenuItem
    at com.myapp.android.food.menu.FoodMenuRecyclerAdapter.onBindViewHolder(FoodMenuRecyclerAdapter.java:104)
    at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
    at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
    at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
    at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
    at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
    at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3875)
    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3639)
    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4194)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.support.design.widget.CoordinatorLayout.layoutChild(CoordinatorLayout.java:1183)
    at android.support.design.widget.CoordinatorLayout.onLayoutChild(CoordinatorLayout.java:870)
    at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:889)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at com.myapp.android.custom.FitsSystemWindowsFrameLayout.onLayout(FitsSystemWindowsFrameLayout.java:247)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1231)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
    at android.view.View.layout(View.java:
</code>```

Update:

After collapsing first item I have checked log for type of first two items in list found that first two items are of type ParentItem which is FoodMenuItem but when I checked log for getItemViewType for same positions it is returning wrong value somehow

Following are logs

```<code>05-28 00:13:47.643 32010-32010/com.myapp.android D/myAdapter: item at first position after remove:com.myapp.android.pojoentities.FoodMenuItem@7fdf002
05-28 00:13:47.643 32010-32010/com.myapp.android D/myAdapter: item at second position after remove:com.myapp.android.pojoentities.FoodMenuItem@9cbfd13
05-28 00:13:47.664 32010-32010/com.myapp.android D/myAdapter: position1:TYPE_FOOD
05-28 00:13:47.678 32010-32010/com.myapp.android D/myAdapter: position2:TYPE_MENU_ITEM
</code>```

here is sample project for reference

答: You got a model foodmenuobject and after that onBindView you directly change this object into items . That's why you got this error.</p>

Body:
I have created expandable recylerview following is my adapter code

public class FoodMenuRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    List<Object> objects;
    FoodMenuParentListener foodMenuParentListener;
    boolean isAddAllowed;

    boolean isVegOnly;
    static final int TYPE_FOOD = 0;
    static final int TYPE_MENU_ITEM = 1;

    public FoodMenuRecyclerAdapter(List<Object> objects, FoodMenuParentListener foodMenuParentListener, boolean isVegOnly, boolean isAddAllowed) {
        this.foodMenuParentListener = foodMenuParentListener;
        this.isVegOnly = isVegOnly;
        this.isAddAllowed = isAddAllowed;
        this.objects = objects;
    }

    @Override
    public int getItemViewType(int position) {
        Object object = objects.get(position);
        if (object instanceof FoodMenuItem) {
            return TYPE_FOOD;
        } else if(this.objects.get(position) == null) {
            throw new IllegalStateException("Null object added");
        }else {
            return TYPE_MENU_ITEM;
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view;
        switch (getItemViewType(i)) {
            case TYPE_FOOD:
                view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_food_parent, viewGroup, false);
                return new MenuViewHolder(view);
            case TYPE_MENU_ITEM:
                view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_food_child, viewGroup, false);
                return new ChildMenuHolder(view);
            default:
                throw new IllegalArgumentException("Invalid viewType");

        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        Object object = objects.get(i);
        Context context = viewHolder.itemView.getContext();
        Log.d("myAdapter","position"+ i + ":"+ ((getItemViewType(i) == TYPE_MENU_ITEM) ? "TYPE_MENU_ITEM" : "TYPE_FOOD"));
         if (getItemViewType(i) == TYPE_MENU_ITEM) {
            ChildMenuHolder childMenuHolder = (ChildMenuHolder) viewHolder;

            Item item = (Item) object;

            childMenuHolder.tvTitle.setText(item.getTitle());
            childMenuHolder.txtQty.setText(String.valueOf(item.getQuatity()));
            childMenuHolder.txtCartInc.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.txtQty.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.txtCartDec.setVisibility(item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.btnAdd.setVisibility(!item.isAddedToCart() ? View.VISIBLE : View.GONE);
            childMenuHolder.btnAdd.setBackgroundResource(isAddAllowed ? R.drawable.rounded_bottom_edge_shape_food : R.drawable.rounded_bottom_edge_shape_disable);
            childMenuHolder.btnAdd.setTextColor(isAddAllowed ? ContextCompat.getColor(context, R.color.button_green) : ContextCompat.getColor(context, R.color.gray_a1));
            childMenuHolder.ivType.setColorFilter(item.getType().equalsIgnoreCase(Item.FOOD_TYPE_VEG) ? ContextCompat.getColor(context, R.color.selected_green) : ContextCompat.getColor(context, R.color.app_red));
        } else {
            FoodMenuItem foodMenuItem = (FoodMenuItem) object;
            MenuViewHolder menuViewHolder = (MenuViewHolder) viewHolder;
            if (isVegOnly) {
                List<Item> items = new ArrayList<>();
                for (Item item : foodMenuItem.getItems()) {
                    if (item.getType().equalsIgnoreCase(Item.FOOD_TYPE_VEG)) {
                        items.add(item);
                    }
                }
                menuViewHolder.tvNumItems.setText("(" + items.size() + " items)");

            } else {
                menuViewHolder.tvNumItems.setText("(" + foodMenuItem.getItems().size() + " items)");

            }
            menuViewHolder.ivArrow.setImageResource(foodMenuItem.isExpanded() ? R.drawable.chev_up : R.drawable.chev_down);
            menuViewHolder.tvTitle.setText(foodMenuItem.getCategoryName());
        }

    }

    @Override
    public int getItemCount() {
        return objects.size();
    }

    public class MenuViewHolder extends RecyclerView.ViewHolder {
        TextView tvTitle;
        TextView tvNumItems;
        ImageView ivArrow;
        // RecyclerView rvMenu;
        View rlArrow;

        public MenuViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
            tvNumItems = (TextView) itemView.findViewById(R.id.tvNumItems);
            ivArrow = (ImageView) itemView.findViewById(R.id.ivArrow);
            // rvMenu.setNestedScrollingEnabled(false);
            rlArrow = itemView.findViewById(R.id.rlArrow);
            rlArrow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (foodMenuParentListener != null) {
                        Object object = objects.get(getAdapterPosition());
                        if (object instanceof FoodMenuItem) {
                            FoodMenuItem foodMenuItem = (FoodMenuItem) object;
                            foodMenuParentListener.OnExpandClick(foodMenuItem, getAdapterPosition());

                        }
                    }
                }
            });
            tvTitle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (foodMenuParentListener != null) {
                        Object object = objects.get(getAdapterPosition());
                        if (object instanceof FoodMenuItem) {
                            FoodMenuItem foodMenuItem = (FoodMenuItem) object;
                            foodMenuParentListener.OnExpandClick(foodMenuItem, getAdapterPosition());

                        }
                    }
                }
            });
        }
    }

    public boolean isVegOnly() {
        return isVegOnly;
    }

    public void setVegOnly(boolean vegOnly) {
        isVegOnly = vegOnly;
    }

    public interface FoodMenuParentListener extends AddItemListener {
        public void OnExpandClick(FoodMenuItem foodMenuItem, int position);

        public void OnVegOnlyClicked();
    }

    public class ChildMenuHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        ImageView ivType;
        TextView tvTitle;
        TextView tvPrice;
        TextView txtCartDec;
        TextView txtQty;
        TextView txtCartInc;

        Button btnAdd;

        public ChildMenuHolder(@NonNull View itemView) {
            super(itemView);
            ivType = (ImageView) itemView.findViewById(R.id.ivType);
            tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
            tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
            txtCartDec = (TextView) itemView.findViewById(R.id.txtCartDec);
            txtQty = (TextView) itemView.findViewById(R.id.txtQty);
            txtCartInc = (TextView) itemView.findViewById(R.id.txtCartInc);
            btnAdd = (Button) itemView.findViewById(R.id.btnAdd);
            btnAdd.setOnClickListener(this);
            txtCartInc.setOnClickListener(this);
            txtCartDec.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {

        }
    }

    public void setExpandIndex(int expandIndex) {
    }

    public boolean isItemExpanded(int position) {
        return true;
    }

    public class VegOnlyViewHolder extends RecyclerView.ViewHolder {
        Switch wtVeg;

        public VegOnlyViewHolder(@NonNull View itemView) {
            super(itemView);
            wtVeg = (Switch) itemView.findViewById(R.id.wtVeg);
            wtVeg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (foodMenuParentListener != null) {
                        foodMenuParentListener.OnVegOnlyClicked();
                    }
                }
            });
        }
    }

    public interface AddItemListener {
        public void onAddClicked(Item item, int parentIndex);

        public void increaseItemCount(Item item, int parentIndex);

        public void decreaseItemCount(Item item, int parentIndex);
    }

    public void addAll(int position, List<Item> objectsToAdd) {
        this.objects.addAll(position, objectsToAdd);
    }

    public void addItem(int position, Item object) {
        this.objects.add(position, object);
    }
    public void removeItem(Object object) {
        this.objects.remove(object);
    }

    public void removeAll(List<Item> objectsToRemove) {
        objects.removeAll(objectsToRemove);
        Log.d("myAdapter","item at first position after remove" + ":"+objects.get(0));
        Log.d("myAdapter","item at second position after remove" + ":"+objects.get(1));
    }

    public Object isItemInList(Item item) {
        for (Object object : objects) {
            if (object instanceof Item && ((Item) object).getId().equals(item.getId())) {
                return object;
            }
        }
        return null;
    }
    }

Following is code in my Fragment to expand collapse RecyclerView

 @Override
        public void OnExpandClick(FoodMenuItem foodMenuItem, int position) {
            if (recyclerViewMenu != null && recyclerViewMenu.getAdapter() != null) {
                recyclerViewMenu.getRecycledViewPool().clear();
                FoodMenuRecyclerAdapter foodMenuRecyclerAdapter = (FoodMenuRecyclerAdapter) recyclerViewMenu.getAdapter();
                foodMenuItem.setExpanded(!foodMenuItem.isExpanded());
                if (foodMenuItem.isExpanded()) {
                    foodMenuRecyclerAdapter.addAll(position + 1, foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeInserted(position, foodMenuItem.getItems().size());

                } else {
                    foodMenuRecyclerAdapter.removeAll(foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeRemoved(position + 1, foodMenuItem.getItems().size());

                }

            }

        }

Following is listener code inside fragment to expand and collapse

public void OnExpandClick(FoodMenuItem foodMenuItem, int position) {
            if (recyclerViewMenu != null && recyclerViewMenu.getAdapter() != null) {
                FoodMenuRecyclerAdapter foodMenuRecyclerAdapter = (FoodMenuRecyclerAdapter) recyclerViewMenu.getAdapter();
                foodMenuItem.setExpanded(!foodMenuItem.isExpanded());
                if (foodMenuItem.isExpanded()) {
                    foodMenuRecyclerAdapter.addAll(position + 1, foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeInserted(position, foodMenuItem.getItems().size());

                } else {
                    foodMenuRecyclerAdapter.removeAll(foodMenuItem.getItems());
                    foodMenuRecyclerAdapter.notifyItemRangeRemoved(position +1 , foodMenuItem.getItems().size());

                }

            }

        }

Above code is throwing exception following is exception stack trace

 java.lang.ClassCastException: com.myapp.android.pojoentities.Item cannot be cast to com.myapp.android.pojoentities.FoodMenuItem
    at com.myapp.android.food.menu.FoodMenuRecyclerAdapter.onBindViewHolder(FoodMenuRecyclerAdapter.java:104)
    at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
    at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
    at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
    at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
    at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
    at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3875)
    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3639)
    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4194)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.support.design.widget.CoordinatorLayout.layoutChild(CoordinatorLayout.java:1183)
    at android.support.design.widget.CoordinatorLayout.onLayoutChild(CoordinatorLayout.java:870)
    at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:889)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at com.myapp.android.custom.FitsSystemWindowsFrameLayout.onLayout(FitsSystemWindowsFrameLayout.java:247)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1231)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
    at android.view.View.layout(View.java:16636)
    at android.view.ViewGroup.layout(ViewGroup.java:5437)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
    at android.view.View.layout(View.java:

Update:

After collapsing first item I have checked log for type of first two items in list found that first two items are of type ParentItem which is FoodMenuItem but when I checked log for getItemViewType for same positions it is returning wrong value somehow

Following are logs

05-28 00:13:47.643 32010-32010/com.myapp.android D/myAdapter: item at first position after remove:com.myapp.android.pojoentities.FoodMenuItem@7fdf002
05-28 00:13:47.643 32010-32010/com.myapp.android D/myAdapter: item at second position after remove:com.myapp.android.pojoentities.FoodMenuItem@9cbfd13
05-28 00:13:47.664 32010-32010/com.myapp.android D/myAdapter: position1:TYPE_FOOD
05-28 00:13:47.678 32010-32010/com.myapp.android D/myAdapter: position2:TYPE_MENU_ITEM

here is sample project for reference