问:
Building tensorflow serving client with cmake
I searched for the best way to do this, but I was unable to find a clear answer.

Was anyone able to build a tensorflow-serving client using cmake?

I am having difficulties with generating CPP files from proto, since they are needed for prediction service. Those proto files also include proto files from tensorflow.

so far I have come up with this:

```<code>project(serving C CXX)
find_package(Protobuf REQUIRED)

file(GLOB_RECURSE proto_files RELATIVE ${serving_SOURCE_DIR}/tensorflow/
    "${serving_SOURCE_DIR}/tensorflow/*.proto")

set(PROTOBUF_GENERATE_CPP_APPEND_PATH OFF)
include_directories(${PROTOBUF_INCLUDE_DIRS})
include_directories( ${CMAKE_CURRENT_BINARY_DIR} )
PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS ${proto_files})

add_library(tf_protos ${PROTO_SRCS} ${PROTO_HDRS})
target_link_libraries(tf_protos PUBLIC ${PROTOBUF_LIBRARIES})
</code>```

Cmake builds successfully but the make command gives me an error:

```<code>No rule to make target '../tensorflow/tools/proto_text/test.proto', needed by 'tensorflow/tools/proto_text/test.pb.cc'.  Stop.
</code>```

To overcome the problem of .proto includes not being found I used command

```<code>set(PROTOBUF_GENERATE_CPP_APPEND_PATH OFF)
</code>```

which was explained here: https://groups.google.com/forum/#!topic/protobuf/eow2fNDUHvc

My current folder structure is

```<code>serving/
    CmakeLists.txt
    tensorflow/
    tensorflow_serving/
        apis/
</code>```

Folder apis contains .proto files that are needed in the client implementation and they include .proto files from the folder tensorflow.

Is this even the right way to go?

Any help/advice would be much appreciated.

答:
I was able to get it to work in the layout you have where the CMakeLists.txt file is placed in the same level as the serving repository here. You'll need to install Tensorflow too though (using tensorflow_cc).

However, you probably don't want to muck with a fork of the official tensorflow/serving repository so I went a step further and moved the CMakeLists.txt out so you can just submodule the official repository. I made an example here

The gist is that the protobuf CMake submodule expects proto files to be laid out in the same directory from which it's called. I made some modifications to the submodules to let us call it from a level above serving and to ensure it invokes the compiler with the include paths in the right order to support the nested structure of the proto files in serving/tensorflow_serving/apis/* (and placing it accordingly in the specified build directory)

Hopefully someone else with better knowhow can make this better!

Body:
I searched for the best way to do this, but I was unable to find a clear answer.

Was anyone able to build a tensorflow-serving client using cmake?

I am having difficulties with generating CPP files from proto, since they are needed for prediction service. Those proto files also include proto files from tensorflow.

so far I have come up with this:

project(serving C CXX)
find_package(Protobuf REQUIRED)

file(GLOB_RECURSE proto_files RELATIVE ${serving_SOURCE_DIR}/tensorflow/
    "${serving_SOURCE_DIR}/tensorflow/*.proto")

set(PROTOBUF_GENERATE_CPP_APPEND_PATH OFF)
include_directories(${PROTOBUF_INCLUDE_DIRS})
include_directories( ${CMAKE_CURRENT_BINARY_DIR} )
PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS ${proto_files})

add_library(tf_protos ${PROTO_SRCS} ${PROTO_HDRS})
target_link_libraries(tf_protos PUBLIC ${PROTOBUF_LIBRARIES})

Cmake builds successfully but the make command gives me an error:

No rule to make target '../tensorflow/tools/proto_text/test.proto', needed by 'tensorflow/tools/proto_text/test.pb.cc'.  Stop.

To overcome the problem of .proto includes not being found I used command

set(PROTOBUF_GENERATE_CPP_APPEND_PATH OFF)

which was explained here: https://groups.google.com/forum/#!topic/protobuf/eow2fNDUHvc

My current folder structure is

serving/
    CmakeLists.txt
    tensorflow/
    tensorflow_serving/
        apis/

Folder apis contains .proto files that are needed in the client implementation and they include .proto files from the folder tensorflow.

Is this even the right way to go?

Any help/advice would be much appreciated.


来源: stackexchange

问:
increment a field in moongose
I want to increment a field automatically on update with condition.

I have two Schemas:

```<code>var History = new Schema({
   action : {type: String},
   eventType : {type : String}
})
</code>```

And:

```<code> var Quote = new Schema({
           name : {type: String},
           email : {type: String},
           quoteNumber : {type: Number}
           history: [History]
        });
</code>```

quoteNumber is the field which I want to increment by 1 as soon as a record histroy field gets updated.

答:
You would use the $inc operator in MongoDB. So whichever function you use to update history, for example:

```<code>db.collection.update({name: "foo"}, {$push: {history: "Log History"}, $inc:{quoteNumber : 1})
</code>```

Read up on it here: https://docs.mongodb.com/manual/reference/operator/update/inc/

However, since history is an array, you could just get the length of the array as well.

ContentLicense: CC BY-SA 4.0

Title: increment a field in moongose

Body:
I want to increment a field automatically on update with condition.

I have two Schemas:

var History = new Schema({
   action : {type: String},
   eventType : {type : String}
})

And:

 var Quote = new Schema({
           name : {type: String},
           email : {type: String},
           quoteNumber : {type: Number}
           history: [History]
        });

quoteNumber is the field which I want to increment by 1 as soon as a record histroy field gets updated.

Body:
You would use the $inc operator in MongoDB. So whichever function you use to update history, for example:

db.collection.update({name: "foo"}, {$push: {history: "Log History"}, $inc:{quoteNumber : 1})

Read up on it here: https://docs.mongodb.com/manual/reference/operator/update/inc/

However, since history is an array, you could just get the length of the array as well.

ContentLicense: CC BY-SA 3.0


问:
SQL- how to retrieve by similar dates
Okay, so I have a table with a user_id column and a submitted_dtm column.

I want to find instances where users submitted multiple records within 1 day of each other, and count how many times that has happened.

I've tried something like

```<code>select * from table_t t where
(select count(*) from table_t t2 where
t.user_id = t2.user_id and
t.pk!=t2.pk and
t.submitted_dtm between t2.submitted_dtm-.5 and t2.submitted_dtm+.5)>0;
</code>```

The problem is that this query returns a result for each record in a date group.  Instead, I just want a result per date group. Ideally, I'd just get the count in that group.

That is, if I have 6 records:

```<code>user_id     submitted_dtm
--------------------------
1            12/04/2017 1:15
1            12/04/2017 5:50
2            11/25/2017 2:00
2            11/25/2017 3:25
2            11/25/2017 6:05
2            10/06/2017 4:00
</code>```

I want 2 results, a count of 2 and a count of 3.

Is it possible to do this in sql?

答:
This is a general idea of how to get the instances.

```<code>select user_id, t1.submitted_dtm t1submitted, t2.submitted_dtm t2submtted
from table_t t1 join table_t t2 using (user_id)
where t2.submitted_dtm > t1.submitted_dtm
and t2.submitted_dtm - t1.submitted_dtm <= 1;
</code>```

The last line could be modified somehow depending on what you mean by within a day.

To count the instances, create a derived table from the above and select count(*) from it.

Title: SQL- how to retrieve by similar dates

Body:
Okay, so I have a table with a user_id column and a submitted_dtm column.

I want to find instances where users submitted multiple records within 1 day of each other, and count how many times that has happened.

I've tried something like

select * from table_t t where
(select count(*) from table_t t2 where
t.user_id = t2.user_id and
t.pk!=t2.pk and
t.submitted_dtm between t2.submitted_dtm-.5 and t2.submitted_dtm+.5)>0;

The problem is that this query returns a result for each record in a date group.  Instead, I just want a result per date group. Ideally, I'd just get the count in that group.

That is, if I have 6 records:

user_id     submitted_dtm
--------------------------
1            12/04/2017 1:15
1            12/04/2017 5:50
2            11/25/2017 2:00
2            11/25/2017 3:25
2            11/25/2017 6:05
2            10/06/2017 4:00

I want 2 results, a count of 2 and a count of 3.

Is it possible to do this in sql?

Body:
This is a general idea of how to get the instances.

select user_id, t1.submitted_dtm t1submitted, t2.submitted_dtm t2submtted
from table_t t1 join table_t t2 using (user_id)
where t2.submitted_dtm > t1.submitted_dtm
and t2.submitted_dtm - t1.submitted_dtm <= 1;

The last line could be modified somehow depending on what you mean by within a day.

To count the instances, create a derived table from the above and select count(*) from it.


问:
How to find a path in cypher the ungreedy way
Actually i'm modelling TEI-encoded XML-Text in a graph (words as a chain of nodes) and i want to find shortestPaths and only the very shortest path in a graph.

My query looks like

```<code>MATCH (w0:XmlWord)-[:NEXT*..6]->(n:XmlTag {_name:'lb'})-[:NEXT*..6]->(w1:XmlWord)
RETURN id(w0), id(w1);
</code>```

And I need only the shortest possible path but neo4j gives me all possibilities until to the 6th step. The result should be the nodes Vorträge, über, des, and Freiherrn

Neo4j gives me back all possible combinations until to the 6th step.

If someone needs access to a sample-database just let me know.

答:
This is a little tough when you're using multiple variable-length relationships in the same path. You can however order the results by path length and filter for the ones with the minimum length.</p>

```<code>MATCH path = (:XmlWord)-[:NEXT*..6]->(:XmlTag {_name:'lb'})-[:NEXT*..6]->(:XmlWord)
WITH length(path) as length, collect(path) as paths
ORDER BY length ASC
LIMIT 1
UNWIND paths as path
WITH head(nodes(path)) as first, last(nodes(path)) as last
RETURN id(first), id(last);
</code>```

Body:
Actually i'm modelling TEI-encoded XML-Text in a graph (words as a chain of nodes) and i want to find shortestPaths and only the very shortest path in a graph.

My query looks like

MATCH (w0:XmlWord)-[:NEXT*..6]->(n:XmlTag {_name:'lb'})-[:NEXT*..6]->(w1:XmlWord)
RETURN id(w0), id(w1);

And I need only the shortest possible path but neo4j gives me all possibilities until to the 6th step. The result should be the nodes Vorträge, über, des, and Freiherrn

Neo4j gives me back all possible combinations until to the 6th step.

If someone needs access to a sample-database just let me know.

Body:
This is a little tough when you're using multiple variable-length relationships in the same path. You can however order the results by path length and filter for the ones with the minimum length.

MATCH path = (:XmlWord)-[:NEXT*..6]->(:XmlTag {_name:'lb'})-[:NEXT*..6]->(:XmlWord)
WITH length(path) as length, collect(path) as paths
ORDER BY length ASC
LIMIT 1
UNWIND paths as path
WITH head(nodes(path)) as first, last(nodes(path)) as last
RETURN id(first), id(last);


问:
xdebug.remote_autostart, remote, and connect_back not turning on
I've spent some time trying to figure out why the autostart, remote , and connect_back settings wont turn on. I've typed in:

```<code>xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_port=9000
xdebug.remote_autostart=1
xdebug.remote_connect_back=1
;xdebug.remote_host=192.168.1.108
</code>```

All this into the php.ini file, restarted servers, and when I check the configuration page on the MAMP page, these settings still read OFF. Any idea why this is...

答:
This is super late, but, you need to edit the correct php.ini file.  MAMP comes with 2 or more!

From the MAMP control/app launch the PHP_INFO() page, or make your own.  Check the path value for the Loaded Configuration File

That is the php.ini to edit.

Body:
I've spent some time trying to figure out why the autostart, remote , and connect_back settings wont turn on. I've typed in:

xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_port=9000
xdebug.remote_autostart=1
xdebug.remote_connect_back=1
;xdebug.remote_host=192.168.1.108

All this into the php.ini file, restarted servers, and when I check the configuration page on the MAMP page, these settings still read OFF. Any idea why this is...


问:
diffutil sort arrayadapter position
We are trying to sort an ArrayList that contains data from sqlite database.
I can sort the list with this added to the query " ORDER BY " + Col_IDBG + " DESC
Which works as desired except the position data in the RecyclerAdapter is not in sync with the DESC ordering. So next we used Collections.reverse(dbList); which works but once again the RecyclerAdapter is not in sync with the reverse order.

We have narrowed the problem to the RecylerAdapter code below.
We would like to know how to use DiffUtil to keep the position in sync with the sort method?

```<code>    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public TextView station;
    public TextView rowid;

    public ViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        rowid = (TextView) itemLayoutView.findViewById(R.id.rvROWID);
        station = (TextView)itemLayoutView.findViewById(R.id.rvWEBSITE);
        // Attach a click listener to the entire row view
        itemLayoutView.setOnClickListener(this);
    }

    @Override // When an item in ListActivity is touched (selected) the RecyclerView has
    //  a OnClickListener attached in the above Code that implements the method below
    public void onClick(View v) {
        Intent intentN = new Intent(context,BuyGasDetailActivity.class);
        Bundle extras = new Bundle();
        extras.putInt("POSITION",getAdapterPosition());
        extras.putString("FROM_LIST_ACTIVITY","false" );
        intentN.putExtras(extras);
        context.startActivity(intentN);
    }
}
</code>```

The position is passed to DetailActivity to view all data associated with the item in the ListActivity with the intentN

答:
This is simple to solve you just need to use the Collections.reverse(dbList); in TWO places the RecyclerAdapter and the DetailActivity
Here is the code in the RecyclerAdapter

```<code>    @Override
public int getItemCount() {
    Collections.reverse(dbList);
    return dbList.size();
}
</code>```

and here is the code in the DetailActivity inside the onCreate method

```<code>    dbList = helper.getDataFrom_BUY_GAS_TABLE();
    Collections.reverse(dbList);
</code>```

Tested and works great

Title: diffutil sort arrayadapter position

Body:
We are trying to sort an ArrayList that contains data from sqlite database.
I can sort the list with this added to the query " ORDER BY " + Col_IDBG + " DESC
Which works as desired except the position data in the RecyclerAdapter is not in sync with the DESC ordering. So next we used Collections.reverse(dbList); which works but once again the RecyclerAdapter is not in sync with the reverse order.

We have narrowed the problem to the RecylerAdapter code below.
We would like to know how to use DiffUtil to keep the position in sync with the sort method?

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public TextView station;
    public TextView rowid;

    public ViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        rowid = (TextView) itemLayoutView.findViewById(R.id.rvROWID);
        station = (TextView)itemLayoutView.findViewById(R.id.rvWEBSITE);
        // Attach a click listener to the entire row view
        itemLayoutView.setOnClickListener(this);
    }

    @Override // When an item in ListActivity is touched (selected) the RecyclerView has
    //  a OnClickListener attached in the above Code that implements the method below
    public void onClick(View v) {
        Intent intentN = new Intent(context,BuyGasDetailActivity.class);
        Bundle extras = new Bundle();
        extras.putInt("POSITION",getAdapterPosition());
        extras.putString("FROM_LIST_ACTIVITY","false" );
        intentN.putExtras(extras);
        context.startActivity(intentN);
    }
}

The position is passed to DetailActivity to view all data associated with the item in the ListActivity with the intentN

Body:
This is simple to solve you just need to use the Collections.reverse(dbList); in TWO places the RecyclerAdapter and the DetailActivity
Here is the code in the RecyclerAdapter

    @Override
public int getItemCount() {
    Collections.reverse(dbList);
    return dbList.size();
}

and here is the code in the DetailActivity inside the onCreate method

    dbList = helper.getDataFrom_BUY_GAS_TABLE();
    Collections.reverse(dbList);

Tested and works great


问:
SQL Error - The multi-part identifier "CF.OBJ" could not be bound
Im getting an error on multi part identifier for Sub query join. Please help. Following is the code I have written

```<code>SELECT CORE.BC_NUMBER AS BC,SEG.BC_NUMBER AS SEGBC,XREF.BC_NUMBER AS XREFBC,CF.OBJ
-- Table CORE
From CORE

-- join seg and core
LEFT JOIN SEG
ON CORE.BC_NUMBER= SEG.BC_NUMBER

-- Join XREF to go from BCNbr to GBC
LEFT JOIN
XREF
ON XREF.BUNL=SEG.BC_NUMBER;

-- GEN JOIN GBC
LEFT JOIN

(SELect JID,P,Obj, JT
From Gen) AS CF

ON CF.Obj=XREF.BC_NUMBER

;
</code>```

sqlfiddle.com/#!6/29f643/15

答:
It looks like you have the alias inside the sub-query; try the following:</p>

```<code>SELECT CORE.BC_NUMBER AS BC,SEG.BC_NUMBER AS SEGBC,XREF.BC_NUMBER AS

XREFBC,CF.OBJ
-- Table CORE
From CORE

-- join seg and core
LEFT JOIN SEG
ON CORE.BC_NUMBER= SEG.BC_NUMBER

-- Join XREF to go from BCNbr to GBC
LEFT JOIN XREF
ON XREF.BUNL=SEG.BC_NUMBER

-- GEN JOIN GBC
LEFT JOIN (
    SELECT JID,P,Obj, JT
    From Gen
    where JT=28 and P=1
)CF
ON CF.Obj=XREF.BC_NUMBER
;
</code>```

Body:
Im getting an error on multi part identifier for Sub query join. Please help. Following is the code I have written

SELECT CORE.BC_NUMBER AS BC,SEG.BC_NUMBER AS SEGBC,XREF.BC_NUMBER AS XREFBC,CF.OBJ
-- Table CORE
From CORE

-- join seg and core
LEFT JOIN SEG
ON CORE.BC_NUMBER= SEG.BC_NUMBER

-- Join XREF to go from BCNbr to GBC
LEFT JOIN
XREF
ON XREF.BUNL=SEG.BC_NUMBER;

-- GEN JOIN GBC
LEFT JOIN

(SELect JID,P,Obj, JT
From Gen) AS CF

ON CF.Obj=XREF.BC_NUMBER

;

sqlfiddle.com/#!6/29f643/15

Body:
It looks like you have the alias inside the sub-query; try the following:

SELECT CORE.BC_NUMBER AS BC,SEG.BC_NUMBER AS SEGBC,XREF.BC_NUMBER AS

XREFBC,CF.OBJ
-- Table CORE
From CORE

-- join seg and core
LEFT JOIN SEG
ON CORE.BC_NUMBER= SEG.BC_NUMBER

-- Join XREF to go from BCNbr to GBC
LEFT JOIN XREF
ON XREF.BUNL=SEG.BC_NUMBER

-- GEN JOIN GBC
LEFT JOIN (
    SELECT JID,P,Obj, JT
    From Gen
    where JT=28 and P=1
)CF
ON CF.Obj=XREF.BC_NUMBER
;


问:
WPF databinding: database or objects?
I'm trying to create this:

Tag1 has the ordered list of objects: O1, O3, O2.
Tag2 has the ordered list of objects: O1, O4.

Every time I click a tag, I want to see the list of objects. So clicking Tag1 would show in a listbox:

O1

O3

O2

But I would like to keep the auto update so every time I edit or add/delete an object it auto updates (I suppose I need to implement something like the interfaces INotifyCollectionChanged and INotifyPropertyChanged?).

I could use a database and have the tables Tag, Object and TagObject, this last one with the TagID and ObjectID. But I also would like to avoid databases, since it's a desktop application.

I could also use objects like ObservableCollections, but I have the problem of having duplicate objects. I can use references to the objects but it gets messy.

Anyone has any suggestion on how to do this?

Thank you.

答:
Move all the logic controlling the updated data out of the WPF page and into another class that pushes the new data into the WPF page, when it changes, rather than the WPF pulling the data out of the objects.

Here is some example code:

```<code>class WpfPage
{
   public List OrderedListForTag1 { set { /* whatever GUI binding code you need to deal with the new list for tag 1 */ }

   public List OrderedListForTag2 { set { /* whatever GUI binding code you need to deal with the new list for tag 2*/ }

}

class WpfPresenter
{
  WpfPage thePage;

  public void Tag1Selected()
  {
      //Calculate changes to 01, 02, 04 etcetce
      //If changed, update the page
      thePage.OrderedListForTag1 = //new list of objects
  }
}
</code>```

This is one of the model-view-controller pattern(s) which is very common in GUI construction.  This series of articles covers the concepts.

OwnerDisplayName: Artur Carvalho

Title: WPF databinding: database or objects?

Body:
Move all the logic controlling the updated data out of the WPF page and into another class that pushes the new data into the WPF page, when it changes, rather than the WPF pulling the data out of the objects.

Here is some example code:

class WpfPage
{
   public List OrderedListForTag1 { set { /* whatever GUI binding code you need to deal with the new list for tag 1 */ }

   public List OrderedListForTag2 { set { /* whatever GUI binding code you need to deal with the new list for tag 2*/ }

}

class WpfPresenter
{
  WpfPage thePage;

  public void Tag1Selected()
  {
      //Calculate changes to 01, 02, 04 etcetce
      //If changed, update the page
      thePage.OrderedListForTag1 = //new list of objects
  }
}

This is one of the model-view-controller pattern(s) which is very common in GUI construction.  This series of articles covers the concepts.

OwnerDisplayName: Jimmy McNulty

ContentLicense: CC BY-SA 2.5


问:
Nesting
 and
 tags?

Question:

Which of these is the proper way to nest the
 and
 tags, and what is your reasoning behind it?

Choice A:

```<code><article>
    <h1>Some Title</h1>
    <p>Here's some text and whatnot.</p>
    <p>Here's another paragraph filled with other text and other whatnots.</p>
</article>
</code>```

Choice B:

```<code><div class="post">
    <h1>Here's a Really Awesome Title</h1>
    <article>
        <p>Here's a paragraph with text and whatnot.</p>
        <p>And here's another paragraph. I think this one is pretty awesome too.</p>
    </article>
</div>
</code>```

Opinions seem mixed about this, and I'm not 100% which is the correct answer.

答:
I'd say that the heading is part of the article.

This is really down to personal taste as far as I can tell. You won't get a right or wrong answer as long as you're writing valid HTML5.

Title: Nesting <article> and <h1> tags?

Body:
Question:

Which of these is the proper way to nest the
 and
 tags, and what is your reasoning behind it?

Choice A:

Some Title

Here's some text and whatnot.

Here's another paragraph filled with other text and other whatnots.

Choice B:

Here's a Really Awesome Title

Here's a paragraph with text and whatnot.

And here's another paragraph. I think this one is pretty awesome too.

Opinions seem mixed about this, and I'm not 100% which is the correct answer.


问:
How to get element by name in vb.net
I am trying to get Element by name in vb.net

HTML Code:

```<code><input name="domains[]" value="gamesolutionz.com" type="text">
</code>```

VB.net:

```<code>Private Sub FlatTextBox1_TextChanged(sender As Object, e As EventArgs) Handles FlatTextBox1.TextChanged
    WebBrowser1.Document.GetElementById("domains[]").SetAttribute("value", FlatTextBox1.Text)
End Sub
</code>```

答:
Finally Done it myself:
        Dim allelements As HtmlElementCollection = WebBrowser1.Document.All</p>

```<code>    For Each webpageelement As HtmlElement In allelements

        If webpageelement.GetAttribute("name") = "domains[]" Then

            webpageelement.SetAttribute("value", FlatTextBox2.Text)

        End If

    Next
</code>```

Title: How to get element by name in vb.net

Body:
I am trying to get Element by name in vb.net

HTML Code:

<input name="domains[]" value="gamesolutionz.com" type="text">

VB.net:

Private Sub FlatTextBox1_TextChanged(sender As Object, e As EventArgs) Handles FlatTextBox1.TextChanged
    WebBrowser1.Document.GetElementById("domains[]").SetAttribute("value", FlatTextBox1.Text)
End Sub

Body:
Finally Done it myself:
        Dim allelements As HtmlElementCollection = WebBrowser1.Document.All

    For Each webpageelement As HtmlElement In allelements

        If webpageelement.GetAttribute("name") = "domains[]" Then

            webpageelement.SetAttribute("value", FlatTextBox2.Text)

        End If

    Next


问:
Xamarin forms custom WebViewRender on Android
I'm trying to add some headers to each request in WebView controller. I'm using a custom web renderer to add the headers. It's working fine on iOS but just adding the renderer class in Android causes an exception.

The code looks like this

In the PCL, I inherited the WebView control to add some custom properties

```<code>public class AuthWebView : WebView
{
    public static readonly BindableProperty UrlProperty =
         BindableProperty.Create("Url", typeof(string), typeof(AuthWebView), default(string));

    public string Url
    {
        get => (string)GetValue(UrlProperty);
        set => SetValue(UrlProperty, value);
    }

    public string UserToken { get; set; }
}
</code>```

In the android project, I just created a blank render as follows

```<code>[assembly: ExportRenderer(typeof(AuthWebView), typeof(TestRenderer))]
namespace Reshare.Droid
{
    public class TestRenderer : WebViewRenderer
    {
    }
}
</code>```

I got a generic exception whenever I tried to launch the page that contains the AuthWebView control

Unhandled Exception:
  System.Reflection.TargetInvocationException: Exception has been thrown by the target invocation

Is there any thing I missed here that can be causing the exception to happen ?

答:
The problem seems related to an older version of Xamarin.Forms package and it just solved when i updated the nuget package to the latest version!

just for reference if anyone ever faced this issue, i was using
  Xamarin.Forms.2.4.0.38779 and updated now to version Xamarin.Forms.2.5.0.91635 and I was using the approach detailed here
  https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/hybridwebview/

Body:
I'm trying to add some headers to each request in WebView controller. I'm using a custom web renderer to add the headers. It's working fine on iOS but just adding the renderer class in Android causes an exception.

The code looks like this

In the PCL, I inherited the WebView control to add some custom properties

public class AuthWebView : WebView
{
    public static readonly BindableProperty UrlProperty =
         BindableProperty.Create("Url", typeof(string), typeof(AuthWebView), default(string));

    public string Url
    {
        get => (string)GetValue(UrlProperty);
        set => SetValue(UrlProperty, value);
    }

    public string UserToken { get; set; }
}

In the android project, I just created a blank render as follows

[assembly: ExportRenderer(typeof(AuthWebView), typeof(TestRenderer))]
namespace Reshare.Droid
{
    public class TestRenderer : WebViewRenderer
    {
    }
}

I got a generic exception whenever I tried to launch the page that contains the AuthWebView control

Unhandled Exception:
  System.Reflection.TargetInvocationException: Exception has been thrown by the target invocation

Is there any thing I missed here that can be causing the exception to happen ?


问:
Can I add a search bar in a <ion-select> tag?
I made a <ion-select> tag to choose some elements as below. In case I have too many elements to show on here, I want to add a search bar in the tag.

Is it possible to do this? Adding <ion-toolbar> in <ion-select> doesn't get this solved...

答: No, but you can create a new page, and add both ion-select and ion-search there. Then show this page instead of your original ion-select.


问:
iScroll: Hide scrollbar when indicator is hidden
I have a horizontal iScroll instance that has an interactive scrollbar.

```<code>    myScroll = new IScroll('#wrapper', {
        scrollX: true,
        scrollY: false,
        mouseWheel: false,
        scrollbars: 'custom',
        interactiveScrollbars: true,
        resizeScrollbars: false,
        bindToWrapper: false,
        click: true,
        fadeScrollbars: true,
    });
</code>```

I want its scrollbars to hide when iScroll makes the indicator hidden (display: none)
I noticed that it changes the indicator's css display property when it detects that scrolling is not needed because of the lack of slides/elements to scroll with.

This usually happens when I resize the browser from small to large viewports.

fadeScrollbars is not exactly what I wanted because it hides the scrollbar and indicator even if it is still okay to scroll.

How do I configure iScroll to not display the scrollbar if the indicator is hidden?

Is there any work-around for this?

答:
There is a work-around using jQuery (just check if indicator is hidden and hide scrollbar):</p>

```<code>if($('#wrapper .iScrollIndicator').is(':hidden')) {
    $('#wrapper .iScrollVerticalScrollbar').hide();
}
</code>```

Body:
I have a horizontal iScroll instance that has an interactive scrollbar.

    myScroll = new IScroll('#wrapper', {
        scrollX: true,
        scrollY: false,
        mouseWheel: false,
        scrollbars: 'custom',
        interactiveScrollbars: true,
        resizeScrollbars: false,
        bindToWrapper: false,
        click: true,
        fadeScrollbars: true,
    });

I want its scrollbars to hide when iScroll makes the indicator hidden (display: none)
I noticed that it changes the indicator's css display property when it detects that scrolling is not needed because of the lack of slides/elements to scroll with.

This usually happens when I resize the browser from small to large viewports.

fadeScrollbars is not exactly what I wanted because it hides the scrollbar and indicator even if it is still okay to scroll.

How do I configure iScroll to not display the scrollbar if the indicator is hidden?

Is there any work-around for this?

Body:
There is a work-around using jQuery (just check if indicator is hidden and hide scrollbar):

if($('#wrapper .iScrollIndicator').is(':hidden')) {
    $('#wrapper .iScrollVerticalScrollbar').hide();
}


问:
What does $$i do in this makefile loop?
I have a simple loop in my makefile:

```<code>@ for i in $(APPDIRS) ; do \
    $(MAKE) -C $$i real_clean ; \
    done
</code>```

I know $$ means process id of the script itself. What does the 'i' do? Am I iterating through the process id with the for loop?

答:
$ is used both as the variable identifier for make and for the shell. So if you want the shell to expand a variable, rather than having the makefile do it, you need to escape the $ by using $$.

As a quick example, let's assume APPDIRS=a b c d e f and MAKE=make (and i unset in the makefile). Then your shell sees:

```<code>for i in a b c d e f ; do
    make -C $i real_clean;
done
</code>```

With a $ in place of the $$, it would see:

```<code>for i in a b c d e f ; do
    make -C  real_lean;
done
</code>```

Which is definitely not what you want.

Title: What does $$i do in this makefile loop?

Body:
I have a simple loop in my makefile:

@ for i in $(APPDIRS) ; do \
    $(MAKE) -C $$i real_clean ; \
    done

I know $$ means process id of the script itself. What does the 'i' do? Am I iterating through the process id with the for loop?

Body:
$ is used both as the variable identifier for make and for the shell. So if you want the shell to expand a variable, rather than having the makefile do it, you need to escape the $ by using $$.

As a quick example, let's assume APPDIRS=a b c d e f and MAKE=make (and i unset in the makefile). Then your shell sees:

for i in a b c d e f ; do
    make -C $i real_clean;
done

With a $ in place of the $$, it would see:

for i in a b c d e f ; do
    make -C  real_lean;
done

Which is definitely not what you want.


答: I'm using first option. Because , article's mean is a part of external content . So this content should have a header.

Title: Nesting <article> and <h1> tags?


问:
Why aren't my CTreeCtrl checkboxes checking?
I've got a MFC CTreeCtrl stuck in a dialog with the TVS_CHECKBOXES style turned on. I get checkboxes next to all my tree items fine. In OnInitDialog I set the checked state of some of the items using CTreeCtrl::SetCheck but none of the items in the tree are checked when the tree is displayed. SetCheck is returning TRUE. Checking items with the mouse works fine. Anyone encounter this before?</p>

答:
Check boxes in tree view controls are quirky. As documented:

If you want to use this style, you must set the TVS_CHECKBOXES style with SetWindowLong after you create the treeview control, and before you populate the tree. Otherwise, the checkboxes might appear unchecked, depending on timing issues.

In other words, you cannot set the TVS_CHECKBOXES tree view style at control creation time. Control styles set in Visual Studio's resource editor (which is just a graphical front-end for the .rc script) are used at control creation time.

The solution is fairly simple: Create the control without the TVS_CHECKBOXES style, and turn it on in code, before you populate the control:

```<code>::SetWindowLong( hwndTreeView, GWL_STYLE,
                 ::GetWindowLong( hwndTreeView, GWL_STYLE ) | TVS_CHECKBOXES );
</code>```

In MFC this can be done using

```<code>m_treeView.ModifyStyle( 0x0, TVS_CHECKBOXES );
</code>```

where m_treeView is the tree view control instance variable.

Background information:

Check boxes weren't part of the initial tree view control implementation. They were added later on, following the scheme developers were using that needed check boxes before they were available: By using a state image list and setting state item indices on the tree view items.

One of the issues that needed to be addressed was determining the check box size. If the tree view control has an image list (the "normal image list") assigned, the check boxes should match the size of those images. Otherwise, the check boxes should use the system small icon size. A corollary of this is that if you are using a "normal image list", you need to enable the TVS_CHECKBOXES style after setting the image list.

Another quirk is, that the state image index 0 means "no state image" at all (1 refers to the "unchecked" state item image). If you add an item to a tree view control that has the TVS_CHECKBOXES style set, the control sets the state item index to 1 (even if you specify 0). That's why all items appear unchecked, when you set the TVS_CHECKBOXES style at creation time. This also implies, that if you want a tree view item without a state image, you have to add the tree view item, and then manually reset the state item index.

This should be enough information, to understand and solve the question as asked. There's a lot more to the tree view implementation, but I'll leave that to someone, that is better equipped to write about it. Refer to the references below.

References:

Raymond Chen (The Old New Thing) has published an extensive series covering the tree view control quirks. Not all of the entries are immediately relevant to this question, but each and every one is insightful and valuable, one way or another, so I'll just list them all:

The TVS_CHECKBOXES style is quirky, which is a polite way of saying that it is crazy

Beware of the leaked image list when using the TVS_CHECKBOXES style

Creating tree view check boxes manually: A simple state image list

Creating tree view check boxes manually: Responding to clicks

Creating tree view check boxes manually: Themed check boxes

Tree view check boxes: A sordid history

Tree view check boxes: The extended check box states

Body:
Check boxes in tree view controls are quirky. As documented:

If you want to use this style, you must set the TVS_CHECKBOXES style with SetWindowLong after you create the treeview control, and before you populate the tree. Otherwise, the checkboxes might appear unchecked, depending on timing issues.

In other words, you cannot set the TVS_CHECKBOXES tree view style at control creation time. Control styles set in Visual Studio's resource editor (which is just a graphical front-end for the .rc script) are used at control creation time.

The solution is fairly simple: Create the control without the TVS_CHECKBOXES style, and turn it on in code, before you populate the control:

::SetWindowLong( hwndTreeView, GWL_STYLE,
                 ::GetWindowLong( hwndTreeView, GWL_STYLE ) | TVS_CHECKBOXES );

In MFC this can be done using

m_treeView.ModifyStyle( 0x0, TVS_CHECKBOXES );

where m_treeView is the tree view control instance variable.

Background information:

Check boxes weren't part of the initial tree view control implementation. They were added later on, following the scheme developers were using that needed check boxes before they were available: By using a state image list and setting state item indices on the tree view items.

One of the issues that needed to be addressed was determining the check box size. If the tree view control has an image list (the "normal image list") assigned, the check boxes should match the size of those images. Otherwise, the check boxes should use the system small icon size. A corollary of this is that if you are using a "normal image list", you need to enable the TVS_CHECKBOXES style after setting the image list.

Another quirk is, that the state image index 0 means "no state image" at all (1 refers to the "unchecked" state item image). If you add an item to a tree view control that has the TVS_CHECKBOXES style set, the control sets the state item index to 1 (even if you specify 0). That's why all items appear unchecked, when you set the TVS_CHECKBOXES style at creation time. This also implies, that if you want a tree view item without a state image, you have to add the tree view item, and then manually reset the state item index.

This should be enough information, to understand and solve the question as asked. There's a lot more to the tree view implementation, but I'll leave that to someone, that is better equipped to write about it. Refer to the references below.

References:

Raymond Chen (The Old New Thing) has published an extensive series covering the tree view control quirks. Not all of the entries are immediately relevant to this question, but each and every one is insightful and valuable, one way or another, so I'll just list them all:

The TVS_CHECKBOXES style is quirky, which is a polite way of saying that it is crazy

Beware of the leaked image list when using the TVS_CHECKBOXES style

Creating tree view check boxes manually: A simple state image list

Creating tree view check boxes manually: Responding to clicks

Creating tree view check boxes manually: Themed check boxes

Tree view check boxes: A sordid history

Tree view check boxes: The extended check box states


问:
amc, aerospike are not recognized inside docker container
I've docker ubuntu 16.04 image and I'm running aerospike server in it.

```<code>$ docker run -d -p 3000:3000 -p 3001:3001 -p 3002:3002 -p 3003:3003  -p 8081:8081  --name aerospike aerospike/aerospike-server
</code>```

The docker container is running successfully.

```<code>$ docker ps
CONTAINER ID        IMAGE                        COMMAND
CREATED             STATUS              PORTS
NAMES
b0b4c63d7e22        aerospike/aerospike-server   "/entrypoint.sh asd"
36 seconds ago      Up 35 seconds       0.0.0.0:3000-3003->3000-3003/tcp, 0.0.0.0:8081->8081/tcp   aerospike
</code>```

I've logged into the docker container

```<code>$ docker exec -it b0b4c63d7e22 bash
root@b0b4c63d7e22:/#
</code>```

I have listed the directories -

```<code>root@b0b4c63d7e22:/# ls
bin  boot  core  dev  entrypoint.sh  etc  home  lib  lib64  media  mnt  opt
proc  root  run  sbin  srv  sys  tmp  usr  var
root@b0b4c63d7e22:/#
</code>```

I changed the directory to bin folder and listed the commands

```<code>root@b0b4c63d7e22:/# cd bin
root@b0b4c63d7e22:/bin# ls
bash   dnsdomainname  ip          mount          readlink    systemctl
touch         zegrep
cat    domainname     journalctl  mountpoint     rm          systemd
true          zfgrep
chgrp  echo           kill        mv             rmdir       systemd-ask-
password            umount        zforce
chmod  egrep          ln          netstat        run-parts   systemd-escape
uname         zgrep
chown  false          login       networkctl     sed         systemd-inhibit
uncompress    zless
cp     fgrep          loginctl    nisdomainname  sh          systemd-machine-
id-setup        vdir          zmore
dash   findmnt        ls          pidof          sh.distrib  systemd-notify
wdctl         znew
date   grep           lsblk       ping           sleep       systemd-tmpfiles
which
dd     gunzip         mkdir       ping6          ss          systemd-tty-ask-
password-agent  ypdomainname
df     gzexe          mknod       ps             stty        tailf
zcat
dir    gzip           mktemp      pwd            su          tar
zcmp
dmesg  hostname       more        rbash          sync        tempfile
zdiff
</code>```

Then I want to check the service -

```<code>root@b0b4c63d7e22:/bin# service amc status
amc: unrecognized service
</code>```

答:
You can build your own Docker container for amc to connect to aerospike running on containers.

Here is a sample Dockerfile for AMC.

```<code>cat Dockerfile

FROM ubuntu:xenial

ENV AMC_VERSION 4.0.13

# Install AMC server

RUN \
  apt-get update -y \
  && apt-get install -y wget python python-argparse python-bcrypt python-openssl logrotate net-tools iproute2 iputils-ping \
  && wget "https://www.aerospike.com/artifacts/aerospike-amc-community/${AMC_VERSION}/aerospike-amc-community-${AMC_VERSION}_amd64.deb" -O aerospike-amc.deb \
  && dpkg -i aerospike-amc.deb \
  && apt-get purge -y

# Expose Aerospike ports
#
#   8081 – amc port
#
EXPOSE 8081

# Execute the run script in foreground mode
ENTRYPOINT ["/opt/amc/amc"]
CMD [" -config-file=/etc/amc/amc.conf -config-dir=/etc/amc"]

#/opt/amc/amc -config-file=/etc/amc/amc.conf -config-dir=/etc/amc

# Docker build sample:
# docker build -t amctest .

# Docker run sample for running amc on port 8081
# docker run -tid --name amc -p 8081:8081 amctest
# and access through http://127.0.0.1:8081
</code>```

Then you can build the image:

```<code>docker build -t amctest .
Sending build context to Docker daemon  50.69kB
Step 1/6 : FROM ubuntu:xenial
 ---> 2fa927b5cdd3
Step 2/6 : ENV AMC_VERSION 4.0.13
 ---> Using cache
 ---> edd6bddfe7ad
Step 3/6 : RUN apt-get update -y   && apt-get install -y wget python python-argparse python-bcrypt python-openssl logrotate net-tools iproute2 iputils-ping   && wget "https://www.aerospike.com/artifacts/aerospike-amc-community/${AMC_VERSION}/aerospike-amc-community-${AMC_VERSION}_amd64.deb" -O aerospike-amc.deb   && dpkg -i aerospike-amc.deb   && apt-get purge -y
 ---> Using cache
 ---> f916199044d8
Step 4/6 : EXPOSE 8081
 ---> Using cache
 ---> 06f7888c1721
Step 5/6 : ENTRYPOINT /opt/amc/amc
 ---> Using cache
 ---> bc39346cd94f
Step 6/6 : CMD  -config-file=/etc/amc/amc.conf -config-dir=/etc/amc
 ---> Using cache
 ---> 8ae4300e7c7c
Successfully built 8ae4300e7c7c
Successfully tagged amctest:latest
</code>```

and finally run it with port forwarding to port 8081:

```<code>docker run -tid --name amc -p 8081:8081 amctest
a07cdd8bf8cec6ba41ce068c01544920136a6905e7a05e9a2c315605f62edfce
</code>```

Body:
I've docker ubuntu 16.04 image and I'm running aerospike server in it.

$ docker run -d -p 3000:3000 -p 3001:3001 -p 3002:3002 -p 3003:3003  -p 8081:8081  --name aerospike aerospike/aerospike-server

The docker container is running successfully.

$ docker ps
CONTAINER ID        IMAGE                        COMMAND
CREATED             STATUS              PORTS
NAMES
b0b4c63d7e22        aerospike/aerospike-server   "/entrypoint.sh asd"
36 seconds ago      Up 35 seconds       0.0.0.0:3000-3003->3000-3003/tcp, 0.0.0.0:8081->8081/tcp   aerospike

I've logged into the docker container

$ docker exec -it b0b4c63d7e22 bash
root@b0b4c63d7e22:/#

I have listed the directories -

root@b0b4c63d7e22:/# ls
bin  boot  core  dev  entrypoint.sh  etc  home  lib  lib64  media  mnt  opt
proc  root  run  sbin  srv  sys  tmp  usr  var
root@b0b4c63d7e22:/#

I changed the directory to bin folder and listed the commands

root@b0b4c63d7e22:/# cd bin
root@b0b4c63d7e22:/bin# ls
bash   dnsdomainname  ip          mount          readlink    systemctl
touch         zegrep
cat    domainname     journalctl  mountpoint     rm          systemd
true          zfgrep
chgrp  echo           kill        mv             rmdir       systemd-ask-
password            umount        zforce
chmod  egrep          ln          netstat        run-parts   systemd-escape
uname         zgrep
chown  false          login       networkctl     sed         systemd-inhibit
uncompress    zless
cp     fgrep          loginctl    nisdomainname  sh          systemd-machine-
id-setup        vdir          zmore
dash   findmnt        ls          pidof          sh.distrib  systemd-notify
wdctl         znew
date   grep           lsblk       ping           sleep       systemd-tmpfiles
which
dd     gunzip         mkdir       ping6          ss          systemd-tty-ask-
password-agent  ypdomainname
df     gzexe          mknod       ps             stty        tailf
zcat
dir    gzip           mktemp      pwd            su          tar
zcmp
dmesg  hostname       more        rbash          sync        tempfile
zdiff

Then I want to check the service -

root@b0b4c63d7e22:/bin# service amc status
amc: unrecognized service

Body:
You can build your own Docker container for amc to connect to aerospike running on containers.

Here is a sample Dockerfile for AMC.

cat Dockerfile

FROM ubuntu:xenial

ENV AMC_VERSION 4.0.13

# Install AMC server

RUN \
  apt-get update -y \
  && apt-get install -y wget python python-argparse python-bcrypt python-openssl logrotate net-tools iproute2 iputils-ping \
  && wget "https://www.aerospike.com/artifacts/aerospike-amc-community/${AMC_VERSION}/aerospike-amc-community-${AMC_VERSION}_amd64.deb" -O aerospike-amc.deb \
  && dpkg -i aerospike-amc.deb \
  && apt-get purge -y

# Expose Aerospike ports
#
#   8081 – amc port
#
EXPOSE 8081

# Execute the run script in foreground mode
ENTRYPOINT ["/opt/amc/amc"]
CMD [" -config-file=/etc/amc/amc.conf -config-dir=/etc/amc"]

#/opt/amc/amc -config-file=/etc/amc/amc.conf -config-dir=/etc/amc

# Docker build sample:
# docker build -t amctest .

# Docker run sample for running amc on port 8081
# docker run -tid --name amc -p 8081:8081 amctest
# and access through http://127.0.0.1:8081

Then you can build the image:

docker build -t amctest .
Sending build context to Docker daemon  50.69kB
Step 1/6 : FROM ubuntu:xenial
 ---> 2fa927b5cdd3
Step 2/6 : ENV AMC_VERSION 4.0.13
 ---> Using cache
 ---> edd6bddfe7ad
Step 3/6 : RUN apt-get update -y   && apt-get install -y wget python python-argparse python-bcrypt python-openssl logrotate net-tools iproute2 iputils-ping   && wget "https://www.aerospike.com/artifacts/aerospike-amc-community/${AMC_VERSION}/aerospike-amc-community-${AMC_VERSION}_amd64.deb" -O aerospike-amc.deb   && dpkg -i aerospike-amc.deb   && apt-get purge -y
 ---> Using cache
 ---> f916199044d8
Step 4/6 : EXPOSE 8081
 ---> Using cache
 ---> 06f7888c1721
Step 5/6 : ENTRYPOINT /opt/amc/amc
 ---> Using cache
 ---> bc39346cd94f
Step 6/6 : CMD  -config-file=/etc/amc/amc.conf -config-dir=/etc/amc
 ---> Using cache
 ---> 8ae4300e7c7c
Successfully built 8ae4300e7c7c
Successfully tagged amctest:latest

and finally run it with port forwarding to port 8081:

docker run -tid --name amc -p 8081:8081 amctest
a07cdd8bf8cec6ba41ce068c01544920136a6905e7a05e9a2c315605f62edfce


问:
Hadoop Type Conversion
I have the following signatures for my mapper and reducer classes:

```<code>MapperPrime extends Mapper<Text, Text, Text, Text>
ReducerPrime extends Reducer<Text, Text, Text, LongWritable>
</code>```

When I run the code, I get the following exception when execution reaches the reducer:

```<code>java.lang.ClassCastException: org.apache.hadoop.io.LongWritable cannot be cast to org.apache.hadoop.io.Text
    at ReducerPrime.reduce(ReducerPrime.java:1)
</code>```

When I change the first generic type in ReducerPrime from Text to LongWritable, i.e.

```<code>ReducerPrime extends Reducer<LongWritable, Text, Text, LongWritable>
</code>```

The exception is no longer thrown. What gives? Why/Where would java be seeing a LongWritable?

Doesn't the input Key,Value type in the Reducer exactly match the ouput Key,Value type in the Mapper?

答:
Why/Where would java be seeing a LongWritable

For the Mapper, the key for the TextInputFormat is the file offset, which is a long. The Value is the line of text, so a Text writable object.

Doesn't the input Key,Value type in the Reducer exactly match the ouput Key,Value type in the Mapper?

Yes, it should, though since we can't see the code at the moment, hard to say what you've written as output.

Title: Hadoop Type Conversion

Body:
I have the following signatures for my mapper and reducer classes:

MapperPrime extends Mapper<Text, Text, Text, Text>
ReducerPrime extends Reducer<Text, Text, Text, LongWritable>

When I run the code, I get the following exception when execution reaches the reducer:

java.lang.ClassCastException: org.apache.hadoop.io.LongWritable cannot be cast to org.apache.hadoop.io.Text
    at ReducerPrime.reduce(ReducerPrime.java:1)

When I change the first generic type in ReducerPrime from Text to LongWritable, i.e.

ReducerPrime extends Reducer<LongWritable, Text, Text, LongWritable>

The exception is no longer thrown. What gives? Why/Where would java be seeing a LongWritable?

Doesn't the input Key,Value type in the Reducer exactly match the ouput Key,Value type in the Mapper?


问:
Allow users to join public or private groups in Meteor?
I have 'groups' in my Meteor application that users can join. On the groups page I show a list of users who have joined. Im publishing this like so:

```<code>Meteor.publish("allUsers", function() {
  return Meteor.users.find({}, {fields: {name: 1, groups: 1}});
});
</code>```

However id also like users to have the option of join groups publicly or privately. The only way I can think to do this would be to have another field for privately joined groups that is only published to the current user:

```<code>Meteor.publish('currentUser', function() {
  return Meteor.users.find(
    { _id: this.userId },
    { fields: { name: 1, groups: 1, groups-private: 1 } },
  );
});
</code>```

This will allow me to show the current user any groups they have joined privately, and also show the public groups data.

However this approach has its limitations. I cant show the total number of members of a group, any private members cannot be counted. How can I get round this? Do I need to store numbers on the groups collection? Im concerned about getting race conditions if I do this.

答:
In terms of modeling you have a many-to-many relationship between users and groups but the relationship itself has properties, i.e. it can be public or private. One could imagine you wanting to track other properties of that relationship in the future such as joinedDate.

Instead of storing an array of groupId strings in the user document you can store an array of objects that include the extra properties. For one user this could look like:

```<code>groups = [
  { groupId: 1, public: true },
  { groupId: 2, public: false },
  { groupId: 3 } // or just omit the public value altogether (default is private)
  ...
]
</code>```

If you want to publish all the public members of a group to a user you can then do:

```<code>Meteor.publish('publicUsersOfGroup',function(groupId){
  check(groupId,String);
  if (this.userId) {
    return Meteor.users.find({ groups: { $elemMatch: { groupId: groupId, public: true }});
  }
  this.ready();
});
</code>```

If you want to count members of a group you can then do:

```<code>const publicCount = Meteor.users.find({ groups: { $elemMatch: { groupId: groupId, public: true }}).count();
const privateCount = Meteor.users.find({ groups: { $elemMatch: { groupId: groupId, public: {$ne: true }}).count();
const totalCount = Meteor.users.find({ groups: { $elemMatch: { groupId: groupId }).count();
</code>```

For performance you'll want to index both those array object keys.

Body:
I have 'groups' in my Meteor application that users can join. On the groups page I show a list of users who have joined. Im publishing this like so:

Meteor.publish("allUsers", function() {
  return Meteor.users.find({}, {fields: {name: 1, groups: 1}});
});

However id also like users to have the option of join groups publicly or privately. The only way I can think to do this would be to have another field for privately joined groups that is only published to the current user:

Meteor.publish('currentUser', function() {
  return Meteor.users.find(
    { _id: this.userId },
    { fields: { name: 1, groups: 1, groups-private: 1 } },
  );
});

This will allow me to show the current user any groups they have joined privately, and also show the public groups data.

However this approach has its limitations. I cant show the total number of members of a group, any private members cannot be counted. How can I get round this? Do I need to store numbers on the groups collection? Im concerned about getting race conditions if I do this.

Body:
In terms of modeling you have a many-to-many relationship between users and groups but the relationship itself has properties, i.e. it can be public or private. One could imagine you wanting to track other properties of that relationship in the future such as joinedDate.

Instead of storing an array of groupId strings in the user document you can store an array of objects that include the extra properties. For one user this could look like:

groups = [
  { groupId: 1, public: true },
  { groupId: 2, public: false },
  { groupId: 3 } // or just omit the public value altogether (default is private)
  ...
]

If you want to publish all the public members of a group to a user you can then do:

Meteor.publish('publicUsersOfGroup',function(groupId){
  check(groupId,String);
  if (this.userId) {
    return Meteor.users.find({ groups: { $elemMatch: { groupId: groupId, public: true }});
  }
  this.ready();
});

If you want to count members of a group you can then do:

const publicCount = Meteor.users.find({ groups: { $elemMatch: { groupId: groupId, public: true }}).count();
const privateCount = Meteor.users.find({ groups: { $elemMatch: { groupId: groupId, public: {$ne: true }}).count();
const totalCount = Meteor.users.find({ groups: { $elemMatch: { groupId: groupId }).count();

For performance you'll want to index both those array object keys.


问:
PostgreSQL query involving integer[]
I have 2 tables:

```<code>CREATE TABLE article (
  id serial NOT NULL,
  title text,
  tags integer[] -- array of tag id's from TAG table
)

CREATE TABLE tag (
  id serial NOT NULL,
  description character varying(250) NOT NULL
)
</code>```

... and need to select tags from TAG table held in ARTICLE's 'tags integer[]'  based on article's title.

So tried something like

```<code>SELECT *
  FROM tag
 WHERE tag.id IN ( (select article.tags::int4
                      from article
                     where article.title = 'some title' ) );
</code>```

... which gives me

ERROR:  cannot cast type integer[] to integer

  LINE 1: ...FROM tag WHERE tag.id IN (  (select article.tags::int4 from ...

I am Stuck with PostgreSql 8.3 in both dev and production environment.

答:
Use the array overlaps operator &&:

```<code>SELECT *
    FROM tag
    WHERE ARRAY[id] && ANY (SELECT tags FROM article WHERE title = '...');
</code>```

Using contrib/intarray you can even index this sort of thing quite well.

Title: PostgreSQL query involving integer[]

Body:
I have 2 tables:

CREATE TABLE article (
  id serial NOT NULL,
  title text,
  tags integer[] -- array of tag id's from TAG table
)

CREATE TABLE tag (
  id serial NOT NULL,
  description character varying(250) NOT NULL
)

... and need to select tags from TAG table held in ARTICLE's 'tags integer[]'  based on article's title.

So tried something like

SELECT *
  FROM tag
 WHERE tag.id IN ( (select article.tags::int4
                      from article
                     where article.title = 'some title' ) );

... which gives me

ERROR:  cannot cast type integer[] to integer

  LINE 1: ...FROM tag WHERE tag.id IN (  (select article.tags::int4 from ...

I am Stuck with PostgreSql 8.3 in both dev and production environment.

Body:
Use the array overlaps operator &&:

SELECT *
    FROM tag
    WHERE ARRAY[id] && ANY (SELECT tags FROM article WHERE title = '...');

Using contrib/intarray you can even index this sort of thing quite well.


问:
Excel - Create a countdown that ignores blanks; Take the minimum date of 3 columns - TODAY(),
I am trying to create a column that displays the number of days between now and the next time a person is required to participate in a study.

If there were no blanks in the columns that list the dates, the following formula works (N,P & R contain dates):

```<code>=MIN(N5,P5,R5)-TODAY()
</code>```

Unfortunately, my data contains blanks in the columns, which returns a "N/A" value.

Does anyone know how to avoid counting blanks in this situation?
Please let me know. Thanks.

答:
use this array formula:

```<code>=MIN(IF(CHOOSE({1,2,3},N5,P5,R5)>0,CHOOSE({1,2,3},N5,P5,R5))) - TODAY()
</code>```

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

Body:
I am trying to create a column that displays the number of days between now and the next time a person is required to participate in a study.

If there were no blanks in the columns that list the dates, the following formula works (N,P & R contain dates):

=MIN(N5,P5,R5)-TODAY()

Unfortunately, my data contains blanks in the columns, which returns a "N/A" value.

Does anyone know how to avoid counting blanks in this situation?
Please let me know. Thanks.

Body:
use this array formula:

=MIN(IF(CHOOSE({1,2,3},N5,P5,R5)>0,CHOOSE({1,2,3},N5,P5,R5))) - TODAY()

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.


问:
Laravel Homestead, npm install --no-bin-links error
I am using fresh Homestead (box version 0.5) for a fresh Laravel 5.3 app. Host OS is Windows 10.

I get this error when running npm install --no-bin-links

```<code>npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
npm ERR! Linux 4.4.0-22-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "--no-bin-links"
npm ERR! node v5.12.0
npm ERR! npm  v3.8.6

npm ERR! Maximum call stack size exceeded
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR! /home/vagrant/t1/t1/npm-debug.log
</code>```

npm-debug.log

```<code>.........
71199 silly build replace-ext@0.0.1
71200 silly build vinyl@1.2.0
71201 silly build require-dir@0.3.1
71202 silly build require-directory@2.1.1
71203 silly build require-main-filename@1.0.1
71204 silly build resolve@1.1.7
71205 silly build rechoir@0.6.2
71206 silly build resolve-url@0.2.1
71207 silly build rev-hash@1.0.0
71208 silly build rev-path@1.0.0
71209 silly build right-align@0.1.3
71210 verbose stack RangeError: Maximum call stack size exceeded
71210 verbose stack     at process.stderr (internal/process/stdio.js:23:46)
71210 verbose stack     at isTTY (/usr/lib/node_modules/npm/node_modules/npmlog/node_modules/gauge/progress-bar.js:11:17)
71210 verbose stack     at Object.ProgressBar.show (/usr/lib/node_modules/npm/node_modules/npmlog/node_modules/gauge/progress-bar.js:132:8)
71210 verbose stack     at Object.ProgressBar.pulse (/usr/lib/node_modules/npm/node_modules/npmlog/node_modules/gauge/progress-bar.js:124:8)
71210 verbose stack     at EventEmitter.log.emitLog (/usr/lib/node_modules/npm/node_modules/npmlog/log.js:178:40)
71210 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npmlog/log.js:170:8)
71210 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npmlog/log.js:231:21)
71210 verbose stack     at tracker.(anonymous function) [as silly] (/usr/lib/node_modules/npm/node_modules/npmlog/log.js:79:19)
71210 verbose stack     at module.exports (/usr/lib/node_modules/npm/lib/install/action/build.js:8:7)
71210 verbose stack     at actions.(anonymous function) (/usr/lib/node_modules/npm/lib/install/actions.js:48:12)
71211 verbose cwd /home/vagrant/t1/t1
71212 error Linux 4.4.0-22-generic
71213 error argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "--no-bin-links"
71214 error node v5.12.0
71215 error npm  v3.8.6
71216 error Maximum call stack size exceeded
71217 error If you need help, you may report this error at:
71217 error     <https://github.com/npm/npm/issues>
71218 verbose exit [ 1, true ]
</code>```

without --no-bin-links it works (of course if not inside of shared folder)

Updated node and npm (6.9.1, 3.10.8), the same issue.

答:
You can try this, as it is the system I usually use:

```<code>> npm install --no-bin-links
> npm install --no-bin-links
> npm rebuild node-sass
</code>```

The first npm install ususally errors out with the "Maximum call stack size exceeded.". The second npm install picks up where it left off and finishes up the install. node-sass is usually broken at this point, so the npm rebuild fixes the node-sass installation.

Body:
I am using fresh Homestead (box version 0.5) for a fresh Laravel 5.3 app. Host OS is Windows 10.

I get this error when running npm install --no-bin-links

npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
npm ERR! Linux 4.4.0-22-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "--no-bin-links"
npm ERR! node v5.12.0
npm ERR! npm  v3.8.6

npm ERR! Maximum call stack size exceeded
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR! /home/vagrant/t1/t1/npm-debug.log

npm-debug.log

.........
71199 silly build replace-ext@0.0.1
71200 silly build vinyl@1.2.0
71201 silly build require-dir@0.3.1
71202 silly build require-directory@2.1.1
71203 silly build require-main-filename@1.0.1
71204 silly build resolve@1.1.7
71205 silly build rechoir@0.6.2
71206 silly build resolve-url@0.2.1
71207 silly build rev-hash@1.0.0
71208 silly build rev-path@1.0.0
71209 silly build right-align@0.1.3
71210 verbose stack RangeError: Maximum call stack size exceeded
71210 verbose stack     at process.stderr (internal/process/stdio.js:23:46)
71210 verbose stack     at isTTY (/usr/lib/node_modules/npm/node_modules/npmlog/node_modules/gauge/progress-bar.js:11:17)
71210 verbose stack     at Object.ProgressBar.show (/usr/lib/node_modules/npm/node_modules/npmlog/node_modules/gauge/progress-bar.js:132:8)
71210 verbose stack     at Object.ProgressBar.pulse (/usr/lib/node_modules/npm/node_modules/npmlog/node_modules/gauge/progress-bar.js:124:8)
71210 verbose stack     at EventEmitter.log.emitLog (/usr/lib/node_modules/npm/node_modules/npmlog/log.js:178:40)
71210 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npmlog/log.js:170:8)
71210 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npmlog/log.js:231:21)
71210 verbose stack     at tracker.(anonymous function) [as silly] (/usr/lib/node_modules/npm/node_modules/npmlog/log.js:79:19)
71210 verbose stack     at module.exports (/usr/lib/node_modules/npm/lib/install/action/build.js:8:7)
71210 verbose stack     at actions.(anonymous function) (/usr/lib/node_modules/npm/lib/install/actions.js:48:12)
71211 verbose cwd /home/vagrant/t1/t1
71212 error Linux 4.4.0-22-generic
71213 error argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "--no-bin-links"
71214 error node v5.12.0
71215 error npm  v3.8.6
71216 error Maximum call stack size exceeded
71217 error If you need help, you may report this error at:
71217 error     <https://github.com/npm/npm/issues>
71218 verbose exit [ 1, true ]

without --no-bin-links it works (of course if not inside of shared folder)

Updated node and npm (6.9.1, 3.10.8), the same issue.

Body:
You can try this, as it is the system I usually use:

> npm install --no-bin-links
> npm install --no-bin-links
> npm rebuild node-sass

The first npm install ususally errors out with the "Maximum call stack size exceeded.". The second npm install picks up where it left off and finishes up the install. node-sass is usually broken at this point, so the npm rebuild fixes the node-sass installation.


问:
Why I should create separate project for ReactJS?
I want to use React for front end and Express for backend in my new web application.

According to guides I have to create subproject with create-react-app tool in my project directory:

```<code>my-project
|-frontend
| |-package.json
| |-components
| | |-...
| |
| |-...
|
|-backend
| |-api
| | |-...
| |-app.js
| |-...
|
|-package.json
</code>```

While development, I should launch two servers on different ports, for backend and for frontend, and proxy requests to backend throw React server.

This scheme looks very ugly to me. How can I configure backend server to provide the same functionality as react-scripts does, to avoid using a separate server for it

答:
It is good to separate Front and Backend,
It increases the maintainability
 and if you want you can serve front-end as a root . And all your rest end points in a single server.</p>

Body:
I want to use React for front end and Express for backend in my new web application.

According to guides I have to create subproject with create-react-app tool in my project directory:

my-project
|-frontend
| |-package.json
| |-components
| | |-...
| |
| |-...
|
|-backend
| |-api
| | |-...
| |-app.js
| |-...
|
|-package.json

While development, I should launch two servers on different ports, for backend and for frontend, and proxy requests to backend throw React server.

This scheme looks very ugly to me. How can I configure backend server to provide the same functionality as react-scripts does, to avoid using a separate server for it


问:
how ot add a kinesis stream to trigger lambda function
When configuring a lambda function in the serverless framework, i am trying to add a kinesis stream as the event course:

here is the snippet from serverless.yml

```<code>functions:
  Foo:
    handler: handler.foo
    events:
      - stream:
        arn: arn:aws:kinesis:us-east-1:783995676505:stream/search-helper
        batchSize: 100
        startingPosition: LATEST
        enabled: false
</code>```

The deployment via "serverless deploy" is successful however the trigger does not get added to the function configuration.

I checked the yml file using a yml validatior and there are no errors. What am i missing here ?

答:
The yml file needs to be indented just after stream:

```<code>functions:
  Foo:
    handler: handler.foo
    events:
      - stream:
          arn: arn:aws:kinesis:us-east-1:783995676505:stream/search-helper
          batchSize: 100
          startingPosition: LATEST
          enabled: false
</code>```

See the Serveless Framework examples at https://serverless.com/framework/docs/providers/aws/events/streams/

Body:
When configuring a lambda function in the serverless framework, i am trying to add a kinesis stream as the event course:

here is the snippet from serverless.yml

functions:
  Foo:
    handler: handler.foo
    events:
      - stream:
        arn: arn:aws:kinesis:us-east-1:783995676505:stream/search-helper
        batchSize: 100
        startingPosition: LATEST
        enabled: false

The deployment via "serverless deploy" is successful however the trigger does not get added to the function configuration.

I checked the yml file using a yml validatior and there are no errors. What am i missing here ?

Body:
The yml file needs to be indented just after stream:

functions:
  Foo:
    handler: handler.foo
    events:
      - stream:
          arn: arn:aws:kinesis:us-east-1:783995676505:stream/search-helper
          batchSize: 100
          startingPosition: LATEST
          enabled: false

See the Serveless Framework examples at https://serverless.com/framework/docs/providers/aws/events/streams/


问:
ReactJS POST Parameters Not Sent
I'm simply trying to get POST parameters on my PHP server, sent from my ReactJS app. In the server response, I can see that 'myParameter' is null. I think this is because of the Cross Origin issue, but I've tried many suggestions from answers to similar questions and nothing I've tried has worked. I believe that I'm looking for the proper code to add to my PHP file. It's been days now of this issue and I'm hoping someone here can help.

Background information (in case it matters at all). My PHP file is on my server hosted with hostgator. GET requests with URL parameters work perfectly, but POST parameters seem to be blocked. I'm trying to send more data than the URL option allows.

Thank you so much!

ReactJS Code:

```<code>axios.post('https://mywebsite.com/endpoint.php', {
  myParameter: 'test',
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});
</code>```

PHP Code:

```<code><?php

header("Access-Control-Allow-Origin: *");

echo json_encode($_POST['myParameter']);

?>
</code>```

I also tried this, but it did not change the result:

```<code><?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Max-Age: 86400');

echo json_encode($_POST['myParameter']);

?>
</code>```

EDIT:

Based on the answer from the post linked by Aaqib, I was able to successfully get the data on my server!

答:
Try this and see if it works. </p>

```<code> axios.post('https://mywebsite.com/endpoint.php', {data: {
     myParameter: 'test'
    }
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});
</code>```

Title: ReactJS POST Parameters Not Sent

Body:
I'm simply trying to get POST parameters on my PHP server, sent from my ReactJS app. In the server response, I can see that 'myParameter' is null. I think this is because of the Cross Origin issue, but I've tried many suggestions from answers to similar questions and nothing I've tried has worked. I believe that I'm looking for the proper code to add to my PHP file. It's been days now of this issue and I'm hoping someone here can help.

Background information (in case it matters at all). My PHP file is on my server hosted with hostgator. GET requests with URL parameters work perfectly, but POST parameters seem to be blocked. I'm trying to send more data than the URL option allows.

Thank you so much!

ReactJS Code:

axios.post('https://mywebsite.com/endpoint.php', {
  myParameter: 'test',
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

PHP Code:

<?php

header("Access-Control-Allow-Origin: *");

echo json_encode($_POST['myParameter']);

?>

I also tried this, but it did not change the result:

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Max-Age: 86400');

echo json_encode($_POST['myParameter']);

?>

EDIT:

Based on the answer from the post linked by Aaqib, I was able to successfully get the data on my server!

Body:
Try this and see if it works.

 axios.post('https://mywebsite.com/endpoint.php', {data: {
     myParameter: 'test'
    }
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});


问:
How do I debug a "[object ErrorEvent] thrown" error in my Karma/Jasmine tests?
I have several failing tests that only output [object ErrorEvent] thrown.  I don't see anything in the console that helps me pinpoint the offending code.  Is there something I need to do to track these down?

[EDIT]: I'm running Karma v1.70, Jasmine v2.7.0

答:
TL;DR: It may be related to testing routing.

I'm getting [object ErrorEvent] thrown too.
An hour later, traced it to one line of code.

```<code>this.username = this.userService.getUser(this.route.snapshot.paramMap.get('id'))[0];
</code>```

The problem lies with the test environment attempting to evaluate this.route.snapshot.paramMap.get('id').

If I replace it with 0, [object ErrorEvent] thrown goes away.

My userService has a user like so:

```<code>public users = [ ["admin", "First name", "Surname", etc... ] ].
</code>```

So 0 just gets this user, at index 0.

Otherwise when normally running my app, this.route.snapshot.paramMap.get('id') is evaluated when the user selects a user to edit from my table of users.

So in my HTML, *ngFor="let user of users; index as i" loops to display all the users then routerLink="/edit/{{i}}" so you can click on edit buttons for each user, which when clicked go to e.g. http://localhost:4200/edit/0 to edit the aforementioned admin user's details.

Body:
TL;DR: It may be related to testing routing.

I'm getting [object ErrorEvent] thrown too.
An hour later, traced it to one line of code.

this.username = this.userService.getUser(this.route.snapshot.paramMap.get('id'))[0];

The problem lies with the test environment attempting to evaluate this.route.snapshot.paramMap.get('id').

If I replace it with 0, [object ErrorEvent] thrown goes away.

My userService has a user like so:

public users = [ ["admin", "First name", "Surname", etc... ] ].

So 0 just gets this user, at index 0.

Otherwise when normally running my app, this.route.snapshot.paramMap.get('id') is evaluated when the user selects a user to edit from my table of users.

So in my HTML, *ngFor="let user of users; index as i" loops to display all the users then routerLink="/edit/{{i}}" so you can click on edit buttons for each user, which when clicked go to e.g. http://localhost:4200/edit/0 to edit the aforementioned admin user's details.


问:
Free OLAP solution for .NET running on Mono / MySQL
I'm developing my university graduation project and I'd like to include an OLAP-based reporting module.

In the past, I've used Mondrian with JPivot as an OLAP solution for Java projects and I'm looking for something similar using .NET. The tricky part is that my project should run on Mono and MySQL (installation environment is a Linux machine) so MSSQL OLAP is out of the question.

Anyone knows anything similar to Mondrian / JPivot that I can use? I don't mind even creating most of the aggregation tables myself as long as I have some sort of a crosstab/pivot control for my aspx page

答: If you still interested... I didnt heard anything about native OLAP for .Net, except SQL Server. But you can use Pentaho-CDA plugin for Mondrian (http://code.google.com/p/pentaho-cda/). With this you can execute your queries and receive results by http. You can call a http link from your .Net code and receive result in Json or XML or CSV. It`s a bit odd and tricky, but it might work :)</p>


问:
Querying the Historian seems to kill business network
I am on composer 0.16.0 and Fabric 1.0.4
While experimenting with Historian queries via composer-client consistently run into a situation when the network becomes non-responsive and the only way to reanimate it seems to be restarting the Fabric and redeploying the network.
The error follows:

```<code>>
Error: Error trying to ping. Error: Error trying to query business network. Error: chaincode error (status: 500, message: Error: The current identity has not been registered: admin)
>
</code>```

So, the questions are:
1. Is this a known issue and is there a workaround? Happy to do more diagnostics and file it properly if that helps.
2. Any way to reboot the network without restarting the Fabric?

Thank you!

答:
so the error "The current identity has not been registered: admin" is fundamentally caused by the fact you are restarting your CA server each time - ie a new CA server, a new authority issuing new credentials effectively for 'admin' (and hence your present admin credentials from 'previous' in your card store are not recognised by the new CA server).

Suggest to

1) clear out old admin cards from your card store eg. composer card delete --name admin@tutorial-network

2) re-import your 'admin' card through playground or CLI - and do a composer network ping to retrieve credentials to the card store.

3) Reduce your Historian queries result sets by adding selection criteria

Note: To restart your existing Dev Fabric - just use docker stop to stop your containers - and docker start you can restart them from the same state (or use docker-compose stop and docker-compose start if you're familiar with that command). Else, use docker persistence to persist your data.

https://hyperledger.github.io/composer/tutorials/developer-tutorial.html

Probably good to

Body:
I am on composer 0.16.0 and Fabric 1.0.4
While experimenting with Historian queries via composer-client consistently run into a situation when the network becomes non-responsive and the only way to reanimate it seems to be restarting the Fabric and redeploying the network.
The error follows:

>
Error: Error trying to ping. Error: Error trying to query business network. Error: chaincode error (status: 500, message: Error: The current identity has not been registered: admin)
>

So, the questions are:
1. Is this a known issue and is there a workaround? Happy to do more diagnostics and file it properly if that helps.
2. Any way to reboot the network without restarting the Fabric?

Thank you!


问:
Want a Mysql SELECT query to returns string instead of numbers
I HAVE THIS QUERY

```<code>mysql> select suppliers.valid AS 'Supplier Status' from suppliers;
+-----------------+
| Supplier Status |
+-----------------+
|               0 |
|               0 |
|               0 |
|               0 |
|               0 |
|               0 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
+-----------------+
</code>```

I want the returned results to be  Supplier status is "valid" where "suppliers.valid > 0" and "invalid" where "suppliers.valid = 0".
Can someone  give me ideas  how to achieve this with mysql SQL query?

答:
Use a case expression:</p>

```<code>Select
CASE
WHEN suppliers.valid = 0 THEN 'Invalid'
WHEN suppliers.valid > 0 THEN 'Valid'
END AS 'Supplier Status' from suppliers;
</code>```

Body:
I HAVE THIS QUERY

mysql> select suppliers.valid AS 'Supplier Status' from suppliers;
+-----------------+
| Supplier Status |
+-----------------+
|               0 |
|               0 |
|               0 |
|               0 |
|               0 |
|               0 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
|               1 |
+-----------------+

I want the returned results to be  Supplier status is "valid" where "suppliers.valid > 0" and "invalid" where "suppliers.valid = 0".
Can someone  give me ideas  how to achieve this with mysql SQL query?

Body:
Use a case expression:

Select
CASE
WHEN suppliers.valid = 0 THEN 'Invalid'
WHEN suppliers.valid > 0 THEN 'Valid'
END AS 'Supplier Status' from suppliers;


问:
Sort in linear time comparison based
I'm given the task to write pseudocode for a comparison based algorithm that unshuffles an array, that was first sorted and then shuffled with the following algorithm. The algorithm running time needs to be theta(n).

```<code>Shuffle(int[] A)
n1 = A.length+1 / 2 // floordiv
n2=A.lenght-n1
L = L[n1]
R = R[n2]
L[1...n1] = A[1...n1]
R[1...n2] = A[n1+1...A.length]
i=j=1;
for k=1 to A.length do
  b=Random(0,1)  // returns 0 or 1 equally likely
  if(b == 0 and i<= n1) or j>n2 then
     A[k] = L[i]
     i++;
  else
     A[k] = R[j]
     j++;
</code>```

I've found that after shuffeling A every Item with index i from the left Subarry L lies inbetween A'[i...n2+i].
And every Item with index i from the right Subarray R lies inbetween A'[i-n2...i].
I know that the solution involves finding the median but i don't understand how that's gonna help.

I also know about Selection in worstcase linear time ( from Cormen's Introduction to Algorithms) but how do i combine this to get the right algorithm?

答:
The shuffled array does not disrupt the order of the elements in R or L arrays. Both of them are contained in the shuffled array but their elements are interleaved.

Knowing this fact, you can calculate the median (can be done in linear time) and then use it to recreate R and L again thus undoing the shuffling.

Title: Sort in linear time comparison based

Body:
I'm given the task to write pseudocode for a comparison based algorithm that unshuffles an array, that was first sorted and then shuffled with the following algorithm. The algorithm running time needs to be theta(n).

Shuffle(int[] A)
n1 = A.length+1 / 2 // floordiv
n2=A.lenght-n1
L = L[n1]
R = R[n2]
L[1...n1] = A[1...n1]
R[1...n2] = A[n1+1...A.length]
i=j=1;
for k=1 to A.length do
  b=Random(0,1)  // returns 0 or 1 equally likely
  if(b == 0 and i<= n1) or j>n2 then
     A[k] = L[i]
     i++;
  else
     A[k] = R[j]
     j++;

I've found that after shuffeling A every Item with index i from the left Subarry L lies inbetween A'[i...n2+i].
And every Item with index i from the right Subarray R lies inbetween A'[i-n2...i].
I know that the solution involves finding the median but i don't understand how that's gonna help.

I also know about Selection in worstcase linear time ( from Cormen's Introduction to Algorithms) but how do i combine this to get the right algorithm?


答:
Try this:</p>

```<code>mysql> SELECT IF(CAST(suppliers.valid AS SIGNED INTEGER)=1, "String is 1", "String is 0") AS 'Supplier Status' FROM suppliers;
</code>```

Title: Want a Mysql SELECT query to returns string instead of numbers

Body:
Try this:

mysql> SELECT IF(CAST(suppliers.valid AS SIGNED INTEGER)=1, "String is 1", "String is 0") AS 'Supplier Status' FROM suppliers;


问:
jQuery click event fires the first time, but not the second
This is the HTML I'm working with:

```<code><ul id="categories">
  <li><a href="#cargo">Cargo Trailers</a></li>
  <div class="dropdown">
    <ul>
      <li><a href="#utility">Utility Trailers</a></li>
    </ul>
  </div>
</ul>
</code>```

I have written a jQuery script to hide the dropdown div. The dropdown div appears the first time the click event is fired. Once the li in the dropdown div is selected and switches places with the first li in the #categories ul, clicking on the li will not bring up the dropdown div.

Here is the jQuery:

```<code>jQuery(document).ready(function($) {

// hide the dropdown div
$('#categories > div').hide();

/*
    Click the drop down arrow function
*/
var $listHeader = $('#categories > li');

$listHeader.click(function() {

    if ( $('#categories > div:hidden') ) {
        //show the drop down
        $('#categories > div').show();
    } else {
        //hide the drop down
        $('#categories > div').hide();
    }
});

/*
    Click a list-item in the drop down function
*/
$('#categories > div a').click(function() {

    /* actions to change the title to the newly selected item */
    // hide the ul
    $('#categories > div').hide();

    // move the clicked item to the header
    $(this).prependTo('#categories > li');

    // move the previous title to the dropdown and sort
    $('#categories > li > a:eq(1)').prependTo('#categories > div > ul > li:empty');

    // Reset the listHeader variable
    $listHeader = $('#categories > li');

    // cancel default browser action
    return false;

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

答:
It could be your if statement needs .length on it, giving:

If ( $('selector').length > 0 )
 // show the drop down

Your current if statement doesn't check whether the object exists. Selectors return an empty collection of elements, not null, if they don't match anything.

Body:
This is the HTML I'm working with:

Cargo Trailers

Utility Trailers

I have written a jQuery script to hide the dropdown div. The dropdown div appears the first time the click event is fired. Once the li in the dropdown div is selected and switches places with the first li in the #categories ul, clicking on the li will not bring up the dropdown div.

Here is the jQuery:

jQuery(document).ready(function($) {

// hide the dropdown div
$('#categories > div').hide();

/*
    Click the drop down arrow function
*/
var $listHeader = $('#categories > li');

$listHeader.click(function() {

    if ( $('#categories > div:hidden') ) {
        //show the drop down
        $('#categories > div').show();
    } else {
        //hide the drop down
        $('#categories > div').hide();
    }
});

/*
    Click a list-item in the drop down function
*/
$('#categories > div a').click(function() {

    /* actions to change the title to the newly selected item */
    // hide the ul
    $('#categories > div').hide();

    // move the clicked item to the header
    $(this).prependTo('#categories > li');

    // move the previous title to the dropdown and sort
    $('#categories > li > a:eq(1)').prependTo('#categories > div > ul > li:empty');

    // Reset the listHeader variable
    $listHeader = $('#categories > li');

    // cancel default browser action
    return false;

});
});


问:
Add a panel to application (specifically Ellie Mae Encompass) via plugin.
I am looking to add a rightpanel menu to the Encompass application to show additional data while in a loan. I had a friend give me the following code as a starting point, but I'm getting lost (not sure if I'm missing references, etc.). I'm a pretty novice programmer looking at code from someone much much better than me. So any help in getting this to work would be appreciated!</p>

```<code>using System;
using EllieMae.Encompass.ComponentModel;
using EllieMae.Encompass.Automation;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;

namespace RightPanel
{

    [Plugin]
    public class RightPanel
    {
        private Form mainForm;
        private TabControl _tabs;
        private bool _created;
        private Panel rightPanel;

        public RightPanel()
        {
            EncompassApplication.Login += new EventHandler(EncompassApplication_Login);
        }
        private void EncompassApplication_Login(object sender, EventArgs e)
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form.Text.ToLower().Contains("encompass"))
                {
                    mainForm = form;
                }
            }

            Control[] controlArray = mainForm.Controls.Find("tabControl", true);
            if ((uint)((IEnumerable<Control>)controlArray).Count<Control>() <= 0U)
                return;

            _tabs = controlArray[0] as TabControl;
            _tabs.SelectedIndexChanged += new EventHandler(SelectedIndex_Changed);
        }

        private void SelectedIndex_Changed(object sender, EventArgs e)
        {
            if (_tabs.SelectedIndex < 0)
                return;
            TabPage tabPage = _tabs.TabPages[_tabs.SelectedIndex];
            if (tabPage != null && (tabPage.Name.Contains("loanTabPage")))
                BindToRightPanel();
        }

        private void BindToRightPanel()
        {
            if (_created)
                return;
            Control[] controlArray = mainForm.Controls.Find("rightPanel", `enter code here`true);
            if (((IEnumerable<Control>)controlArray).Count() > 0)
            {
                rightPanel = controlArray[0] as Panel;
                CreateMenu();
            }
        }

        private void CreateMenu()
        {
            if (mainForm == null)
                return;

            RemoveControlById(Settings.MainMenu, rightPanel);
            RemoveControlById(Settings.MenuButtonPanel, rightPanel);

            MenuButton menuButton = GetMenuButton("Open Loan Tools", "MtgMenuButton");
            menuButton.BackColor = Color.White;

            MenuPanel = new MenuPanel(Settings.GetMenu(), menuButton);
            MenuPanel.Name = Settings.MainMenu;
            MenuPanel.Dock = DockStyle.Right;

            Panel panel = new Panel();
            panel.Name = Settings.MenuButtonPanel;
            panel.Width = 27;
            panel.Dock = DockStyle.Right;
            panel.Controls.Add((Control)menuButton);

            rightPanel.Controls.Add((Control)MenuPanel);
            rightPanel.Controls.Add((Control)panel);
            _created = true;
        }

        private List<MenuPanelSection> GetMenu()
        {
            return new List<MenuPanelSection>()
      {  new MenuPanelSection(Utilities.GetHeading("Loan Information"), Utilities.HighestWeightedPersona() == "Loan Officer", new Control[1]
        {
          (Control) new LoanInformation()
        })
      };
        }

        private void RemoveControlById(string controlID, Panel panel)
        {
            Control[] controlArray = panel.Controls.Find(controlID, true);
            if ((uint)((IEnumerable<Control>)controlArray).Count<Control>() <= 0U)
                return;

            for (int i = 0; i < ((IEnumerable<Control>)controlArray).Count<Control>(); ++i)
                controlArray[i].Parent.Controls.Remove(controlArray[i]);
        }

        private MenuButton GetMenuButton(string buttonText, string buttonName)
        {
            MenuButton menuButton = new MenuButton();
            menuButton.AutoSize = true;
            menuButton.FlatAppearance.BorderSize = 0;
            menuButton.FlatStyle = 0;
            menuButton.Height = 100;
            menuButton.Name = buttonName;
            menuButton.VerticalText = buttonText;
            menuButton.Width = 27;

            return menuButton;
        }
    }
</code>```

答:
This line of code appears a couple times in your sample above:

```<code>Control[] controlArray = mainForm.Controls.Find("rightPanel", true);
</code>```

The Controls.Find function only takes one parameter, the name of the control you are looking for and it only returns that control if it is found, not an array of controls.

Changing the above line to this will correct that problem.

```<code>Control control = mainForm.Controls.Find("rightPanel");
</code>```

Ellie Mae provides is own form objects and controls to be used in side the application. Remove the reference to the System.Windows.Forms and add:

```<code>using Elliemae.Encompass.Forms;
</code>```

I haven't tried running the code, this is what I found looking through the sample you provided. If you have more specific errors I might be able to help you through them.

Body:
I am looking to add a rightpanel menu to the Encompass application to show additional data while in a loan. I had a friend give me the following code as a starting point, but I'm getting lost (not sure if I'm missing references, etc.). I'm a pretty novice programmer looking at code from someone much much better than me. So any help in getting this to work would be appreciated!

using System;
using EllieMae.Encompass.ComponentModel;
using EllieMae.Encompass.Automation;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;

namespace RightPanel
{

    [Plugin]
    public class RightPanel
    {
        private Form mainForm;
        private TabControl _tabs;
        private bool _created;
        private Panel rightPanel;

        public RightPanel()
        {
            EncompassApplication.Login += new EventHandler(EncompassApplication_Login);
        }
        private void EncompassApplication_Login(object sender, EventArgs e)
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form.Text.ToLower().Contains("encompass"))
                {
                    mainForm = form;
                }
            }

            Control[] controlArray = mainForm.Controls.Find("tabControl", true);
            if ((uint)((IEnumerable<Control>)controlArray).Count<Control>() <= 0U)
                return;

            _tabs = controlArray[0] as TabControl;
            _tabs.SelectedIndexChanged += new EventHandler(SelectedIndex_Changed);
        }

        private void SelectedIndex_Changed(object sender, EventArgs e)
        {
            if (_tabs.SelectedIndex < 0)
                return;
            TabPage tabPage = _tabs.TabPages[_tabs.SelectedIndex];
            if (tabPage != null && (tabPage.Name.Contains("loanTabPage")))
                BindToRightPanel();
        }

        private void BindToRightPanel()
        {
            if (_created)
                return;
            Control[] controlArray = mainForm.Controls.Find("rightPanel", `enter code here`true);
            if (((IEnumerable<Control>)controlArray).Count() > 0)
            {
                rightPanel = controlArray[0] as Panel;
                CreateMenu();
            }
        }

        private void CreateMenu()
        {
            if (mainForm == null)
                return;

            RemoveControlById(Settings.MainMenu, rightPanel);
            RemoveControlById(Settings.MenuButtonPanel, rightPanel);

            MenuButton menuButton = GetMenuButton("Open Loan Tools", "MtgMenuButton");
            menuButton.BackColor = Color.White;

            MenuPanel = new MenuPanel(Settings.GetMenu(), menuButton);
            MenuPanel.Name = Settings.MainMenu;
            MenuPanel.Dock = DockStyle.Right;

            Panel panel = new Panel();
            panel.Name = Settings.MenuButtonPanel;
            panel.Width = 27;
            panel.Dock = DockStyle.Right;
            panel.Controls.Add((Control)menuButton);

            rightPanel.Controls.Add((Control)MenuPanel);
            rightPanel.Controls.Add((Control)panel);
            _created = true;
        }

        private List<MenuPanelSection> GetMenu()
        {
            return new List<MenuPanelSection>()
      {  new MenuPanelSection(Utilities.GetHeading("Loan Information"), Utilities.HighestWeightedPersona() == "Loan Officer", new Control[1]
        {
          (Control) new LoanInformation()
        })
      };
        }

        private void RemoveControlById(string controlID, Panel panel)
        {
            Control[] controlArray = panel.Controls.Find(controlID, true);
            if ((uint)((IEnumerable<Control>)controlArray).Count<Control>() <= 0U)
                return;

            for (int i = 0; i < ((IEnumerable<Control>)controlArray).Count<Control>(); ++i)
                controlArray[i].Parent.Controls.Remove(controlArray[i]);
        }

        private MenuButton GetMenuButton(string buttonText, string buttonName)
        {
            MenuButton menuButton = new MenuButton();
            menuButton.AutoSize = true;
            menuButton.FlatAppearance.BorderSize = 0;
            menuButton.FlatStyle = 0;
            menuButton.Height = 100;
            menuButton.Name = buttonName;
            menuButton.VerticalText = buttonText;
            menuButton.Width = 27;

            return menuButton;
        }
    }

Body:
This line of code appears a couple times in your sample above:

Control[] controlArray = mainForm.Controls.Find("rightPanel", true);

The Controls.Find function only takes one parameter, the name of the control you are looking for and it only returns that control if it is found, not an array of controls.

Changing the above line to this will correct that problem.

Control control = mainForm.Controls.Find("rightPanel");

Ellie Mae provides is own form objects and controls to be used in side the application. Remove the reference to the System.Windows.Forms and add:

using Elliemae.Encompass.Forms;

I haven't tried running the code, this is what I found looking through the sample you provided. If you have more specific errors I might be able to help you through them.