问:
woocommerce multiple products recipe page
I am currently looking for a solution for recipe pages.

Basically, I will have a blog post recipes where we will use our products to make something and users can read. I would like to add a button below the recipe page for example "Make this recipe" and when the button is clicked, all the ingredients that are used to make this recipe are added to the cart.

Is there a plugin that I can use so when I write the blog post, I can select the products that is added to the cart for different recipes?

Or do I need to get a developer to do this?

答:
This plugin will take care of allowing your customers to build their order exactly the way you want: https://codecanyon.net/item/woocommerce-order-builder-combo-products-extra-options/20839198

Then you can change add to cart to what ever you want by adding this to your theme functions.php file

```<code>add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );
function woo_custom_cart_button_text() {
        return __( 'Make this recipe', 'woocommerce' );
}
</code>```

Body:
This plugin will take care of allowing your customers to build their order exactly the way you want: https://codecanyon.net/item/woocommerce-order-builder-combo-products-extra-options/20839198

Then you can change add to cart to what ever you want by adding this to your theme functions.php file

add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );
function woo_custom_cart_button_text() {
        return __( 'Make this recipe', 'woocommerce' );
}


来源: stackexchange

问:
while (i<=sqrt(static_cast<double>(n))
In the "C++ Without Fear: A Beginner's Guide That Makes You Feel Smart" book, in Chapter (2): Decisions, Decisions, you can see this lin of code as part of the prime number program:

```<code>while (i<=sqrt(static_cast<double>(n))
</code>```

Provided that "i" was initialized to "2", and "n" is the user's input.

Why are we comparing to the "sqrt" of "n" and not to "n" itself?

Thanks.

答:
```<code>while (i<=sqrt(static_cast<double>(n))
</code>```

Is equivalent to

```<code>while(n >= i*i)
</code>```

Why the author choose the first solution may depend on other parts of the code.

ContentLicense: CC BY-SA 2.5

Title: while (i<=sqrt(static_cast<double>(n))

Body:
In the "C++ Without Fear: A Beginner's Guide That Makes You Feel Smart" book, in Chapter (2): Decisions, Decisions, you can see this lin of code as part of the prime number program:

while (i<=sqrt(static_cast<double>(n))

Provided that "i" was initialized to "2", and "n" is the user's input.

Why are we comparing to the "sqrt" of "n" and not to "n" itself?

Thanks.

Body:
while (i<=sqrt(static_cast<double>(n))

Is equivalent to

while(n >= i*i)

Why the author choose the first solution may depend on other parts of the code.


问:
Render partials inside loop in Rails 5
Question: How do I make a partial (that has to be generic) loop through different variables?

I have a tabbed page where I want to use a partial to avoid duplicating my HTML. The tabs are "Videos" and "Articles". It's the exact same HTML but I want to iterate through @videos for videos and @articles for articles.

The idea was to make the product partial completely generic and then somehow pass in @videos or @articles that I want to iterate through.

Partial: _product.html.slim

```<code>.col-md-5
  .thumbnail
    .thumb.spacer-sm
      - if product.image.blank?
        iframe allowfullscreen="" frameborder="0" mozallowfullscreen="" src="https://player.vimeo.com/product/#{product.vimeo_id}" webkitallowfullscreen=""
      - elsif product.vimeo_id.blank?
        = image_tag(product.image.url,
          class: 'img img-responsive img-rounded')
    .caption
      .content-group-sm.media
        .media-body
          h6.text-semibold.no-margin
            = product.name
          small.text-muted
            | by
            = product.user.name
        - unless product.price.blank?
          h6.text-success.media-right.no-margin-bottom.text-semibold
            | $
            = product.price
      = product.description
    .panel-footer.panel-footer-transparent
      .heading-elements
        ul.list-inline.list-inline-separate.heading-text
          li
            = link_to 'Delete', product_path(product), method: :delete
          li
            = link_to 'Edit', edit_product_path(product)
</code>```

HTML view rendering the partial:

```<code> .page-container.spacer-minus
    .page-content
      .row
        .col-md-4
          .sidebar-default.sidebar-separate
            .sidebar-content
              .content-group
                .panel.no-border-radius-top
                  ul.navigation
                    li.navigation-header Navigation
                    li.active
                      a data-toggle="tab" href="#videos"
                        i.icon-video-camera2
                        | Videos
                    li
                      a data-toggle="tab" href="#articles"
                        i.icon-graduation
                        | Articles

        .col-md-8
          .tab-content
            #videos.tab-pane.fade.in.active
              .row
                - @videos.each do |product|
                  = render 'shared/product'

            #articles.tab-pane.fade
              .row
                - @articles.each do |product|
                  = render 'shared/product'
</code>```

I just need my loop to understand what variable I want to iterate through. I cannot include @video or @article in the partial since that will defeat the purpose of having a generic partial.

With this implementation, I get the error:
undefined local variable or method `product' for #<#<Class:0x007fc58053ae60>:0x007fc58884ea68>

答:
Hi this is pretty stuff if you want articles to come after the videos then try this.

```<code>= render partial: "product", collection: @videos

= render partial: "product", collection: @articles
</code>```

this will remove the loop from your main view but in your case you are not using locals try this

```<code>          .row
            - @videos.each do |video|
              = render 'shared/product', locals: {product: video}
          .row
            - @articles.each do |article|
              = render 'shared/product' , locals: {product: article}
</code>```

It will work.

ContentLicense: CC BY-SA 3.0

Title: Render partials inside loop in Rails 5

Body:
Question: How do I make a partial (that has to be generic) loop through different variables?

I have a tabbed page where I want to use a partial to avoid duplicating my HTML. The tabs are "Videos" and "Articles". It's the exact same HTML but I want to iterate through @videos for videos and @articles for articles.

The idea was to make the product partial completely generic and then somehow pass in @videos or @articles that I want to iterate through.

Partial: _product.html.slim

.col-md-5
  .thumbnail
    .thumb.spacer-sm
      - if product.image.blank?
        iframe allowfullscreen="" frameborder="0" mozallowfullscreen="" src="https://player.vimeo.com/product/#{product.vimeo_id}" webkitallowfullscreen=""
      - elsif product.vimeo_id.blank?
        = image_tag(product.image.url,
          class: 'img img-responsive img-rounded')
    .caption
      .content-group-sm.media
        .media-body
          h6.text-semibold.no-margin
            = product.name
          small.text-muted
            | by
            = product.user.name
        - unless product.price.blank?
          h6.text-success.media-right.no-margin-bottom.text-semibold
            | $
            = product.price
      = product.description
    .panel-footer.panel-footer-transparent
      .heading-elements
        ul.list-inline.list-inline-separate.heading-text
          li
            = link_to 'Delete', product_path(product), method: :delete
          li
            = link_to 'Edit', edit_product_path(product)

HTML view rendering the partial:

 .page-container.spacer-minus
    .page-content
      .row
        .col-md-4
          .sidebar-default.sidebar-separate
            .sidebar-content
              .content-group
                .panel.no-border-radius-top
                  ul.navigation
                    li.navigation-header Navigation
                    li.active
                      a data-toggle="tab" href="#videos"
                        i.icon-video-camera2
                        | Videos
                    li
                      a data-toggle="tab" href="#articles"
                        i.icon-graduation
                        | Articles

        .col-md-8
          .tab-content
            #videos.tab-pane.fade.in.active
              .row
                - @videos.each do |product|
                  = render 'shared/product'

            #articles.tab-pane.fade
              .row
                - @articles.each do |product|
                  = render 'shared/product'

I just need my loop to understand what variable I want to iterate through. I cannot include @video or @article in the partial since that will defeat the purpose of having a generic partial.

With this implementation, I get the error:
undefined local variable or method `product' for #<#<Class:0x007fc58053ae60>:0x007fc58884ea68>

Body:
Hi this is pretty stuff if you want articles to come after the videos then try this.

= render partial: "product", collection: @videos

= render partial: "product", collection: @articles

this will remove the loop from your main view but in your case you are not using locals try this

          .row
            - @videos.each do |video|
              = render 'shared/product', locals: {product: video}
          .row
            - @articles.each do |article|
              = render 'shared/product' , locals: {product: article}

It will work.


问:
How to make request every 2 seconds with angular js and node js?
I have a server written with Nodejs that collects data. My client side is written with AngularJS. I need to create http request every two seconds to my server (setInterval) and display updated data. My server running 24/7. Can chrome block my requests if it reaches maximum? Can I implement another way, instead of create request from client side, maybe to push from my server?

Example of some request:

```<code>var indicesTimer = setInterval(getIndices,2000);
getIndices();

function getIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
  });
}
</code>```

答:
This is the typically behavior of a heartbeat. Chrome or any other browser does not block requests.
As long as your setInterval() handler doesn't run forever, it won't block other things from eventually running.

Body:
I have a server written with Nodejs that collects data. My client side is written with AngularJS. I need to create http request every two seconds to my server (setInterval) and display updated data. My server running 24/7. Can chrome block my requests if it reaches maximum? Can I implement another way, instead of create request from client side, maybe to push from my server?

Example of some request:

var indicesTimer = setInterval(getIndices,2000);
getIndices();

function getIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
  });
}


问:
Regular expression for string in Inno Setup
In Inno Setup tool (Windows OS)

InstallDir: string;
```

<p>I have a string <code>InstallDir</code> which contains  <code>C:\-=[]\.,';</code></p>

<p>I want to set a regular expression pattern as below</p>

```^([a-zA-Z]:)\\([0-9a-zA-Z_\\\s\.\-\(\)]*)$
```

Ex:
It should be c:\ or number or _ and so on (means a valid path).

I could not find any function in Inno Setup, which tells it supports regular expression for string operations.

Can any body help me out to resolve this?

答:
No, Inno Setup does not support regular expressions.

You may be able to invoke PowerShell for that, but that's an overkill.

You do not need a regular expression for your check:

function IsPathValid(Path: string): Boolean;
var
  I: Integer;
begin
  Path := Uppercase(Path);
  Result :=
    (Length(Path) >= 3) and
    (Path[1] >= 'A') and (Path[1] <= 'Z') and
    (Path[2] = ':') and
    (Path[3] = '\');

  if Result then
  begin
    for I := 3 to Length(Path) do
    begin
      case Path[I] of
        '0'..'9', 'A'..'Z', '\', ' ', '.', '-', '(', ')':
          else
        begin
          Result := False;
          Break;
        end;
      end;
    end;
  end;
end;
```

(The code requires Unicode version of Inno Setup, what you should use anyway and it is the only version as of current Inno Setup 6).

Similar questions:

Basic email validation within Inno Setup script

Wildcard characters in Inno Setup (test if there is any value after fixed string prefix)

Body:
In Inno Setup tool (Windows OS)

InstallDir: string;

I have a string InstallDir which contains  C:\-=[]\.,';

I want to set a regular expression pattern as below

^([a-zA-Z]:)\\([0-9a-zA-Z_\\\s\.\-\(\)]*)$

Ex:
It should be c:\ or number or _ and so on (means a valid path).

I could not find any function in Inno Setup, which tells it supports regular expression for string operations.

Can any body help me out to resolve this?

Body:
No, Inno Setup does not support regular expressions.

You may be able to invoke PowerShell for that, but that's an overkill.

You do not need a regular expression for your check:

function IsPathValid(Path: string): Boolean;
var
  I: Integer;
begin
  Path := Uppercase(Path);
  Result :=
    (Length(Path) >= 3) and
    (Path[1] >= 'A') and (Path[1] <= 'Z') and
    (Path[2] = ':') and
    (Path[3] = '\');

  if Result then
  begin
    for I := 3 to Length(Path) do
    begin
      case Path[I] of
        '0'..'9', 'A'..'Z', '\', ' ', '.', '-', '(', ')':
          else
        begin
          Result := False;
          Break;
        end;
      end;
    end;
  end;
end;

(The code requires Unicode version of Inno Setup, what you should use anyway and it is the only version as of current Inno Setup 6).

Similar questions:

Basic email validation within Inno Setup script

Wildcard characters in Inno Setup (test if there is any value after fixed string prefix)

ContentLicense: CC BY-SA 4.0


问:
wso2 api manager secure public API
I have designed a public REST API with JSON which is used primarily from native mobile applications. The application which should subscribe to this API does not have any username/password login mechanism as it should be public.

The API is designed using WSO2 API Manager in version 2.1.0 and application should establish TLSv1.2 trusted connection in order to consume services.

The API on the backend side is subscribing to internal REST API which has mutual TLS authentication.

Currently the OAuth2 is disabled for the API and I am thinking how to use it in order to get a higher assurance and identification of the end point who is trying to use the API.

The only OAuth2 Grant Type that I can use in this case is Client Credential from my point of view, where the application can get its consumer key and consumer secret to be able to request access tokens. But it can be obtained from application source code or configuration.

As there is no username/password mechanism Implicit Grant Type can't be used.

How to use API Manager in this case?

答:
For mutual ssl you can refer following blog post.

http://ishara-cooray.blogspot.com/2016/07/how-to-secure-your-backend-services-and.html

Here is the important part from the blog post.

Configure API Manager to enable dynamic ssl profiles

To configure APIM for Dynamic SSL Profiles for HHTPS transport Sender,
  you need to create a new XML file
  /repository/deployment/server/multi_ssl_profiles.xml (this
  path is configurable) and copy the below configuration into it.This
  will configure client-truststore.jks as Trust Store for all
  connections to 10.100.5.130:9443

```<code><parameter name="customSSLProfiles">
 <profile>
  <servers>10.100.5.130:9443</servers>
  <TrustStore>
          <Location>repository/resources/security/client-truststore.jks
   </Location>
   <Type>JKS</Type>
   <Password>wso2carbon</Password>
  </TrustStore>
</profile>
</parameter>
</code>```

To enable dynamic loading of this configuration, add below
  configurations  to the Transport Sender configuration
  (PassThroughHttpSSLSender) of API Manager
  ({AM_HOME}/repository/conf/axis2.xml). Set above file’s path as
  “filePath” parameter.

```<code><parameter name="dynamicSSLProfilesConfig">
  <filePath>repository/deployment/server/multi_ssl_profiles.xml</filePath>
  <fileReadInterval>3600000</fileReadInterval>
</parameter>
<parameter name="HostnameVerifier">AllowAll</parameter>
</code>```

Now both back end service and ESB is configured to use default key
  stores and API Manager is configured to load dynamic SSL profiles.
  Restart API Manager. It will show below message in the console
  confirming that dynamic configurations loaded.

ClientConnFactoryBuilder customSSLProfiles configuration is loaded
  from path:

Title: wso2 api manager secure public API

Body:
For mutual ssl you can refer following blog post.

http://ishara-cooray.blogspot.com/2016/07/how-to-secure-your-backend-services-and.html

Here is the important part from the blog post.

Configure API Manager to enable dynamic ssl profiles

To configure APIM for Dynamic SSL Profiles for HHTPS transport Sender,
  you need to create a new XML file
  /repository/deployment/server/multi_ssl_profiles.xml (this
  path is configurable) and copy the below configuration into it.This
  will configure client-truststore.jks as Trust Store for all
  connections to 10.100.5.130:9443

<parameter name="customSSLProfiles">
 <profile>
  <servers>10.100.5.130:9443</servers>
  <TrustStore>
          <Location>repository/resources/security/client-truststore.jks
   </Location>
   <Type>JKS</Type>
   <Password>wso2carbon</Password>
  </TrustStore>
</profile>
</parameter>

To enable dynamic loading of this configuration, add below
  configurations  to the Transport Sender configuration
  (PassThroughHttpSSLSender) of API Manager
  ({AM_HOME}/repository/conf/axis2.xml). Set above file’s path as
  “filePath” parameter.

<parameter name="dynamicSSLProfilesConfig">
  <filePath>repository/deployment/server/multi_ssl_profiles.xml</filePath>
  <fileReadInterval>3600000</fileReadInterval>
</parameter>
<parameter name="HostnameVerifier">AllowAll</parameter>

Now both back end service and ESB is configured to use default key
  stores and API Manager is configured to load dynamic SSL profiles.
  Restart API Manager. It will show below message in the console
  confirming that dynamic configurations loaded.

ClientConnFactoryBuilder customSSLProfiles configuration is loaded
  from path:


问:
Why is this code correct?
```<code>#include <stdio.h>
void reverseSentence();

int main()
{
  printf("Enter a sentence: ");
  reverseSentence();

  return 0;
}

void reverseSentence()
{
  char c;
  scanf("%c", &c);

  if( c != '\n')
  {
    reverseSentence();
    printf("%c",c);
  }
</code>```

I tried out this code and I know it is correct, but i don't know why the recursion works. It seems a bit non-intuitive. Could someone please shed some light on why it works? Also, what is \n doing exactly?(This is where i think the answer to my question lies). Thanks.

答:
Let's say you are trying to type the word "elf" (with the "\n") character at the end.

The program should print: "fle".

The program enters reverseSentence().

The program scans 'e', it's not '\n', therefore enters reverseSentence(). c='e'

The program scans 'l', it's not '\n', therefore enters reverseSentence(). c='l'

The program scans 'f', it's not '\n', therefore enters reverseSentence(). c='f'

The program scans '\n', it is '\n', therefore exits reverseSentence() and goes to the last called instance  of reverseSentece() in (4).

The last call in reverseSentence() stoped just before printf, it now prints c. c in the last call (4) was: 'f'. It prints f and exits. It goes to the previous call of reverseSentence() in (3).

Just like before it prints c='l' and exits.

It goes to the previous call or reverseSentence() in (2). It prints c='e' and exits.

I hope that helped

Title: Why is this code correct?

Body:
#include <stdio.h>
void reverseSentence();

int main()
{
  printf("Enter a sentence: ");
  reverseSentence();

  return 0;
}

void reverseSentence()
{
  char c;
  scanf("%c", &c);

  if( c != '\n')
  {
    reverseSentence();
    printf("%c",c);
  }

I tried out this code and I know it is correct, but i don't know why the recursion works. It seems a bit non-intuitive. Could someone please shed some light on why it works? Also, what is \n doing exactly?(This is where i think the answer to my question lies). Thanks.


问:
Finding strict prefixes in lucene
I'm trying to implement an autocomplete feature with Lucene. For example, if the user types "Lucene", the returned results may be "Lucene in Action" and "Lucene for Dummies".

The problem I'm having is that the field should start with with the searched text, it shouldn't be somewhere in the middle; searching for "Lucene" shouldn't return "Enterprise Lucene". Here's my code so far, which doesn't exclude the above:

```<code>    StandardAnalyzer analyzer = new StandardAnalyzer();
    Directory index = new RAMDirectory();
    IndexWriterConfig config = new IndexWriterConfig(analyzer);

    IndexWriter indexWriter = new IndexWriter(index, config);
    addDocument(indexWriter, "Luceneinaction");
    addDocument(indexWriter, "LuceneforDummies");
    addDocument(indexWriter, "WhyisLucenesohard");
    addDocument(indexWriter, "Managing Gigabytes");
    addDocument(indexWriter, "The Art of Computer Science");
    indexWriter.close();

    Query query = new PrefixQuery(new Term("title", "lucene"));

    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs docs = searcher.search(query, 10);
    for (ScoreDoc scoreDoc : docs.scoreDocs) {
        System.out.println(searcher.doc(scoreDoc.doc).get("title"));
    }
</code>```

Is there an easy way to solve this? It appears that PrefixQuery is not compatible with StringField, and I can't find a tokenizer that doesn't split on whitespace.

答:
If you want to use a field for Fulltext-Search you should always use Textfield, because this will be analyzed (base on your given analyzer).
See javadoc of: Field

It's really important that you understand what kind of field you need to use for which purpose.

For your use case, if you search in a TextField you don't have to use a PrefixQuery.

Title: Finding strict prefixes in lucene

Body:
I'm trying to implement an autocomplete feature with Lucene. For example, if the user types "Lucene", the returned results may be "Lucene in Action" and "Lucene for Dummies".

The problem I'm having is that the field should start with with the searched text, it shouldn't be somewhere in the middle; searching for "Lucene" shouldn't return "Enterprise Lucene". Here's my code so far, which doesn't exclude the above:

    StandardAnalyzer analyzer = new StandardAnalyzer();
    Directory index = new RAMDirectory();
    IndexWriterConfig config = new IndexWriterConfig(analyzer);

    IndexWriter indexWriter = new IndexWriter(index, config);
    addDocument(indexWriter, "Luceneinaction");
    addDocument(indexWriter, "LuceneforDummies");
    addDocument(indexWriter, "WhyisLucenesohard");
    addDocument(indexWriter, "Managing Gigabytes");
    addDocument(indexWriter, "The Art of Computer Science");
    indexWriter.close();

    Query query = new PrefixQuery(new Term("title", "lucene"));

    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs docs = searcher.search(query, 10);
    for (ScoreDoc scoreDoc : docs.scoreDocs) {
        System.out.println(searcher.doc(scoreDoc.doc).get("title"));
    }

Is there an easy way to solve this? It appears that PrefixQuery is not compatible with StringField, and I can't find a tokenizer that doesn't split on whitespace.


问:
Kotlin warning: Conditional branch result of type ... is implicity cast of Any?
I have "Conditional branch result of type ... is implicity cast of Any?" warning when i try to do something like this:

```<code>objects?.forEach {

     val gson = Gson()

     val chatObject = if(it.type == CHAT_TEXT_TYPE) gson.fromJson(it.value, ChatText::class.java)  //WARNING
                      else gson.fromJson(it.value, ChatProduct::class.java) //WARNING

     //TEST
     if(chatObject is ChatText) Log.e("ChatText: It works!", chatObject.text)
     if(chatObject is ChatProduct) Log.e("ChatProduct: It works!", chatObject.name)
}
</code>```

But finally it works. Is anything wrong with my code? Is it any possibility to remove this warning?

EDIT (as @Xavier Bouclet suggested - warning disappeared)

```<code>val chatObject = when (it.type)
            {
                CHAT_TEXT_TYPE ->  gson.fromJson(it.value, ChatText::class.java)
                CHAT_PRODUCT_TYPE -> gson.fromJson(it.value, ChatProduct::class.java)
                else -> gson.fromJson(it.value, Any::class.java)
            }
</code>```

答:
The warning is telling you that you've returned different types in your branches, and that the variable you're assigning will be inferred to be their first common supertype, which in this case is Any?. This is not the way you usually use the if-else expression, you usually return the same type from both branches. The IDE is warning you because what you're doing is usually accidental.

If you're going to check the type of the result later for the actual types you're using anyway, you're probably fine with your code.

To remove the warning, you can either suppress the warning with a comment:

```<code>@Suppress("IMPLICIT_CAST_TO_ANY")
val chatObject = ...
</code>```

Or explicitly state that the type that the if-else expression returns is unknown:

```<code>val chatObject: Any = ...
</code>```

Body:
I have "Conditional branch result of type ... is implicity cast of Any?" warning when i try to do something like this:

objects?.forEach {

     val gson = Gson()

     val chatObject = if(it.type == CHAT_TEXT_TYPE) gson.fromJson(it.value, ChatText::class.java)  //WARNING
                      else gson.fromJson(it.value, ChatProduct::class.java) //WARNING

     //TEST
     if(chatObject is ChatText) Log.e("ChatText: It works!", chatObject.text)
     if(chatObject is ChatProduct) Log.e("ChatProduct: It works!", chatObject.name)
}

But finally it works. Is anything wrong with my code? Is it any possibility to remove this warning?

EDIT (as @Xavier Bouclet suggested - warning disappeared)

val chatObject = when (it.type)
            {
                CHAT_TEXT_TYPE ->  gson.fromJson(it.value, ChatText::class.java)
                CHAT_PRODUCT_TYPE -> gson.fromJson(it.value, ChatProduct::class.java)
                else -> gson.fromJson(it.value, Any::class.java)
            }

Body:
The warning is telling you that you've returned different types in your branches, and that the variable you're assigning will be inferred to be their first common supertype, which in this case is Any?. This is not the way you usually use the if-else expression, you usually return the same type from both branches. The IDE is warning you because what you're doing is usually accidental.

If you're going to check the type of the result later for the actual types you're using anyway, you're probably fine with your code.

To remove the warning, you can either suppress the warning with a comment:

@Suppress("IMPLICIT_CAST_TO_ANY")
val chatObject = ...

Or explicitly state that the type that the if-else expression returns is unknown:

val chatObject: Any = ...


问:
Executing a function in a dictionary | Python 3
So I am making a program in python 3.6 that selects and executes a specific function based on the user_input.

The code can properly decide what function to execute, just not actually execute it. The functions also work

```<code>def addition():
    1+1

user_input = input("What operator do you wish to use?")

myOperators = {"Addition":addition}

if user_input in myOperators:
    myOperators.get(user_input)
</code>```

Using this code the function addition() never executes. However, I can check that it selects the correct value, because if I do this:

```<code>if user_input in myOperators:
    print(myOperators.get(user_input))
</code>```

it prints <function addition at 0x7f0973026620>

答:
Python treats functions as object which can be passed around and stored in lists and dictionaries.  To actually call the function you need to use parenthesis after the object.

In your case myOperators.get(user_input) returns the function object, so it would become

```<code>myOperators.get(user_input)()
</code>```

Body:
So I am making a program in python 3.6 that selects and executes a specific function based on the user_input.

The code can properly decide what function to execute, just not actually execute it. The functions also work

def addition():
    1+1

user_input = input("What operator do you wish to use?")

myOperators = {"Addition":addition}

if user_input in myOperators:
    myOperators.get(user_input)

Using this code the function addition() never executes. However, I can check that it selects the correct value, because if I do this:

if user_input in myOperators:
    print(myOperators.get(user_input))

it prints <function addition at 0x7f0973026620>

Body:
Python treats functions as object which can be passed around and stored in lists and dictionaries.  To actually call the function you need to use parenthesis after the object.

In your case myOperators.get(user_input) returns the function object, so it would become

myOperators.get(user_input)()


问:
Histogram Binning of Gradient Vectors
I am working on a project that has a small component requiring the comparison of distributions over image gradients. Assume I have computed the image gradients in the x and y directions using a Sobel filter and have for each pixel a 2-vector. Obviously getting the magnitude and direction is reasonably trivial and is as follows:

However, what is not clear to me is how to bin these two components in to a two dimensional histogram for an arbitrary number of bins.

I had considered something along these lines(written in browser):

```<code>//Assuming normalised magnitudes.
//Histogram dimensions are bins * bins.
int getHistIdx(float mag, float dir, int bins) {
    const int magInt = reinterpret_cast<int>(mag);
    const int dirInt = reinterpret_cast<int>(dir);
    const int magMod = reinterpret_cast<int>(static_cast<float>(1.0));
    const int dirMod = reinterpret_cast<int>(static_cast<float>(TWO_PI));

    const int idxMag = (magInt % magMod) & bins
    const int idxDir = (dirInt % dirMod) & bins;
    return idxMag * bins + idxDir;
}
</code>```

However, I suspect that the mod operation will introduce a lot of incorrect overlap, i.e. completely different gradients getting placed in to the same bin.

Any insight in to this problem would be very much appreciated.

I would like to avoid using any off the shelf libraries as I want to keep this project as dependency light as possible. Also I intend to implement this in CUDA.

答:
I think you should arrange your bins in a square array, and then bin by vx and vy independently.

If your gradients are reasonably even you just need to scan the data first to accumulate the min and max in x and y, and then split the gradients evenly.

If the gradients are very unevenly distributed, you might want to sort the (eg) vx first and arrange that the boundaries between each bin exactly evenly divides the values.

An intermediate solution might be to obtain the min and max ignoring the (eg) 10% most extreme values.

Title: Histogram Binning of Gradient Vectors

Body:
I am working on a project that has a small component requiring the comparison of distributions over image gradients. Assume I have computed the image gradients in the x and y directions using a Sobel filter and have for each pixel a 2-vector. Obviously getting the magnitude and direction is reasonably trivial and is as follows:

However, what is not clear to me is how to bin these two components in to a two dimensional histogram for an arbitrary number of bins.

I had considered something along these lines(written in browser):

//Assuming normalised magnitudes.
//Histogram dimensions are bins * bins.
int getHistIdx(float mag, float dir, int bins) {
    const int magInt = reinterpret_cast<int>(mag);
    const int dirInt = reinterpret_cast<int>(dir);
    const int magMod = reinterpret_cast<int>(static_cast<float>(1.0));
    const int dirMod = reinterpret_cast<int>(static_cast<float>(TWO_PI));

    const int idxMag = (magInt % magMod) & bins
    const int idxDir = (dirInt % dirMod) & bins;
    return idxMag * bins + idxDir;
}

However, I suspect that the mod operation will introduce a lot of incorrect overlap, i.e. completely different gradients getting placed in to the same bin.

Any insight in to this problem would be very much appreciated.

I would like to avoid using any off the shelf libraries as I want to keep this project as dependency light as possible. Also I intend to implement this in CUDA.


问:
How to use an array in actionscript?
```<code>var fruit:Array = new Array();

var frName:String;

var i:Number;

save_btn.addEventListener(MouseEvent.CLICK, storeName);

function storeName(Event:MouseEvent)
{

 frName = name_txt.text;

 fruit[i] = frName;

 i++;
}

detail_btn.addEventListener(MouseEvent.CLICK, dispName);

function dispName(Event:MouseEvent)

{

 for(i=0; i<=1; i++)

 {
  trace(fruit[i]);
 }
}
</code>```

The script has two buttons: one for saving the text in a fruit array and the other for displaying the text.

However, when I click the display button, the script shows undefined as output in actionscript. Please help.

答:
When you defined your "i" variable you never set a value... e.g. it is "undefined".  Just set it to zero.</p>

```<code>var i:Number = 0;
</code>```

Title: How to use an array in actionscript?

Body:
var fruit:Array = new Array();

var frName:String;

var i:Number;

save_btn.addEventListener(MouseEvent.CLICK, storeName);

function storeName(Event:MouseEvent)
{

 frName = name_txt.text;

 fruit[i] = frName;

 i++;
}

detail_btn.addEventListener(MouseEvent.CLICK, dispName);

function dispName(Event:MouseEvent)

{

 for(i=0; i<=1; i++)

 {
  trace(fruit[i]);
 }
}

The script has two buttons: one for saving the text in a fruit array and the other for displaying the text.

However, when I click the display button, the script shows undefined as output in actionscript. Please help.

Body:
When you defined your "i" variable you never set a value... e.g. it is "undefined".  Just set it to zero.

var i:Number = 0;


问:
Java: Instantiate a generic type by returning a Supplier vs returning a new instance
I was reading how to instantiate a generic and after reading and applying this answer; I would like to know what would be the differences between expecting a Supplier<T> vs. expecting a new instance of T.

Example:

```<code>abstract class AbstractService<T extends AbstractEntity> {
    protected Supplier<T> makeNewThing();  // supplier is expected

    public T myMethod(){
        T object = makeNewThing().get(); // local object by calling supplier
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Supplier<Car> makeNewThing(){
        return Car::new;
    }
}
</code>```

vs.

```<code>abstract class AbstractService<T extends SomeAbstractEntity> {
    protected T makeNewThing();  // object is expected, newness is assumed

    public T myMethod(){
        T object = makeNewThing(); // local object by calling constructor
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Car makeNewThing(){
        return new Car();
    }
}
</code>```

The only thing I can think of is that expecting a supplier ensures that a new object will be created, but when expecting an object we can only assume that the implementing classes are calling the constructor and not re-using an existing instance.

I'd like to know of other objective differences and possible use cases, if any. Thanks in advance.

答:
Using a Supplier postpones the creation of the instance.

This means that you might avoid a creation of an unnecessary instance.

For example, suppose you pass the output of makeNewThing() to some method.

```<code>public void makeNewThingSometimes (T newInstance)
{
    if (someCondition) {
        this.instance = newInstance;
    }
}

public void makeNewThingSometimes (Supplier<T> supplier)
{
    if (someCondition) {
        this.instance = supplier.get();
    }
}
</code>```

Calling the first variant requires creating an instance of T even if you are not going to use it.

Calling the second variant only creates an instance of T when necessary.

Using a Consumer can save both storage (if the create instance requires a significant amount of memory) and time (if the execution of the constructor is expansive).

Body:
I was reading how to instantiate a generic and after reading and applying this answer; I would like to know what would be the differences between expecting a Supplier<T> vs. expecting a new instance of T.

Example:

abstract class AbstractService<T extends AbstractEntity> {
    protected Supplier<T> makeNewThing();  // supplier is expected

    public T myMethod(){
        T object = makeNewThing().get(); // local object by calling supplier
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Supplier<Car> makeNewThing(){
        return Car::new;
    }
}

vs.

abstract class AbstractService<T extends SomeAbstractEntity> {
    protected T makeNewThing();  // object is expected, newness is assumed

    public T myMethod(){
        T object = makeNewThing(); // local object by calling constructor
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Car makeNewThing(){
        return new Car();
    }
}

The only thing I can think of is that expecting a supplier ensures that a new object will be created, but when expecting an object we can only assume that the implementing classes are calling the constructor and not re-using an existing instance.

I'd like to know of other objective differences and possible use cases, if any. Thanks in advance.

Body:
Using a Supplier postpones the creation of the instance.

This means that you might avoid a creation of an unnecessary instance.

For example, suppose you pass the output of makeNewThing() to some method.

public void makeNewThingSometimes (T newInstance)
{
    if (someCondition) {
        this.instance = newInstance;
    }
}

public void makeNewThingSometimes (Supplier<T> supplier)
{
    if (someCondition) {
        this.instance = supplier.get();
    }
}

Calling the first variant requires creating an instance of T even if you are not going to use it.

Calling the second variant only creates an instance of T when necessary.

Using a Consumer can save both storage (if the create instance requires a significant amount of memory) and time (if the execution of the constructor is expansive).


问:
How to reset selects inside an array without v-model

Problem

I need to reset all selects inside an array that has no v-models within Vue.js.

Template

```<code><div id="app">
  <div v-for="(element, index) in elements">
    <select @input="setElement(index, $event.target.value)">
      <option v-for="option in options" :value="option">{{option}}</option>
    </select>
  </div>

  <button @click="addElement">
    Set three elements
  </button>
</div>
</code>```

Script

```<code>new Vue({
  el: '#app',
  data() {
    return {
      options: ['a', 'b', 'c'],
      elements: [{
        element: ''
      }, {
        element: ''
      }]
    }
  },

  methods: {
    addElement() {
        this.elements = []
        this.elements.push({
          element: ''
        })
        this.elements.push({
          element: ''
        })
        this.elements.push({
          element: ''
        })
      },

      setElement(index, el) {
        let element = {
          element: el
        }

        this.$set(this.elements, index, element)
      }
  }
})
</code>```

Demo: https://jsfiddle.net/jqb99tks/4/

Wish

When the length of elements change (e. g. a reset), the selects should be reset.

Approach

I can iterate through all HTML selects and manually reset them but that feels like a hacked solution.

答:
This maybe better for you.
v-model can be used for 'select'.

https://jsfiddle.net/loocao/jqb99tks/8/

```<code><div v-for="(element, index) in elements">
  <select v-model="element.element">
    <option v-for="option in options" :value="option" :selected="element.element === option">{{option}}</option>
  </select>
</div>
</code>```

methods:

```<code>addElement() {
    // first select
    this.elements.splice(0,1,{element: ''})
    // add one
    this.elements.push({element: 'a'})
}
</code>```

Body:
Problem

I need to reset all selects inside an array that has no v-models within Vue.js.

Template

    <select @input="setElement(index, $event.target.value)">
      <option v-for="option in options" :value="option">{{option}}</option>
    </select>

  <button @click="addElement">
    Set three elements
  </button>

Script

new Vue({
  el: '#app',
  data() {
    return {
      options: ['a', 'b', 'c'],
      elements: [{
        element: ''
      }, {
        element: ''
      }]
    }
  },

  methods: {
    addElement() {
        this.elements = []
        this.elements.push({
          element: ''
        })
        this.elements.push({
          element: ''
        })
        this.elements.push({
          element: ''
        })
      },

      setElement(index, el) {
        let element = {
          element: el
        }

        this.$set(this.elements, index, element)
      }
  }
})

Demo: https://jsfiddle.net/jqb99tks/4/

Wish

When the length of elements change (e. g. a reset), the selects should be reset.

Approach

I can iterate through all HTML selects and manually reset them but that feels like a hacked solution.

Body:
This maybe better for you.
v-model can be used for 'select'.

https://jsfiddle.net/loocao/jqb99tks/8/

<div v-for="(element, index) in elements">
  <select v-model="element.element">
    <option v-for="option in options" :value="option" :selected="element.element === option">{{option}}</option>
  </select>
</div>

methods:

addElement() {
    // first select
    this.elements.splice(0,1,{element: ''})
    // add one
    this.elements.push({element: 'a'})
}


问:
How to add an object and array in an existing object using typescript or angular
I am a beginner in angular 4 and using form builder,On  ngSubmit  I am creating an object containing the data of form fields. However before passing that object as a payload i need to add another object and an array inside the form object, I am wracking my brains but couldn't able to achieve it.

As you can see below 1 is the object that i am getting from form builder.
and 2. is the final object expected and i need to add "childrenCustomerIds" and "properties" respectively in the object after form builder object is created, but i have no clue how to add that.

Any help would be appreciated..

thanks in advance..!!!

1

```<code>{
    "address": "string",
    "customerId": "BGroup",
    "email": "test@gmail.com",
    "name": "Testing",
    "parentCustomerId": "myCustomerId3",
    "phoneNumber": "1111111111",
    "primaryContactUserId": "primaryContactUserId",
    "status": "ACTIVE",
    "xylemPrimaryContactId": "testing"
}
</code>```

2

```<code>{
    "address": "string",
    "childrenCustomerIds": ["testing"],
    "customerId": "BGroup",
    "email": "test@gmail.com",
    "name": "Testing",
    "parentCustomerId": "myCustomerId3",
    "phoneNumber": "1111111111",
    "primaryContactUserId": "primaryContactUserId",
    "properties": {},
    "status": "ACTIVE",
    "xylemPrimaryContactId": "testing"
}
</code>```

答:
```<code>var obj={
    "address": "string",
    "customerId": "BGroup",
    "email": "test@gmail.com",
    "name": "Testing",
    "parentCustomerId": "myCustomerId3",
    "phoneNumber": "1111111111",
    "primaryContactUserId": "primaryContactUserId",
    "status": "ACTIVE",
    "xylemPrimaryContactId": "testing"
}
</code>```

Add "childrenCustomerIds": ["testing"]

```<code>Object.assign(obj, {"childrenCustomerIds": ["testing"]});
</code>```

similarly you can add "properties": {}

```<code>Object.assign(obj, {"properties": {}});
</code>```

Body:
I am a beginner in angular 4 and using form builder,On  ngSubmit  I am creating an object containing the data of form fields. However before passing that object as a payload i need to add another object and an array inside the form object, I am wracking my brains but couldn't able to achieve it.

As you can see below 1 is the object that i am getting from form builder.
and 2. is the final object expected and i need to add "childrenCustomerIds" and "properties" respectively in the object after form builder object is created, but i have no clue how to add that.

Any help would be appreciated..

thanks in advance..!!!

1

{
    "address": "string",
    "customerId": "BGroup",
    "email": "test@gmail.com",
    "name": "Testing",
    "parentCustomerId": "myCustomerId3",
    "phoneNumber": "1111111111",
    "primaryContactUserId": "primaryContactUserId",
    "status": "ACTIVE",
    "xylemPrimaryContactId": "testing"
}

2

{
    "address": "string",
    "childrenCustomerIds": ["testing"],
    "customerId": "BGroup",
    "email": "test@gmail.com",
    "name": "Testing",
    "parentCustomerId": "myCustomerId3",
    "phoneNumber": "1111111111",
    "primaryContactUserId": "primaryContactUserId",
    "properties": {},
    "status": "ACTIVE",
    "xylemPrimaryContactId": "testing"
}

Body:
var obj={
    "address": "string",
    "customerId": "BGroup",
    "email": "test@gmail.com",
    "name": "Testing",
    "parentCustomerId": "myCustomerId3",
    "phoneNumber": "1111111111",
    "primaryContactUserId": "primaryContactUserId",
    "status": "ACTIVE",
    "xylemPrimaryContactId": "testing"
}

Add "childrenCustomerIds": ["testing"]

Object.assign(obj, {"childrenCustomerIds": ["testing"]});

similarly you can add "properties": {}

Object.assign(obj, {"properties": {}});


问:
User idle time being reset to 0 after 30 secs on Linux
I am trying to detect time since last user input using the X11 Screen Saver extension client library. I make periodic calls to XScreenSaverQueryInfo to get the idle time. The problem I am facing is that after every 20-30 seconds the idle time, as reported by this call, resets to 0. This happens even though there has been no actual user input in that time. I am totally puzzled by this. The only lead I have is that the problem disappears if I uninstall gnome-screensaver. My question is, does the gnome-screensaver simulate user inputs for some reason? I know it sounds unlikely, and if it does, it will most definitely be a bug with gnome-screensaver, but I cannot think of anything else right now. Does anyone know where I can find more information on how gnome-screensaver works and how it influences the XScreenSaverQueryInfo call without actually having to go through the code. I have gone through the info at gnome-screensaver home but could not find anything relevant to my issue.

Update: I got the following output from dbus-monitor. How do I interpret this:

```<code>method call sender=:1.97538 -> dest=org.gnome.ScreenSaver serial=3 path=/org/gnome/ScreenSaver; interface=org.gnome.ScreenSaver; member=SimulateUserActivity
</code>```

I think some process is asking gnome-screensaver to SimulateUserActivity. Or, is gnome-screensaver sending a SimulateUserActivity signal to dbus? If it is the first, how can I find out which process is asking gnome-screensaver to do that?

答:
Once you have the dbus sender (as shown on dbus-monitor there) you can do:

```<code>dbus-send --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.GetConnectionUnixProcessID string:':1.97538'
</code>```

plugging in the actual sender. That gives you the pid that's sending the message.

Then say the pid is 2144, you'd do:

```<code>cat /proc/2144/cmdline
</code>```

as one way to see what the program is.

Body:
I am trying to detect time since last user input using the X11 Screen Saver extension client library. I make periodic calls to XScreenSaverQueryInfo to get the idle time. The problem I am facing is that after every 20-30 seconds the idle time, as reported by this call, resets to 0. This happens even though there has been no actual user input in that time. I am totally puzzled by this. The only lead I have is that the problem disappears if I uninstall gnome-screensaver. My question is, does the gnome-screensaver simulate user inputs for some reason? I know it sounds unlikely, and if it does, it will most definitely be a bug with gnome-screensaver, but I cannot think of anything else right now. Does anyone know where I can find more information on how gnome-screensaver works and how it influences the XScreenSaverQueryInfo call without actually having to go through the code. I have gone through the info at gnome-screensaver home but could not find anything relevant to my issue.

Update: I got the following output from dbus-monitor. How do I interpret this:

method call sender=:1.97538 -> dest=org.gnome.ScreenSaver serial=3 path=/org/gnome/ScreenSaver; interface=org.gnome.ScreenSaver; member=SimulateUserActivity

I think some process is asking gnome-screensaver to SimulateUserActivity. Or, is gnome-screensaver sending a SimulateUserActivity signal to dbus? If it is the first, how can I find out which process is asking gnome-screensaver to do that?

Body:
Once you have the dbus sender (as shown on dbus-monitor there) you can do:

dbus-send --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.GetConnectionUnixProcessID string:':1.97538'

plugging in the actual sender. That gives you the pid that's sending the message.

Then say the pid is 2144, you'd do:

cat /proc/2144/cmdline

as one way to see what the program is.


问:
Adding a 'view all' endpoint to restful Django
I have this row in my urls.py:

```<code>url(r'^rss/(?P<rss_id>\d+)/', views.RSSList.as_view())
</code>```

I want to be able to server also something like

```<code>http://example.com/rss
</code>```

Which will show the complete rss list.

How can I add it while keeping the id option?

答:
You need to change the given line to:

```<code>url(r'^rss/(?P<rss_id>\d*)/?', views.RSSList.as_view())
</code>```

The character '*' means zero or more character.

Body:
I have this row in my urls.py:

url(r'^rss/(?P<rss_id>\d+)/', views.RSSList.as_view())

I want to be able to server also something like

http://example.com/rss

Which will show the complete rss list.

How can I add it while keeping the id option?

Body:
You need to change the given line to:

url(r'^rss/(?P<rss_id>\d*)/?', views.RSSList.as_view())

The character '*' means zero or more character.


问:
Improve DataTable performance when modifying class of cell
I'm very satisified using jquery DataTables, but I have found one situation where I need to boost performance. I'm updating the class of a cell depending on the data. To do this I'm using the render function and creating an api instance from the settings to get hold of the cell via the api. Is there a better way for doing this?</p>

```<code>{
        "data": "statusText", "className": "status",
        "render": function (data, type, full, meta) {
            switch (type) {
                case "display":
                    var api = new $.fn.dataTable.Api(meta.settings);
                    var td = api.cell({ row: meta.row, column: meta.col }).node();
                    switch (full.status) {
                        case Status.Saved:
                            $(td).addClass("status-saved");
                            break;
                        case Status.Sent:
                            $(td).addClass("status-sent");
                            break;
                        default:
                            $(td).addClass("status-saved");
                    }
                    return full.statusText;
                case "sort":
                    return full.status;
                default:
                    return full.statusText;
             }
        }
    }
</code>```

答:
One possibility I can see is that If you somehow manage to get api and td out of render function. Because that looks like heavy operation.

and make td like below, probably that will work.

```<code>var td = $(api.cell({ row: meta.row, column: meta.col }).node());
</code>```

Further more what you can do is to use vanillaJS instead of addClass

Body:
I'm very satisified using jquery DataTables, but I have found one situation where I need to boost performance. I'm updating the class of a cell depending on the data. To do this I'm using the render function and creating an api instance from the settings to get hold of the cell via the api. Is there a better way for doing this?

{
        "data": "statusText", "className": "status",
        "render": function (data, type, full, meta) {
            switch (type) {
                case "display":
                    var api = new $.fn.dataTable.Api(meta.settings);
                    var td = api.cell({ row: meta.row, column: meta.col }).node();
                    switch (full.status) {
                        case Status.Saved:
                            $(td).addClass("status-saved");
                            break;
                        case Status.Sent:
                            $(td).addClass("status-sent");
                            break;
                        default:
                            $(td).addClass("status-saved");
                    }
                    return full.statusText;
                case "sort":
                    return full.status;
                default:
                    return full.statusText;
             }
        }
    }

Body:
One possibility I can see is that If you somehow manage to get api and td out of render function. Because that looks like heavy operation.

and make td like below, probably that will work.

var td = $(api.cell({ row: meta.row, column: meta.col }).node());

Further more what you can do is to use vanillaJS instead of addClass


问:
ng-bootstrap not displaying tooltip
I want to display a tooltip. I went to ng-bootstrap and integrated that code. Getting console error.

```<code>core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: No provider for
NgbTooltipConfig!
Error: No provider for NgbTooltipConfig!
at injectionError (core.es5.js:1169)
at noProviderError (core.es5.js:1207)
at ReflectiveInjector_._throwOrNull (core.es5.js:2649)
at ReflectiveInjector_._getByKeyDefault (core.es5.js:2688)
at ReflectiveInjector_._getByKey (core.es5.js:2620)
at ReflectiveInjector_.get (core.es5.js:2489)
at resolveNgModuleDep (core.es5.js:9492)
at NgModuleRef_.get (core.es5.js:10562)
at resolveDep (core.es5.js:11050)
at createClass (core.es5.js:10920)
</code>```

Added these lines in app.module.ts

```<code>import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  imports: [
    NgbModule
  ]
})
</code>```

Installed ng-bootstrap using command

```<code>npm install --save @ng-bootstrap/ng-bootstrap
</code>```

答:
You should import NgbModule.forRoot() not NgbModule.

The exact method will be slightly different for the root (top-level)
  module for which you should end up with the code similar to (notice
  NgbModule.forRoot()):

```<code>import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [AppComponent, ...],
  imports: [NgbModule.forRoot(), ...],
  bootstrap: [AppComponent]
})
export class AppModule {
}
</code>```

Other modules in your application can simply import NgbModule:

```<code>import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [OtherComponent, ...],
  imports: [NgbModule, ...]
})
export class OtherModule {
}
</code>```

For more details , please read :

https://ng-bootstrap.github.io/#/getting-started

Here is the working example of tooltip :

http://plnkr.co/edit/AVylfgSqv5iLVi73LGz7?p=preview

Please compare your code with it.

Title: ng-bootstrap not displaying tooltip

Body:
I want to display a tooltip. I went to ng-bootstrap and integrated that code. Getting console error.

core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: No provider for
NgbTooltipConfig!
Error: No provider for NgbTooltipConfig!
at injectionError (core.es5.js:1169)
at noProviderError (core.es5.js:1207)
at ReflectiveInjector_._throwOrNull (core.es5.js:2649)
at ReflectiveInjector_._getByKeyDefault (core.es5.js:2688)
at ReflectiveInjector_._getByKey (core.es5.js:2620)
at ReflectiveInjector_.get (core.es5.js:2489)
at resolveNgModuleDep (core.es5.js:9492)
at NgModuleRef_.get (core.es5.js:10562)
at resolveDep (core.es5.js:11050)
at createClass (core.es5.js:10920)

Added these lines in app.module.ts

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  imports: [
    NgbModule
  ]
})

Installed ng-bootstrap using command

npm install --save @ng-bootstrap/ng-bootstrap

Body:
You should import NgbModule.forRoot() not NgbModule.

The exact method will be slightly different for the root (top-level)
  module for which you should end up with the code similar to (notice
  NgbModule.forRoot()):

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [AppComponent, ...],
  imports: [NgbModule.forRoot(), ...],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Other modules in your application can simply import NgbModule:

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [OtherComponent, ...],
  imports: [NgbModule, ...]
})
export class OtherModule {
}

For more details , please read :

https://ng-bootstrap.github.io/#/getting-started

Here is the working example of tooltip :

http://plnkr.co/edit/AVylfgSqv5iLVi73LGz7?p=preview

Please compare your code with it.


问:
Redeclaration of static constexpr data members?
N4687:

[Annex D (normative) Compatibility features]

D.1 Redeclaration of static constexpr data members

1 For compatibility with prior C++ International Standards, a constexpr static data member may be redundantly
redeclared outside the class with no initializer. This usage is deprecated. [ Example:

```<code>struct A {
static constexpr int n = 5; // definition (declaration in C++ 2014)
};

constexpr int A::n; // redundant declaration (definition in C++ 2014)
</code>```

— end example ]

I don't have a good command of English, so I am confronted with several questions when learning standard(I'm just coming from odr-use)

This usage is deprecated which usage does here mean?

definition (declaration in C++ 2014)

redundant declaration (definition in C++ 2014)

the two comments confuse me.
Here is two possibility:

i.

Until C++ 2014(c++14/1y), static constexpr int n = 5; is a definition. constexpr int A::n; is a redundant declaration.

Since C++17(or after c++14), static constexpr int n = 5; is a declaration. constexpr int A::n; is a definition

ii.

Since C++17(or after c++14), static constexpr int n = 5; is a definition. constexpr int A::n; is a redundant declaration.

Before c++17(which include c++ 2014), static constexpr int n = 5 is a declaration. constexpr int A::n; is a definition.

i and ii, which is true?

答:
Redeclaring the constexpr static data member outside the class is deprecated. That is, in C++17 you should only have the definition inside the class and nothing outside.

Second option: C++17 makes the in-class thingy a definition, and the outer thingy a redundant declaration.

The parentheses recall that in C++14, they were respectively a declaration and a definition.

Body:
N4687:

[Annex D (normative) Compatibility features]

D.1 Redeclaration of static constexpr data members

1 For compatibility with prior C++ International Standards, a constexpr static data member may be redundantly
redeclared outside the class with no initializer. This usage is deprecated. [ Example:

struct A {
static constexpr int n = 5; // definition (declaration in C++ 2014)
};

constexpr int A::n; // redundant declaration (definition in C++ 2014)

— end example ]

I don't have a good command of English, so I am confronted with several questions when learning standard(I'm just coming from odr-use)

This usage is deprecated which usage does here mean?

definition (declaration in C++ 2014)

redundant declaration (definition in C++ 2014)

the two comments confuse me.
Here is two possibility:

i.

Until C++ 2014(c++14/1y), static constexpr int n = 5; is a definition. constexpr int A::n; is a redundant declaration.

Since C++17(or after c++14), static constexpr int n = 5; is a declaration. constexpr int A::n; is a definition

ii.

Since C++17(or after c++14), static constexpr int n = 5; is a definition. constexpr int A::n; is a redundant declaration.

Before c++17(which include c++ 2014), static constexpr int n = 5 is a declaration. constexpr int A::n; is a definition.

i and ii, which is true?


问:
Adding button outside the binded Listbox in xaml
I have encountered a problem - i have created a project where i bind my code to xaml by using a bind to the listbox. However, it has created some problems in my future code - i want to add button to my form, but i encounter some errors.

'Items collection must be empty before using ItemsSource.'

This Error occurs when i try to bind something outside of my bindable Listbox.

The property "VisualTree" can only be set once.

This Error occurs when i try to add button underneath the Listbox.

Can someone guide me on how can i fix this?

My code:

```<code><ListBox x:Name="ItemsControl1">
    <ListBox.ItemsPanel>

        <ItemsPanelTemplate>

            <UniformGrid Columns="5">
            </UniformGrid>

        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Black" BorderThickness="2" Width="Auto" Height="Auto">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Number}"/>
                    <Image Source="{Binding Source}" Margin="0,0,5,0"/>
                </StackPanel>
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

The desirable result would be a button under the listbox.

答:
You should add your button below ListBox declaration.
Exceptions you are facing are thrown because visual tree is populated via binding and you cannot alter it manually anymore.
You will need to put all this stuff inside of some layout container (Grid, StackPanel, etc.), since you cannot set Window's/UserControl's Content property twice:

```<code><StackPanel>
    <ListBox x:Name="ItemsControl1">
        <ListBox.ItemsPanel>

            <ItemsPanelTemplate>

                <UniformGrid Columns="5">
                </UniformGrid>

            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Black" BorderThickness="2" Width="Auto" Height="Auto">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Number}"/>
                        <Image Source="{Binding Source}" Margin="0,0,5,0"/>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Button/>
</StackPanel>
</code>```

Body:
I have encountered a problem - i have created a project where i bind my code to xaml by using a bind to the listbox. However, it has created some problems in my future code - i want to add button to my form, but i encounter some errors.

'Items collection must be empty before using ItemsSource.'

This Error occurs when i try to bind something outside of my bindable Listbox.

The property "VisualTree" can only be set once.

This Error occurs when i try to add button underneath the Listbox.

Can someone guide me on how can i fix this?

My code:

<ListBox x:Name="ItemsControl1">
    <ListBox.ItemsPanel>

        <ItemsPanelTemplate>

            <UniformGrid Columns="5">
            </UniformGrid>

        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Black" BorderThickness="2" Width="Auto" Height="Auto">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Number}"/>
                    <Image Source="{Binding Source}" Margin="0,0,5,0"/>
                </StackPanel>
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The desirable result would be a button under the listbox.

Body:
You should add your button below ListBox declaration.
Exceptions you are facing are thrown because visual tree is populated via binding and you cannot alter it manually anymore.
You will need to put all this stuff inside of some layout container (Grid, StackPanel, etc.), since you cannot set Window's/UserControl's Content property twice:

<StackPanel>
    <ListBox x:Name="ItemsControl1">
        <ListBox.ItemsPanel>

            <ItemsPanelTemplate>

                <UniformGrid Columns="5">
                </UniformGrid>

            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Black" BorderThickness="2" Width="Auto" Height="Auto">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Number}"/>
                        <Image Source="{Binding Source}" Margin="0,0,5,0"/>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Button/>
</StackPanel>


问:
Weibull MLE in R
The loglikelihood function looks like this. I wrote to this a function in R, this return of negative one times the loglikelihood. I generated a vector with rWeibull with parameters shape=1.5, scale=0.5. But when i call the nlm function with my loglikelihood function, the estimated values for the parameters are: 2.124180 and 4.003675. What wrong with my R code?
The code:</p>

```<code>vec<-rWeibull(n=1000, params=list(shape=1.5, scale=0.5))
weibull_loglik<-function(parm){
n<-length(vec)
gamma<-parm[1]
lambda<-parm[2]
loglik<-n*log(gamma/lambda)+(gamma-1)*sum(vec-log((lambda^(gamma-1))))-sum((vec/lambda)^gamma)
return(-loglik)}
weibull<-nlm(weibull_loglik,parm<-c(1,1), hessian=TRUE)
weibull$estimate
</code>```

答:
Your log-likelihood is not correct. I get correct estimates when I use dweibull(..., log=TRUE):

```<code>vec <- rweibull(n=1000, shape=1.5, scale=0.5)
weibull_loglik <- function(parm){
  n <- length(vec)
  gamma <- parm[1]
  lambda <- parm[2]
  loglik <- sum(dweibull(vec, shape=gamma, scale=lambda, log=TRUE))
  return(-loglik)
}
weibull <- nlm(weibull_loglik, p = c(1,1), hessian=TRUE)

> weibull$estimate
[1] 1.5547181 0.5116119
</code>```

Title: Weibull MLE in R

Body:
The loglikelihood function looks like this. I wrote to this a function in R, this return of negative one times the loglikelihood. I generated a vector with rWeibull with parameters shape=1.5, scale=0.5. But when i call the nlm function with my loglikelihood function, the estimated values for the parameters are: 2.124180 and 4.003675. What wrong with my R code?
The code:

vec<-rWeibull(n=1000, params=list(shape=1.5, scale=0.5))
weibull_loglik<-function(parm){
n<-length(vec)
gamma<-parm[1]
lambda<-parm[2]
loglik<-n*log(gamma/lambda)+(gamma-1)*sum(vec-log((lambda^(gamma-1))))-sum((vec/lambda)^gamma)
return(-loglik)}
weibull<-nlm(weibull_loglik,parm<-c(1,1), hessian=TRUE)
weibull$estimate

Body:
Your log-likelihood is not correct. I get correct estimates when I use dweibull(..., log=TRUE):

vec <- rweibull(n=1000, shape=1.5, scale=0.5)
weibull_loglik <- function(parm){
  n <- length(vec)
  gamma <- parm[1]
  lambda <- parm[2]
  loglik <- sum(dweibull(vec, shape=gamma, scale=lambda, log=TRUE))
  return(-loglik)
}
weibull <- nlm(weibull_loglik, p = c(1,1), hessian=TRUE)

> weibull$estimate
[1] 1.5547181 0.5116119


问:
while (i<=sqrt(static_cast<double>(n))
In the "C++ Without Fear: A Beginner's Guide That Makes You Feel Smart" book, in Chapter (2): Decisions, Decisions, you can see this lin of code as part of the prime number program:

```<code>while (i<=sqrt(static_cast<double>(n))
</code>```

Provided that "i" was initialized to "2", and "n" is the user's input.

Why are we comparing to the "sqrt" of "n" and not to "n" itself?

Thanks.

答:
Because you won't get any factors for non-primes which are > sqrt(n) (you would have already found the other, smaller factor).

It's a really bad test though, it would be much better to write it as:

```<code>while (i*i <= n)
</code>```

Title: while (i<=sqrt(static_cast<double>(n))

Body:
In the "C++ Without Fear: A Beginner's Guide That Makes You Feel Smart" book, in Chapter (2): Decisions, Decisions, you can see this lin of code as part of the prime number program:

while (i<=sqrt(static_cast<double>(n))

Provided that "i" was initialized to "2", and "n" is the user's input.

Why are we comparing to the "sqrt" of "n" and not to "n" itself?

Thanks.

Body:
Because you won't get any factors for non-primes which are > sqrt(n) (you would have already found the other, smaller factor).

It's a really bad test though, it would be much better to write it as:

while (i*i <= n)


问:
How to fetch children of node via webroot path in Gentics Mesh?
I have a webroot path of a parent node and would like to return the children of this node.
Using https://demo.getmesh.io/api/v1/demo/webroot/images/ for example just yields the node itself.</p>

答:
Unfortunately it's not possible to do so with just the webroot. However, there're other ways to accomplish it:

Use the GraphQL-Enpoint by using this query for example:

```<code>query childrenByWebroot($path: String) {
 node(path: $path) {
   uuid
   children {
     elements {
       uuid
     }
   }
  }
}
</code>```

This will just load all UUIDs of the children and the parent. For more functionality, check the Docs of GraphQL for more information.

Load the Node from the webroot first and and then load the children via the Children-Endpoint: /api/v1/<project>/nodes/<uuid>/children

Search for Nodes which have the webroot-element as parent. This allows you to filter the content more clearly if it is required:

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "parentNode.uuid": "<uuid>"
          },
          // ... Other checks
        }
      ]
    }
  }
}
</code>```

Body:
Unfortunately it's not possible to do so with just the webroot. However, there're other ways to accomplish it:

Use the GraphQL-Enpoint by using this query for example:

query childrenByWebroot($path: String) {
 node(path: $path) {
   uuid
   children {
     elements {
       uuid
     }
   }
  }
}

This will just load all UUIDs of the children and the parent. For more functionality, check the Docs of GraphQL for more information.

Load the Node from the webroot first and and then load the children via the Children-Endpoint: /api/v1/<project>/nodes/<uuid>/children

Search for Nodes which have the webroot-element as parent. This allows you to filter the content more clearly if it is required:

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "parentNode.uuid": "<uuid>"
          },
          // ... Other checks
        }
      ]
    }
  }
}


问:
React Native App crashes if signed and released. Works fine in debug mode
React Native App crashes if signed and released. Works fine in debug mode. It doesn't throw any error in the screen. It simply crashes. When I looked at cat log. no error.

I also tried build apk with --info, but no additional info while crashing. I also tried building APK by setting minifyEnabled false.

When run the app in debug mode by connecting my phone via USB, it works.
I'm tried creating apk with --debug but I'm unable to install it my phone, it says parsing error when I try to install using app installer.

I got the following logcat errors.  What does it mean?

```<code>09-03 11:03:07.968 W/ActivityManager(1344):   Force finishing activity com.myapp/.MainActivity

09-03 11:03:08.012 W/BroadcastQueue(1344): Skipping deliver [background] BroadcastRecord{cb72147 u-1 android.net.conn.CONNECTIVITY_CHANGE} to ReceiverList{7bf2161 22421 com.myapp/10100/u0 remote:b9cdcc8}: process crashing

09-03 11:03:08.035 W/ActivityManager(1344):  Dismiss app error dialog : com.myapp

09-03 11:03:13.095 I/WindowState(1344): WIN DEATH: Window{3f22c22 u0 /com.myapp.MainActivity}
</code>```

答: I fixed this error by uninstalling uglifyjs and reinstalled the latest (using NPM).

Body:
React Native App crashes if signed and released. Works fine in debug mode. It doesn't throw any error in the screen. It simply crashes. When I looked at cat log. no error.

I also tried build apk with --info, but no additional info while crashing. I also tried building APK by setting minifyEnabled false.

When run the app in debug mode by connecting my phone via USB, it works.
I'm tried creating apk with --debug but I'm unable to install it my phone, it says parsing error when I try to install using app installer.

I got the following logcat errors.  What does it mean?

09-03 11:03:07.968 W/ActivityManager(1344):   Force finishing activity com.myapp/.MainActivity

09-03 11:03:08.012 W/BroadcastQueue(1344): Skipping deliver [background] BroadcastRecord{cb72147 u-1 android.net.conn.CONNECTIVITY_CHANGE} to ReceiverList{7bf2161 22421 com.myapp/10100/u0 remote:b9cdcc8}: process crashing

09-03 11:03:08.035 W/ActivityManager(1344):  Dismiss app error dialog : com.myapp

09-03 11:03:13.095 I/WindowState(1344): WIN DEATH: Window{3f22c22 u0 /com.myapp.MainActivity}


问:
SQL SERVER The number of elements in the select list exceeds the maximum allowed number of 4096 elements
SQL SERVER 2008

i have a data and i am trying to do pivot.
while running the below code encountered with error as

```<code>The number of elements in the select list exceeds the maximum allowed number of 4096 elements.
</code>```

Code:

```<code>DECLARE @Cols NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);
DECLARE @Sel NVARCHAR(MAX);
DECLARE @GENERIC NVARCHAR(MAX)

SET @Cols = STUFF((SELECT distinct ',' + QUOTENAME([Description])
            FROM STAGING_TEMP
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');
SET @Sel = STUFF((SELECT distinct ',' + QUOTENAME([Description]) +
' AS DESC'+CAST(row_number () over (order by ([Description])) as varchar(250))
            FROM STAGING_TEMP
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');

SET @SQL = N'
SELECT DISTINCT [Generic Name], '+ @Sel+N'
FROM STAGING_TEMP
    pivot
    (
      MAX(Description) For Description IN ('+ @Cols + N')

    ) P';

EXECUTE( @SQL);
</code>```

When i run the individual segment of code i came to know the below code produce 40000 desc value which has 35k Duplicate value AS Different DESC.

```<code>SET @Sel = STUFF((SELECT distinct ',' + QUOTENAME([Description]) +
' AS DESC'+CAST(row_number () over (order by ([Description])) as varchar(250))
            FROM STAGING_TEMP
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');
</code>```

is there any way to handle such scenario. Please suggest

答:
No, there isn't.  The maximum number of columns in a SELECT statement is 4,096 (see here).

You would have a column for each value in the IN list.  Even if you fixed one problem, you would just face another.

Body:
SQL SERVER 2008

i have a data and i am trying to do pivot.
while running the below code encountered with error as

The number of elements in the select list exceeds the maximum allowed number of 4096 elements.

Code:

DECLARE @Cols NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);
DECLARE @Sel NVARCHAR(MAX);
DECLARE @GENERIC NVARCHAR(MAX)

SET @Cols = STUFF((SELECT distinct ',' + QUOTENAME([Description])
            FROM STAGING_TEMP
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');
SET @Sel = STUFF((SELECT distinct ',' + QUOTENAME([Description]) +
' AS DESC'+CAST(row_number () over (order by ([Description])) as varchar(250))
            FROM STAGING_TEMP
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');

SET @SQL = N'
SELECT DISTINCT [Generic Name], '+ @Sel+N'
FROM STAGING_TEMP
    pivot
    (
      MAX(Description) For Description IN ('+ @Cols + N')

    ) P';

EXECUTE( @SQL);

When i run the individual segment of code i came to know the below code produce 40000 desc value which has 35k Duplicate value AS Different DESC.

SET @Sel = STUFF((SELECT distinct ',' + QUOTENAME([Description]) +
' AS DESC'+CAST(row_number () over (order by ([Description])) as varchar(250))
            FROM STAGING_TEMP
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'');

is there any way to handle such scenario. Please suggest


问:
How to include the output from database query in div using GET
i have index.html with the following code

```<code><html>
<head><title>Testing</title></head>
<body>
<script>
  var javascriptVariable = "abc";
  window.location.href = "test_selected.php?name=" + javascriptVariable;
</script>
</body>
</html>
</code>```

and test_selected file containing the code

```<code><?php

$host = 'localhost';
$port = '5432';
$database = 'postgis';
$user = 'postgres';
$password = 'postgres';
$reg_name=$_GET['name'];

$connectString = 'host=' . $host . ' port=' . $port . ' dbname=' . $database .
    ' user=' . $user . ' password=' . $password;

$link = pg_connect ($connectString);
if (!$link)
{
    die('Error: Could not connect: ' . pg_last_error());
}
$query="select * from table where name='{$reg_name}'";
$result = pg_query($query);

$i = 0;
echo '<html><body><table border="1"><tr>';
while ($i < pg_num_fields($result))
{
    $fieldName = pg_field_name($result, $i);
    echo '<td>' . $fieldName . '</td>';
    $i = $i + 1;
}
echo '</tr>';
$i = 0;

while ($row = pg_fetch_row($result))
{
    echo '<tr>';
    $count = count($row);
    $y = 0;
    while ($y < $count)
    {
        $c_row = current($row);
        echo '<td>' . $c_row . '</td>';
        next($row);
        $y = $y + 1;
    }
    echo '</tr>';
    $i = $i + 1;
}
pg_free_result($result);

echo '</table></body></html>';
?>
</code>```

The output is displayed in a new page because i have used windows.location. Is it possible to display the output in the same page in a div instead of another new page.

答:
include jquery in page. and replace

```<code>window.location.href = "test_selected.php?name=" + javascriptVariable;
</code>```

with

```<code> $.ajax({
    type:'GET'
  url: "test_selected.php?name=" + javascriptVariable,
  success: function(result){
        $("#div_id").html(result);
},error:(error){
    console.log(error);
});
</code>```

replace div_id with the id of div you want to load into.

Body:
i have index.html with the following code

<title>Testing</title>

and test_selected file containing the code

<?php

$host = 'localhost';
$port = '5432';
$database = 'postgis';
$user = 'postgres';
$password = 'postgres';
$reg_name=$_GET['name'];

$connectString = 'host=' . $host . ' port=' . $port . ' dbname=' . $database .
    ' user=' . $user . ' password=' . $password;

$link = pg_connect ($connectString);
if (!$link)
{
    die('Error: Could not connect: ' . pg_last_error());
}
$query="select * from table where name='{$reg_name}'";
$result = pg_query($query);

$i = 0;
echo '

';
while ($i < pg_num_fields($result))
{
    $fieldName = pg_field_name($result, $i);
    echo '' . $fieldName . '	';
    $i = $i + 1;
}
echo '
';
$i = 0;

while ($row = pg_fetch_row($result))
{
    echo '
';
    $count = count($row);
    $y = 0;
    while ($y < $count)
    {
        $c_row = current($row);
        echo '' . $c_row . '	';
        next($row);
        $y = $y + 1;
    }
    echo '
';
    $i = $i + 1;
}
pg_free_result($result);

echo '
';
?>

The output is displayed in a new page because i have used windows.location. Is it possible to display the output in the same page in a div instead of another new page.

Body:
include jquery in page. and replace

window.location.href = "test_selected.php?name=" + javascriptVariable;

with

 $.ajax({
    type:'GET'
  url: "test_selected.php?name=" + javascriptVariable,
  success: function(result){
        $("#div_id").html(result);
},error:(error){
    console.log(error);
});

replace div_id with the id of div you want to load into.


答:
Neither is really correct. I found a good explanation of definition and declaration in this answer:

Declaration "Somewhere, there exists a foo".

Definition: "...and here it is!"

For regular class members, they can be declared in the header file and defined in the implementation (cpp) file.

What C++17 changes is that when you provide a compile-time constant as the value for that class member, it is a definition and you are defining it in the class definition. You can neither redefine it outside of the class, nor redeclare it.

This usage is deprecated which usage does here mean?

Usage refers to the redeclaration.

Title: Redeclaration of static constexpr data members?


问:
Using SSL sockets and non-SSL sockets simultaneously in Boost.Asio?
I'm in the process of converting a library to Boost.Asio (which has worked very well so far), but I've hit something of a stumbling block with regards to a design decision.

Boost.Asio provides support for SSL, but a boost::asio::ssl::stream<boost::asio::ip::tcp::socket> type must be used for the socket. My library has the option of connecting to SSL servers or connecting normally, so I've made a class with two sockets like this:

```<code>class client : public boost::enable_shared_from_this<client>
{
public:
    client(boost::asio::io_service & io_service, boost::asio::ssl::context & context) : socket_(io_service), secureSocket_(io_service, context) {}
private:
    boost::asio::ip::tcp::socket socket_;
    boost::asio::ssl::stream<boost::asio::ip::tcp::socket> secureSocket_;
};
</code>```

And within there are a bunch of handlers that reference socket_. (For example, I have socket_.is_open() in several places, which would need to become secureSocket_.lowest_layer().is_open() for the other socket.)

Can anyone suggest the best way to go about this? I'd rather not create a separate class just for this purpose, because that would mean duplicating a lot of code.

Edit: I rephrased my original question because I misunderstood the purpose of an OpenSSL function.

答:
There's a couple of ways you can do this. In the past, I've done something like

```<code>if ( sslEnabled )
    boost::asio::async_write( secureSocket_ );
} else {
    boost::asio::async_write( secureSocket_.lowest_layer() );
}
</code>```

Which can get messy pretty quickly with a lot of if/else statements. You could also create an abstract class (pseudo code - oversimplified)

```<code>class Socket
{
    public:
       virtual void connect( ... );
       virtual void accept( ... );
       virtual void async_write( ... );
       virtual void async_read( ... );
    private:
        boost::asio::ip::tcp::socket socket_;
};
</code>```

Then create a derived class SecureSocket to operate on a secureSocket_ instead of socket_. I don't think it would be duplicating a lot of code, and it's probably cleaner than if/else whenever you need to async_read or async_write.

Body:
I'm in the process of converting a library to Boost.Asio (which has worked very well so far), but I've hit something of a stumbling block with regards to a design decision.

Boost.Asio provides support for SSL, but a boost::asio::ssl::stream<boost::asio::ip::tcp::socket> type must be used for the socket. My library has the option of connecting to SSL servers or connecting normally, so I've made a class with two sockets like this:

class client : public boost::enable_shared_from_this<client>
{
public:
    client(boost::asio::io_service & io_service, boost::asio::ssl::context & context) : socket_(io_service), secureSocket_(io_service, context) {}
private:
    boost::asio::ip::tcp::socket socket_;
    boost::asio::ssl::stream<boost::asio::ip::tcp::socket> secureSocket_;
};

And within there are a bunch of handlers that reference socket_. (For example, I have socket_.is_open() in several places, which would need to become secureSocket_.lowest_layer().is_open() for the other socket.)

Can anyone suggest the best way to go about this? I'd rather not create a separate class just for this purpose, because that would mean duplicating a lot of code.

Edit: I rephrased my original question because I misunderstood the purpose of an OpenSSL function.

Body:
There's a couple of ways you can do this. In the past, I've done something like

if ( sslEnabled )
    boost::asio::async_write( secureSocket_ );
} else {
    boost::asio::async_write( secureSocket_.lowest_layer() );
}

Which can get messy pretty quickly with a lot of if/else statements. You could also create an abstract class (pseudo code - oversimplified)

class Socket
{
    public:
       virtual void connect( ... );
       virtual void accept( ... );
       virtual void async_write( ... );
       virtual void async_read( ... );
    private:
        boost::asio::ip::tcp::socket socket_;
};

Then create a derived class SecureSocket to operate on a secureSocket_ instead of socket_. I don't think it would be duplicating a lot of code, and it's probably cleaner than if/else whenever you need to async_read or async_write.


问:
How is sorting done in cassandra?
I am a newbie in Cassandra.
Does Cassandra follow any specified sorting algorithm like bubble sort, binary sort, etc.? If not, How does it sort in order by command?

答:
It doesn't, or at least it shouldn't. In Cassandra you build your data model around your use cases. So if you want to retrieve sorted data you have to store it sorted. If you want the same data sorted in different ways, you store the same data multiple times sorted differently. There is a lot more to read about how Cassandra works, and I think every user of Cassandra should.

Links related to your question:

https://docs.datastax.com/en/cql/3.3/cql/cql_using/useSimplePrimaryKeyConcept.html

https://docs.datastax.com/en/cql/3.3/cql/cql_using/useCompoundPrimaryKeyConcept.html

https://docs.datastax.com/en/cql/3.3/cql/cql_reference/cqlCreateIndex.html

Getting started with Cassandra:

https://academy.datastax.com/courses (the first two courses is a must do. You need to register but they 100% free)

Title: How is sorting done in cassandra?


问:
Java: Instantiate a generic type by returning a Supplier vs returning a new instance
I was reading how to instantiate a generic and after reading and applying this answer; I would like to know what would be the differences between expecting a Supplier<T> vs. expecting a new instance of T.

Example:

```<code>abstract class AbstractService<T extends AbstractEntity> {
    protected Supplier<T> makeNewThing();  // supplier is expected

    public T myMethod(){
        T object = makeNewThing().get(); // local object by calling supplier
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Supplier<Car> makeNewThing(){
        return Car::new;
    }
}
</code>```

vs.

```<code>abstract class AbstractService<T extends SomeAbstractEntity> {
    protected T makeNewThing();  // object is expected, newness is assumed

    public T myMethod(){
        T object = makeNewThing(); // local object by calling constructor
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Car makeNewThing(){
        return new Car();
    }
}
</code>```

The only thing I can think of is that expecting a supplier ensures that a new object will be created, but when expecting an object we can only assume that the implementing classes are calling the constructor and not re-using an existing instance.

I'd like to know of other objective differences and possible use cases, if any. Thanks in advance.

答:
The first solution is more flexible, because an extra level of indirection in object creation lets users of your class library change the source of new items independently of ServiceImpl<SomeEntityImplementation> class.

You can make a new Supplier<T> instance without subclassing or recompiling ServiceImpl, because there is an extra level of indirection. ServiceImpl could be implemented as follows:

```<code>class ServiceImpl<SomeEntityImplementation> {
    private final Supplier<SomeEntityImplementation> supplier;
    public Supplier<T> makeNewThing(){
        return supplier;
    }
    public ServiceImpl(Supplier<SomeEntityImplementation> s) {
        supplier = s;
    }
}
</code>```

This makes it possible for users of ServiceImpl to provide their own Supplier<T>, which is not possible using the second approach, in which the source of new items is merged into the implementation of service itself.

Body:
I was reading how to instantiate a generic and after reading and applying this answer; I would like to know what would be the differences between expecting a Supplier<T> vs. expecting a new instance of T.

Example:

abstract class AbstractService<T extends AbstractEntity> {
    protected Supplier<T> makeNewThing();  // supplier is expected

    public T myMethod(){
        T object = makeNewThing().get(); // local object by calling supplier
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Supplier<Car> makeNewThing(){
        return Car::new;
    }
}

vs.

abstract class AbstractService<T extends SomeAbstractEntity> {
    protected T makeNewThing();  // object is expected, newness is assumed

    public T myMethod(){
        T object = makeNewThing(); // local object by calling constructor
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Car makeNewThing(){
        return new Car();
    }
}

The only thing I can think of is that expecting a supplier ensures that a new object will be created, but when expecting an object we can only assume that the implementing classes are calling the constructor and not re-using an existing instance.

I'd like to know of other objective differences and possible use cases, if any. Thanks in advance.

Body:
The first solution is more flexible, because an extra level of indirection in object creation lets users of your class library change the source of new items independently of ServiceImpl<SomeEntityImplementation> class.

You can make a new Supplier<T> instance without subclassing or recompiling ServiceImpl, because there is an extra level of indirection. ServiceImpl could be implemented as follows:

class ServiceImpl<SomeEntityImplementation> {
    private final Supplier<SomeEntityImplementation> supplier;
    public Supplier<T> makeNewThing(){
        return supplier;
    }
    public ServiceImpl(Supplier<SomeEntityImplementation> s) {
        supplier = s;
    }
}

This makes it possible for users of ServiceImpl to provide their own Supplier<T>, which is not possible using the second approach, in which the source of new items is merged into the implementation of service itself.


问:
Why I get error when I try to generate ActionLink?
I have this HtmlHelper:

```<code>@foreach (var item in Model)
{
<tr>
    <td>
        @Html.ActionLink(modelItem => item.LayoutID, "someAction");
    </td>
</tr>
}
</code>```

On this row,

```<code>@Html.ActionLink(modelItem => item.LayoutID, "someAction");
</code>```

i get this error:

```<code>CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type
</code>```

Why do I get the above error ?
The LayoutID is of string type.

EDIT
Improved Formatting

答:
The first parameter of ActionLink method has to be a string which will appear as the anchor tag text. You are trying to pass a lamda expression.

```<code>@foreach(var item in Model)
{
   <tr>
      <td> @Html.ActionLink(item.LayoutID, "someAction") </td>
   </tr>
}
</code>```

Body:
I have this HtmlHelper:

@foreach (var item in Model)
{

        @Html.ActionLink(modelItem => item.LayoutID, "someAction");

}

On this row,

@Html.ActionLink(modelItem => item.LayoutID, "someAction");

i get this error:

CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type

Why do I get the above error ?
The LayoutID is of string type.

EDIT
Improved Formatting

Body:
The first parameter of ActionLink method has to be a string which will appear as the anchor tag text. You are trying to pass a lamda expression.

@foreach(var item in Model)
{
   <tr>
      <td> @Html.ActionLink(item.LayoutID, "someAction") </td>
   </tr>
}


问:
view a PDF without downloading it
Now my controller returns the file in this way:

```<code>[HttpGet]
public IActionResult document(int id)
{
      var byteArray = db.instances.Where(c => c.id == id).FirstOrDefault().document;
      if (byteArray == null)
      {
            return null;
      }
      Stream stream = new MemoryStream(byteArray);

      return File(stream, "application/pdf", "document.pdf");
}
</code>```

Client:

```<code><a href="@Url.Action("document", "Catalog", new { id = Model.id })" target="_blank">Open pdf</a>
</code>```

I would like to view the PDF without downloading it, how can I do it?

答:
You should append a header to your response saying it should display it instead of downloading

This way:

```<code>[HttpGet]
public IActionResult document(int id)
{
      var byteArray = db.instances.Where(c => c.id == id).FirstOrDefault().document;
      if (byteArray == null)
      {
            return null;
      }
      Stream stream = new MemoryStream(byteArray);

      Response.AppendHeader("content-disposition", "inline; filename=file.pdf");
      return File(stream, "application/pdf", "document.pdf");
}
</code>```

Title: view a PDF without downloading it

Body:
Now my controller returns the file in this way:

[HttpGet]
public IActionResult document(int id)
{
      var byteArray = db.instances.Where(c => c.id == id).FirstOrDefault().document;
      if (byteArray == null)
      {
            return null;
      }
      Stream stream = new MemoryStream(byteArray);

      return File(stream, "application/pdf", "document.pdf");
}

Client:

Open pdf

I would like to view the PDF without downloading it, how can I do it?

Body:
You should append a header to your response saying it should display it instead of downloading

This way:

[HttpGet]
public IActionResult document(int id)
{
      var byteArray = db.instances.Where(c => c.id == id).FirstOrDefault().document;
      if (byteArray == null)
      {
            return null;
      }
      Stream stream = new MemoryStream(byteArray);

      Response.AppendHeader("content-disposition", "inline; filename=file.pdf");
      return File(stream, "application/pdf", "document.pdf");
}


问:
Enable button if the mentioned input boxed are filled using jquery?
HTML:

```<code><input type="text" id="message"/>
<input type="text" id="message1"/>
<input type="button" class="sendButton" value="submit"/>
</code>```

This code displays two input boxes and one submit button.

jQuery:

```<code>$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $("#message,#message1").bind(" change",function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);
        }
    });
});
</code>```

This is my jQuery to enable and disable buttons. But it enables the button, if one of the field is filled.I want to enable it only when both the input fields are filled.

答:
$(document).ready(function(){
$('#message'&&'#message1').keyup(function(){
$('.sendButton').attr('disabled', false)
})
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message"/>
<input type="text" id="message1"/>
<input type="button" class="sendButton" value="submit" disabled/></code>```

Body:
HTML:

<input type="text" id="message"/>
<input type="text" id="message1"/>
<input type="button" class="sendButton" value="submit"/>

This code displays two input boxes and one submit button.

jQuery:

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $("#message,#message1").bind(" change",function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);
        }
    });
});

This is my jQuery to enable and disable buttons. But it enables the button, if one of the field is filled.I want to enable it only when both the input fields are filled.

Body:
$(document).ready(function(){
$('#message'&&'#message1').keyup(function(){
$('.sendButton').attr('disabled', false)
})
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message"/>
<input type="text" id="message1"/>
<input type="button" class="sendButton" value="submit" disabled/>