问:
Getting the best of static_assert and std::is_invocable
I have a library with several function objects that might only accept a few types depending on std::is_integral. I want std::is_invocable to return false when the condition fails, but I also want a nice static_assert error message when a user tries to call an instance of the function object. Here is a simplified example of the function objects I currently have:

```<code>struct function
{
    template<typename Iterator>
    auto operator()(Iterator first, Iterator last) const
        -> std::enable_if_t<std::is_integral_v<
            typename std::iterator_traits<Iterator>::value_type
        >>
    { /* something */ }
};
</code>```

With such an implementation, std::is_invocable is std::false_type as expected when the SFINAE condition is not met, but users encounter ugly SFINAE error messages when they try to call the function object with parameters that don't meet the SFINAE condition.

To get better error messages, I tried the following solution instead:

```<code>struct function
{
    template<typename Iterator>
    auto operator()(Iterator first, Iterator last) const
        -> void
    {
        static_assert(std::is_integral_v<typename std::iterator_traits<Iterator>::value_type>,
                      "function can only be called with a collection of integers");

        /* something */
    }
};
</code>```

With this implementation, users get friendly error messages when the original SFINAE condition is not met, but std::is_invocable is std::true_type when asked whether a function instance can handle a type that does not satisfy std::is_integral.

I tried several tricks and variations involving decltype(auto), if constexpr and other mechanisms, but couldn't get a class where error messages were nice and where std::is_invocable corresponded to the expected std::false_type when asking whether function could be invoked with incorrect types.

What am I missing here? Is there a way to get both proper std::is_invocable and user-friendly error messages?

答:
Here's one awful way. Add an overload:

```<code>template <typename Iterator>
auto operator()(Iterator first, Iterator last) const
    -> std::enable_if_t<std::is_integral_v<
        typename std::iterator_traits<Iterator>::value_type
    >>;

template <typename Iterator, class... Args>
void operator()(Iterator, Iterator, Args&&... ) const = delete; // must be integral
</code>```

This satisfies the is_invocable<> condition, since the contrained function template is more specialized and preferred - so if the condition is met, the function is invocable, else it's deleted.

This does a little bit better on the error case, since if you try to call it, you get:

```<code>foo.cxx: In function ‘int main()’:
foo.cxx:31:13: error: use of deleted function ‘void function::operator()(Iterator, Iterator, Args&& ...) const [with Iterator = std::__cxx11::basic_string<char>*; Args = {}]’
     f(&i, &i);
             ^
foo.cxx:19:10: note: declared here
     void operator()(Iterator, Iterator, Args&&... ) const = delete; // must be integral
          ^~~~~~~~
</code>```

The comment shows up in the error message, which is sort of like a static assert message?

This is actually one of the motivations for Concepts. With a requires instead of an enable_if, we get:

```<code>foo.cxx: In function ‘int main()’:
foo.cxx:26:13: error: no match for call to ‘(function) (std::__cxx11::string*, std::__cxx11::string*)’
     f(&i, &i);
             ^
foo.cxx:11:10: note: candidate: void function::operator()(Iterator, Iterator) const requires  is_integral_v<typename std::iterator_traits<_Iter>::value_type> [with Iterator = std::__cxx11::basic_string<char>*]
     void operator()(Iterator first, Iterator last) const
          ^~~~~~~~
foo.cxx:11:10: note:   constraints not satisfied
foo.cxx:11:10: note: ‘is_integral_v<typename std::iterator_traits<_Iter>::value_type>’ evaluated to false
</code>```

That's... a little better I guess.

Body:
I have a library with several function objects that might only accept a few types depending on std::is_integral. I want std::is_invocable to return false when the condition fails, but I also want a nice static_assert error message when a user tries to call an instance of the function object. Here is a simplified example of the function objects I currently have:

struct function
{
    template<typename Iterator>
    auto operator()(Iterator first, Iterator last) const
        -> std::enable_if_t<std::is_integral_v<
            typename std::iterator_traits<Iterator>::value_type
        >>
    { /* something */ }
};

With such an implementation, std::is_invocable is std::false_type as expected when the SFINAE condition is not met, but users encounter ugly SFINAE error messages when they try to call the function object with parameters that don't meet the SFINAE condition.

To get better error messages, I tried the following solution instead:

struct function
{
    template<typename Iterator>
    auto operator()(Iterator first, Iterator last) const
        -> void
    {
        static_assert(std::is_integral_v<typename std::iterator_traits<Iterator>::value_type>,
                      "function can only be called with a collection of integers");

        /* something */
    }
};

With this implementation, users get friendly error messages when the original SFINAE condition is not met, but std::is_invocable is std::true_type when asked whether a function instance can handle a type that does not satisfy std::is_integral.

I tried several tricks and variations involving decltype(auto), if constexpr and other mechanisms, but couldn't get a class where error messages were nice and where std::is_invocable corresponded to the expected std::false_type when asking whether function could be invoked with incorrect types.

What am I missing here? Is there a way to get both proper std::is_invocable and user-friendly error messages?

Body:
Here's one awful way. Add an overload:

template <typename Iterator>
auto operator()(Iterator first, Iterator last) const
    -> std::enable_if_t<std::is_integral_v<
        typename std::iterator_traits<Iterator>::value_type
    >>;

template <typename Iterator, class... Args>
void operator()(Iterator, Iterator, Args&&... ) const = delete; // must be integral

This satisfies the is_invocable<> condition, since the contrained function template is more specialized and preferred - so if the condition is met, the function is invocable, else it's deleted.

This does a little bit better on the error case, since if you try to call it, you get:

foo.cxx: In function ‘int main()’:
foo.cxx:31:13: error: use of deleted function ‘void function::operator()(Iterator, Iterator, Args&& ...) const [with Iterator = std::__cxx11::basic_string<char>*; Args = {}]’
     f(&i, &i);
             ^
foo.cxx:19:10: note: declared here
     void operator()(Iterator, Iterator, Args&&... ) const = delete; // must be integral
          ^~~~~~~~

The comment shows up in the error message, which is sort of like a static assert message?

This is actually one of the motivations for Concepts. With a requires instead of an enable_if, we get:

foo.cxx: In function ‘int main()’:
foo.cxx:26:13: error: no match for call to ‘(function) (std::__cxx11::string*, std::__cxx11::string*)’
     f(&i, &i);
             ^
foo.cxx:11:10: note: candidate: void function::operator()(Iterator, Iterator) const requires  is_integral_v<typename std::iterator_traits<_Iter>::value_type> [with Iterator = std::__cxx11::basic_string<char>*]
     void operator()(Iterator first, Iterator last) const
          ^~~~~~~~
foo.cxx:11:10: note:   constraints not satisfied
foo.cxx:11:10: note: ‘is_integral_v<typename std::iterator_traits<_Iter>::value_type>’ evaluated to false

That's... a little better I guess.


来源: stackexchange

问:
ionic2 datepicker current date
I am new to Ionic2.

Is there any way to display showing current date in ionic2 of datepicker ?? I mean current date won't show before datepicker's pick.It will only show only when datepicker apears. Thanks in advance.

答:
Try mapping the datepicker model to a variable which holds the current date:

```<code><ion-datetime [(ngModel)]="currentDate" /></ion-datetime
</code>```

and in your controller:

```<code>var currentDate = new Date();
</code>```

here's an example :

https://codesundar.com/ionic2-tutorial/ionic-2-date-picker-example/

ContentLicense: CC BY-SA 3.0

Title: ionic2 datepicker current date

Body:
Try mapping the datepicker model to a variable which holds the current date:

<ion-datetime [(ngModel)]="currentDate" /></ion-datetime

and in your controller:

var currentDate = new Date();

here's an example :

https://codesundar.com/ionic2-tutorial/ionic-2-date-picker-example/


问:
How do I shape my input data for use with Conv1D in keras?
I have in my dummy dataset 12 vectors of length 200, each vector representing one sample. Let's say x_train is an array with shape (12, 200).

When I do:

```<code>model = Sequential()
model.add(Conv1D(2, 4, input_shape=(1, 200)))
</code>```

I get the error:

```<code>ValueError: Error when checking model input: expected conv1d_1_input to have 3 dimensions, but got array with shape (12, 200)
</code>```

How do I shape my input array correctly?

Here is my updated script:

```<code>data = np.loadtxt('temp/data.csv', delimiter=' ')
trainData = []
testData = []
trainlabels = []
testlabels = []

with open('temp/trainlabels', 'r') as f:
    trainLabelFile = list(csv.reader(f))

with open('temp/testlabels', 'r') as f:
    testLabelFile = list(csv.reader(f))

for i in range(2):
    for idx in trainLabelFile[i]:
        trainData.append(data[int(idx)])
        # append 0 to labels for neg, 1 for pos
        trainlabels.append(i)

for i in range(2):
    for idx in testLabelFile[i]:
        testData.append(data[int(idx)])
        # append 0 to labels for neg, 1 for pos
        testlabels.append(i)

# print(trainData.shape)
X = np.array(trainData)
Y = np.array(trainlabels)
X2 = np.array(testData)
Y2 = np.array(testlabels)

model = Sequential()
model.add(Conv1D(1, 1, input_shape=(12, 1, 200)))

opt = 'adam'
model.compile(loss='mean_squared_error', optimizer=opt, metrics=['accuracy'])

model.fit(X, Y, epochs=epochs)
</code>```

I am now getting a new error:

```<code>ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=4
</code>```

答:
In Keras documentation, it is written that input_shape is a 3D tensor with shape (batch_size, steps, input_dim). The meaning is as follows:

batch_size is the number of samples. It is 12 for you.

steps is the time dimension of the data. You can set it to 1 as you have only one channel in the data.

input_dim is the dimension of one sample. It is 200 for you.

Answer to your question is to reshape your data to (12,1,200).

Body:
I have in my dummy dataset 12 vectors of length 200, each vector representing one sample. Let's say x_train is an array with shape (12, 200).

When I do:

model = Sequential()
model.add(Conv1D(2, 4, input_shape=(1, 200)))

I get the error:

ValueError: Error when checking model input: expected conv1d_1_input to have 3 dimensions, but got array with shape (12, 200)

How do I shape my input array correctly?

Here is my updated script:

data = np.loadtxt('temp/data.csv', delimiter=' ')
trainData = []
testData = []
trainlabels = []
testlabels = []

with open('temp/trainlabels', 'r') as f:
    trainLabelFile = list(csv.reader(f))

with open('temp/testlabels', 'r') as f:
    testLabelFile = list(csv.reader(f))

for i in range(2):
    for idx in trainLabelFile[i]:
        trainData.append(data[int(idx)])
        # append 0 to labels for neg, 1 for pos
        trainlabels.append(i)

for i in range(2):
    for idx in testLabelFile[i]:
        testData.append(data[int(idx)])
        # append 0 to labels for neg, 1 for pos
        testlabels.append(i)

# print(trainData.shape)
X = np.array(trainData)
Y = np.array(trainlabels)
X2 = np.array(testData)
Y2 = np.array(testlabels)

model = Sequential()
model.add(Conv1D(1, 1, input_shape=(12, 1, 200)))

opt = 'adam'
model.compile(loss='mean_squared_error', optimizer=opt, metrics=['accuracy'])

model.fit(X, Y, epochs=epochs)

I am now getting a new error:

ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=4


问:
Getting Error while executing lambda through step functions
I am executing step function. but, i am getting error in execution of one state.

It giving error : Lambda.Unknown cause: The cause could not be determined because Lambda did not return an error type.

My lambda function calls external webservice. I don't want to wait until webservice response is received.

Can we return data from function without waiting for webservice response ??

My Lambda function

```<code>var http = require('http');
exports.handler = (event, context, callback) => {

    var inputJson= {};

    inputJson.firstname= event.firstname;
    inputJson.lastname= event.lastname;
    inputJson.workspacename= event.workspacename;
    inputJson.customermailid= event.customermailid;
    inputJson.mobilenumber= event.mobilenumber;
    inputJson.orgname= event.orgname;

    inputJson.sessionid= event.sessionid;

    var post_data = JSON.stringify({
        "domainname" : inputJson.domainname,
        "orgname" : inputJson.orgname,
        "customermailid" : inputJson.customermailid,
        "adminmailid":"postmaster@test.int",
        "product":3
    });

  // An object of options to indicate where to post to
  var post_options = {
      host: 'host_ip',
      path: 'path',
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      }
  };

  // Set up the request
  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');

  });

   post_req.on('error', function (event) {
          console.log('Response: Error=' + event);
          callback(null, inputJson);
   });

  // post the data
  post_req.write(post_data);
  post_req.end();

  callback(null, inputJson);

};
</code>```

答: You can, but it might not give the results you expect. Especially with your post error handling.  However, if you want Lambda to return without waiting for your post response. You can set: context.callbackWaitsForEmptyEventLoop = false

Body:
I am executing step function. but, i am getting error in execution of one state.

It giving error : Lambda.Unknown cause: The cause could not be determined because Lambda did not return an error type.

My lambda function calls external webservice. I don't want to wait until webservice response is received.

Can we return data from function without waiting for webservice response ??

My Lambda function

var http = require('http');
exports.handler = (event, context, callback) => {

    var inputJson= {};

    inputJson.firstname= event.firstname;
    inputJson.lastname= event.lastname;
    inputJson.workspacename= event.workspacename;
    inputJson.customermailid= event.customermailid;
    inputJson.mobilenumber= event.mobilenumber;
    inputJson.orgname= event.orgname;

    inputJson.sessionid= event.sessionid;

    var post_data = JSON.stringify({
        "domainname" : inputJson.domainname,
        "orgname" : inputJson.orgname,
        "customermailid" : inputJson.customermailid,
        "adminmailid":"postmaster@test.int",
        "product":3
    });

  // An object of options to indicate where to post to
  var post_options = {
      host: 'host_ip',
      path: 'path',
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      }
  };

  // Set up the request
  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');

  });

   post_req.on('error', function (event) {
          console.log('Response: Error=' + event);
          callback(null, inputJson);
   });

  // post the data
  post_req.write(post_data);
  post_req.end();

  callback(null, inputJson);

};


问:
Sample AlarmController application Service registeration in AndroidManifest
I am new to Android and trying to implement the sample AlarmController application. Everything is fine but its Alarm Service is not working. I was wondering that do I need to register these services in the AndroidManifest.xml file as the other activities a are registered and if yes. How do I do that, I guess the alarm controller code is Available on Android's website therefore I am just putting the AndroidManifest.xml code of my application.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.AlarmController"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AlarmActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>
</code>```

答:
I just found it as the "CommonsWare" said in the other answer there needs to be a service tag in AndroidManifest.xml

```<code>?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.AlarmController"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AlarmActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="AlarmService_service" />

    </application>

</manifest>
</code>```

So whatever service, reciever, activity and etc you are using, you need to register it in your AndroidManifest.xml.

ContentLicense: CC BY-SA 2.5

Body:
I am new to Android and trying to implement the sample AlarmController application. Everything is fine but its Alarm Service is not working. I was wondering that do I need to register these services in the AndroidManifest.xml file as the other activities a are registered and if yes. How do I do that, I guess the alarm controller code is Available on Android's website therefore I am just putting the AndroidManifest.xml code of my application.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.AlarmController"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AlarmActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Body:
I just found it as the "CommonsWare" said in the other answer there needs to be a service tag in AndroidManifest.xml

?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.AlarmController"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AlarmActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="AlarmService_service" />

    </application>

</manifest>

So whatever service, reciever, activity and etc you are using, you need to register it in your AndroidManifest.xml.


问:
Embeeded *ngFor in Angular4
Hi i have a problem with embeeded *ngFor loop. I try to make make something like that.

```<code><div *ngFor = let console of consoles>
...
...
<li *ngFor = let pad of console.pad>
{{pad}
</li>
...
...
</div>
</code>```

I tryed to put [innerHtml] data binding and it works but i have to make that second ngFor working because it will work great with my css styling.

Thank you in advance.

PS. I'm using Angular4

答:
Do you mean use innerHTML in the {{pad}} location?
you may try this way if so:</p>

```<code><div *ngFor = let console of consoles>
    ...
    ...
    <li *ngFor = let pad of console.pad>
        <span [innerHTML] = {{pad}}></span>
    </li>
    ...
    ...
</div>
</code>```

Title: Embeeded *ngFor in Angular4

Body:
Hi i have a problem with embeeded *ngFor loop. I try to make make something like that.

...
...

{{pad}

...
...

I tryed to put [innerHtml] data binding and it works but i have to make that second ngFor working because it will work great with my css styling.

Thank you in advance.

PS. I'm using Angular4

Body:
Do you mean use innerHTML in the {{pad}} location?
you may try this way if so:

<div *ngFor = let console of consoles>
    ...
    ...
    <li *ngFor = let pad of console.pad>
        <span [innerHTML] = {{pad}}></span>
    </li>
    ...
    ...
</div>


问:
Understanding map in Scala
Please help me understand what map(_(0)) means here:</p>

```<code>scala> a.collect
res97: Array[org.apache.spark.sql.Row] = Array([1039], [1010], [1002], [926])

scala> a.collect.map(_(0))
res98: Array[Any] = Array(1039, 1010, 1002, 926)
</code>```

答:
1. .map in functional programming applies the function you want to each element of your collection.

Say, you want to add some data to each element in an array you have, which can be done as below,

```<code>scala> val data = Array("a", "b", "c")
data: Array[String] = Array(a, b, c)

scala> data.map(element => element+"-add something")
res10: Array[String] = Array(a-add something, b-add something, c-add something)
</code>```

Here, I'm saying, on each element add something, but element is unnecessary because you are adding on every element anyway. So, _ is what represents any element here.

So, same map can be done in following way.

```<code>scala> data.map(_+"-add something")
res9: Array[String] = Array(a-add something, b-add something, c-add something)
</code>```

Also, note that _ is used when you have one line mapping function.

2. collection(index) is the way to access nth element in a collection.

eg.

```<code>scala> val collection = Array(Vector(1039), Vector(1010), Vector(1002), Vector(926))
collection: Array[scala.collection.immutable.Vector[Int]] = Array(Vector(1039), Vector(1010), Vector(1002), Vector(926))

scala> collection(0)
res13: scala.collection.immutable.Vector[Int] = Vector(1039)
</code>```

So, combining #1 and #2, in your case you are mapping the original collection and getting the first element.

```<code>scala> collection.map(_.head)
res17: Array[Int] = Array(1039, 1010, 1002, 926)
</code>```

Refs

https://twitter.github.io/scala_school/collections.html#map

Map, Map and flatMap in Scala

Title: Understanding map in Scala

Body:
Please help me understand what map(_(0)) means here:

scala> a.collect
res97: Array[org.apache.spark.sql.Row] = Array([1039], [1010], [1002], [926])

scala> a.collect.map(_(0))
res98: Array[Any] = Array(1039, 1010, 1002, 926)

Body:
1. .map in functional programming applies the function you want to each element of your collection.

Say, you want to add some data to each element in an array you have, which can be done as below,

scala> val data = Array("a", "b", "c")
data: Array[String] = Array(a, b, c)

scala> data.map(element => element+"-add something")
res10: Array[String] = Array(a-add something, b-add something, c-add something)

Here, I'm saying, on each element add something, but element is unnecessary because you are adding on every element anyway. So, _ is what represents any element here.

So, same map can be done in following way.

scala> data.map(_+"-add something")
res9: Array[String] = Array(a-add something, b-add something, c-add something)

Also, note that _ is used when you have one line mapping function.

2. collection(index) is the way to access nth element in a collection.

eg.

scala> val collection = Array(Vector(1039), Vector(1010), Vector(1002), Vector(926))
collection: Array[scala.collection.immutable.Vector[Int]] = Array(Vector(1039), Vector(1010), Vector(1002), Vector(926))

scala> collection(0)
res13: scala.collection.immutable.Vector[Int] = Vector(1039)

So, combining #1 and #2, in your case you are mapping the original collection and getting the first element.

scala> collection.map(_.head)
res17: Array[Int] = Array(1039, 1010, 1002, 926)

Refs

https://twitter.github.io/scala_school/collections.html#map

Map, Map and flatMap in Scala


问:
Why doesn't the additive constant in Big-O notation matter?
In definition of Big-O notation we care only about C coefficient:

```<code>f(n) ≤ Cg(n) for all n ≥ k
</code>```

Why don't we care about A as well:

```<code>f(n) ≤ Cg(n) + A for all n ≥ k
</code>```

答:
There are really two cases to consider here. For starters, imagine that your function g(n) has the property that g(n) ≥ 1 for all "sufficiently large" choices of n. In that case, if you know that

f(n) ≥ cg(n) + A,

then you also know that

f(n) ≥ cg(n) + Ag(n),

so

f(n) ≥ (c + A)g(n).

In other words, if your function g is always at least one, then bounding f(n) by something of the form cg(n) + A is equivalent to bounding it with something of the form c'g(n) for some new constant c'. In that sense, adding some extra flexibility into the definition of big-O notation, at least in this case, wouldn't make a difference.

In the context of the analysis of algorithms, pretty much every function g(n) you might bound something with will be at least one, and so we can "munch up" that extra additive term by choosing a larger multiple of g.

However, big-O notation is also used in many cases to bound functions that decrease as n increases. For example, we might say that the probability that some algorithm gives back the right answer is O(1 / n), where the function 1/n drops to 0 as a function of n. In this case, we use big-O notation to talk about how fast the function drops off. If the success probability is O(1 / n2), for example, that's a better guarantee than the earlier O(1 / n) success probability, assuming n gets sufficiently large. In that case, allowing for additive terms in the definition of big-O notation would actually break things. For example, intuitively, the function 1 / n2 drops to 0 faster than the function 1 / n, and using the formal definition of big-O notation you can see this because 1 / n2 ≤ 1 / n for all n ≥ 1. However, with your modified definition of big-O notation, we could also say that 1 / n = O(1 / n2), since

1 / n ≤ 1 / n2 + 1 for all n ≥ 1,

which is true only because the additive 1 term bounds the 1/n term, not the 1/n2 we might have been initially interested in.

So the long answer to your question is "the definition you proposed above is equivalent to the regular definition of big-O if we only restrict ourselves to the case where g(n) doesn't drop to zero as a function of n, and in the case where g(n) does drop the zero as a function of n your new definition isn't particularly useful."

Body:
In definition of Big-O notation we care only about C coefficient:

f(n) ≤ Cg(n) for all n ≥ k

Why don't we care about A as well:

f(n) ≤ Cg(n) + A for all n ≥ k


问:
How to resolve ipython (show) install error
I'm trying to install show on linux and am getting the following error:

```<code>sudo pip install show
...
Collecting ipython (from show)
Downloading ipython-6.1.0.tar.gz (5.1MB)
100% |████████████████████████████████| 5.1MB 89kB/s
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "<string>", line 20, in <module

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-xYQAaZ/ipython
</code>```

There is no such file/dir /tmp/pip-build-xYQAaZ/ipython so I don't have any more details.  Any ideas how to debug this further or resolve the install issue?  I'm on python 2.6.6.  I was able to install show on another linux system with python 2.6.6 without any issues.

答: I had similar issues installing a python package (had the same error code). What eventually worked was installing the wheel. First install support for wheels by doing pip install wheel and then you can download the wheel file from here and install it using pip install ____

Body:
I'm trying to install show on linux and am getting the following error:

sudo pip install show
...
Collecting ipython (from show)
Downloading ipython-6.1.0.tar.gz (5.1MB)
100% |████████████████████████████████| 5.1MB 89kB/s
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
  File "<string>", line 20, in <module

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-xYQAaZ/ipython

There is no such file/dir /tmp/pip-build-xYQAaZ/ipython so I don't have any more details.  Any ideas how to debug this further or resolve the install issue?  I'm on python 2.6.6.  I was able to install show on another linux system with python 2.6.6 without any issues.


问:
qt virtual keyboard does not show up
I am trying to use the qt virtual keyboard on a raspberry pi and am having issues summoning the keyboard.

I have configured the project as follows to allow for the use of virtual keyboard:

```<code>//In the PRO file
QT += qml quick quickcontrols2 xml
static {
    QT += svg
    QTPLUGIN += qtvirtualkeyboardplugin
}

CONFIG += c++11 disable-desktop
</code>```

I think the disable-desktop should be enough to summon the virtual keyboard, at least that is my assumption.

The first line in my main file is:

```<code>qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
</code>```

This ensures that the module is loaded. I have verified that without this line, the program barfs with the virtual keyboard module not found error.

Now, I have a simple component which has a text field as:

```<code>import QtQuick 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.1
import QtQuick.VirtualKeyboard 2.1

TextField {
            id: idField
            width: 80
            height: 30
            placeholderText: qsTr("ID")
            Layout.maximumHeight: 30
            Layout.minimumHeight: 30
            Layout.minimumWidth: 80
            Layout.maximumWidth: 80
            focus: true
            anchors.horizontalCenter: parent.horizontalCenter
            inputMethodHints: Qt.ImhDigitsOnly
        }
</code>```

When I click on it, the keyboard does not show up. I wonder if there is additional setup I need to do in order to summon the keyboard?

答:
disable-desktop should be passed as an argument to qmake before building Qt Virtual Keyboard, not the application that uses the keyboard:

```<code>qmake CONFIG+=disable-desktop qtvirtualkeyboard.pro
</code>```

However, I think that this code would automatically handle that for embedded devices (meaning that a pre-built/packaged Qt should work).

When using disable-desktop, it's up to you to provide the InputPanel:

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.VirtualKeyboard 2.0

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480

    TextField {
        anchors.centerIn: parent
    }

    InputPanel {
        id: inputPanel
        z: 89
        y: active ? parent.height - height : parent.height
        anchors.left: parent.left
        anchors.right: parent.right
    }
}
</code>```

There's a more advanced example of this here. This part of the documentation mentions it, and the next chapter also has an example:

In the application integration method, the application is required to create an instance of InputPanel as explained in the following chapter.

Title: qt virtual keyboard does not show up

Body:
I am trying to use the qt virtual keyboard on a raspberry pi and am having issues summoning the keyboard.

I have configured the project as follows to allow for the use of virtual keyboard:

//In the PRO file
QT += qml quick quickcontrols2 xml
static {
    QT += svg
    QTPLUGIN += qtvirtualkeyboardplugin
}

CONFIG += c++11 disable-desktop

I think the disable-desktop should be enough to summon the virtual keyboard, at least that is my assumption.

The first line in my main file is:

qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));

This ensures that the module is loaded. I have verified that without this line, the program barfs with the virtual keyboard module not found error.

Now, I have a simple component which has a text field as:

import QtQuick 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.1
import QtQuick.VirtualKeyboard 2.1

TextField {
            id: idField
            width: 80
            height: 30
            placeholderText: qsTr("ID")
            Layout.maximumHeight: 30
            Layout.minimumHeight: 30
            Layout.minimumWidth: 80
            Layout.maximumWidth: 80
            focus: true
            anchors.horizontalCenter: parent.horizontalCenter
            inputMethodHints: Qt.ImhDigitsOnly
        }

When I click on it, the keyboard does not show up. I wonder if there is additional setup I need to do in order to summon the keyboard?

Body:
disable-desktop should be passed as an argument to qmake before building Qt Virtual Keyboard, not the application that uses the keyboard:

qmake CONFIG+=disable-desktop qtvirtualkeyboard.pro

However, I think that this code would automatically handle that for embedded devices (meaning that a pre-built/packaged Qt should work).

When using disable-desktop, it's up to you to provide the InputPanel:

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.VirtualKeyboard 2.0

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480

    TextField {
        anchors.centerIn: parent
    }

    InputPanel {
        id: inputPanel
        z: 89
        y: active ? parent.height - height : parent.height
        anchors.left: parent.left
        anchors.right: parent.right
    }
}

There's a more advanced example of this here. This part of the documentation mentions it, and the next chapter also has an example:

In the application integration method, the application is required to create an instance of InputPanel as explained in the following chapter.


问:
Make function wait until element exists
I'm trying to add a canvas over another canvas – how can I make this function wait to start until the first canvas is created?</p>

```<code>function PaintObject(brush) {

    this.started = false;

    // get handle of the main canvas, as a DOM object, not as a jQuery Object. Context is unfortunately not yet
    // available in jquery canvas wrapper object.
    var mainCanvas = $("#" + brush).get(0);

    // Check if everything is ok
    if (!mainCanvas) {alert("canvas undefined, does not seem to be supported by your browser");}
    if (!mainCanvas.getContext) {alert('Error: canvas.getContext() undefined !');}

    // Get the context for drawing in the canvas
    var mainContext = mainCanvas.getContext('2d');
    if (!mainContext) {alert("could not get the context for the main canvas");}

    this.getMainCanvas = function () {
        return mainCanvas;
    }
    this.getMainContext = function () {
        return mainContext;
    }

    // Prepare a second canvas on top of the previous one, kind of second "layer" that we will use
    // in order to draw elastic objects like a line, a rectangle or an ellipse we adjust using the mouse
    // and that follows mouse movements
    var frontCanvas = document.createElement('canvas');
    frontCanvas.id = 'canvasFront';
    // Add the temporary canvas as a second child of the mainCanvas parent.
    mainCanvas.parentNode.appendChild(frontCanvas);

    if (!frontCanvas) {
        alert("frontCanvas null");
    }
    if (!frontCanvas.getContext) {
        alert('Error: no frontCanvas.getContext!');
    }
    var frontContext = frontCanvas.getContext('2d');
    if (!frontContext) {
        alert("no TempContext null");
    }

    this.getFrontCanvas = function () {
        return frontCanvas;
    }
    this.getFrontContext = function () {
        return frontContext;
    }
</code>```

答:
Is better to relay in requestAnimationFrame than in a setTimeout. this is my solution in es6 modules and using Promises.

es6, modules and promises:

```<code>// onElementReady.js
const onElementReady = $element => (
  new Promise((resolve) => {
    const waitForElement = () => {
      if ($element) {
        resolve($element);
      } else {
        window.requestAnimationFrame(waitForElement);
      }
    };
    waitForElement();
  })
);

export default onElementReady;

// in your app
import onElementReady from './onElementReady';

const $someElement = document.querySelector('.some-className');
onElementReady($someElement)
  .then(() => {
    // your element is ready
  }
</code>```

plain js and promises:

```<code>var onElementReady = function($element) {
  return new Promise((resolve) => {
    var waitForElement = function() {
      if ($element) {
        resolve($element);
      } else {
        window.requestAnimationFrame(waitForElement);
      }
    };
    waitForElement();
  })
};

var $someElement = document.querySelector('.some-className');
onElementReady($someElement)
  .then(() => {
    // your element is ready
  });
</code>```

Title: Make function wait until element exists

Body:
I'm trying to add a canvas over another canvas – how can I make this function wait to start until the first canvas is created?

function PaintObject(brush) {

    this.started = false;

    // get handle of the main canvas, as a DOM object, not as a jQuery Object. Context is unfortunately not yet
    // available in jquery canvas wrapper object.
    var mainCanvas = $("#" + brush).get(0);

    // Check if everything is ok
    if (!mainCanvas) {alert("canvas undefined, does not seem to be supported by your browser");}
    if (!mainCanvas.getContext) {alert('Error: canvas.getContext() undefined !');}

    // Get the context for drawing in the canvas
    var mainContext = mainCanvas.getContext('2d');
    if (!mainContext) {alert("could not get the context for the main canvas");}

    this.getMainCanvas = function () {
        return mainCanvas;
    }
    this.getMainContext = function () {
        return mainContext;
    }

    // Prepare a second canvas on top of the previous one, kind of second "layer" that we will use
    // in order to draw elastic objects like a line, a rectangle or an ellipse we adjust using the mouse
    // and that follows mouse movements
    var frontCanvas = document.createElement('canvas');
    frontCanvas.id = 'canvasFront';
    // Add the temporary canvas as a second child of the mainCanvas parent.
    mainCanvas.parentNode.appendChild(frontCanvas);

    if (!frontCanvas) {
        alert("frontCanvas null");
    }
    if (!frontCanvas.getContext) {
        alert('Error: no frontCanvas.getContext!');
    }
    var frontContext = frontCanvas.getContext('2d');
    if (!frontContext) {
        alert("no TempContext null");
    }

    this.getFrontCanvas = function () {
        return frontCanvas;
    }
    this.getFrontContext = function () {
        return frontContext;
    }

Body:
Is better to relay in requestAnimationFrame than in a setTimeout. this is my solution in es6 modules and using Promises.

es6, modules and promises:

// onElementReady.js
const onElementReady = $element => (
  new Promise((resolve) => {
    const waitForElement = () => {
      if ($element) {
        resolve($element);
      } else {
        window.requestAnimationFrame(waitForElement);
      }
    };
    waitForElement();
  })
);

export default onElementReady;

// in your app
import onElementReady from './onElementReady';

const $someElement = document.querySelector('.some-className');
onElementReady($someElement)
  .then(() => {
    // your element is ready
  }

plain js and promises:

var onElementReady = function($element) {
  return new Promise((resolve) => {
    var waitForElement = function() {
      if ($element) {
        resolve($element);
      } else {
        window.requestAnimationFrame(waitForElement);
      }
    };
    waitForElement();
  })
};

var $someElement = document.querySelector('.some-className');
onElementReady($someElement)
  .then(() => {
    // your element is ready
  });

ContentLicense: CC BY-SA 4.0


问:
Best practice around using UIViews as containers for background etc
While designing the views in IB, i find it simple to use the UIVIews as containers for other controls. I use this to give a special background color etc..

Is this a good practice or should i be doing something else ? I guess i could programmatically draw a Rectangle. But i'm trying to leverage IB as much as i can.

Thanks

答:
Yes, I think so. I also tend to use UIViews to group together controls that need to be changed together e.g. hiding a group of buttons.
I don't believe there is a performance penalty from doing this.

Re: Interface Builder, I guess it all depends on what you feel confortable with. You can also create UIView containers programatically ;)


问:
map.fitBounds() with JSON data in a featureGroup
I cannot get the fitBounds command to work on a project where I am bringing in data to a featureLayer using GeoJSON.

This:

```<code>map.fitBounds(pointsFeatureGroup.getBounds()); // Uncaught Error: Bounds are not valid. at e.fitBounds (leaflet.js:5)
</code>```

and this:

```<code>var bounds = L.latLngBounds(pointsFeatureGroup); // Uncaught Error: Bounds are not valid. at e.fitBounds
map.fitBounds(bounds);
</code>```

don't work

My simplified code is here:
https://github.com/DPB61/leafletjs_problem2

If I just bring in markers individually into a normal Layer then a command like this works:

```<code>map.fitBounds(PointsLayer.getBounds());
</code>```

but that raises other issues with other functionality for which a features layer is required.

Am I doing something wrong?

答:
The root cause is a classic asynchronous issue.

See How do I return the response from an asynchronous call?

At the time you call map.fitBounds(vesselsFeatureGroup.getBounds()), the vesselsFeatureGroup is still empty (no child layer), therefore Leaflet cannot compute bounds.

Simply call the getBounds and fitBounds within the callback of your asynchronous task ($.getJSON)

Body:
I cannot get the fitBounds command to work on a project where I am bringing in data to a featureLayer using GeoJSON.

This:

map.fitBounds(pointsFeatureGroup.getBounds()); // Uncaught Error: Bounds are not valid. at e.fitBounds (leaflet.js:5)

and this:

var bounds = L.latLngBounds(pointsFeatureGroup); // Uncaught Error: Bounds are not valid. at e.fitBounds
map.fitBounds(bounds);

don't work

My simplified code is here:
https://github.com/DPB61/leafletjs_problem2

If I just bring in markers individually into a normal Layer then a command like this works:

map.fitBounds(PointsLayer.getBounds());

but that raises other issues with other functionality for which a features layer is required.

Am I doing something wrong?


问:
Verilog-A & Verilog ; Are they the same?

Is Verilog-A the same as Verilog ?

Is there a testing compiler for Verilog-A?

Because when I just paste some sources code of Verilog-A on ModelSim, there are always some errors that can't be removed. Can ModelSim run Verilog-A?

答:
Verilog is a deprecated standard for digital hardware description. Formally that last version was IEEE 1364-2005. It has been superseded by SystemVerilog (IEEE 1800-2017). Though deprecated, many tools still support it.

Verilog-A is an analog extension. Unlike its digital counterpart, the language is only for verification (simulation), it cannot be synthesized. It was standardized by the "Open Verilog International" trade association. Later the standard was incorporated as a subset of Verilog-AMS (analog and mixed signal extensions to Verilog).

If you want to simulate Verilog-A you will need a suitable simulator. This could be a mixed signal simulator (VCS AMS, Questa ADMS or Allegro AMS for instance). Alternatively most commercial SPICE simulators support Verilog-A.


问:
Moving the screen scroll position after page jumps to anchor point?
I have a menu on a single webpage whose links move the page to the section with the corresponding ID. However, there is a sticky header that is covering the top part of each section, so I want to scroll slightly to compensate.

I'm trying to determine a way to scroll the page by 50px after the page moves to a section. I tried doing a .click() event listener on each link, but it appears that the page is moved after the callback is issued, negating my attempt to scroll.

My code looks like the following:

HTML:

```<code><ul id="menu">
    <li id="menu-item-1"><a href="#1">1</a></li>
    <li id="menu-item-2"><a href="#2">2</a></li>
    <li id="menu-item-3"><a href="#3">3</a></li>
    <li id="menu-item-4"><a href="#4">4</a></li>
</ul>
</code>```

JS: (the two interior lines work in the console but not in the page code itself)

```<code>$('#menu-item-1 a').click(function(){
    var y = $(window).scrollTop();
    $(window).scrollTop(y-50);
});
</code>```

Is there a way to listen for a link action to be completed, then run my scroll code?

答:
As you observed:

but it appears that the page is moved after the callback is issued, negating my attempt to scroll

This happens because your events attached to anchor tag will be executed before the anchor tags default behaviour.
You are using id so you can use it to scroll also via javascript.
Here is a sample which I have tried out:
http://plnkr.co/edit/FzHYaxMCeOMTvWurtNRe?p=preview

```<code><ul id="menu">
  <li id="menu-item-1"><a href="#1" onClick = "handleClick(event, 1)">1</a></li>
  <li id="menu-item-2"><a href="#2" onClick = "handleClick(event, 2)">2</a></li>
  <li id="menu-item-3"><a href="#3" onClick = "handleClick(event, 3)">3</a></li>
  <li id="menu-item-4"><a href="#4" onClick = "handleClick(event, 4)">4</a></li>
</ul>

function handleClick(e, scrollElemId){
  e.preventDefault();
  window.scrollTo(0,document.getElementById(scrollElemId).offsetTop+50);
}
</code>```

Body:
I have a menu on a single webpage whose links move the page to the section with the corresponding ID. However, there is a sticky header that is covering the top part of each section, so I want to scroll slightly to compensate.

I'm trying to determine a way to scroll the page by 50px after the page moves to a section. I tried doing a .click() event listener on each link, but it appears that the page is moved after the callback is issued, negating my attempt to scroll.

My code looks like the following:

HTML:

1

2

3

4

JS: (the two interior lines work in the console but not in the page code itself)

$('#menu-item-1 a').click(function(){
    var y = $(window).scrollTop();
    $(window).scrollTop(y-50);
});

Is there a way to listen for a link action to be completed, then run my scroll code?

Body:
As you observed:

but it appears that the page is moved after the callback is issued, negating my attempt to scroll

This happens because your events attached to anchor tag will be executed before the anchor tags default behaviour.
You are using id so you can use it to scroll also via javascript.
Here is a sample which I have tried out:
http://plnkr.co/edit/FzHYaxMCeOMTvWurtNRe?p=preview

<ul id="menu">
  <li id="menu-item-1"><a href="#1" onClick = "handleClick(event, 1)">1</a></li>
  <li id="menu-item-2"><a href="#2" onClick = "handleClick(event, 2)">2</a></li>
  <li id="menu-item-3"><a href="#3" onClick = "handleClick(event, 3)">3</a></li>
  <li id="menu-item-4"><a href="#4" onClick = "handleClick(event, 4)">4</a></li>
</ul>

function handleClick(e, scrollElemId){
  e.preventDefault();
  window.scrollTo(0,document.getElementById(scrollElemId).offsetTop+50);
}


问:
Get returned value from post method with observables
I need returned value from post method. I tried to map data, but it (newTask) stays null. I don't know how to get Tasks object out of this function.  Any help, please.</p>

```<code>    public PostTask(task:Tasks){

        let headers=new Headers({'Content-Type':'application/json'});
        let options=new RequestOptions({headers:headers});

       this._http.post('http://localhost:58592/api/tasks',task,options)
            .map(res => res.json() as Tasks)
            .map(newTask=>this.newTask=newTask)
            .catch(this.handleError).subscribe();

    }
</code>```

答:
http.get() returns an observable. To extract a value from an observable once it is emitted we should subscribe to it after transforming emitted values.

```<code>this._http.post('http://localhost:58592/api/tasks',task,options)
        .map(res => res.json() as Tasks)
        .subscribe(
                newTask =>  this.newTask = newTask ,
                error => console.log(error);
        );
</code>```

Please read through the angular.io documentation and examples.

Body:
I need returned value from post method. I tried to map data, but it (newTask) stays null. I don't know how to get Tasks object out of this function.  Any help, please.

    public PostTask(task:Tasks){

        let headers=new Headers({'Content-Type':'application/json'});
        let options=new RequestOptions({headers:headers});

       this._http.post('http://localhost:58592/api/tasks',task,options)
            .map(res => res.json() as Tasks)
            .map(newTask=>this.newTask=newTask)
            .catch(this.handleError).subscribe();

    }

Body:
http.get() returns an observable. To extract a value from an observable once it is emitted we should subscribe to it after transforming emitted values.

this._http.post('http://localhost:58592/api/tasks',task,options)
        .map(res => res.json() as Tasks)
        .subscribe(
                newTask =>  this.newTask = newTask ,
                error => console.log(error);
        );

Please read through the angular.io documentation and examples.


问:
How to set the outline of the elements on tab only and not on click?
I am doing some tasks for accessibility(ADA) and the team asked me to set a visual pointer on tab only and not on click.

Right now I may see the light-blue outline when I click on the anchors and also when I tab over them.
I need that outline to appear only on tab.

Any suggestions?

答:
You just need to remove outline on click event, and set outline on focus event.

var elements = Array.from(document.querySelectorAll("a"));

elements.forEach(a => a.addEventListener("click", function() {
  a.classList.add("no-outline");
}));

elements.forEach(a => a.addEventListener("focus", function() {
  a.classList.remove("no-outline");
}));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.no-outline {
  outline: 0;
}</code>```

Some text. This is link.
Also we have another link```

Body:
You just need to remove outline on click event, and set outline on focus event.

var elements = Array.from(document.querySelectorAll("a"));

elements.forEach(a => a.addEventListener("click", function() {
  a.classList.add("no-outline");
}));

elements.forEach(a => a.addEventListener("focus", function() {
  a.classList.remove("no-outline");
}));

.no-outline {
  outline: 0;
}

Some text. <a href="#">This is link</a>.
Also we have <a href="#">another link</a>


问:
Convert a MMM yyyy string date to a DateTime value without a massive nested if using c#?
I have an incoming string variable called strDate that's formatted with the first three characters of the month and a four character year, like this: "Jul 2017".

I need to convert that string to a date formatted like this: "7/1/2017". I'm wondering if there's a better way to do this than creating a massive nested if along the pattern shown below to account for all 12 months. I hate repeating code. Can anyone make a suggestion?

```<code>string strDate = "Jul 2017";
string strNewDate = "";

if (strDate.Substring(0,3) == "Jul")
{
    string strMonth = "7";
    strNewDate = strMonth + "/1/";
    strNewDate = strNewDate + strDate.Substring(4, 4);
    DateTime newDate = Convert.ToDateTime(strNewDate);
}
</code>```

答:
You just need to do a DateTime.TryParse():

```<code>string input = "Jul 2017";
DateTime newDateTime;
if(DateTime.TryParse(input, out newDateTime ))
{
    //newDateTime was parsed successfully
}
</code>```

Your format ("MMM yyyy") is a standard format that C# recognizes to it should parse fine.  However there is the DateTime.TryParseExact method that lets you specify the exact format you are expecting the string to be in.

Body:
I have an incoming string variable called strDate that's formatted with the first three characters of the month and a four character year, like this: "Jul 2017".

I need to convert that string to a date formatted like this: "7/1/2017". I'm wondering if there's a better way to do this than creating a massive nested if along the pattern shown below to account for all 12 months. I hate repeating code. Can anyone make a suggestion?

string strDate = "Jul 2017";
string strNewDate = "";

if (strDate.Substring(0,3) == "Jul")
{
    string strMonth = "7";
    strNewDate = strMonth + "/1/";
    strNewDate = strNewDate + strDate.Substring(4, 4);
    DateTime newDate = Convert.ToDateTime(strNewDate);
}

Body:
You just need to do a DateTime.TryParse():

string input = "Jul 2017";
DateTime newDateTime;
if(DateTime.TryParse(input, out newDateTime ))
{
    //newDateTime was parsed successfully
}

Your format ("MMM yyyy") is a standard format that C# recognizes to it should parse fine.  However there is the DateTime.TryParseExact method that lets you specify the exact format you are expecting the string to be in.


问:
how to use one hive result as condition in another hive query?
I have a question. I have two hive tables, first one has condition. need dynamically looking for the condition in sec query.
for example
first query:

```<code>select col1, col2 from table1. will return account = 'abc'
</code>```

in second query, I need to use this as condition for example:

```<code>select * from table2
where account = 'abc'
</code>```

anybody has some idea? thanks in advance

答:
Apache Hive supports use of a join to combine rows from multiple tables based on a related column.

In this example, there is an accounts table and an orders table.  The query uses a join to find all orders corresponding to each account, filtered to just account1 and account2.  The accounts table is simplified to just one column in this example, which perhaps makes it look unnecessary.  In real-world usage, an accounts table would have multiple columns, but the join syntax remains the same.

Query

```<code>WITH
    accounts AS (
        SELECT 'account1' AS account_name UNION ALL
        SELECT 'account2' AS account_name UNION ALL
        SELECT 'account3' AS account_name
    ),
    orders AS (
        SELECT 'account1' AS account_name, 'order1' AS order_name UNION ALL
        SELECT 'account1' AS account_name, 'order2' AS order_name UNION ALL
        SELECT 'account1' AS account_name, 'order3' AS order_name UNION ALL
        SELECT 'account2' AS account_name, 'order4' AS order_name UNION ALL
        SELECT 'account2' AS account_name, 'order5' AS order_name UNION ALL
        SELECT 'account2' AS account_name, 'order6' AS order_name UNION ALL
        SELECT 'account3' AS account_name, 'order7' AS order_name UNION ALL
        SELECT 'account3' AS account_name, 'order8' AS order_name UNION ALL
        SELECT 'account3' AS account_name, 'order9' AS order_name
    )
SELECT
    orders.account_name,
    orders.order_name
FROM accounts
JOIN orders ON accounts.account_name = orders.account_name
WHERE accounts.account_name IN ('account1', 'account2');
</code>```

Results

```<code>    account_name    order_name
0   account1    order1
1   account1    order2
2   account1    order3
3   account2    order4
4   account2    order5
5   account2    order6
</code>```

Body:
I have a question. I have two hive tables, first one has condition. need dynamically looking for the condition in sec query.
for example
first query:

select col1, col2 from table1. will return account = 'abc'

in second query, I need to use this as condition for example:

select * from table2
where account = 'abc'

anybody has some idea? thanks in advance

Body:
Apache Hive supports use of a join to combine rows from multiple tables based on a related column.

In this example, there is an accounts table and an orders table.  The query uses a join to find all orders corresponding to each account, filtered to just account1 and account2.  The accounts table is simplified to just one column in this example, which perhaps makes it look unnecessary.  In real-world usage, an accounts table would have multiple columns, but the join syntax remains the same.

Query

WITH
    accounts AS (
        SELECT 'account1' AS account_name UNION ALL
        SELECT 'account2' AS account_name UNION ALL
        SELECT 'account3' AS account_name
    ),
    orders AS (
        SELECT 'account1' AS account_name, 'order1' AS order_name UNION ALL
        SELECT 'account1' AS account_name, 'order2' AS order_name UNION ALL
        SELECT 'account1' AS account_name, 'order3' AS order_name UNION ALL
        SELECT 'account2' AS account_name, 'order4' AS order_name UNION ALL
        SELECT 'account2' AS account_name, 'order5' AS order_name UNION ALL
        SELECT 'account2' AS account_name, 'order6' AS order_name UNION ALL
        SELECT 'account3' AS account_name, 'order7' AS order_name UNION ALL
        SELECT 'account3' AS account_name, 'order8' AS order_name UNION ALL
        SELECT 'account3' AS account_name, 'order9' AS order_name
    )
SELECT
    orders.account_name,
    orders.order_name
FROM accounts
JOIN orders ON accounts.account_name = orders.account_name
WHERE accounts.account_name IN ('account1', 'account2');

Results

    account_name    order_name
0   account1    order1
1   account1    order2
2   account1    order3
3   account2    order4
4   account2    order5
5   account2    order6


问:
Use certificate in Azure Key Vault to sign IdentityServer4
I've uploaded a pfx certificate as a secret to my Azure Portal and I now want to use this to sign the credentials in IdentityServer4.

I've got reference to the vault in the startup of the api using:

```<code>builder.AddAzureKeyVault(
       $"https://{config["Vault"]}.vault.azure.net/",
       config["ClientId"],
       config["ClientSecret"]);
</code>```

But not too sure how to get the certificate out to pass to:

```<code> services.AddIdentityServer()
            .AddSigningCredential(...)
</code>```

Is it possibly to be able to reference the certificate directly from the key vault, or do I need to deploy the cert to the web app the api is running on?

Thanks

答:
You are already building the IConfiguration object, so you can reference the pfx key just like you would reference any other object from the configuration.
If the key is in the keyvault you can reference it something like:

```<code>// Name of your pfx in the keyvault.
var key = _configuration["pfx"];
var pfxBytes = Convert.FromBase64String(key);

// Create the certificate.
var cert = new X509Certificate2(pfxBytes);
services.AddIdentityServer()
    .AddSigningCredential(cert);
</code>```

I would recommend using the keyvault for this but you could decide to upload the pfx to the certificate store of the web app. You can do this in Azure by going to your web app -> SSL Certificates -> Upload certificate and enter the password. Go to the Application Settings and add the app setting WEBSITE_LOAD_CERTIFICATES : <thumbprint>. The last thing you would do is retrieve the certificate from the store and add it again like AddSigningCredential(cert);.

Body:
I've uploaded a pfx certificate as a secret to my Azure Portal and I now want to use this to sign the credentials in IdentityServer4.

I've got reference to the vault in the startup of the api using:

builder.AddAzureKeyVault(
       $"https://{config["Vault"]}.vault.azure.net/",
       config["ClientId"],
       config["ClientSecret"]);

But not too sure how to get the certificate out to pass to:

 services.AddIdentityServer()
            .AddSigningCredential(...)

Is it possibly to be able to reference the certificate directly from the key vault, or do I need to deploy the cert to the web app the api is running on?

Thanks

Body:
You are already building the IConfiguration object, so you can reference the pfx key just like you would reference any other object from the configuration.
If the key is in the keyvault you can reference it something like:

// Name of your pfx in the keyvault.
var key = _configuration["pfx"];
var pfxBytes = Convert.FromBase64String(key);

// Create the certificate.
var cert = new X509Certificate2(pfxBytes);
services.AddIdentityServer()
    .AddSigningCredential(cert);

I would recommend using the keyvault for this but you could decide to upload the pfx to the certificate store of the web app. You can do this in Azure by going to your web app -> SSL Certificates -> Upload certificate and enter the password. Go to the Application Settings and add the app setting WEBSITE_LOAD_CERTIFICATES : <thumbprint>. The last thing you would do is retrieve the certificate from the store and add it again like AddSigningCredential(cert);.


问:
MVC Entity Framework Model not returning correct data
Run into a strange problem while writing an ASP.NET MVC site. I have a view in my SQL Server database that returns a few date ranges. The view works fine when running the query in SSMS.

When the view data is returned by the Entity Framework Model, It returns the correct number of rows but some of the rows are duplicated.

Here is an example of what I have done:

SQL Server code:

EDITED: (table A)

```<code>CREATE TABLE [dbo].[A](
    [ID] [int] NOT NULL,
    [PhID] [int] NULL,
    [FromDate] [datetime] NOT NULL,
    [ToDate] [datetime] NULL,
 CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED
(   [ID] ASC,
    [FromDate] ASC
)) ON [PRIMARY]

CREATE TABLE [dbo].[B](
    [PhID] [int] NOT NULL,
    [FromDate] [datetime] NULL,
    [ToDate] [datetime] NULL,
 CONSTRAINT [PK_B] PRIMARY KEY CLUSTERED
(   [PhID] ASC )) ON [PRIMARY]
go

CREATE VIEW C as
SELECT  A.ID,
        CASE WHEN A.PhID IS NULL THEN A.FromDate ELSE B.FromDate END AS FromDate,
        CASE WHEN A.PhID IS NULL THEN A.ToDate ELSE B.ToDate END AS ToDate
FROM    A
LEFT OUTER JOIN B ON A.PhID = B.PhID
go

INSERT INTO B (PhID, FromDate, ToDate) VALUES (100, '20100615', '20100715')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (1, NULL, '20100101', '20100201')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (1, 100, '20100615', '20100715')

INSERT INTO B (PhID, FromDate, ToDate) VALUES (101, '20101201', '20101231')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (2, NULL, '20100801', '20100901')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (2, 101, '20101201', '20101231')
</code>```

So now, if you select all from C, you get 4 separate date ranges

In the Entity Framework Model (which I call 'Core'), the view 'C' is added.

in MVC Controller:

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {
        CoreEntities db = new CoreEntities();
        var clist = from c in db.C
                    select c;

        return View(clist.ToList());
    }

}
</code>```

in MVC View:

```<code>@model List<RM.Models.C>

@{
    foreach (RM.Models.C c in Model)
    {
        @String.Format("{0:dd-MMM-yyyy}", c.FromDate)
        <span>-</span>
        @String.Format("{0:dd-MMM-yyyy}", c.ToDate)
        <br />
    }
}
</code>```

When I run all this, it outputs this:

```<code>01-Jan-2010 - 01-Feb-2010
01-Jan-2010 - 01-Feb-2010
01-Aug-2010 - 01-Sep-2010
01-Aug-2010 - 01-Sep-2010
</code>```

When it should do this (this is what the view returns):

```<code>01-Jan-2010 - 01-Feb-2010
15-Jun-2010 - 15-Jul-2010
01-Aug-2010 - 01-Sep-2010
01-Dec-2010 - 31-Dec-2010
</code>```

Also, I've run the SQL profiler over it and according to that, the query being executed is:

```<code>SELECT
[Extent1].[ID] AS [ID],
[Extent1].[FromDate] AS [FromDate],
[Extent1].[ToDate] AS [ToDate]
FROM (SELECT
      [C].[ID] AS [ID],
      [C].[FromDate] AS [FromDate],
      [C].[ToDate] AS [ToDate]
      FROM [dbo].[C] AS [C]) AS [Extent1]
</code>```

Which returns the correct data

So it seems that the entity framework is doing something to the data in the meantime.

To me, everything looks fine! Have I missed something?

Cheers,
Ben

EDIT:

sorry, table A should be:

```<code>CREATE TABLE [dbo].[A](
    [ID] [int] NOT NULL,
    [PhID] [int] NULL,
    [FromDate] [datetime] NOT NULL,
    [ToDate] [datetime] NULL,
 CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED
(   [ID] ASC,
    [FromDate] ASC
)) ON [PRIMARY]
</code>```

答:
I figured it out myself.

The problem was with the way the view was mapped in the entity model.

When it was added, it made the entity key just the ID. I needed it over the ID and FromDate. So I included the FromDate in the entity key and it works fine.

Body:
Run into a strange problem while writing an ASP.NET MVC site. I have a view in my SQL Server database that returns a few date ranges. The view works fine when running the query in SSMS.

When the view data is returned by the Entity Framework Model, It returns the correct number of rows but some of the rows are duplicated.

Here is an example of what I have done:

SQL Server code:

EDITED: (table A)

CREATE TABLE [dbo].[A](
    [ID] [int] NOT NULL,
    [PhID] [int] NULL,
    [FromDate] [datetime] NOT NULL,
    [ToDate] [datetime] NULL,
 CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED
(   [ID] ASC,
    [FromDate] ASC
)) ON [PRIMARY]

CREATE TABLE [dbo].[B](
    [PhID] [int] NOT NULL,
    [FromDate] [datetime] NULL,
    [ToDate] [datetime] NULL,
 CONSTRAINT [PK_B] PRIMARY KEY CLUSTERED
(   [PhID] ASC )) ON [PRIMARY]
go

CREATE VIEW C as
SELECT  A.ID,
        CASE WHEN A.PhID IS NULL THEN A.FromDate ELSE B.FromDate END AS FromDate,
        CASE WHEN A.PhID IS NULL THEN A.ToDate ELSE B.ToDate END AS ToDate
FROM    A
LEFT OUTER JOIN B ON A.PhID = B.PhID
go

INSERT INTO B (PhID, FromDate, ToDate) VALUES (100, '20100615', '20100715')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (1, NULL, '20100101', '20100201')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (1, 100, '20100615', '20100715')

INSERT INTO B (PhID, FromDate, ToDate) VALUES (101, '20101201', '20101231')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (2, NULL, '20100801', '20100901')
INSERT INTO A (ID, PhID, FromDate, ToDate) VALUES (2, 101, '20101201', '20101231')

So now, if you select all from C, you get 4 separate date ranges

In the Entity Framework Model (which I call 'Core'), the view 'C' is added.

in MVC Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        CoreEntities db = new CoreEntities();
        var clist = from c in db.C
                    select c;

        return View(clist.ToList());
    }

}

in MVC View:

@model List<RM.Models.C>

@{
    foreach (RM.Models.C c in Model)
    {
        @String.Format("{0:dd-MMM-yyyy}", c.FromDate)
        -
        @String.Format("{0:dd-MMM-yyyy}", c.ToDate)

    }
}

When I run all this, it outputs this:

01-Jan-2010 - 01-Feb-2010
01-Jan-2010 - 01-Feb-2010
01-Aug-2010 - 01-Sep-2010
01-Aug-2010 - 01-Sep-2010

When it should do this (this is what the view returns):

01-Jan-2010 - 01-Feb-2010
15-Jun-2010 - 15-Jul-2010
01-Aug-2010 - 01-Sep-2010
01-Dec-2010 - 31-Dec-2010

Also, I've run the SQL profiler over it and according to that, the query being executed is:

SELECT
[Extent1].[ID] AS [ID],
[Extent1].[FromDate] AS [FromDate],
[Extent1].[ToDate] AS [ToDate]
FROM (SELECT
      [C].[ID] AS [ID],
      [C].[FromDate] AS [FromDate],
      [C].[ToDate] AS [ToDate]
      FROM [dbo].[C] AS [C]) AS [Extent1]

Which returns the correct data

So it seems that the entity framework is doing something to the data in the meantime.

To me, everything looks fine! Have I missed something?

Cheers,
Ben

EDIT:

sorry, table A should be:

CREATE TABLE [dbo].[A](
    [ID] [int] NOT NULL,
    [PhID] [int] NULL,
    [FromDate] [datetime] NOT NULL,
    [ToDate] [datetime] NULL,
 CONSTRAINT [PK_A] PRIMARY KEY CLUSTERED
(   [ID] ASC,
    [FromDate] ASC
)) ON [PRIMARY]


问:
Issues with openpyxl: Attempting to insert dictionary into new excel file
I am new to programming.
I am learning to write in the python language. I am currently trying to put an existing dictionary into a new excel file. I have a feeling that because I have a dictionary may be the issue?
I am using openpyxl. </p>

<p>I am getting an error message(AttributeError: 'WriteOnlyWorksheet' object has no attribute 'cell' ) whenever I attempt to insert the dictionary. However I can write to a simple cell with no issue.
It is when trying to fill in large data into a column that I get the error. </p>

```<code> #Writing a new excel file with key information
    print("Would you like to create a new excel document?")
    b_input = input("Type: 'Y' or 'N' -> ").lower()
    if b_input == "y":
        wb = Workbook(write_only=True)
        ws = wb.create_sheet()

        print("I can only put in the contract status and serial numbers together in a file.")
        c_input = input("Would you like to do that? Type: 'Y' or 'N' -> ")
        if c_input == 'y':
            ws.cell(row=r, column=1).value = excel_info

    wb.save('new_test_book.xlsx')
</code>```

答:
from the write_only mode.docs:

In a write-only workbook, rows can only be added with append(). It is not possible to write (or read) cells at arbitrary locations with cell() or iter_rows().

that's why error tells you there is no attribute cell so use append() instead.

You can also refer to this topic for more help and understanding.

Hope this was helpful.

Body:
I am new to programming.
I am learning to write in the python language. I am currently trying to put an existing dictionary into a new excel file. I have a feeling that because I have a dictionary may be the issue?
I am using openpyxl.

I am getting an error message(AttributeError: 'WriteOnlyWorksheet' object has no attribute 'cell' ) whenever I attempt to insert the dictionary. However I can write to a simple cell with no issue.
It is when trying to fill in large data into a column that I get the error.

 #Writing a new excel file with key information
    print("Would you like to create a new excel document?")
    b_input = input("Type: 'Y' or 'N' -> ").lower()
    if b_input == "y":
        wb = Workbook(write_only=True)
        ws = wb.create_sheet()

        print("I can only put in the contract status and serial numbers together in a file.")
        c_input = input("Would you like to do that? Type: 'Y' or 'N' -> ")
        if c_input == 'y':
            ws.cell(row=r, column=1).value = excel_info

    wb.save('new_test_book.xlsx')


问:
Traversing / Editing DOM in React JS
I am new to React JS and planning to use it in one of my projects. I have gone through the docs and have a slight idea of React. I have a scenario with the following details :

Server pushes array of items / list to UI in frequent intervals.

The items in the list are not similar to each other or multiple lists      but will be displayed in the order they are received.

Items will have to appended to DOM upon AJAX response / push notification from server.

Few cases, will have to edit / delete the items from DOM based on a reference.

I was going through few articles in stack overflow for appending data dynamically and few of them are below :

Can I append my component to a div's existing content in ReactJS?.

ReactJS component rendering and how to append elements to the div the component is mounted on.

React.js: How to append a component on click?.

How to append to dom in React?.

All the above solutions doesn't provide a direct option for appending. They recommend to create a map / array and add the values to the map and re-render the values.

I am not very comfortable in using maps as I won't be passing the details to server and its only shown to user. I think creating a map will have redundant values which occupies memory if the list grows huge.

I dont want to mix jQuery / any other library along with React. Is there any possibility where a render function / component will append to DOM instead of maintaining in an array as the items in the list are not similar.

Why there isn't any option to traverse / edit DOM directly instead of maintaining a list. Can you guide me if there is an option so that I will be able to understand its advantages.

答:
You definitely don't need to use jQuery or any other direct DOM manipulation tool.

There is no need to worry about the fact that your list becomes so huge that it affects the performance / consumes too much memory — the fact that you have a lot of elements in the DOM will hit the resource constraints much sooner. You can easily store way more data in a JSON map/array than you can render.

I believe you don't seed a map, you need an array, but that's not a significant thing.

So just update the data like this when you receive some updates from the server and render will take care about displaying them:

```<code>onDataReceived(newData) {
  // or you can mutate the `data` array here, doesn't matter too much
  this.setState({data: data.concat(newData)})
}

render() {
  // render this.state.data
}
</code>```

Title: Traversing / Editing DOM in React JS

Body:
You definitely don't need to use jQuery or any other direct DOM manipulation tool.

There is no need to worry about the fact that your list becomes so huge that it affects the performance / consumes too much memory — the fact that you have a lot of elements in the DOM will hit the resource constraints much sooner. You can easily store way more data in a JSON map/array than you can render.

I believe you don't seed a map, you need an array, but that's not a significant thing.

So just update the data like this when you receive some updates from the server and render will take care about displaying them:

onDataReceived(newData) {
  // or you can mutate the `data` array here, doesn't matter too much
  this.setState({data: data.concat(newData)})
}

render() {
  // render this.state.data
}


问:
How can we classify various Algorithms?
How can we classify various Algorithms?

I have heard various names: Divide & Conquer Algorithms, Deterministic Algorithms, Probabilistic Algorithms, In-place Algorithms and so on.

Do they form any kind of classification hierarchy?

Please provide me with any web link.

答:
There are enormous numbers of algorithm classification schemes, some more useful than others (for an example of a very foolish scheme, consider classifying by the checksum of the algorithm description!) and this is a consequence of the classifications being not so much a fundamental property of the algorithms, but rather of what we know about them. Classifying knowledge is very difficult, and tends to produce many overlapping classifications; the whole field of building such classifications is called ontology. (Confusingly, the word “ontology” is also attached to computer-readable classification schemes in languages like OWL.)

As such, it's an open question whether there's a useful hierarchy of classifications, and doubly so if there is a useful hierarchy when it comes to algorithms. I suspect that the answer is “not really”, and urge you to just be flexible when it comes to classifying things.

Title: How can we classify various Algorithms?


问:
express4 reusing mongodb handle
I am new to javascript and nodejs programming. I am trying to connect mongodb in express framework but like to keep code modular. I have below code written. I am using express version 4.14.0 and mongodb driver 2.2.27 version and nodejs v6.10.3

```<code>//app.js
var express = require('express');
var app = express();
var index = require('./routes/index');
app.use('/', index);
app.listen(3000);

//routes/index.js
var router = require('express').Router();
var anotherfile = require('../controllers/anotherfile');

router.get('/', function(req, res) {
        res.send('Connected');
});
module.exports = router;

//controllers/db.js
var MongoClient = require('mongodb').MongoClient;
var connectionString = 'mongodb://user:password@127.0.0.1:27017/testdb';
var _db;

MongoClient.connect(connectionString, function(err, db) {
  if (err) {
    console.log('Error: ', err);
  } else {
    console.log('Connected!');
    _db = db;
    console.log("_db",_db);
  }
});

module.exports.getDb = function() {
  return _db;
}

//controllers/anotherfile.js
var connect = require('./db.js');
var db1 = connect.getDb();
console.log("print db1",db1);
</code>```

What I want from above code is access to db handle in anotherfile.js. What am I doing wrong here?

答:
This is basically the classic new JS developer vs async code problem.

```<code>// When you require db.js, you're kicking off `MongoClient.connect`, which is
// an async function.
var connect = require('./db.js');

// On the very next line when you `getDb`, the connect function callback has not
// happened yet, and db1 is undefined.
var db1 = connect.getDb(); //=> undefined
</code>```

If you defer the execution of getDb to after the connect function has completed, it should work.

```<code>setTimeout(function () {
  var db1 = connect.getDb(); //=> no longer undefined
}, 5000);
</code>```

In an express app, you're typically running code inside routes, which are async.  As such the database is accessed long after connect is called and this becomes a non-issue (which is why if you google you'll see people doing it the exact way you are trying).

If you wanted to solve the problem a different way though, you might consider that MongoClient.connect, when not passed a callback, returns a promise.  Meaning you could write rewrite your example very simply like:

```<code>// db.js
var MongoClient = require('mongodb').MongoClient;
var connectionString = '...';
var connectPromise = MongoClient.connect(connectionString);

exports.getDb = function () {
  return connectPromise;
}

// anotherfile.js
var db = require('./db');
db.getDb().then(function (db) {
  // This callback will never run until the connect promise has
  // resolved and the db is ready.  Calling `getDb` again will not
  // initiate another call to `MongoClient.connect`
  console.log(db);
});
</code>```

Title: express4 reusing mongodb handle

Body:
I am new to javascript and nodejs programming. I am trying to connect mongodb in express framework but like to keep code modular. I have below code written. I am using express version 4.14.0 and mongodb driver 2.2.27 version and nodejs v6.10.3

//app.js
var express = require('express');
var app = express();
var index = require('./routes/index');
app.use('/', index);
app.listen(3000);

//routes/index.js
var router = require('express').Router();
var anotherfile = require('../controllers/anotherfile');

router.get('/', function(req, res) {
        res.send('Connected');
});
module.exports = router;

//controllers/db.js
var MongoClient = require('mongodb').MongoClient;
var connectionString = 'mongodb://user:password@127.0.0.1:27017/testdb';
var _db;

MongoClient.connect(connectionString, function(err, db) {
  if (err) {
    console.log('Error: ', err);
  } else {
    console.log('Connected!');
    _db = db;
    console.log("_db",_db);
  }
});

module.exports.getDb = function() {
  return _db;
}

//controllers/anotherfile.js
var connect = require('./db.js');
var db1 = connect.getDb();
console.log("print db1",db1);

What I want from above code is access to db handle in anotherfile.js. What am I doing wrong here?

Body:
This is basically the classic new JS developer vs async code problem.

// When you require db.js, you're kicking off `MongoClient.connect`, which is
// an async function.
var connect = require('./db.js');

// On the very next line when you `getDb`, the connect function callback has not
// happened yet, and db1 is undefined.
var db1 = connect.getDb(); //=> undefined

If you defer the execution of getDb to after the connect function has completed, it should work.

setTimeout(function () {
  var db1 = connect.getDb(); //=> no longer undefined
}, 5000);

In an express app, you're typically running code inside routes, which are async.  As such the database is accessed long after connect is called and this becomes a non-issue (which is why if you google you'll see people doing it the exact way you are trying).

If you wanted to solve the problem a different way though, you might consider that MongoClient.connect, when not passed a callback, returns a promise.  Meaning you could write rewrite your example very simply like:

// db.js
var MongoClient = require('mongodb').MongoClient;
var connectionString = '...';
var connectPromise = MongoClient.connect(connectionString);

exports.getDb = function () {
  return connectPromise;
}

// anotherfile.js
var db = require('./db');
db.getDb().then(function (db) {
  // This callback will never run until the connect promise has
  // resolved and the db is ready.  Calling `getDb` again will not
  // initiate another call to `MongoClient.connect`
  console.log(db);
});


问:
C++ segfault only if cout not used
Why does the following code give segmentation fault only when I don't have a cout statement (run with g++ -std=c++11 test.cpp):
Why does the following code give segmentation fault only when I don't have a cout statement (run with g++ -std=c++11 test.cpp)</p>

```<code>#include <iostream>
#include <string>
#include <ctype.h>
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;

struct node {
        int data;
        node *left;
        node *right;

        node(int d, node *l, node *r) : data{d}, left{l}, right{r} {}
};

node* findNode(node *root, node *find) {

    if (!root) return nullptr;

    if (root->data == find->data) {
            return root;
    }

    node *left, *right;

    if (root->left) left = findNode(root->left, find);
    if (root->right) right = findNode(root->right, find);

    // Uncomment this to avoid a segfault. Why ?
    //cout << "left = " << left << " right = " << right <<  " find = " << find << endl;

    if (left && left->data == find->data) {
            return left;
    }
    if (right && right->data == find->data) {
            return right;
    }
    return nullptr;
}

int main() {

    node *newNode1 = new node(20, nullptr, nullptr);
    node *newNode2 = new node(60, nullptr, nullptr);

    node *root = new node(50, newNode1, newNode2);

    findNode(root, newNode1);

    return 0;
}
</code>```

答:
The line node *left, *right; produce uninitialized pointers, their value is undefined. It seems like you are relying on them being initially nullptr, but this is not necessarily the case.

When you reach the condition if(left && left->data == find->data), unless left was assigned earlier, you are checking the value of an uninitialized variable (left). Reading from an uninitialized variable is undefined behavior, which means that it can do anything including crashing, appearing to work fine or something totally unpredictable. The resulting behavior can change at any time for any reason, including changes that appear unrelated to the problem. It's futile to try to reason on why a program with undefined behavior does what it does beyond simply noting that it is undefined behavior.

One solution is to initialize your pointers to null so that they are never in an uninitialized state :

```<code>node *left = nullptr;
node *right = nullptr;
</code>```

Title: C++ segfault only if cout not used

Body:
Why does the following code give segmentation fault only when I don't have a cout statement (run with g++ -std=c++11 test.cpp):
Why does the following code give segmentation fault only when I don't have a cout statement (run with g++ -std=c++11 test.cpp)

#include <iostream>
#include <string>
#include <ctype.h>
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;

struct node {
        int data;
        node *left;
        node *right;

        node(int d, node *l, node *r) : data{d}, left{l}, right{r} {}
};

node* findNode(node *root, node *find) {

    if (!root) return nullptr;

    if (root->data == find->data) {
            return root;
    }

    node *left, *right;

    if (root->left) left = findNode(root->left, find);
    if (root->right) right = findNode(root->right, find);

    // Uncomment this to avoid a segfault. Why ?
    //cout << "left = " << left << " right = " << right <<  " find = " << find << endl;

    if (left && left->data == find->data) {
            return left;
    }
    if (right && right->data == find->data) {
            return right;
    }
    return nullptr;
}

int main() {

    node *newNode1 = new node(20, nullptr, nullptr);
    node *newNode2 = new node(60, nullptr, nullptr);

    node *root = new node(50, newNode1, newNode2);

    findNode(root, newNode1);

    return 0;
}

Body:
The line node *left, *right; produce uninitialized pointers, their value is undefined. It seems like you are relying on them being initially nullptr, but this is not necessarily the case.

When you reach the condition if(left && left->data == find->data), unless left was assigned earlier, you are checking the value of an uninitialized variable (left). Reading from an uninitialized variable is undefined behavior, which means that it can do anything including crashing, appearing to work fine or something totally unpredictable. The resulting behavior can change at any time for any reason, including changes that appear unrelated to the problem. It's futile to try to reason on why a program with undefined behavior does what it does beyond simply noting that it is undefined behavior.

One solution is to initialize your pointers to null so that they are never in an uninitialized state :

node *left = nullptr;
node *right = nullptr;


问:
AutoMapper: access destination meta info in v6.x
moving from AutoMapper 4 to 6

In the ITypeConverter, how do we access the parent context, so we know what property is being populated, in version 4:

```<code>context.PropertyMap.DestinationProperty
</code>```

So following was possible:

```<code>public class UserDetailsConvertor : ITypeConverter<OAuthProfile, UserDetials>
{
    public Dto.Accounts.UserDetials Convert(ResolutionContext context)
    {
        var src = context.SourceValue as OAuthProfile;

        if (src == null) return null;

        if (!context.PropertyMap.DestinationProperty.Name.Contains("Internal"))
        {
            return new UserDetials()
            {
                Id = src.Id
            };
        }

        if (src.InternalAccountId.IsNullOrEmpty())
        {
            return null;
        }

        return new UserDetials()
        {
            Id = src.InternalAccountId
        };
    }
}
</code>```

note that the User details is being mapped to 2 properties (Internal and Provider) that is what the above conditional logic was sorting out.

in V6 this is not posisble from what i can see, there is an items collection, but this seems to contain information for the entire mapping (of all objects)

答: That's all gone. It was very expensive to capture and pass that context everywhere. You might want to look at member resolvers instead.</p>

Body:
moving from AutoMapper 4 to 6

In the ITypeConverter, how do we access the parent context, so we know what property is being populated, in version 4:

context.PropertyMap.DestinationProperty

So following was possible:

public class UserDetailsConvertor : ITypeConverter<OAuthProfile, UserDetials>
{
    public Dto.Accounts.UserDetials Convert(ResolutionContext context)
    {
        var src = context.SourceValue as OAuthProfile;

        if (src == null) return null;

        if (!context.PropertyMap.DestinationProperty.Name.Contains("Internal"))
        {
            return new UserDetials()
            {
                Id = src.Id
            };
        }

        if (src.InternalAccountId.IsNullOrEmpty())
        {
            return null;
        }

        return new UserDetials()
        {
            Id = src.InternalAccountId
        };
    }
}

note that the User details is being mapped to 2 properties (Internal and Provider) that is what the above conditional logic was sorting out.

in V6 this is not posisble from what i can see, there is an items collection, but this seems to contain information for the entire mapping (of all objects)


问:
Vivado Sim Error: "root scope declaration is not allowed in verilog 95/2K mode"
When I go to simulate my top-level module in Xilinx Vivado 2016.4, I receive the peculiar error:

```<code>ERROR: [VRFC 10-1342] root scope declaration is not allowed in verilog 95/2K mode [<...>/header.vh]
</code>```

I am using the built-in Vivado Simulator with Verilog 2001 specified. My header.vh looks like the following:

```<code>`ifndef _header_vh_
`define _header_vh_

    function integer clog2;
        input integer value;
        begin
            value = value - 1;
            for (clog2 = 0; value > 0; clog2 = clog2 + 1)
                value = value >> 1;
        end
    endfunction

`endif
</code>```

答:
This error arises as the scope of the function, clog2, is effectively set to root (as it's not declared within a module); this scope declaration is not allowed in Verilog 2001, but is in later versions (e.g. SystemVerilog). Switching to SystemVerilog would solve the issue (but is not recommended), but introducing a module wrapper for the function will suffice.

```<code>`ifndef _header_vh_
`define _header_vh_

module header();
    function integer clog2;
        input integer value;
        begin
            value = value - 1;
            for (clog2 = 0; value > 0; clog2 = clog2 + 1)
                value = value >> 1;
        end
    endfunction
endmodule

`endif
</code>```

Body:
When I go to simulate my top-level module in Xilinx Vivado 2016.4, I receive the peculiar error:

ERROR: [VRFC 10-1342] root scope declaration is not allowed in verilog 95/2K mode [<...>/header.vh]

I am using the built-in Vivado Simulator with Verilog 2001 specified. My header.vh looks like the following:

`ifndef _header_vh_
`define _header_vh_

    function integer clog2;
        input integer value;
        begin
            value = value - 1;
            for (clog2 = 0; value > 0; clog2 = clog2 + 1)
                value = value >> 1;
        end
    endfunction

`endif

Body:
This error arises as the scope of the function, clog2, is effectively set to root (as it's not declared within a module); this scope declaration is not allowed in Verilog 2001, but is in later versions (e.g. SystemVerilog). Switching to SystemVerilog would solve the issue (but is not recommended), but introducing a module wrapper for the function will suffice.

`ifndef _header_vh_
`define _header_vh_

module header();
    function integer clog2;
        input integer value;
        begin
            value = value - 1;
            for (clog2 = 0; value > 0; clog2 = clog2 + 1)
                value = value >> 1;
        end
    endfunction
endmodule

`endif


问:
Java deadlock with Eclipse CDT headless build
My case is similar to this one:
Eclipse CDT Headless build hangs after build is finished, but I digged a little bit into it and found other problems.

Scenario: I have a C++ application and a Jenkins build server on Linux (Debian Jessie 8.2). I have Eclipse CDT in my dev environment and it perfectly builds my C++ App (local build). I installed Eclipse CDT on the build server and my Jenkins script runs a headlessbuild to build my App.

Problem: Jenkins hangs even after the build finishes. But that's not Jenkins fault. I removed Jenkins from the equation and did an Eclipse headlessbuild in the build server and the result was the same, it hangs after printing out "Build Finished". It's worth noting that I can successfully build my App if I open Eclipse CDT in the build server and trigger a build using the UI.

Versions: In the build server, I tried Java 1.7 and 1.8. As for Eclipse, I tried Kepler, Luna, Mars and Neon (this last one required Java 1.8). For this post, I'm using this:

```<code>java -version
java version "1.7.0_111"
OpenJDK Runtime Environment (IcedTea 2.6.7) (7u111-2.6.7-1~deb8u1)
OpenJDK 64-Bit Server VM (build 24.111-b01, mixed mode)
</code>```

Commands: Here is the Eclipse CDT command for the headless build that I used:

```<code>~/eclipse/eclipse -nosplash -application org.eclipse.cdt.managedbuilder.core.headlessbuild -import ~/myAppProj/ -build myAppProj/Release -data ~/workspace/
</code>```

Observations:

While Java is hanging, I can kill its process and get the executable
ready to use. When I trigger the build from Jenkins and kill that
deadlocked Java process, Jenkins just continues running normally
further scripts.

In the build server, while Java is janging, if I run:

jstack [java pid]

Then I get the following:

```<code>Attaching to process ID 25262, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 24.111-b01
Deadlock Detection:

java.lang.RuntimeException: Unable to deduce type of thread from address 0x00007fc5c8032800 (expected type JavaThread, CompilerThread, ServiceThread, JvmtiAgentThread, or SurrogateLockerThread)
</code>```

Conclusion: it does seem that Java is deadlocking when Eclipse is run in headless mode. It doesn't happen all the time, but 99% I guess. Also, it doesn't stay hanging forever, it comes back after an hour or two, which is bad for any build server.

So, did anybody have problems like that?

答:
(As confirmed in the comments)

The problem you are facing is likely a lock-up in the CDT indexer. Sometimes when the life cycle is short in Eclipse the CDT indexer unfortunately locks up. At the command line you can disable it by using the -no-indexer command line option (added in Eclipse Mars).

The lockup is itself filed as a bug, See Bug 327126 - Deadlock attempting to cancel PDOMIndexerJob during a resource delta notification

Your jstack problem is most likely unrelated and is likely due to mismatch in permissions, users, or JVMs between the java process and the jstack process.

Body:
My case is similar to this one:
Eclipse CDT Headless build hangs after build is finished, but I digged a little bit into it and found other problems.

Scenario: I have a C++ application and a Jenkins build server on Linux (Debian Jessie 8.2). I have Eclipse CDT in my dev environment and it perfectly builds my C++ App (local build). I installed Eclipse CDT on the build server and my Jenkins script runs a headlessbuild to build my App.

Problem: Jenkins hangs even after the build finishes. But that's not Jenkins fault. I removed Jenkins from the equation and did an Eclipse headlessbuild in the build server and the result was the same, it hangs after printing out "Build Finished". It's worth noting that I can successfully build my App if I open Eclipse CDT in the build server and trigger a build using the UI.

Versions: In the build server, I tried Java 1.7 and 1.8. As for Eclipse, I tried Kepler, Luna, Mars and Neon (this last one required Java 1.8). For this post, I'm using this:

java -version
java version "1.7.0_111"
OpenJDK Runtime Environment (IcedTea 2.6.7) (7u111-2.6.7-1~deb8u1)
OpenJDK 64-Bit Server VM (build 24.111-b01, mixed mode)

Commands: Here is the Eclipse CDT command for the headless build that I used:

~/eclipse/eclipse -nosplash -application org.eclipse.cdt.managedbuilder.core.headlessbuild -import ~/myAppProj/ -build myAppProj/Release -data ~/workspace/

Observations:

While Java is hanging, I can kill its process and get the executable
ready to use. When I trigger the build from Jenkins and kill that
deadlocked Java process, Jenkins just continues running normally
further scripts.

In the build server, while Java is janging, if I run:

jstack [java pid]

Then I get the following:

Attaching to process ID 25262, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 24.111-b01
Deadlock Detection:

java.lang.RuntimeException: Unable to deduce type of thread from address 0x00007fc5c8032800 (expected type JavaThread, CompilerThread, ServiceThread, JvmtiAgentThread, or SurrogateLockerThread)

Conclusion: it does seem that Java is deadlocking when Eclipse is run in headless mode. It doesn't happen all the time, but 99% I guess. Also, it doesn't stay hanging forever, it comes back after an hour or two, which is bad for any build server.

So, did anybody have problems like that?


问:
Should the tmp/sockets/unicorn.sock be symlinked for capistrano deploys of our unicorn server
I have deployed a rails app on unicorn, and am using Capistrano to manage deployment. Is it a good idea to symlink the tmp/sockets/unicorn.sock file to file in the shared directory?

答:
This is a file that links two system processes, your app server and your web server.

I would definitely do put it at least under the shared directory or even better under /var file system.

If you leave it under current directory it is in fact bound to a particular deployment release.