问:
saving CGAL alpha shape surface mesh
I have never used CGAL and have got almost no C/C++ experience. But following
Google I have however managed to compile the example "Alpha_shapes_3"
(\CGAL-4.1-beta1\examples\Alpha_shapes_3) on a Windows 7 64bit machine using
visual studio 2010.

Now if we check the source code for the program "ex_alpha_shapes_3" we
notice that a data file called "bunny_1000" is red where the 3d point
cluster resides.
Now my question is how can I change the source code so that after the alpha
shape is computed for the given points, surface mesh of the alpha shape is
saved/wrote in an external file. It can be simply the list of polygons and
their respective 3D vertices. I guess these polygons will be defining the
surface mesh of the alpha shape. If I can do that I can see the output of
the alpha shape generation program in an external tool I am familiar with.

I know this is very straightforward but I could not figure this out with my
limited knowledge of CGAL.

I know you gueys have the code but I am pasting it again for completion.

```<code>#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Delaunay_triangulation_3.h>
#include <CGAL/Alpha_shape_3.h>

#include <fstream>
#include <list>
#include <cassert>

typedef CGAL::Exact_predicates_inexact_constructions_kernel Gt;

typedef CGAL::Alpha_shape_vertex_base_3<Gt>          Vb;
typedef CGAL::Alpha_shape_cell_base_3<Gt>            Fb;
typedef CGAL::Triangulation_data_structure_3<Vb,Fb>  Tds;
typedef CGAL::Delaunay_triangulation_3<Gt,Tds>       Triangulation_3;
typedef CGAL::Alpha_shape_3<Triangulation_3>         Alpha_shape_3;

typedef Gt::Point_3                                  Point;
typedef Alpha_shape_3::Alpha_iterator               Alpha_iterator;

int main()
{
  std::list<Point> lp;

  //read input
  std::ifstream is("./data/bunny_1000");
  int n;
  is >> n;
  std::cout << "Reading " << n << " points " << std::endl;
  Point p;
  for( ; n>0 ; n--)    {
    is >> p;
    lp.push_back(p);
  }

  // compute alpha shape
  Alpha_shape_3 as(lp.begin(),lp.end());
  std::cout << "Alpha shape computed in REGULARIZED mode by default"
            << std::endl;

  // find optimal alpha value
  Alpha_iterator opt = as.find_optimal_alpha(1);
  std::cout << "Optimal alpha value to get one connected component is "
            <<  *opt    << std::endl;
  as.set_alpha(*opt);
  assert(as.number_of_solid_components() == 1);
  return 0;
}
</code>```

After searching a lot in the internet I found that probably we need to use something like

```<code>std::list<Facet> facets;
alpha_shape.get_alpha_shape_facets
(
  std::back_inserter(facets),Alpha_shape::REGULAR
);
</code>```

But I am still completely clueless how to use this in the above code!

答:
Here is my code, which outputs vtk file for visualization in Paraview.  Comparing with slorior's solutions, no duplicated points are saved in the file. But my code is just for the visualization, if you need to figure out the exterior or interior simplexes, you should modify the code to get these results.</p>

```<code>void writevtk(Alpha_shape_3 &as, const std::string &asfile) {

// http://cgal-discuss.949826.n4.nabble.com/Help-with-filtration-and-filtration-with-alpha-values-td4659524.html#a4659549

std::cout << "Information of the Alpha_Complex:\n";
std::vector<Alpha_shape_3::Cell_handle> cells;
std::vector<Alpha_shape_3::Facet> facets;
std::vector<Alpha_shape_3::Edge> edges;
// tetrahedron = cell, they should be the interior, it is inside the 3D space
as.get_alpha_shape_cells(std::back_inserter(cells), Alpha_shape_3::INTERIOR);
// triangles
// for the visualiization, don't need regular because tetrahedron will show it
//as.get_alpha_shape_facets(std::back_inserter(facets), Alpha_shape_3::REGULAR);
as.get_alpha_shape_facets(std::back_inserter(facets), Alpha_shape_3::SINGULAR);
// edges
as.get_alpha_shape_edges(std::back_inserter(edges), Alpha_shape_3::SINGULAR);

std::cout << "The alpha-complex has : " << std::endl;
std::cout << cells.size() << " cells as tetrahedrons" << std::endl;
std::cout << facets.size() << " triangles" << std::endl;
std::cout << edges.size() << " edges" << std::endl;

size_t tetra_num, tri_num, edge_num;
tetra_num = cells.size();
tri_num = facets.size();
edge_num = edges.size();

// vertices: points <-> id
std::map<Point, size_t> points;
size_t index = 0;
// finite_.. is from DT class
for (auto v_it = as.finite_vertices_begin(); v_it != as.finite_vertices_end(); v_it++) {
    points[v_it->point()] = index;
    index++;
}

// write
std::ofstream of(asfile);
of << "# vtk DataFile Version 2.0\n\nASCII\nDATASET UNSTRUCTURED_GRID\n\n";
of << "POINTS " << index << " float\n";
for (auto v_it = as.finite_vertices_begin(); v_it != as.finite_vertices_end(); v_it++) {
    of << v_it->point() << std::endl;
}

of << std::endl;
of << "CELLS " << tetra_num + tri_num + edge_num << " " << 5 * tetra_num + 4 * tri_num + 3 * edge_num << std::endl;
for (auto cell:cells) {
    size_t v0 = points.find(cell->vertex(0)->point())->second;
    size_t v1 = points.find(cell->vertex(1)->point())->second;
    size_t v2 = points.find(cell->vertex(2)->point())->second;
    size_t v3 = points.find(cell->vertex(3)->point())->second;
    of << "4 " << v0 << " " << v1 << " " << v2 << " " << v3 << std::endl;
}
// https://doc.cgal.org/latest/TDS_3/classTriangulationDataStructure__3.html#ad6a20b45e66dfb690bfcdb8438e9fcae
for (auto tri_it = facets.begin(); tri_it != facets.end(); ++tri_it) {
    of << "3 ";
    auto tmp_tetra = tri_it->first;
    for (int i = 0; i < 4; i++) {
        if (i != tri_it->second) {
            of << points.find(tmp_tetra->vertex(i)->point())->second << " ";
        }
    }
    of << std::endl;
}
// https://doc.cgal.org/latest/TDS_3/classTriangulationDataStructure__3.html#af31db7673a6d7d28c0bb90a3115ac695
for (auto e : edges) {
    of << "2 ";
    auto tmp_tetra = e.get<0>();
    int p1, p2;
    p1 = e.get<1>();
    p2 = e.get<2>();
    of << points.find(tmp_tetra->vertex(p1)->point())->second << " "
       << points.find(tmp_tetra->vertex(p2)->point())->second << std::endl;
}

of << std::endl;
of << "CELL_TYPES " << tetra_num + tri_num + edge_num << std::endl;
for (int i = 0; i < tetra_num; i++) {
    of << "10 ";
}
for (int i = 0; i < tri_num; i++) {
    of << "5 ";
}
for (int i = 0; i < edge_num; i++) {
         of << "3 ";
}
of << std::endl;
of.close();
}
</code>```

Title: saving CGAL alpha shape surface mesh

Body:
I have never used CGAL and have got almost no C/C++ experience. But following
Google I have however managed to compile the example "Alpha_shapes_3"
(\CGAL-4.1-beta1\examples\Alpha_shapes_3) on a Windows 7 64bit machine using
visual studio 2010.

Now if we check the source code for the program "ex_alpha_shapes_3" we
notice that a data file called "bunny_1000" is red where the 3d point
cluster resides.
Now my question is how can I change the source code so that after the alpha
shape is computed for the given points, surface mesh of the alpha shape is
saved/wrote in an external file. It can be simply the list of polygons and
their respective 3D vertices. I guess these polygons will be defining the
surface mesh of the alpha shape. If I can do that I can see the output of
the alpha shape generation program in an external tool I am familiar with.

I know this is very straightforward but I could not figure this out with my
limited knowledge of CGAL.

I know you gueys have the code but I am pasting it again for completion.

#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Delaunay_triangulation_3.h>
#include <CGAL/Alpha_shape_3.h>

#include <fstream>
#include <list>
#include <cassert>

typedef CGAL::Exact_predicates_inexact_constructions_kernel Gt;

typedef CGAL::Alpha_shape_vertex_base_3<Gt>          Vb;
typedef CGAL::Alpha_shape_cell_base_3<Gt>            Fb;
typedef CGAL::Triangulation_data_structure_3<Vb,Fb>  Tds;
typedef CGAL::Delaunay_triangulation_3<Gt,Tds>       Triangulation_3;
typedef CGAL::Alpha_shape_3<Triangulation_3>         Alpha_shape_3;

typedef Gt::Point_3                                  Point;
typedef Alpha_shape_3::Alpha_iterator               Alpha_iterator;

int main()
{
  std::list<Point> lp;

  //read input
  std::ifstream is("./data/bunny_1000");
  int n;
  is >> n;
  std::cout << "Reading " << n << " points " << std::endl;
  Point p;
  for( ; n>0 ; n--)    {
    is >> p;
    lp.push_back(p);
  }

  // compute alpha shape
  Alpha_shape_3 as(lp.begin(),lp.end());
  std::cout << "Alpha shape computed in REGULARIZED mode by default"
            << std::endl;

  // find optimal alpha value
  Alpha_iterator opt = as.find_optimal_alpha(1);
  std::cout << "Optimal alpha value to get one connected component is "
            <<  *opt    << std::endl;
  as.set_alpha(*opt);
  assert(as.number_of_solid_components() == 1);
  return 0;
}

After searching a lot in the internet I found that probably we need to use something like

std::list<Facet> facets;
alpha_shape.get_alpha_shape_facets
(
  std::back_inserter(facets),Alpha_shape::REGULAR
);

But I am still completely clueless how to use this in the above code!

Body:
Here is my code, which outputs vtk file for visualization in Paraview.  Comparing with slorior's solutions, no duplicated points are saved in the file. But my code is just for the visualization, if you need to figure out the exterior or interior simplexes, you should modify the code to get these results.

void writevtk(Alpha_shape_3 &as, const std::string &asfile) {

// http://cgal-discuss.949826.n4.nabble.com/Help-with-filtration-and-filtration-with-alpha-values-td4659524.html#a4659549

std::cout << "Information of the Alpha_Complex:\n";
std::vector<Alpha_shape_3::Cell_handle> cells;
std::vector<Alpha_shape_3::Facet> facets;
std::vector<Alpha_shape_3::Edge> edges;
// tetrahedron = cell, they should be the interior, it is inside the 3D space
as.get_alpha_shape_cells(std::back_inserter(cells), Alpha_shape_3::INTERIOR);
// triangles
// for the visualiization, don't need regular because tetrahedron will show it
//as.get_alpha_shape_facets(std::back_inserter(facets), Alpha_shape_3::REGULAR);
as.get_alpha_shape_facets(std::back_inserter(facets), Alpha_shape_3::SINGULAR);
// edges
as.get_alpha_shape_edges(std::back_inserter(edges), Alpha_shape_3::SINGULAR);

std::cout << "The alpha-complex has : " << std::endl;
std::cout << cells.size() << " cells as tetrahedrons" << std::endl;
std::cout << facets.size() << " triangles" << std::endl;
std::cout << edges.size() << " edges" << std::endl;

size_t tetra_num, tri_num, edge_num;
tetra_num = cells.size();
tri_num = facets.size();
edge_num = edges.size();

// vertices: points <-> id
std::map<Point, size_t> points;
size_t index = 0;
// finite_.. is from DT class
for (auto v_it = as.finite_vertices_begin(); v_it != as.finite_vertices_end(); v_it++) {
    points[v_it->point()] = index;
    index++;
}

// write
std::ofstream of(asfile);
of << "# vtk DataFile Version 2.0\n\nASCII\nDATASET UNSTRUCTURED_GRID\n\n";
of << "POINTS " << index << " float\n";
for (auto v_it = as.finite_vertices_begin(); v_it != as.finite_vertices_end(); v_it++) {
    of << v_it->point() << std::endl;
}

of << std::endl;
of << "CELLS " << tetra_num + tri_num + edge_num << " " << 5 * tetra_num + 4 * tri_num + 3 * edge_num << std::endl;
for (auto cell:cells) {
    size_t v0 = points.find(cell->vertex(0)->point())->second;
    size_t v1 = points.find(cell->vertex(1)->point())->second;
    size_t v2 = points.find(cell->vertex(2)->point())->second;
    size_t v3 = points.find(cell->vertex(3)->point())->second;
    of << "4 " << v0 << " " << v1 << " " << v2 << " " << v3 << std::endl;
}
// https://doc.cgal.org/latest/TDS_3/classTriangulationDataStructure__3.html#ad6a20b45e66dfb690bfcdb8438e9fcae
for (auto tri_it = facets.begin(); tri_it != facets.end(); ++tri_it) {
    of << "3 ";
    auto tmp_tetra = tri_it->first;
    for (int i = 0; i < 4; i++) {
        if (i != tri_it->second) {
            of << points.find(tmp_tetra->vertex(i)->point())->second << " ";
        }
    }
    of << std::endl;
}
// https://doc.cgal.org/latest/TDS_3/classTriangulationDataStructure__3.html#af31db7673a6d7d28c0bb90a3115ac695
for (auto e : edges) {
    of << "2 ";
    auto tmp_tetra = e.get<0>();
    int p1, p2;
    p1 = e.get<1>();
    p2 = e.get<2>();
    of << points.find(tmp_tetra->vertex(p1)->point())->second << " "
       << points.find(tmp_tetra->vertex(p2)->point())->second << std::endl;
}

of << std::endl;
of << "CELL_TYPES " << tetra_num + tri_num + edge_num << std::endl;
for (int i = 0; i < tetra_num; i++) {
    of << "10 ";
}
for (int i = 0; i < tri_num; i++) {
    of << "5 ";
}
for (int i = 0; i < edge_num; i++) {
         of << "3 ";
}
of << std::endl;
of.close();
}


来源: stackexchange

问:
Failed optional dependency /chokidar/fsevents:
I am installing "cordova-plugin-geolocation" via npm but "cordova-plugin-geolocation" is unable to install. I am seeing the following warnings:

npm WARN optional Skipping failed optional dependency /chokidar/fsevents:

npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.14

Is there any possible solution?

答:
Make .npmignore with

node_modules
chokidar/fsevents
 inside

ContentLicense: CC BY-SA 3.0


问:
how to write a recursive function that would return the minimum values in a BST?
I am trying to write a recursive fucntion that will return the
minimum value in a binary search tree.

```<code>int RecursiveFindMin(Tree t) {
  if (t==NULL)
    return -1;
  else {
    if (t!=NULL)
        RecursiveFindMin(t->left);
  }

  return t->val;
}
</code>```

I expect to get the minimum value in the BST

Instead, I am getting the second smallest result, most of the time!
I am not very good at recursive functions and I would appreciate the
help!

答:
When you make recursive calls to your function, you discard the return value.  So the recursion is effectively doing nothing.  All you're doing is returning the value of the first node passed in.

You're also not using the right exit condition.  You want to stop not when the current node is NULL (because what can you do with it then?) but when the left node is NULL.  Then the value you want is in that node.

So change the condition to check the left node, and return the value of the recursive call:

```<code>int RecursiveFindMin(Tree t) {
  if (t->left==NULL)
    return t->val;
  else {
    return RecursiveFindMin(t->left);
  }
}
</code>```

Body:
I am trying to write a recursive fucntion that will return the
minimum value in a binary search tree.

int RecursiveFindMin(Tree t) {
  if (t==NULL)
    return -1;
  else {
    if (t!=NULL)
        RecursiveFindMin(t->left);
  }

  return t->val;
}

I expect to get the minimum value in the BST

Instead, I am getting the second smallest result, most of the time!
I am not very good at recursive functions and I would appreciate the
help!

Body:
When you make recursive calls to your function, you discard the return value.  So the recursion is effectively doing nothing.  All you're doing is returning the value of the first node passed in.

You're also not using the right exit condition.  You want to stop not when the current node is NULL (because what can you do with it then?) but when the left node is NULL.  Then the value you want is in that node.

So change the condition to check the left node, and return the value of the recursive call:

int RecursiveFindMin(Tree t) {
  if (t->left==NULL)
    return t->val;
  else {
    return RecursiveFindMin(t->left);
  }
}


问:
Adapting checking for member functions existence to function arguments
I've been trying to adapt this
solution for enabling the existence of ordinary (non-member) functions.
In my case, I have a lot of global string-utility-type functions that take any string type T such that T has has, say, a char const* c_str() const member function.

The goal is to eliminate weird compiler error messages if the user attempt to pass some type T that has no c_str() member function, i.e., rather than the compiler saying, "c_str(): no such member function", I'd rather the compiler say, "foo(T&): no such function" where foo is the global function.

Here is the adapted code:

```<code>template<bool B,typename T = void>
struct enable_if {
  typedef T type;
};

template<typename T>
struct enable_if<false,T> {
};

//
// This macro is adapted from the linked-to question -- this part works fine.
//
#define DECL_HAS_MEM_FN(FN_NAME)                                            \
  template<class ClassType,typename MemFnSig>                               \
  struct has_##FN_NAME##_type {                                             \
    typedef char yes[1];                                                    \
    typedef char no[2];                                                     \
    template<typename T,T> struct type_check;                               \
    template<class T> static yes& has( type_check<MemFnSig,&T::FN_NAME>* ); \
    template<class T> static no&  has( ... );                               \
    enum { value = sizeof( has<ClassType>(0) ) == sizeof( yes ) };          \
  }

// Declare an instance of the above type that checks for "c_str()".
DECL_HAS_MEM_FN(c_str);

// Define another macro just to make life easier.
#define has_c_str(STRINGTYPE) \
  has_c_str_type<STRINGTYPE,char const* (STRINGTYPE::*)() const>::value

//
// A "ValidatedStringType" is a StringType that uses the above machinery to ensure that
// StringType has a c_str() member function
//
template<class StringType>
struct ValidatedStringType {
  typedef typename enable_if<has_c_str(StringType),StringType>::type type;
};

// Here's the global function where I want to accept only validated StringTypes.
template<class StringType>
void f( typename ValidatedStringType<StringType>::type const& s ) {
}

struct S { // Class for testing that has c_str().
  char const* c_str() const {
    return 0;
  }
};

struct N { // Class for testing that does not have c_str().
};

using namespace std;

int main() {
  S s;
  N n;
  cout << has_c_str(S) << endl; // correctly prints '1'
  cout << has_c_str(N) << endl; // correctly prints '0'
  f( s ); // error: no matching function for call to 'f(S&)'
}
</code>```

However, as shown above, the compiler doesn't "see" the f(S&) -- why not?

答:
I can't answer your question ("why not?") but I can provide a work-around.  But man, it's ugly.  You end up defining a structure and a function for every function:

```<code>template<class StringType, class T = typename ValidatedStringType<StringType>::type>
struct f_helper {
  void operator()( T const& s ) {
      // Put the contents of f() here
  }
};

template<class StringType>
void f(StringType const &s) {
  f_helper<StringType>()( s );
}
</code>```

I'm sure there's some preprocessing magic you could write to eliminate some of the boilerplate, but it would also be quite ugly:

```<code>#define DECL_VALIDATED_FUNC( RetType, name, Validator, contents ) \
  template<class StringType, class T = typename Validator<StringType>::type> \
  struct name ## _helper { \
    RetType operator()( T const& s ) contents \
  }; \
  \
  template<class StringType> \
  RetType name(StringType const& s) { \
     name ## _helper<StringType>()( s ); \
}

DECL_VALIDATED_FUNC( void, f, ValidatedStringType, {
   // put contents of f() here
}) // note the closing parenthesis
</code>```

Unfortunately, you can't specify default template arguments to free functions, or else you could have done:

```<code>template<class StringType, class T = typename ValidatedStringType<StringType>::type>
void f( T const& s ) {}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've been trying to adapt this
solution for enabling the existence of ordinary (non-member) functions.
In my case, I have a lot of global string-utility-type functions that take any string type T such that T has has, say, a char const* c_str() const member function.

The goal is to eliminate weird compiler error messages if the user attempt to pass some type T that has no c_str() member function, i.e., rather than the compiler saying, "c_str(): no such member function", I'd rather the compiler say, "foo(T&): no such function" where foo is the global function.

Here is the adapted code:

template<bool B,typename T = void>
struct enable_if {
  typedef T type;
};

template<typename T>
struct enable_if<false,T> {
};

//
// This macro is adapted from the linked-to question -- this part works fine.
//
#define DECL_HAS_MEM_FN(FN_NAME)                                            \
  template<class ClassType,typename MemFnSig>                               \
  struct has_##FN_NAME##_type {                                             \
    typedef char yes[1];                                                    \
    typedef char no[2];                                                     \
    template<typename T,T> struct type_check;                               \
    template<class T> static yes& has( type_check<MemFnSig,&T::FN_NAME>* ); \
    template<class T> static no&  has( ... );                               \
    enum { value = sizeof( has<ClassType>(0) ) == sizeof( yes ) };          \
  }

// Declare an instance of the above type that checks for "c_str()".
DECL_HAS_MEM_FN(c_str);

// Define another macro just to make life easier.
#define has_c_str(STRINGTYPE) \
  has_c_str_type<STRINGTYPE,char const* (STRINGTYPE::*)() const>::value

//
// A "ValidatedStringType" is a StringType that uses the above machinery to ensure that
// StringType has a c_str() member function
//
template<class StringType>
struct ValidatedStringType {
  typedef typename enable_if<has_c_str(StringType),StringType>::type type;
};

// Here's the global function where I want to accept only validated StringTypes.
template<class StringType>
void f( typename ValidatedStringType<StringType>::type const& s ) {
}

struct S { // Class for testing that has c_str().
  char const* c_str() const {
    return 0;
  }
};

struct N { // Class for testing that does not have c_str().
};

using namespace std;

int main() {
  S s;
  N n;
  cout << has_c_str(S) << endl; // correctly prints '1'
  cout << has_c_str(N) << endl; // correctly prints '0'
  f( s ); // error: no matching function for call to 'f(S&)'
}

However, as shown above, the compiler doesn't "see" the f(S&) -- why not?

Body:
I can't answer your question ("why not?") but I can provide a work-around.  But man, it's ugly.  You end up defining a structure and a function for every function:

template<class StringType, class T = typename ValidatedStringType<StringType>::type>
struct f_helper {
  void operator()( T const& s ) {
      // Put the contents of f() here
  }
};

template<class StringType>
void f(StringType const &s) {
  f_helper<StringType>()( s );
}

I'm sure there's some preprocessing magic you could write to eliminate some of the boilerplate, but it would also be quite ugly:

#define DECL_VALIDATED_FUNC( RetType, name, Validator, contents ) \
  template<class StringType, class T = typename Validator<StringType>::type> \
  struct name ## _helper { \
    RetType operator()( T const& s ) contents \
  }; \
  \
  template<class StringType> \
  RetType name(StringType const& s) { \
     name ## _helper<StringType>()( s ); \
}

DECL_VALIDATED_FUNC( void, f, ValidatedStringType, {
   // put contents of f() here
}) // note the closing parenthesis

Unfortunately, you can't specify default template arguments to free functions, or else you could have done:

template<class StringType, class T = typename ValidatedStringType<StringType>::type>
void f( T const& s ) {}


问:
HashSet.contains is returning false while it should not
I'm trying to learn Java, and I reached the HashSet part, Long story short I'm testing the contain method.

```<code>public static void main(String[] args) {
    HashSet<Integer> firstSet = new HashSet<>();
    firstSet.add(3);

    HashSet<Integer> secondSet = new HashSet<>();
    secondSet.add(3);

    boolean var = firstSet.contains(secondSet);

    System.out.println(var);

}
</code>```

I believe this piece of  code should return true, while it is returning false. Any help!

答:
Let's look at the docs for contains:

Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

Since we all know that there is no null values here, we can say that contains will return true if o.equals(e).

o is the parameter you pass to contains, which is a HashSet. e is the element of the first set, which should be an Integer. Since Integer and HashSet are unrelated types, it is very unlikely that they will equal.

You seem to have made a logical error here. To check if a set is a superset of another, call containsAll instead:

Returns true if this collection contains all of the elements in the specified collection.

Body:
I'm trying to learn Java, and I reached the HashSet part, Long story short I'm testing the contain method.

public static void main(String[] args) {
    HashSet<Integer> firstSet = new HashSet<>();
    firstSet.add(3);

    HashSet<Integer> secondSet = new HashSet<>();
    secondSet.add(3);

    boolean var = firstSet.contains(secondSet);

    System.out.println(var);

}

I believe this piece of  code should return true, while it is returning false. Any help!


问:
Is there automatic load balancing in CrateDB?
I am currently evaluating CrateDB and came up this question. I know that CrateDB proudly claims itself to be a no-config database. So, is there automatic load balancing? Or is it possible to add a load balancer before the dabase?

After browsing the web for a bit I found this howto indicating there is no automatic load balancing in CrateDB. Is that correct?

答:
yes, load balancing happens automatically:

the client libraries can be configured with multiple nodes and then do round-robin scheduling

if you pass a query to a node - the execution of the query will happen distributed in the cluster anyhow.


问:
Get differences between matrix values within one unit
I have a list of lists nxm and am trying to take the difference between each value i and every other value j within one unit and add to a new list. How would I be able to do this in Python?

答:
Let's define a test matrix and a function to get all neighbours of the cell:

```<code>m = [[i for i in range(10)] for i in range(10)]

# Size of "board"
X = len(m)
Y = len(m[0])

neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)
                               for y2 in range(y-1, y+2)
                               if (-1 < x <= X and
                                   -1 < y <= Y and
                                   (x != x2 or y != y2) and
                                   (0 <= x2 <= X) and
                                   (0 <= y2 <= Y))]
</code>```

Then for calculating the differences:

```<code>def get_differences(point, neigh, m):
    px, py = point
    return [m[px][py] - m[nx][ny] for nx, ny in neigh]
</code>```

And test both for a single point:

```<code>point = (1,1)
print('Neighbours: ', neighbors(*(point)))
print('Differences: ')
print(get_differences(point, neighbors(*(point)), m))
</code>```

The part with this elegant neighbours function is taken from this post.

Body:
Let's define a test matrix and a function to get all neighbours of the cell:

m = [[i for i in range(10)] for i in range(10)]

# Size of "board"
X = len(m)
Y = len(m[0])

neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)
                               for y2 in range(y-1, y+2)
                               if (-1 < x <= X and
                                   -1 < y <= Y and
                                   (x != x2 or y != y2) and
                                   (0 <= x2 <= X) and
                                   (0 <= y2 <= Y))]

Then for calculating the differences:

def get_differences(point, neigh, m):
    px, py = point
    return [m[px][py] - m[nx][ny] for nx, ny in neigh]

And test both for a single point:

point = (1,1)
print('Neighbours: ', neighbors(*(point)))
print('Differences: ')
print(get_differences(point, neighbors(*(point)), m))

The part with this elegant neighbours function is taken from this post.


问:
Correct syntax for a async/await function?
I've defined a resolversMap and I need to use async/await for that as I'm doing a DB request. I'm failing with the correct syntax:

```<code>const resolvers = {
  Mutation: {
    signinUser: (root, { username, password }) => {
      const db = DB.getDB()
      const Users = db.collection('users')
      const user = Users.findOne({ username: username })
    }
  }
}
</code>```

I tried this:

```<code>const resolvers = {
  Mutation: {
    async signinUser: (root, { username, password }) => {
      const db = DB.getDB()
      const Users = db.collection('users')
      const user = await Users.findOne({ username: username })
    }
  }
}
</code>```

Update

It's working if I define the function like this:

```<code>async signinUser (obj, args) {}
</code>```

But what is the difference between this and signinUser: (obj, args) => {}?

答:
Your syntax is close, but you actually need to declare async in front of the arrow function:

```<code>const resolvers = {
  Mutation: {
    signinUser: async (root, { username, password }) => {
      const db = DB.getDB()
      const Users = db.collection('users')
      const user = await Users.findOne({ username: username })
    }
  }
}
</code>```

Regarding your question as to why async signinUser (obj, args) {} works, this is an ES6 shorthand for the following:

```<code>signinUser: async function signinUser(obj, args) {}
</code>```

See this article on Object Initializers (specifically, take a look at the new, ES2015 syntax)

Body:
I've defined a resolversMap and I need to use async/await for that as I'm doing a DB request. I'm failing with the correct syntax:

const resolvers = {
  Mutation: {
    signinUser: (root, { username, password }) => {
      const db = DB.getDB()
      const Users = db.collection('users')
      const user = Users.findOne({ username: username })
    }
  }
}

I tried this:

const resolvers = {
  Mutation: {
    async signinUser: (root, { username, password }) => {
      const db = DB.getDB()
      const Users = db.collection('users')
      const user = await Users.findOne({ username: username })
    }
  }
}

Update

It's working if I define the function like this:

async signinUser (obj, args) {}

But what is the difference between this and signinUser: (obj, args) => {}?

Body:
Your syntax is close, but you actually need to declare async in front of the arrow function:

const resolvers = {
  Mutation: {
    signinUser: async (root, { username, password }) => {
      const db = DB.getDB()
      const Users = db.collection('users')
      const user = await Users.findOne({ username: username })
    }
  }
}

Regarding your question as to why async signinUser (obj, args) {} works, this is an ES6 shorthand for the following:

signinUser: async function signinUser(obj, args) {}

See this article on Object Initializers (specifically, take a look at the new, ES2015 syntax)


问:
Unable to compile a project due to duplicate class definitions in Kryonet
```<code>Caused by: com.android.dex.DexException: Multiple dex files define Lcom/esotericsoftware/reflectasm/MethodAccess;
</code>```

The above error is preventing my Android project from building, I'm using Kryonet and including it in my build.gradle as a dependency below.

```<code>dependancies{
    implementation group: 'kryonet', name: 'kryonet', version: '2.21'
    implementation group: 'com.esotericsoftware', name: 'kryo', version: '4.0.1'
</code>```

It seems both Kryo and Kryonet include this class, but I don't know how to go about resolving the issue, I can't simply remove Kryo because then I lose access to the serialization libraries.

答:
If you run gradle app:dependencies you can notice that the dependencies tree is:

```<code>+--- kryonet:kryonet:2.21
|    +--- com.esotericsoftware.reflectasm:reflectasm:1.07
|    +--- com.esotericsoftware.minlog:minlog:1.2
|    \--- org.objenesis:objenesis:2.1 -> 2.5.1
+--- com.esotericsoftware:kryo:4.0.1
|    +--- com.esotericsoftware:reflectasm:1.11.3
|    |    \--- org.ow2.asm:asm:5.0.4
|    +--- com.esotericsoftware:minlog:1.3.0
|    \--- org.objenesis:objenesis:2.5.1
</code>```

They have exactly the same dependencies, but Kyro depends on newer versions.
So I would simply remove the dependency on kyronet

```<code>implementation group: 'kryonet', name: 'kryonet', version: '2.21'
</code>```

EDIT

This should solve your problem and let you keep both of the libraries

```<code>implementation (group: 'kryonet', name: 'kryonet', version: '2.21') {
    exclude group: 'com.esotericsoftware.reflectasm', module: 'reflectasm'
    exclude group: 'com.esotericsoftware.minlog', module: 'minlog'
}
implementation group: 'com.esotericsoftware', name: 'kryo', version: '4.0.1'
</code>```

Body:
Caused by: com.android.dex.DexException: Multiple dex files define Lcom/esotericsoftware/reflectasm/MethodAccess;

The above error is preventing my Android project from building, I'm using Kryonet and including it in my build.gradle as a dependency below.

dependancies{
    implementation group: 'kryonet', name: 'kryonet', version: '2.21'
    implementation group: 'com.esotericsoftware', name: 'kryo', version: '4.0.1'

It seems both Kryo and Kryonet include this class, but I don't know how to go about resolving the issue, I can't simply remove Kryo because then I lose access to the serialization libraries.

Body:
If you run gradle app:dependencies you can notice that the dependencies tree is:

+--- kryonet:kryonet:2.21
|    +--- com.esotericsoftware.reflectasm:reflectasm:1.07
|    +--- com.esotericsoftware.minlog:minlog:1.2
|    \--- org.objenesis:objenesis:2.1 -> 2.5.1
+--- com.esotericsoftware:kryo:4.0.1
|    +--- com.esotericsoftware:reflectasm:1.11.3
|    |    \--- org.ow2.asm:asm:5.0.4
|    +--- com.esotericsoftware:minlog:1.3.0
|    \--- org.objenesis:objenesis:2.5.1

They have exactly the same dependencies, but Kyro depends on newer versions.
So I would simply remove the dependency on kyronet

implementation group: 'kryonet', name: 'kryonet', version: '2.21'

EDIT

This should solve your problem and let you keep both of the libraries

implementation (group: 'kryonet', name: 'kryonet', version: '2.21') {
    exclude group: 'com.esotericsoftware.reflectasm', module: 'reflectasm'
    exclude group: 'com.esotericsoftware.minlog', module: 'minlog'
}
implementation group: 'com.esotericsoftware', name: 'kryo', version: '4.0.1'


问:
NULL radio button value
On line 13 of my code, I am getting a NULL $NaN value. If I replace $_POST['amount'] with static integer, the code POST the correct value. But trying to add a little functionality, now I can't get data to pass???

http://i40.tinypic.com/34gxauw.png

```<code><div id="container">
<?php
    require_once('stripe-php/lib/Stripe.php');
    $stripe = array(
    'secret_key' => 'sk_07C5ukIdqxyDGFqIKB8f7TXqGGyQt',
    'publishable_key' => 'pk_07C58BHnzuFYQr9AUoZD6SCLiwANw'
    );
    Stripe::setApiKey($stripe['secret_key']);

    if ($_POST) {
        $charge = Stripe_Charge::create(array(
            'card' => $_POST['stripeToken'],
            'amount' => $_POST['amount'],
            'currency' => 'usd'
        ));
        var_dump($_POST['amount']);
        $quotes = array(
            "Thank you for your purchase!",
            "Enjoy your experience with with us!"
        );

        echo "<h1>Here's your quote!</h1>";
        echo "<h2>".$quotes[array_rand($quotes)]."</h2>";
    }
    else {
?>

    <h2>TPC Holdings</h2>
    <h3>Select your campaign package!!</h3>

    <form>
        <fieldset>
            <legend>Select your package</legend>
            <p>
                <label>Select your package</label>
                <input type = "radio"
                        name = "amount[]"
                        id = "sizeSmall"
                        value = "50"
                        checked = "checked" />
                <label for = "sizeSmall">$50.00</label>

                <input type = "radio"
                        name = "amount[]"
                        id = "sizeMed"
                        value = "75" />
                <label for = "sizeMed">$75.00</label>

                <input type = "radio"
                        name = "amount[]"
                        id = "sizeLarge"
                        value = "large" />
                <label for = "sizeLarge">$100.00</label>
           </p>
       </fieldset>
    </form>

    <form action="paybill.php" method="post">
        <script src="https://button.stripe.com/v1/button.js"
             class="stripe-button"
             data-key="<?php echo $stripe['publishable_key']; ?>"
             data-amount="<?php echo $d_charge; ?>"
             data-description="TPC purchase"
             data-label="Buy"></script>
    </form>

<?php
  }
?>

</div><!-- #container -->
</code>```

答: You NAN issue is coming from your value="large".  It should be value="100" or whatever value you need it to be.  I can only assume, how the value is handled, that your handler is expecting a number and not a string.

Title: NULL radio button value

Body:
On line 13 of my code, I am getting a NULL $NaN value. If I replace $_POST['amount'] with static integer, the code POST the correct value. But trying to add a little functionality, now I can't get data to pass???

http://i40.tinypic.com/34gxauw.png

<?php
    require_once('stripe-php/lib/Stripe.php');
    $stripe = array(
    'secret_key' => 'sk_07C5ukIdqxyDGFqIKB8f7TXqGGyQt',
    'publishable_key' => 'pk_07C58BHnzuFYQr9AUoZD6SCLiwANw'
    );
    Stripe::setApiKey($stripe['secret_key']);

    if ($_POST) {
        $charge = Stripe_Charge::create(array(
            'card' => $_POST['stripeToken'],
            'amount' => $_POST['amount'],
            'currency' => 'usd'
        ));
        var_dump($_POST['amount']);
        $quotes = array(
            "Thank you for your purchase!",
            "Enjoy your experience with with us!"
        );

        echo "
Here's your quote!
";
        echo "
".$quotes[array_rand($quotes)]."
";
    }
    else {
?>

TPC Holdings

Select your campaign package!!

    <form>
        <fieldset>
            <legend>Select your package</legend>

                Select your package
                <input type = "radio"
                        name = "amount[]"
                        id = "sizeSmall"
                        value = "50"
                        checked = "checked" />
                $50.00

                <input type = "radio"
                        name = "amount[]"
                        id = "sizeMed"
                        value = "75" />
                $75.00

                <input type = "radio"
                        name = "amount[]"
                        id = "sizeLarge"
                        value = "large" />
                $100.00

       </fieldset>
    </form>

    <form action="paybill.php" method="post">

    </form>

<?php
  }
?>


答:
You are returning every left node value. So finally it returns the root value. You should find the leftmost node and fixed that value as the minimum one.

```<code>const int kInf = 100000000;
int RecursiveFindMin(Tree t) {
    if (t == NULL) return kInf;
    int v = RecursiveFindMin(t->left);
    return v == kInf? t->val : v;
}
</code>```

I have used kInf for a value not present in the tree.

Title: how to write a recursive function that would return the minimum values in a BST?

Body:
You are returning every left node value. So finally it returns the root value. You should find the leftmost node and fixed that value as the minimum one.

const int kInf = 100000000;
int RecursiveFindMin(Tree t) {
    if (t == NULL) return kInf;
    int v = RecursiveFindMin(t->left);
    return v == kInf? t->val : v;
}

I have used kInf for a value not present in the tree.


问:
Creating arrays dynamically using PHP
Hey folks, please lend a hand to a PHP beginner. I'm trying to put a load of dynamically created variabled into an array to re-read later, reason is a SOAP message sent is a mess and im trying to create a less complicated array:

```<code>$placea = "place a";
$placeb = "place b";

$myarray = array();

echo "```";
print_r($myarray);
echo "```";
</code>```

what i want to be able to do:

```<code>Array
(
    [0] => [Place A] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 001
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 002
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )    Array
(
    [1] => [Place B] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 101
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 102
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )

)
</code>```

how would i write that out in php? sorry if its bleek and/or the array structure is incorrect

答:
If you want to have a 'less complicated' array, you have a two arrays, one fore place a and one for place b and then merge them using array_merger() http://www.php.net/manual/en/function.array-merge.php.

Study up on the array functions control structures in the manual. Many different ways of achieving bloated arrays uglying up your code.

Title: Creating arrays dynamically using PHP

Body:
Hey folks, please lend a hand to a PHP beginner. I'm trying to put a load of dynamically created variabled into an array to re-read later, reason is a SOAP message sent is a mess and im trying to create a less complicated array:

$placea = "place a";
$placeb = "place b";

$myarray = array();

echo "
";
print_r($myarray);
echo "
";

what i want to be able to do:

Array
(
    [0] => [Place A] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 001
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 002
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )    Array
(
    [1] => [Place B] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 101
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 102
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )

)

how would i write that out in php? sorry if its bleek and/or the array structure is incorrect


问:
What is the best way to create and populate a numbers table?
I've seen many different ways to create and populate a numbers table.  However, what is the best way to create and populate one?  With "best" being defined from most to least important:

Table created with optimal indexing

rows generated fastest

simple code used to create and populate

If you don't know what a numbers table is, look here: Why should I consider using an auxiliary numbers table?

答:
I know this thread is old and answered, but there is a way to squeeze a little extra performance out of Method 7:

Instead of this (essentially method 7 but with some ease of use polish):

```<code>DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM sys.objects s1       --use sys.columns if you don't get enough rows returned to generate all the numbers you need
    CROSS JOIN sys.objects s2 --use sys.co
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'
</code>```

Try this:

```<code>DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM        (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T32]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T64]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T128]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T256]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T512]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T1024]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2048]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4096]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8192]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16384]
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'
</code>```

On my server this takes ~10 ms as opposed to the ~16-20 ms when selecting from sys.objects.  It also has the added benefit of not being dependent on how many objects are in sys.objects.  While it's pretty safe, it's technically a dependency and the other one goes faster anyway.  I think the speed boost is down to using BITs if you change:

```<code>DECLARE @BIT AS BIT = 0
</code>```

to:

```<code>DECLARE @BIT AS BIGINT = 0
</code>```

It adds ~8-10 ms to the total time on my server.  That said, when you scale up to 1,000,000 records BIT vs BIGINT doesn't appreciably affect my query anymore, but it still runs around ~680ms vs ~730ms from sys.objects.

Body:
I know this thread is old and answered, but there is a way to squeeze a little extra performance out of Method 7:

Instead of this (essentially method 7 but with some ease of use polish):

DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM sys.objects s1       --use sys.columns if you don't get enough rows returned to generate all the numbers you need
    CROSS JOIN sys.objects s2 --use sys.co
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'

Try this:

DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM        (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T32]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T64]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T128]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T256]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T512]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T1024]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2048]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4096]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8192]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16384]
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'

On my server this takes ~10 ms as opposed to the ~16-20 ms when selecting from sys.objects.  It also has the added benefit of not being dependent on how many objects are in sys.objects.  While it's pretty safe, it's technically a dependency and the other one goes faster anyway.  I think the speed boost is down to using BITs if you change:

DECLARE @BIT AS BIT = 0

to:

DECLARE @BIT AS BIGINT = 0

It adds ~8-10 ms to the total time on my server.  That said, when you scale up to 1,000,000 records BIT vs BIGINT doesn't appreciably affect my query anymore, but it still runs around ~680ms vs ~730ms from sys.objects.


问:
For refresh flow, do I need to create an OpenIddictApplicationDescriptor for my client?
I'm using the refresh flow sample, but i added the instrospection middleware since my resource server is separated from my authorization server.  Using the angular app, I'm able to connect to the authorization server.  Everything works. But I noticed in the Implicit Flow sample that the following code was added:

```<code>            if (await manager.FindByClientIdAsync("aurelia", cancellationToken) == null)
            {
                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId = "aurelia",
                    DisplayName = "Aurelia client application",
                    PostLogoutRedirectUris = { new Uri("http://localhost:9000/signout-oidc") },
                    RedirectUris = { new Uri("http://localhost:9000/signin-oidc") }
                };

                await manager.CreateAsync(descriptor, cancellationToken);
            }
</code>```

Do I need to add something similar to this for the Refresh flow?

答: If you don't configure OpenIddict to require a client_id for token requests (by calling options.RequireClientIdentification()) then creating an application in the database is not mandatory to be able to use the refresh token flow.

Body:
I'm using the refresh flow sample, but i added the instrospection middleware since my resource server is separated from my authorization server.  Using the angular app, I'm able to connect to the authorization server.  Everything works. But I noticed in the Implicit Flow sample that the following code was added:

            if (await manager.FindByClientIdAsync("aurelia", cancellationToken) == null)
            {
                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId = "aurelia",
                    DisplayName = "Aurelia client application",
                    PostLogoutRedirectUris = { new Uri("http://localhost:9000/signout-oidc") },
                    RedirectUris = { new Uri("http://localhost:9000/signin-oidc") }
                };

                await manager.CreateAsync(descriptor, cancellationToken);
            }

Do I need to add something similar to this for the Refresh flow?


问:
Translate cURL to RestSharp (Could not create SSL/TLS secure channel)
I am working to integrate with a third-party that provides sample code for use with cURL.  I've been able to successfully connect using cURL via the following command:

curl -k -d "grant_type=client_cert" --basic -u "myUserName:myPassword" -H "Content-Type: application/x-www-form-urlencoded" --cert c:\certs\myCert.pem https://vendorUrl/method

In reading the cURL docs, I believe this is what all the switches translate to:

-k: insecure (proceed even if connection is not secure)

-d: data.  Also indicates this is a POST.

--basic: basic auth

-u username/password

-H additional header

--cert: pass certificate

I have tried many (!) different tips I've found online, so there are some lines of code that may be unnecessary.  I have tried to indicate where I have interpreted cURL switches to C# in my code comments.

```<code>        //Not sure if these are needed or not.
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.CheckCertificateRevocationList = false;

        //allow every possible protocol for now just to eliminate the protocol as the source of the problem
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

        //this should be the equivalent of cURL's "-k" (insecure) switch.
        ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

        var certificatePath = ConfigurationManager.AppSettings.GetValue("myPath");
        var clientKey = "myKey";
        var clientSecret = "mySecret";

        var url = "https://vendorUrl/method";

        //create the request
        var request = new RestRequest(Method.POST);

        ////this should be the equivalent of cURL's -d (data) switch.  no idea if this is done correctly.  I have also tried adding this as "AddJsonBody()"
        var body = "grant_type=client_cert";
        request.AddBody(body);

        //this should be the equivalent of cURL's "-H" (header) switch
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

        //Import certificate
        var certificates = new X509Certificate();
        certificates.Import(certificatePath);

        var client = new RestClient
        {
            BaseUrl = new Uri(url),
            //this should be the equivalent of cURL's "--cert" switch
            ClientCertificates = new X509CertificateCollection { certificates },
            //this should be the equivalent of cURL's "--basic" (Basic Auth) switch and the "-u" switch
            Authenticator = new HttpBasicAuthenticator(clientKey, clientSecret)
        };

        var response = client.Execute(request);
</code>```

The error message I get is the dreaded "The request was aborted: Could not create SSL/TLS secure channel."

I also added trace logging as described here:  The request was aborted: Could not create SSL/TLS secure channel.

I don't really know how to parse the output of the trace, but one of the last messages in the trace looks like a problem:

System.Net Information: 0 : [9232] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=IllegalMessage).

答:
In my case, I had to install the certificate on the local computer/server in order to get this to work.  It's not clear to me why cURL works without the certificate installed.

The certificate I had to install had a .p12 extension.  So in code I loaded the .pem file, which is a file derived from the .p12 file.  I'm not claiming to understand why.

By switching to HttpClient, I was able to avoid loading the .pem file by adding:

```<code>            var handler = new WebRequestHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
            var httpClient = new HttpClient(handler);
</code>```

I was not able to find a RestSharp/WebRequest  equivalent to  ClientCertificateOptions.

Body:
I am working to integrate with a third-party that provides sample code for use with cURL.  I've been able to successfully connect using cURL via the following command:

curl -k -d "grant_type=client_cert" --basic -u "myUserName:myPassword" -H "Content-Type: application/x-www-form-urlencoded" --cert c:\certs\myCert.pem https://vendorUrl/method

In reading the cURL docs, I believe this is what all the switches translate to:

-k: insecure (proceed even if connection is not secure)

-d: data.  Also indicates this is a POST.

--basic: basic auth

-u username/password

-H additional header

--cert: pass certificate

I have tried many (!) different tips I've found online, so there are some lines of code that may be unnecessary.  I have tried to indicate where I have interpreted cURL switches to C# in my code comments.

        //Not sure if these are needed or not.
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.CheckCertificateRevocationList = false;

        //allow every possible protocol for now just to eliminate the protocol as the source of the problem
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

        //this should be the equivalent of cURL's "-k" (insecure) switch.
        ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

        var certificatePath = ConfigurationManager.AppSettings.GetValue("myPath");
        var clientKey = "myKey";
        var clientSecret = "mySecret";

        var url = "https://vendorUrl/method";

        //create the request
        var request = new RestRequest(Method.POST);

        ////this should be the equivalent of cURL's -d (data) switch.  no idea if this is done correctly.  I have also tried adding this as "AddJsonBody()"
        var body = "grant_type=client_cert";
        request.AddBody(body);

        //this should be the equivalent of cURL's "-H" (header) switch
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

        //Import certificate
        var certificates = new X509Certificate();
        certificates.Import(certificatePath);

        var client = new RestClient
        {
            BaseUrl = new Uri(url),
            //this should be the equivalent of cURL's "--cert" switch
            ClientCertificates = new X509CertificateCollection { certificates },
            //this should be the equivalent of cURL's "--basic" (Basic Auth) switch and the "-u" switch
            Authenticator = new HttpBasicAuthenticator(clientKey, clientSecret)
        };

        var response = client.Execute(request);

The error message I get is the dreaded "The request was aborted: Could not create SSL/TLS secure channel."

I also added trace logging as described here:  The request was aborted: Could not create SSL/TLS secure channel.

I don't really know how to parse the output of the trace, but one of the last messages in the trace looks like a problem:

System.Net Information: 0 : [9232] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=IllegalMessage).

Body:
In my case, I had to install the certificate on the local computer/server in order to get this to work.  It's not clear to me why cURL works without the certificate installed.

The certificate I had to install had a .p12 extension.  So in code I loaded the .pem file, which is a file derived from the .p12 file.  I'm not claiming to understand why.

By switching to HttpClient, I was able to avoid loading the .pem file by adding:

            var handler = new WebRequestHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
            var httpClient = new HttpClient(handler);

I was not able to find a RestSharp/WebRequest  equivalent to  ClientCertificateOptions.


问:
Comparing only the first index of two array
I have two arrays one that has just one index which list id's. The other array has many indexes but I want to compare only the id index of both arrays which is index [0] I want to get only the rows that ids don't match and return those rows. Example:

```<code>$array1 = [
    '12345',
    '23457'
];

$array2 = [
   [id => '12345', 'fake_data' => 'something'],
   [id => '23457', 'more_data' => 'something else'],
   [id => '76389','more_data' => 'something else 3'],
   [id => '10293', 'more_data' => 'something else 4'],
   [id => '09229', 'more_data' => 'something else 5']
];
</code>```

The first array just have id's the other has ids place other data. I need to keep that data and only return the rows that don't match the first array. Help is very much appriciated.

答:
```<code>$array1 = [
    '12345',
    '23457'
];

$array2 = [
   ['id' => '12345', 'fake_data' => 'something'],
   ['id' => '23457', 'more_data' => 'something else'],
   ['id' => '76389','more_data' => 'something else 3'],
   ['id' => '10293', 'more_data' => 'something else 4'],
   ['id' => '09229', 'more_data' => 'something else 5']
];

$found_id_rows = array_filter($array2, function($row) use($array1) {
    return in_array($row['id'], $array1);
});

$not_found_id_rows = array_filter($array2, function($row) use($array1) {
    return !in_array($row['id'], $array1);
});
</code>```

Gives:

```<code>Array
(
    [0] => Array
        (
            [id] => 12345
            [fake_data] => something
        )

    [1] => Array
        (
            [id] => 23457
            [more_data] => something else
        )

)
Array
(
    [2] => Array
        (
            [id] => 76389
            [more_data] => something else 3
        )

    [3] => Array
        (
            [id] => 10293
            [more_data] => something else 4
        )

    [4] => Array
        (
            [id] => 09229
            [more_data] => something else 5
        )

)
</code>```

https://3v4l.org/6OVjP

Body:
I have two arrays one that has just one index which list id's. The other array has many indexes but I want to compare only the id index of both arrays which is index [0] I want to get only the rows that ids don't match and return those rows. Example:

$array1 = [
    '12345',
    '23457'
];

$array2 = [
   [id => '12345', 'fake_data' => 'something'],
   [id => '23457', 'more_data' => 'something else'],
   [id => '76389','more_data' => 'something else 3'],
   [id => '10293', 'more_data' => 'something else 4'],
   [id => '09229', 'more_data' => 'something else 5']
];

The first array just have id's the other has ids place other data. I need to keep that data and only return the rows that don't match the first array. Help is very much appriciated.

Body:
$array1 = [
    '12345',
    '23457'
];

$array2 = [
   ['id' => '12345', 'fake_data' => 'something'],
   ['id' => '23457', 'more_data' => 'something else'],
   ['id' => '76389','more_data' => 'something else 3'],
   ['id' => '10293', 'more_data' => 'something else 4'],
   ['id' => '09229', 'more_data' => 'something else 5']
];

$found_id_rows = array_filter($array2, function($row) use($array1) {
    return in_array($row['id'], $array1);
});

$not_found_id_rows = array_filter($array2, function($row) use($array1) {
    return !in_array($row['id'], $array1);
});

Gives:

Array
(
    [0] => Array
        (
            [id] => 12345
            [fake_data] => something
        )

    [1] => Array
        (
            [id] => 23457
            [more_data] => something else
        )

)
Array
(
    [2] => Array
        (
            [id] => 76389
            [more_data] => something else 3
        )

    [3] => Array
        (
            [id] => 10293
            [more_data] => something else 4
        )

    [4] => Array
        (
            [id] => 09229
            [more_data] => something else 5
        )

)

https://3v4l.org/6OVjP


答:
```<code><?php

$array1 = [
    '12345',
    '23457'
];

$array2 = [
   ['id' => '12345', 'fake_data' => 'something'],
   ['id' => '23457', 'more_data' => 'something else'],
   ['id' => '76389','more_data' => 'something else 3'],
   ['id' => '10293', 'more_data' => 'something else 4'],
   ['id' => '09229', 'more_data' => 'something else 5']
];

foreach($array2 as $key => $array)
    if(array_search($array['id'], $array1) !== false)
        unset($array2[$key]);

var_export($array2);
</code>```

Output:

```<code>array (
    2 =>
    array (
      'id' => '76389',
      'more_data' => 'something else 3',
    ),
    3 =>
    array (
      'id' => '10293',
      'more_data' => 'something else 4',
    ),
    4 =>
    array (
      'id' => '09229',
      'more_data' => 'something else 5',
    ),
  )
</code>```

Title: Comparing only the first index of two array

Body:
<?php

$array1 = [
    '12345',
    '23457'
];

$array2 = [
   ['id' => '12345', 'fake_data' => 'something'],
   ['id' => '23457', 'more_data' => 'something else'],
   ['id' => '76389','more_data' => 'something else 3'],
   ['id' => '10293', 'more_data' => 'something else 4'],
   ['id' => '09229', 'more_data' => 'something else 5']
];

foreach($array2 as $key => $array)
    if(array_search($array['id'], $array1) !== false)
        unset($array2[$key]);

var_export($array2);

Output:

array (
    2 =>
    array (
      'id' => '76389',
      'more_data' => 'something else 3',
    ),
    3 =>
    array (
      'id' => '10293',
      'more_data' => 'something else 4',
    ),
    4 =>
    array (
      'id' => '09229',
      'more_data' => 'something else 5',
    ),
  )


问:
Create an Excel Macro to filter sheets with a certain title to a new workbook

I have an Excel Workbook containing ~50 different sheets. These sheets are organized into raw data and organized data summaries.

The data summaries are sheets that I'm trying to upload to an Access database, and these sheets all include the string "Summary" or "Sum" as part of their name. I'm new to VBA and I'm wondering if there is a way I can set up a script to filter out the sheets so that I am left with just the summary sheets and not the raw data sheets as part of my workbook.

Ideally I would copy the summary sheets over to a new Excel workbook since I don't want to lose my raw data. Any help? Or is this not even possible?

答:
```<code>Option explicit

Sub CopySumSheetsOver()

Const SUBSTRING as string = "Sum" 'Change this to whatever string you want to search for.'

With thisworkbook

Dim ws as Worksheet
Dim SheetNames() as string
Redim SheetNames(1 to .worksheets.count)

Dim SheetIndex as long

For each ws in .worksheets
SheetIndex = SheetIndex + 1
SheetNames(SheetIndex) = ws.name
Next ws

Redim preserve sheetnames(1 to sheetindex)

SheetNames = filter(sheetnames,SUBSTRING,True,vbTextCompare) 'vbBinaryCompare is faster, but case-sensitive, use whichever one you need.'

Dim DestinationWorkbook as workbook
Set DestinationWorkbook = application.workbooks.add

.worksheets(SheetNames).copy destinationworkbook.worksheets(destinationworkbook.worksheets.count)

End with

End sub
</code>```

Untested, written on mobile. Sorry for bad formatting.

Body:
Option explicit

Sub CopySumSheetsOver()

Const SUBSTRING as string = "Sum" 'Change this to whatever string you want to search for.'

With thisworkbook

Dim ws as Worksheet
Dim SheetNames() as string
Redim SheetNames(1 to .worksheets.count)

Dim SheetIndex as long

For each ws in .worksheets
SheetIndex = SheetIndex + 1
SheetNames(SheetIndex) = ws.name
Next ws

Redim preserve sheetnames(1 to sheetindex)

SheetNames = filter(sheetnames,SUBSTRING,True,vbTextCompare) 'vbBinaryCompare is faster, but case-sensitive, use whichever one you need.'

Dim DestinationWorkbook as workbook
Set DestinationWorkbook = application.workbooks.add

.worksheets(SheetNames).copy destinationworkbook.worksheets(destinationworkbook.worksheets.count)

End with

End sub

Untested, written on mobile. Sorry for bad formatting.


问:
Crash on FragmentTransaction in onCreate
My app was recently working great on everything until the latest version of Android came out. The Google Pixel is now crashing with the code below. I am trying to use the Caldroid calendar solution and it's been awesome working with it. However, it now crashes when I try and replace the Fragment and do a .commit() on it.

After reading countless articles on stack about this issue I'm still not seeing what I'm doing wrong.

Here is my onCreate:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_schedule);
    context=this;
    initComponents();
    getSharedData();

    getAllGameData();

    addCaldroidCalendar();
}
</code>```

And the addCaldroidCalendar function:

```<code>public void addCaldroidCalendar() {

    caldroidFragment = new CaldroidFragment();

    Calendar calendar = Calendar.getInstance();

    // setup arguments for calendar view
    Bundle args = new Bundle();
    args.putInt(CaldroidFragment.MONTH, calendar.get(Calendar.MONTH) + 1);
    args.putInt(CaldroidFragment.YEAR, calendar.get(Calendar.YEAR));
    args.putBoolean(CaldroidFragment.SQUARE_TEXT_VIEW_CELL, false);
    caldroidFragment.setArguments(args);

    android.support.v4.app.FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.replace(R.id.calendar1, caldroidFragment);
    t.commitNow();
</code>```

}

And here is my UI XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:layout_marginBottom="90dp">

    <RelativeLayout
        android:id="@+id/rl_main_schedule_screen"
        android:layout_width="fill_parent"
        android:layout_height="match_parent">

       <!-- android:layout_above="@+id/rl_calender_view_schedule_screen"-->

        <TextView
            android:id="@+id/tv_calender_view_schedule_screen"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:text="Calendar View"
            android:textColor="#000000"
            android:foregroundGravity="center"
            android:textSize="15sp"
            android:gravity="center"
            android:visibility="gone" />

        <RelativeLayout
            android:id="@+id/rl_list_view_layout_schedule_screen"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/tv_calender_view_schedule_screen"
            android:layout_above="@+id/rl_calender_view_schedule_screen"
            android:layout_marginBottom="-20dp">
            <TextView
                android:id="@+id/tv_no_data_schedule_screen"
                android:layout_width="fill_parent"
                android:layout_height="30dp"
                android:text="No Data"
                android:textColor="#000000"
                android:foregroundGravity="center"
                android:textSize="12dp"
                android:gravity="center"
                android:visibility="gone" />
            <ListView
                android:id="@+id/lv_all_schedule_screen"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scrollbars="none"
                android:cacheColorHint="@null"
                android:divider="@null"
                android:layout_marginBottom="30dp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/rl_calender_view_schedule_screen"
            android:layout_width="fill_parent"
            android:layout_height="250dp"
            android:translationY="0dp"
            android:layout_alignParentBottom="true"
            android:background="@null">

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:text=""
                    android:layout_alignParentTop="true"
                    android:id="@+id/expand_cal_button"
                    android:background="@color/caldroid_transparent"
                    android:layout_marginLeft="70dp"
                    android:layout_marginRight="70dp"/>

                <CalendarView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/calendar1"
                    android:layout_gravity="center_vertical" />

        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>
</code>```

This results in the following crash:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.duffek.officiatingUpdate, PID: 31099
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.duffek.officiatingUpdate/com.duffek.officiatingUpdate.TabHomeActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.duffek.officiatingUpdate/com.duffek.officiatingUpdate.ActivitySchedule}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class Button
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                   Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.duffek.officiatingUpdate/com.duffek.officiatingUpdate.ActivitySchedule}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class Button
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                      at android.app.ActivityThread.startActivityNow(ActivityThread.java:2615)
                      at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:136)
                      at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:348)
                      at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:769)
                      at android.widget.TabHost.setCurrentTab(TabHost.java:423)
                      at android.widget.TabHost.addTab(TabHost.java:233)
                      at com.duffek.officiatingUpdate.TabHomeActivity.onCreate(TabHomeActivity.java:40)
                      at android.app.Activity.performCreate(Activity.java:6975)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                   Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class Button
                   Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class Button
                   Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 6: TypedValue{t=0x2/d=0x101009b a=1}
                      at android.content.res.TypedArray.getColorStateList(TypedArray.java:538)
                      at android.widget.TextView.<init>(TextView.java:904)
                      at android.widget.Button.<init>(Button.java:172)
                      at android.widget.Button.<init>(Button.java:147)
                      at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:70)
                      at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:66)
                      at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:109)
                      at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1016)
                      at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1073)
                      at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:189)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:772)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:866)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                      at com.roomorama.caldroid.CaldroidFragment.onCreateView(CaldroidFragment.java:1257)
                      at android.support.v4.app.Fragment.performCreateView(Fragment.java:2261)
E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
                      at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1750)
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1819)
                      at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3227)
                      at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3181)
                      at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
                      at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:572)
                      at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
                      at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1333)
                      at android.app.Activity.performStart(Activity.java:6992)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2780)
                      at android.app.ActivityThread.startActivityNow(ActivityThread.java:2615)
                      at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:136)
                      at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:348)
                      at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:769)
                      at android.widget.TabHost.setCurrentTab(TabHost.java:423)
                      at android.widget.TabHost.addTab(TabHost.java:233)
                      at com.duffek.officiatingUpdate.TabHomeActivity.onCreate(TabHomeActivity.java:40)
                      at android.app.Activity.performCreate(Activity.java:6975)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

If I comment out the line on onCreate:

```<code>t.commitNow();
</code>```

Then it works but obviously my calendar doesn't show up

This is an issue with the latest version of Android and did not have any issues before now. What could have changed and what could I be doing wrong? This one has me completely stumped.

答: Well, from your Logs you can see that is because it was not able to resolve the color resource in your button at runtime. Just as a test, remove the background attribute in your XML.</p>

Body:
My app was recently working great on everything until the latest version of Android came out. The Google Pixel is now crashing with the code below. I am trying to use the Caldroid calendar solution and it's been awesome working with it. However, it now crashes when I try and replace the Fragment and do a .commit() on it.

After reading countless articles on stack about this issue I'm still not seeing what I'm doing wrong.

Here is my onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_schedule);
    context=this;
    initComponents();
    getSharedData();

    getAllGameData();

    addCaldroidCalendar();
}

And the addCaldroidCalendar function:

public void addCaldroidCalendar() {

    caldroidFragment = new CaldroidFragment();

    Calendar calendar = Calendar.getInstance();

    // setup arguments for calendar view
    Bundle args = new Bundle();
    args.putInt(CaldroidFragment.MONTH, calendar.get(Calendar.MONTH) + 1);
    args.putInt(CaldroidFragment.YEAR, calendar.get(Calendar.YEAR));
    args.putBoolean(CaldroidFragment.SQUARE_TEXT_VIEW_CELL, false);
    caldroidFragment.setArguments(args);

    android.support.v4.app.FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.replace(R.id.calendar1, caldroidFragment);
    t.commitNow();

}

And here is my UI XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:layout_marginBottom="90dp">

    <RelativeLayout
        android:id="@+id/rl_main_schedule_screen"
        android:layout_width="fill_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tv_calender_view_schedule_screen"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:text="Calendar View"
            android:textColor="#000000"
            android:foregroundGravity="center"
            android:textSize="15sp"
            android:gravity="center"
            android:visibility="gone" />

        <RelativeLayout
            android:id="@+id/rl_list_view_layout_schedule_screen"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/tv_calender_view_schedule_screen"
            android:layout_above="@+id/rl_calender_view_schedule_screen"
            android:layout_marginBottom="-20dp">
            <TextView
                android:id="@+id/tv_no_data_schedule_screen"
                android:layout_width="fill_parent"
                android:layout_height="30dp"
                android:text="No Data"
                android:textColor="#000000"
                android:foregroundGravity="center"
                android:textSize="12dp"
                android:gravity="center"
                android:visibility="gone" />
            <ListView
                android:id="@+id/lv_all_schedule_screen"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scrollbars="none"
                android:cacheColorHint="@null"
                android:divider="@null"
                android:layout_marginBottom="30dp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/rl_calender_view_schedule_screen"
            android:layout_width="fill_parent"
            android:layout_height="250dp"
            android:translationY="0dp"
            android:layout_alignParentBottom="true"
            android:background="@null">

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:text=""
                    android:layout_alignParentTop="true"
                    android:id="@+id/expand_cal_button"
                    android:background="@color/caldroid_transparent"
                    android:layout_marginLeft="70dp"
                    android:layout_marginRight="70dp"/>

                <CalendarView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/calendar1"
                    android:layout_gravity="center_vertical" />

        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>

This results in the following crash:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.duffek.officiatingUpdate, PID: 31099
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.duffek.officiatingUpdate/com.duffek.officiatingUpdate.TabHomeActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.duffek.officiatingUpdate/com.duffek.officiatingUpdate.ActivitySchedule}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class Button
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                   Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.duffek.officiatingUpdate/com.duffek.officiatingUpdate.ActivitySchedule}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class Button
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                      at android.app.ActivityThread.startActivityNow(ActivityThread.java:2615)
                      at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:136)
                      at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:348)
                      at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:769)
                      at android.widget.TabHost.setCurrentTab(TabHost.java:423)
                      at android.widget.TabHost.addTab(TabHost.java:233)
                      at com.duffek.officiatingUpdate.TabHomeActivity.onCreate(TabHomeActivity.java:40)
                      at android.app.Activity.performCreate(Activity.java:6975)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                   Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class Button
                   Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class Button
                   Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 6: TypedValue{t=0x2/d=0x101009b a=1}
                      at android.content.res.TypedArray.getColorStateList(TypedArray.java:538)
                      at android.widget.TextView.<init>(TextView.java:904)
                      at android.widget.Button.<init>(Button.java:172)
                      at android.widget.Button.<init>(Button.java:147)
                      at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:70)
                      at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:66)
                      at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:109)
                      at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1016)
                      at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1073)
                      at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:189)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:772)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:866)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                      at com.roomorama.caldroid.CaldroidFragment.onCreateView(CaldroidFragment.java:1257)
                      at android.support.v4.app.Fragment.performCreateView(Fragment.java:2261)
E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
                      at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1750)
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1819)
                      at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3227)
                      at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3181)
                      at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
                      at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:572)
                      at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
                      at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1333)
                      at android.app.Activity.performStart(Activity.java:6992)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2780)
                      at android.app.ActivityThread.startActivityNow(ActivityThread.java:2615)
                      at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:136)
                      at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:348)
                      at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:769)
                      at android.widget.TabHost.setCurrentTab(TabHost.java:423)
                      at android.widget.TabHost.addTab(TabHost.java:233)
                      at com.duffek.officiatingUpdate.TabHomeActivity.onCreate(TabHomeActivity.java:40)
                      at android.app.Activity.performCreate(Activity.java:6975)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

If I comment out the line on onCreate:

t.commitNow();

Then it works but obviously my calendar doesn't show up

This is an issue with the latest version of Android and did not have any issues before now. What could have changed and what could I be doing wrong? This one has me completely stumped.


问:
Unhelpful (maybe wrong?) gcc error message
I just spent a couple of hours debugging a compiler error that I could have fixed immediately if the compiler's error message had been more helpful.

I've reduced it to a simple example:

```<code>template <typename T>
int f(int);

template <typename U>
auto g(U x) -> decltype(f(x));

int main()
{
    g(0);
}
</code>```

The error is:

```<code>test.cpp: In function 'int main()':
test.cpp:9:8: error: no matching function for call to 'g(int)'
test.cpp:9:8: note: candidate is:
test.cpp:5:29: note: template<class U> decltype (f(x)) g(U)
</code>```

Is this error not at best misleading and at worst, outright wrong? The way I see it, the problem is not that the given definition of g is not a match for the call, but that the definition is malformed (since in the expression f(x) in the decltype, it tries to call f without specifying f's template parameter).

Wouldn't a much more reasonable error message be something like:

```<code>no matching function for call to 'f(int)' in 'decltype(f(x))'
in instantiation of 'g(U)' with U = int
</code>```

or even better:

```<code>failed to deduce template parameter 1 in call to 'f(int)' in 'decltype(f(x))'
in instantiation of 'g(U)' with U = int
</code>```

I would have expected something like that...

答:
You are most likely hitting the "extended SFINAE" rules in C++0x; since the call to f(x) is not working within the instantiation of the return type of g (because of the inability to deduce T for the call to f), g has an invalid return type and thus is removed from the overload set silently.  This is a feature, despite its harm to error message quality, because the compiler is assuming that g is an unrelated function that you aren't intending to call.  In this case, there are no other overloads of g, so the compiler should give a better message, though.

There is more information on extended SFINAE available at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2634.html.

Body:
I just spent a couple of hours debugging a compiler error that I could have fixed immediately if the compiler's error message had been more helpful.

I've reduced it to a simple example:

template <typename T>
int f(int);

template <typename U>
auto g(U x) -> decltype(f(x));

int main()
{
    g(0);
}

The error is:

test.cpp: In function 'int main()':
test.cpp:9:8: error: no matching function for call to 'g(int)'
test.cpp:9:8: note: candidate is:
test.cpp:5:29: note: template<class U> decltype (f(x)) g(U)

Is this error not at best misleading and at worst, outright wrong? The way I see it, the problem is not that the given definition of g is not a match for the call, but that the definition is malformed (since in the expression f(x) in the decltype, it tries to call f without specifying f's template parameter).

Wouldn't a much more reasonable error message be something like:

no matching function for call to 'f(int)' in 'decltype(f(x))'
in instantiation of 'g(U)' with U = int

or even better:

failed to deduce template parameter 1 in call to 'f(int)' in 'decltype(f(x))'
in instantiation of 'g(U)' with U = int

I would have expected something like that...