问:
How to set default value to a Rcpp::Function in argument of function in Rcpp?

I want to set default value in argument of function to Rcpp::Function argument.

Just simple assignment, Rcpp::Function func = mean, is not possible. It returns error: no viable conversion from '<overloaded function type>' to 'Rcpp::Function' (aka 'Function_Impl<PreserveStorage>')

Or, I tried something like this: Rcpp::Function func = Function("mean"), but again, it is not working. It returns warning message: Unable to parse C++ default value 'Function("mean")' for argument func of function.

For example, I have my own function to maximum called maxC:

```<code>// [[Rcpp::export]]
double maxC(NumericVector x) {
  double max;
  max = *std::max_element(x.begin(), x.end());

  return max;
}
</code>```

Now, I want to use it (maxC) as default argument to another function, for example like this:

```<code>// [[Rcpp::export]]
double aggregate(NumericVector x, Rcpp::Function func = maxC) {
  double agg;
  agg = Rcpp::as<double>(func(x));

  return agg;
}
</code>```

But it doesn't work. Any suggestions? Thank you.

答:
I do not believe you can set a default function in this way... The best that can be achieved is setting function to a NULL value and then having the code execute the appropriate default later on. For example...

```<code>#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector func_defaults(Rcpp::NumericVector x,
                                  Rcpp::Nullable<Rcpp::Function> f = R_NilValue) {

  if (f.isNotNull()) {
    Rcpp::NumericVector res = Rcpp::as<Rcpp::Function>(f)(x);
    return res;
  }

  Rcpp::Environment global_funcs = Rcpp::Environment::global_env();
  Rcpp::Function mean_r = global_funcs["mean"];
  return mean_r(x);
}
</code>```

testing:

```<code>func_defaults(c(2.5,3,1))
# [1] 2.166667
func_defaults(c(2.5,3,1), mean)
# [1] 2.166667
func_defaults(c(2.5,3,1), median)
# [1] 2.5
</code>```

Body:
I want to set default value in argument of function to Rcpp::Function argument.

Just simple assignment, Rcpp::Function func = mean, is not possible. It returns error: no viable conversion from '<overloaded function type>' to 'Rcpp::Function' (aka 'Function_Impl<PreserveStorage>')

Or, I tried something like this: Rcpp::Function func = Function("mean"), but again, it is not working. It returns warning message: Unable to parse C++ default value 'Function("mean")' for argument func of function.

For example, I have my own function to maximum called maxC:

// [[Rcpp::export]]
double maxC(NumericVector x) {
  double max;
  max = *std::max_element(x.begin(), x.end());

  return max;
}

Now, I want to use it (maxC) as default argument to another function, for example like this:

// [[Rcpp::export]]
double aggregate(NumericVector x, Rcpp::Function func = maxC) {
  double agg;
  agg = Rcpp::as<double>(func(x));

  return agg;
}

But it doesn't work. Any suggestions? Thank you.

Body:
I do not believe you can set a default function in this way... The best that can be achieved is setting function to a NULL value and then having the code execute the appropriate default later on. For example...

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector func_defaults(Rcpp::NumericVector x,
                                  Rcpp::Nullable<Rcpp::Function> f = R_NilValue) {

  if (f.isNotNull()) {
    Rcpp::NumericVector res = Rcpp::as<Rcpp::Function>(f)(x);
    return res;
  }

  Rcpp::Environment global_funcs = Rcpp::Environment::global_env();
  Rcpp::Function mean_r = global_funcs["mean"];
  return mean_r(x);
}

testing:

func_defaults(c(2.5,3,1))
# [1] 2.166667
func_defaults(c(2.5,3,1), mean)
# [1] 2.166667
func_defaults(c(2.5,3,1), median)
# [1] 2.5


来源: stackexchange

问:
Datomic: on a Peer, does Connection.db() read your writes after Connection.transact()
Consider the following operations, occuring in a Datomic Peer:

```<code>(require '[datomic.api :as d])

(let [;; running a transaction and awaiting completion
      tx-res @(d/transact-async conn tx-data)
      ;; reading the current database value
      db1 (d/db conn)]
  ,,,)
</code>```

In the consistency model of Datomic, can I expect the changes made by tx-res to be visible in db1?

(I know about both :db-after (d/sync conn t), but it can be practical to rely on reading your writes on the Connection, e.g for doing successive writes on a connection without having to carry along database values).

答:
Can not be sure about a datomic implementation without seeing code

But from what I understand about the datomic cache

as tx was derefed, "this" jvm get back "live index", so, (>= (d/basis-t (d/db conn)) (d/basis-t db-after)).
> may occur in case of 2 concurrent transactions,

thread 1 transact

thread 2 transact

!transactor do 1, then 2!

thread 2 deref

thread 1 deref

thread 1 asks for db.

ContentLicense: CC BY-SA 3.0

Body:
Consider the following operations, occuring in a Datomic Peer:

(require '[datomic.api :as d])

(let [;; running a transaction and awaiting completion
      tx-res @(d/transact-async conn tx-data)
      ;; reading the current database value
      db1 (d/db conn)]
  ,,,)

In the consistency model of Datomic, can I expect the changes made by tx-res to be visible in db1?

(I know about both :db-after (d/sync conn t), but it can be practical to rely on reading your writes on the Connection, e.g for doing successive writes on a connection without having to carry along database values).


问:
Comparing cells in two CSV files using powershell
Pretty new to this. I need to compare a column with usernames from one CSV file, against a column with usernames in another CSV file and output if duplicates exists or remove them.

How they currently look:

$File1:

```
Firstname,Lastname,Username
Peter,Larsen,Larsen.123
Pia,Jensen,Jensen.123
Poul,Hansen,Hansen.123
```

$File2:

```
Username
Larsen.123
Andersen.123
Jensen.123
```

What I'm looking for:

```
Firstname,Lastname,Username,Duplicate
Peter,Larsen,Larsen.123,True
Pia,Jensen,Jensen.123,True
Poul,Hansen,Hansen.123,False
```

It doesn't necessarily have to be a true/false output, removing all duplicate entries from File1 or similar, would be perfectly fine as well. It's essentially just to compare users in our AD against users in our user database, to see if anyone still have access who shouldn't have.

Edit:

Tried with this so far, found in a similar question in here:

```<code>foreach ($user in $File1) {
    $MatchAccount = (Compare-Object $File2 $user -Property 'Username' -PassThru).Value
    $user = Add-Member -InputObject $user -Type NoteProperty -Name 'Value' -Value $MatchAccount
</code>```

And just importing and exporting the CSV files before and after, in that order.

答:
Read the second file into a hashtable:

```<code>$users = @{}
Import-Csv 'file2.csv' | ForEach-Object {
    $users[$_.Username] = $true
}
</code>```

Then check if each row of the first CSV contains a username from that hashtable and add a field with the result of that check:

```<code>(Import-Csv 'file1.csv') |
    Select-Object *,@{n='Duplicate';e={$users.ContainsKey($_.Username)}} |
    Export-Csv 'file1.csv' -NoType
</code>```

Body:
Pretty new to this. I need to compare a column with usernames from one CSV file, against a column with usernames in another CSV file and output if duplicates exists or remove them.

How they currently look:

$File1:

Firstname,Lastname,Username
Peter,Larsen,Larsen.123
Pia,Jensen,Jensen.123
Poul,Hansen,Hansen.123

$File2:

Username
Larsen.123
Andersen.123
Jensen.123

What I'm looking for:

Firstname,Lastname,Username,Duplicate
Peter,Larsen,Larsen.123,True
Pia,Jensen,Jensen.123,True
Poul,Hansen,Hansen.123,False

It doesn't necessarily have to be a true/false output, removing all duplicate entries from File1 or similar, would be perfectly fine as well. It's essentially just to compare users in our AD against users in our user database, to see if anyone still have access who shouldn't have.

Edit:

Tried with this so far, found in a similar question in here:

foreach ($user in $File1) {
    $MatchAccount = (Compare-Object $File2 $user -Property 'Username' -PassThru).Value
    $user = Add-Member -InputObject $user -Type NoteProperty -Name 'Value' -Value $MatchAccount

And just importing and exporting the CSV files before and after, in that order.

Body:
Read the second file into a hashtable:

$users = @{}
Import-Csv 'file2.csv' | ForEach-Object {
    $users[$_.Username] = $true
}

Then check if each row of the first CSV contains a username from that hashtable and add a field with the result of that check:

(Import-Csv 'file1.csv') |
    Select-Object *,@{n='Duplicate';e={$users.ContainsKey($_.Username)}} |
    Export-Csv 'file1.csv' -NoType


问:
'Operation' object has no attribute 'compute_gradients' - tensorflow
I want to clip gradient value when use LSTM model.

I calculate the gradient by using optimizer.compute_gradients() and got the error. Here is my code:

```<code>self.optimizer =  tf.train.GradientDescentOptimizer(self.lr).minimize(self.loss)

gvs = self.optimizer.compute_gradients(self.loss)
</code>```

Error message:

'Operation' object has no attribute 'compute_gradients'

How to solve this problem or is there any method to clip the value in tensorflow?

答:
Try this:</p>

```<code>self.optimizer =  tf.train.GradientDescentOptimizer(self.lr)
self.train_step = self.optimizer.minimize(self.loss)
gvs = self.optimizer.compute_gradients(self.loss)
</code>```

Body:
I want to clip gradient value when use LSTM model.

I calculate the gradient by using optimizer.compute_gradients() and got the error. Here is my code:

self.optimizer =  tf.train.GradientDescentOptimizer(self.lr).minimize(self.loss)

gvs = self.optimizer.compute_gradients(self.loss)

Error message:

'Operation' object has no attribute 'compute_gradients'

How to solve this problem or is there any method to clip the value in tensorflow?

Body:
Try this:

self.optimizer =  tf.train.GradientDescentOptimizer(self.lr)
self.train_step = self.optimizer.minimize(self.loss)
gvs = self.optimizer.compute_gradients(self.loss)


问:
On MSVC why does the warning "unreferenced formal parameter" does not appear for std::string?
I have a function with three unused arguments:

```<code>#include <string>

void Test(int b, std::string a, int c)
{
}

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

When compiling it on level 4 in Visual Studio 2017,  I get warnings for b and c:

```<code>1>consoleapplication2.cpp(8): warning C4100: 'c': unreferenced formal parameter
1>consoleapplication2.cpp(8): warning C4100: 'b': unreferenced formal parameter
</code>```

Why don't I get the same warning for std::string a?

答:
While I can't answer why it behaves like this, I noticed there is a pattern.

Looks like MSVC doesn't warn on the unused object as long as the destructor is not defaulted:

```<code>struct X {
    ~X();// = default;
};

void Test(int b, X x)
{

}

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

This code doesn't warn about x, but if you uncomment the = default warning appears.

I am not sure if it is a feature (for example, considering the potential side effects of destroying an object) or an artifact of an analyzer.

Body:
I have a function with three unused arguments:

#include <string>

void Test(int b, std::string a, int c)
{
}

int main()
{
    return 0;
}

When compiling it on level 4 in Visual Studio 2017,  I get warnings for b and c:

1>consoleapplication2.cpp(8): warning C4100: 'c': unreferenced formal parameter
1>consoleapplication2.cpp(8): warning C4100: 'b': unreferenced formal parameter

Why don't I get the same warning for std::string a?

Body:
While I can't answer why it behaves like this, I noticed there is a pattern.

Looks like MSVC doesn't warn on the unused object as long as the destructor is not defaulted:

struct X {
    ~X();// = default;
};

void Test(int b, X x)
{

}

int main()
{
    return 0;
}

This code doesn't warn about x, but if you uncomment the = default warning appears.

I am not sure if it is a feature (for example, considering the potential side effects of destroying an object) or an artifact of an analyzer.


问:
How to Calculate Execution Time of a Code Snippet in C++
I have to compute execution time of a C++ code snippet in seconds. It must be working either on Windows or Unix machines.

I use code the following code to do this. (import  before)

```<code>clock_t startTime = clock();
// some code here
// to compute its execution duration in runtime
cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
</code>```

However for small inputs or short statements such as a = a + 1, I get "0 seconds" result. I think it must be something like 0.0000001 seconds or something like that.

I remember that System.nanoTime() in Java works pretty well in this case. However I can't get same exact functionality from clock() function of C++.

Do you have a solution?

答:
(windows specific solution)
The current (circa 2017) way to get accurate timings under windows is to use "QueryPerformanceCounter". This approach has the benefit of giving very accurate results and  is recommended by MS. Just plop the code blob into a new console app to get a working sample. There is a lengthy discussion here: Acquiring High resolution time stamps</p>

```<code>#include <iostream>
#include <tchar.h>
#include <windows.h>

int main()
{
constexpr int MAX_ITER{ 10000 };
constexpr __int64 us_per_hour{ 3600000000ull }; // 3.6e+09
constexpr __int64 us_per_min{ 60000000ull };
constexpr __int64 us_per_sec{ 1000000ull };
constexpr __int64 us_per_ms{ 1000ull };

// easy to work with
__int64 startTick, endTick, ticksPerSecond, totalTicks = 0ull;

QueryPerformanceFrequency((LARGE_INTEGER *)&ticksPerSecond);

for (int iter = 0; iter < MAX_ITER; ++iter) {// start looping
    QueryPerformanceCounter((LARGE_INTEGER *)&startTick); // Get start tick
    // code to be timed
    std::cout << "cur_tick = " << iter << "\n";
    QueryPerformanceCounter((LARGE_INTEGER *)&endTick); // Get end tick
    totalTicks += endTick - startTick; // accumulate time taken
}

// convert to elapsed microseconds
__int64 totalMicroSeconds =  (totalTicks * 1000000ull)/ ticksPerSecond;

__int64 hours = totalMicroSeconds / us_per_hour;
totalMicroSeconds %= us_per_hour;
__int64 minutes = totalMicroSeconds / us_per_min;
totalMicroSeconds %= us_per_min;
__int64 seconds = totalMicroSeconds / us_per_sec;
totalMicroSeconds %= us_per_sec;
__int64 milliseconds = totalMicroSeconds / us_per_ms;
totalMicroSeconds %= us_per_ms;

std::cout << "Total time: " << hours << "h ";
std::cout << minutes << "m " << seconds << "s " << milliseconds << "ms ";
std::cout << totalMicroSeconds << "us\n";

return 0;
}
</code>```

Body:
I have to compute execution time of a C++ code snippet in seconds. It must be working either on Windows or Unix machines.

I use code the following code to do this. (import  before)

clock_t startTime = clock();
// some code here
// to compute its execution duration in runtime
cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;

However for small inputs or short statements such as a = a + 1, I get "0 seconds" result. I think it must be something like 0.0000001 seconds or something like that.

I remember that System.nanoTime() in Java works pretty well in this case. However I can't get same exact functionality from clock() function of C++.

Do you have a solution?

Body:
(windows specific solution)
The current (circa 2017) way to get accurate timings under windows is to use "QueryPerformanceCounter". This approach has the benefit of giving very accurate results and  is recommended by MS. Just plop the code blob into a new console app to get a working sample. There is a lengthy discussion here: Acquiring High resolution time stamps

#include <iostream>
#include <tchar.h>
#include <windows.h>

int main()
{
constexpr int MAX_ITER{ 10000 };
constexpr __int64 us_per_hour{ 3600000000ull }; // 3.6e+09
constexpr __int64 us_per_min{ 60000000ull };
constexpr __int64 us_per_sec{ 1000000ull };
constexpr __int64 us_per_ms{ 1000ull };

// easy to work with
__int64 startTick, endTick, ticksPerSecond, totalTicks = 0ull;

QueryPerformanceFrequency((LARGE_INTEGER *)&ticksPerSecond);

for (int iter = 0; iter < MAX_ITER; ++iter) {// start looping
    QueryPerformanceCounter((LARGE_INTEGER *)&startTick); // Get start tick
    // code to be timed
    std::cout << "cur_tick = " << iter << "\n";
    QueryPerformanceCounter((LARGE_INTEGER *)&endTick); // Get end tick
    totalTicks += endTick - startTick; // accumulate time taken
}

// convert to elapsed microseconds
__int64 totalMicroSeconds =  (totalTicks * 1000000ull)/ ticksPerSecond;

__int64 hours = totalMicroSeconds / us_per_hour;
totalMicroSeconds %= us_per_hour;
__int64 minutes = totalMicroSeconds / us_per_min;
totalMicroSeconds %= us_per_min;
__int64 seconds = totalMicroSeconds / us_per_sec;
totalMicroSeconds %= us_per_sec;
__int64 milliseconds = totalMicroSeconds / us_per_ms;
totalMicroSeconds %= us_per_ms;

std::cout << "Total time: " << hours << "h ";
std::cout << minutes << "m " << seconds << "s " << milliseconds << "ms ";
std::cout << totalMicroSeconds << "us\n";

return 0;
}


问:
RxJava, What happened if I don't call dispose?
My Android app needs to support to upload a big file, but I do not want a user wait until the upload is completed.

Usually, when I use Observable, I call dispose() for it when the view is destroyed.

But in uploading case, I can not dispose it in any case until it finished.

So I was thinking to try to like this,

```<code>private val compositeDisposable: CompositeDisposable = CompositeDisposable()

fun upload() {
    val disposable = Observable.just(true).delay(20, TimeUnit.SECONDS).subscribe({
        Log.d("=>", "Upload finished")
        disposeUploader()
    })

    compositeDisposable.add(disposable)
}

fun disposeUploader() {
    compositeDisposable.clear()
    compositeDisposable.dispose()
}
</code>```

But the problem is the upload() could be called multiple times, so the first uploader will dispose of all other processing calls.

What happened if I don't call dispose? or is there any way dispose of itself when it is completed?

答:
The idea of disposing an Observable serves two purposes:

1) Avoid memory leaks - detach view references that might be held by ongoing request module.

2) Release resources - stop ongoing background task to free unneeded resources, when the user exit your activity for instance, a request/processing might not be relevant anymore, so no point to keep it running.

In your case you want your background task (uploading file) to resume, avoiding (2), while having your view detaching from it (1).

Your solution of disposing after some period of time miss the point as Observable will dispose itself at completion. moreover, you can't assume a specific duration for the upload (at most it is timeout value).

The solution with RxJava is multicasting your Observable using operator like publish and share, in your case:

```<code>val multicastedObservable = uploadObservable.publish()
            .autoConnect()
            .subscriber(//your view related subscriber);
</code>```

This way, uploadObservable will start execute at first subscribe but will not stop when dispose is called, but rather will detach the reference to view.

Having said all that, it's worth noting that your upload scenario cannot be done reliably without foreground service in Android.

Body:
My Android app needs to support to upload a big file, but I do not want a user wait until the upload is completed.

Usually, when I use Observable, I call dispose() for it when the view is destroyed.

But in uploading case, I can not dispose it in any case until it finished.

So I was thinking to try to like this,

private val compositeDisposable: CompositeDisposable = CompositeDisposable()

fun upload() {
    val disposable = Observable.just(true).delay(20, TimeUnit.SECONDS).subscribe({
        Log.d("=>", "Upload finished")
        disposeUploader()
    })

    compositeDisposable.add(disposable)
}

fun disposeUploader() {
    compositeDisposable.clear()
    compositeDisposable.dispose()
}

But the problem is the upload() could be called multiple times, so the first uploader will dispose of all other processing calls.

What happened if I don't call dispose? or is there any way dispose of itself when it is completed?

Body:
The idea of disposing an Observable serves two purposes:

1) Avoid memory leaks - detach view references that might be held by ongoing request module.

2) Release resources - stop ongoing background task to free unneeded resources, when the user exit your activity for instance, a request/processing might not be relevant anymore, so no point to keep it running.

In your case you want your background task (uploading file) to resume, avoiding (2), while having your view detaching from it (1).

Your solution of disposing after some period of time miss the point as Observable will dispose itself at completion. moreover, you can't assume a specific duration for the upload (at most it is timeout value).

The solution with RxJava is multicasting your Observable using operator like publish and share, in your case:

val multicastedObservable = uploadObservable.publish()
            .autoConnect()
            .subscriber(//your view related subscriber);

This way, uploadObservable will start execute at first subscribe but will not stop when dispose is called, but rather will detach the reference to view.

Having said all that, it's worth noting that your upload scenario cannot be done reliably without foreground service in Android.


问:
SSIS Flat file column delimiter
I have a csv file that I process and import into a database. the problem is the delimiter needs to be " but within SSIS is this possible as currently the default options are :-

答: The text box for the Column delimiter can be edited by clicking in it and writing whatever column delimiter you need.

Title: SSIS Flat file column delimiter


问:
Creating a Label for a checkbox inside a repeater
```<code><asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="countryDataBound">
  <HeaderTemplate>
  </HeaderTemplate>
  <ItemTemplate>
    <div class="accordion">
      <span><h3><%# Eval("key") %>
      <div class="panelCountry">
        <input type="checkbox" runat="server" class="chbSelectAll"/><label>SelectAll</label>
        <asp:CheckBoxList
           ID="chbListCountries"
           CssClass="chbList"
           RepeatColumns="4"
           RepeatDirection="Horizontal"
           DataTextField ="Name"
           DataValueField = "CountryCode"
           runat="server">
           <asp:ListItem></asp:ListItem>
         </asp:CheckBoxList>
     </div>
  </div>
  </ItemTemplate>
  <FooterTemplate>
  </FooterTemplate>
</asp:Repeater>
</code>```

I have a dialog containing a repeater of all the countries in the world grouped by continent. Each continent is separated by a jquery accordion. Inside each accordion there is a checkboxlist of countries, with a checkbox at the top that functions as a select all. I need to have the label associated with the select all, be responsive. By this i mean if i click the label i need to be able to trigger the checkbox to select all.
I considered

```<code><label for="IDHERE">Select all</label>
</code>```

I cannot however figure out how to correctly target the checkbox so that when i click the specific label it only selects the check boxes in this specific checkboxlist.

Is there anyway to create an ID for each "select all" checkbox that is unique from the other seven so that when the label is clicked on it correclty selects the checkboxes in its respective accordion.
for reference, when the checbox is clicked this javascript runs:

```<code>$(document).on('change', '.chbSelectAll', function (e) {
   var selectAllValue = $(this).prop('checked')
   var panel = $(this).closest('.panelCountry');
   var checkboxes = panel.find('input[type=checkbox]:not(.chbSelectAll)');
   checkboxes.prop('checked',selectAllValue);
 });
</code>```

Visual view of the problem

答:
If you don't need the runat=server tag you can create your own label for= by using the ItemIndex.

```<code><input type="checkbox" class="chbSelectAll" id="CheckBox_<%# Container.ItemIndex %>" />
<label for="CheckBox_<%# Container.ItemIndex %>">SelectAll</label>
</code>```

But why not use an aspnet CheckBox? Then you won't have that problem anyway.

```<code><asp:CheckBox ID="CheckBox1" runat="server" Text="SelectAll" CssClass="chbSelectAll" />
</code>```

Body:
<asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="countryDataBound">
  <HeaderTemplate>
  </HeaderTemplate>
  <ItemTemplate>

<%# Eval("key") %>

        <input type="checkbox" runat="server" class="chbSelectAll"/>SelectAll
        <asp:CheckBoxList
           ID="chbListCountries"
           CssClass="chbList"
           RepeatColumns="4"
           RepeatDirection="Horizontal"
           DataTextField ="Name"
           DataValueField = "CountryCode"
           runat="server">
           <asp:ListItem></asp:ListItem>
         </asp:CheckBoxList>

  </ItemTemplate>
  <FooterTemplate>
  </FooterTemplate>
</asp:Repeater>

I have a dialog containing a repeater of all the countries in the world grouped by continent. Each continent is separated by a jquery accordion. Inside each accordion there is a checkboxlist of countries, with a checkbox at the top that functions as a select all. I need to have the label associated with the select all, be responsive. By this i mean if i click the label i need to be able to trigger the checkbox to select all.
I considered

Select all

I cannot however figure out how to correctly target the checkbox so that when i click the specific label it only selects the check boxes in this specific checkboxlist.

Is there anyway to create an ID for each "select all" checkbox that is unique from the other seven so that when the label is clicked on it correclty selects the checkboxes in its respective accordion.
for reference, when the checbox is clicked this javascript runs:

$(document).on('change', '.chbSelectAll', function (e) {
   var selectAllValue = $(this).prop('checked')
   var panel = $(this).closest('.panelCountry');
   var checkboxes = panel.find('input[type=checkbox]:not(.chbSelectAll)');
   checkboxes.prop('checked',selectAllValue);
 });

Visual view of the problem

Body:
If you don't need the runat=server tag you can create your own label for= by using the ItemIndex.

<input type="checkbox" class="chbSelectAll" id="CheckBox_<%# Container.ItemIndex %>" />
<label for="CheckBox_<%# Container.ItemIndex %>">SelectAll</label>

But why not use an aspnet CheckBox? Then you won't have that problem anyway.

<asp:CheckBox ID="CheckBox1" runat="server" Text="SelectAll" CssClass="chbSelectAll" />


问:
Using arrays to generate a players score
I'm trying to use the array method to keep track of scores on my game, I'm having difficulty in doing so when I try to compile and run.</p>

```<code>import java.util.Scanner;
import java.io.*;

public class score
{

    public static void main (String[]args)
    {

    Scanner scan = new Scanner(System.in);

    int [] arrPlayer = new int[7];

    System.out.println("Please Enter Your Score");
    arrPlayer[0]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[1]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[2]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[3]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[4]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[5]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[6]=scan.nextInt();

    System.out.println("Player 1 : Score: "arrPlayer[0];
    System.out.println("Player 1 : Score: "arrPlayer[1];
    System.out.println("Player 1 : Score: "arrPlayer[2];
    System.out.println("Player 1 : Score: "arrPlayer[3];
    System.out.println("Player 1 : Score: "arrPlayer[4];
    System.out.println("Player 1 : Score: "arrPlayer[5];
    System.out.println("Player 1 : Score: "arrPlayer[6];

    for(int i=0;i<7;i++);

    }

}
</code>```

答:
you missed + to concatenate the array value with the string. And also you didn't close your System.out.println() method.

Here is the correction:

```<code>    System.out.println("Player 1 : Score: " + arrPlayer[0]);
    System.out.println("Player 1 : Score: " + arrPlayer[1]);
    System.out.println("Player 1 : Score: " + arrPlayer[2]);
    System.out.println("Player 1 : Score: " + arrPlayer[3]);
    System.out.println("Player 1 : Score: " + arrPlayer[4]);
    System.out.println("Player 1 : Score: " + arrPlayer[5]);
    System.out.println("Player 1 : Score: " + arrPlayer[6]);
</code>```

And bonus:

You can simplify your code with the following changes making use of loops.

```<code>for (int i = 0; i < 7; i++) {
    System.out.println("Please Enter Your Score");
    arrPlayer[i] = scan.nextInt();
}

for (int i = 0; i < 7; i++) {
    System.out.println("Player 1 : Score: " + arrPlayer[i]);
}
</code>```

Body:
I'm trying to use the array method to keep track of scores on my game, I'm having difficulty in doing so when I try to compile and run.

import java.util.Scanner;
import java.io.*;

public class score
{

    public static void main (String[]args)
    {

    Scanner scan = new Scanner(System.in);

    int [] arrPlayer = new int[7];

    System.out.println("Please Enter Your Score");
    arrPlayer[0]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[1]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[2]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[3]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[4]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[5]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[6]=scan.nextInt();

    System.out.println("Player 1 : Score: "arrPlayer[0];
    System.out.println("Player 1 : Score: "arrPlayer[1];
    System.out.println("Player 1 : Score: "arrPlayer[2];
    System.out.println("Player 1 : Score: "arrPlayer[3];
    System.out.println("Player 1 : Score: "arrPlayer[4];
    System.out.println("Player 1 : Score: "arrPlayer[5];
    System.out.println("Player 1 : Score: "arrPlayer[6];

    for(int i=0;i<7;i++);

    }

}

Body:
you missed + to concatenate the array value with the string. And also you didn't close your System.out.println() method.

Here is the correction:

    System.out.println("Player 1 : Score: " + arrPlayer[0]);
    System.out.println("Player 1 : Score: " + arrPlayer[1]);
    System.out.println("Player 1 : Score: " + arrPlayer[2]);
    System.out.println("Player 1 : Score: " + arrPlayer[3]);
    System.out.println("Player 1 : Score: " + arrPlayer[4]);
    System.out.println("Player 1 : Score: " + arrPlayer[5]);
    System.out.println("Player 1 : Score: " + arrPlayer[6]);

And bonus:

You can simplify your code with the following changes making use of loops.

for (int i = 0; i < 7; i++) {
    System.out.println("Please Enter Your Score");
    arrPlayer[i] = scan.nextInt();
}

for (int i = 0; i < 7; i++) {
    System.out.println("Player 1 : Score: " + arrPlayer[i]);
}


问:
TypeScript generic constraints to multiple primitive types
Given this function:

```<code>myFunc(object: string | null): string | null {}
</code>```

I would like this function to be of return type string when the object is string, and return type of string | null when the object is of type string | null.

I have tried:

```<code>myFunc<T extends string | null>(object: T): T {
    return "returnValue"; //Type '"returnValue"' is not assignable to type 'T'.
}
</code>```

and

```<code>myFunc<T extends string & null>(object: T): T {
    return "returnValue"; //Type '"returnValue"' is not assignable to type 'T'.
}
</code>```

Both produce the same compile error. I have not found the correct syntax to do this.

答:
I can't believe I'm actually going to suggest overloads, as I spend a goodly portion of my time explaining how most of them can be avoided... but an overload would be a good way to model this!

```<code>class Example {
    myFunc(obj: string): string;
    myFunc(obj: string | null): string | null;
    myFunc(obj: string | null): string | null {
        return "returnValue";
    }
}

function test(a: string | null, b: string) {
    const example = new Example();

    // resultA: string | null
    const resultA = example.myFunc(a);

    // resultB: string
    const resultB = example.myFunc(b);
}
</code>```

In the above example, the return types are mapped to the input types, so resultA and resultB have the expected types, provided you are running with strict null checks enabled.

Body:
Given this function:

myFunc(object: string | null): string | null {}

I would like this function to be of return type string when the object is string, and return type of string | null when the object is of type string | null.

I have tried:

myFunc<T extends string | null>(object: T): T {
    return "returnValue"; //Type '"returnValue"' is not assignable to type 'T'.
}

and

myFunc<T extends string & null>(object: T): T {
    return "returnValue"; //Type '"returnValue"' is not assignable to type 'T'.
}

Both produce the same compile error. I have not found the correct syntax to do this.

Body:
I can't believe I'm actually going to suggest overloads, as I spend a goodly portion of my time explaining how most of them can be avoided... but an overload would be a good way to model this!

class Example {
    myFunc(obj: string): string;
    myFunc(obj: string | null): string | null;
    myFunc(obj: string | null): string | null {
        return "returnValue";
    }
}

function test(a: string | null, b: string) {
    const example = new Example();

    // resultA: string | null
    const resultA = example.myFunc(a);

    // resultB: string
    const resultB = example.myFunc(b);
}

In the above example, the return types are mapped to the input types, so resultA and resultB have the expected types, provided you are running with strict null checks enabled.


问:
Closing Sessions in Spring Boot JMS CachingConnectionFactory
I have my JMS configuration like below (Spring boot 1.3.8);

```<code>    @Configuration
    @EnableJms
    public class JmsConfig {

    @Autowired
    private AppProperties properties;

    @Bean
    TopicConnectionFactory topicConnectionFactory() throws JMSException {
        return new TopicConnectionFactory(properties.getBrokerURL(), properties.getBrokerUserName(),
                properties.getBrokerPassword());
    }

    @Bean
    CachingConnectionFactory connectionFactory() throws JMSException {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(topicConnectionFactory());
        connectionFactory.setSessionCacheSize(50);
        return connectionFactory;
    }

    @Bean
    JmsTemplate jmsTemplate() throws JMSException {
        JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory());
        jmsTemplate.setPubSubDomain(Boolean.TRUE);
        return jmsTemplate;
    }

    @Bean
    DefaultJmsListenerContainerFactory defaultContainerFactory() throws JMSException {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory());
        factory.setPubSubDomain(Boolean.TRUE);
        factory.setRecoveryInterval(30 * 1000L);
        return factory;
    }
}
</code>```

This should work fine. But i am worried about whats written on the doc of CachingConnectionFactory

Specially, these parts;

NOTE: This ConnectionFactory requires explicit closing of all Sessions obtained from its shared Connection

Note also that MessageConsumers obtained from a cached Session won't get closed until the Session will eventually be removed from the pool. This may lead to semantic side effects in some cases.

I thought the framework handled the closing session and connection part? If it does not; how should i close them properly?

or maybe i am missing something?

Any help is appreciated :)

F.Y.I : I Use SonicMQ as the broker

答: Yes, the JmsTemplate will close the session; the javadocs refer to direct use outside of the framework.

Body:
I have my JMS configuration like below (Spring boot 1.3.8);

    @Configuration
    @EnableJms
    public class JmsConfig {

    @Autowired
    private AppProperties properties;

    @Bean
    TopicConnectionFactory topicConnectionFactory() throws JMSException {
        return new TopicConnectionFactory(properties.getBrokerURL(), properties.getBrokerUserName(),
                properties.getBrokerPassword());
    }

    @Bean
    CachingConnectionFactory connectionFactory() throws JMSException {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(topicConnectionFactory());
        connectionFactory.setSessionCacheSize(50);
        return connectionFactory;
    }

    @Bean
    JmsTemplate jmsTemplate() throws JMSException {
        JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory());
        jmsTemplate.setPubSubDomain(Boolean.TRUE);
        return jmsTemplate;
    }

    @Bean
    DefaultJmsListenerContainerFactory defaultContainerFactory() throws JMSException {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory());
        factory.setPubSubDomain(Boolean.TRUE);
        factory.setRecoveryInterval(30 * 1000L);
        return factory;
    }
}

This should work fine. But i am worried about whats written on the doc of CachingConnectionFactory

Specially, these parts;

NOTE: This ConnectionFactory requires explicit closing of all Sessions obtained from its shared Connection

Note also that MessageConsumers obtained from a cached Session won't get closed until the Session will eventually be removed from the pool. This may lead to semantic side effects in some cases.

I thought the framework handled the closing session and connection part? If it does not; how should i close them properly?

or maybe i am missing something?

Any help is appreciated :)

F.Y.I : I Use SonicMQ as the broker


问:
How to send data in request body with a GET when using jQuery $.ajax()
The service API I am consuming has a given GET method that requires the data be sent in the body of the request.

The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.

I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...

```<code>$.ajax({
   url: "htttp://api.com/entity/list($body)",
   type: "GET",
   data: "id1-id2-id3",
   contentType: "text/plain",
   dataType: "json",
   processData: false, // avoid the data being parsed to query string params
   success: onSuccess,
   error: onError
});
</code>```

Anyone know how I can force the "data" value to be sent in the body of the request?

答:
Just in case somebody ist still coming along this question:

There is a body query object in any request. You do not need to parse it yourself.

E.g. if you want to send an accessToken from a client with GET, you could do it like this:

const request = require('superagent');

request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
  if (err) throw new Error(err);
  console.log(res);
});```

The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }

ContentLicense: CC BY-SA 4.0

Body:
The service API I am consuming has a given GET method that requires the data be sent in the body of the request.

The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.

I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...

$.ajax({
   url: "htttp://api.com/entity/list($body)",
   type: "GET",
   data: "id1-id2-id3",
   contentType: "text/plain",
   dataType: "json",
   processData: false, // avoid the data being parsed to query string params
   success: onSuccess,
   error: onError
});

Anyone know how I can force the "data" value to be sent in the body of the request?

Body:
Just in case somebody ist still coming along this question:

There is a body query object in any request. You do not need to parse it yourself.

E.g. if you want to send an accessToken from a client with GET, you could do it like this:

const request = require('superagent');

request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
  if (err) throw new Error(err);
  console.log(res);
});

The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }


问:
How to populate Pandas dataframe as function of index and columns
I have a dataframe where the index and column are both numbers--i.e.

```<code>rng = np.arange(2,51)
box = pd.DataFrame(index = rng, columns = rng)
</code>```

I want the values of the dataframe to be a function of the index and column--so for instance box[2][2] should equal 4.

Currently I have it in

```<code>for x in range(2,len(box)+2):
    for y in range(2,len(box)+2):
        box[x][y] = x*y
box
</code>```

but I feel like there should be a more elegant solution. Is there a way to do this purely with slicing/dataframe assignment methods?

Body:
I have a dataframe where the index and column are both numbers--i.e.

rng = np.arange(2,51)
box = pd.DataFrame(index = rng, columns = rng)

I want the values of the dataframe to be a function of the index and column--so for instance box[2][2] should equal 4.

Currently I have it in

for x in range(2,len(box)+2):
    for y in range(2,len(box)+2):
        box[x][y] = x*y
box

but I feel like there should be a more elegant solution. Is there a way to do this purely with slicing/dataframe assignment methods?

Body:
Use np.outer:

box_out = pd.DataFrame(np.outer(box.index, box.columns), index=box.index, columns=box.columns)

Output:

     2    3    4    5    6    7    8    9    10   11  ...     41    42    43    44    45    46    47    48    49    50
2     4    6    8   10   12   14   16   18   20   22  ...     82    84    86    88    90    92    94    96    98   100
3     6    9   12   15   18   21   24   27   30   33  ...    123   126   129   132   135   138   141   144   147   150
4     8   12   16   20   24   28   32   36   40   44  ...    164   168   172   176   180   184   188   192   196   200
5    10   15   20   25   30   35   40   45   50   55  ...    205   210   215   220   225   230   235   240   245   250
6    12   18   24   30   36   42   48   54   60   66  ...    246   252   258   264   270   276   282   288   294   300
7    14   21   28   35   42   49   56   63   70   77  ...    287   294   301   308   315   322   329   336   343   350
8    16   24   32   40   48   56   64   72   80   88  ...    328   336   344   352   360   368   376   384   392   400
9    18   27   36   45   54   63   72   81   90   99  ...    369   378   387   396   405   414   423   432   441   450
10   20   30   40   50   60   70   80   90  100  110  ...    410   420   430   440   450   460   470   480   490   500
11   22   33   44   55   66   77   88   99  110  121  ...    451   462   473   484   495   506   517   528   539   550
12   24   36   48   60   72   84   96  108  120  132  ...    492   504   516   528   540   552   564   576   588   600
13   26   39   52   65   78   91  104  117  130  143  ...    533   546   559   572   585   598   611   624   637   650
14   28   42   56   70   84   98  112  126  140  154  ...    574   588   602   616   630   644   658   672   686   700
15   30   45   60   75   90  105  120  135  150  165  ...    615   630   645   660   675   690   705   720   735   750
16   32   48   64   80   96  112  128  144  160  176  ...    656   672   688   704   720   736   752   768   784   800
17   34   51   68   85  102  119  136  153  170  187  ...    697   714   731   748   765   782   799   816   833   850
18   36   54   72   90  108  126  144  162  180  198  ...    738   756   774   792   810   828   846   864   882   900
19   38   57   76   95  114  133  152  171  190  209  ...    779   798   817   836   855   874   893   912   931   950
20   40   60   80  100  120  140  160  180  200  220  ...    820   840   860   880   900   920   940   960   980  1000
21   42   63   84  105  126  147  168  189  210  231  ...    861   882   903   924   945   966   987  1008  1029  1050
22   44   66   88  110  132  154  176  198  220  242  ...    902   924   946   968   990  1012  1034  1056  1078  1100
23   46   69   92  115  138  161  184  207  230  253  ...    943   966   989  1012  1035  1058  1081  1104  1127  1150
24   48   72   96  120  144  168  192  216  240  264  ...    984  1008  1032  1056  1080  1104  1128  1152  1176  1200
25   50   75  100  125  150  175  200  225  250  275  ...   1025  1050  1075  1100  1125  1150  1175  1200  1225  1250
26   52   78  104  130  156  182  208  234  260  286  ...   1066  1092  1118  1144  1170  1196  1222  1248  1274  1300
27   54   81  108  135  162  189  216  243  270  297  ...   1107  1134  1161  1188  1215  1242  1269  1296  1323  1350
28   56   84  112  140  168  196  224  252  280  308  ...   1148  1176  1204  1232  1260  1288  1316  1344  1372  1400
29   58   87  116  145  174  203  232  261  290  319  ...   1189  1218  1247  1276  1305  1334  1363  1392  1421  1450
30   60   90  120  150  180  210  240  270  300  330  ...   1230  1260  1290  1320  1350  1380  1410  1440  1470  1500
31   62   93  124  155  186  217  248  279  310  341  ...   1271  1302  1333  1364  1395  1426  1457  1488  1519  1550
32   64   96  128  160  192  224  256  288  320  352  ...   1312  1344  1376  1408  1440  1472  1504  1536  1568  1600
33   66   99  132  165  198  231  264  297  330  363  ...   1353  1386  1419  1452  1485  1518  1551  1584  1617  1650
34   68  102  136  170  204  238  272  306  340  374  ...   1394  1428  1462  1496  1530  1564  1598  1632  1666  1700
35   70  105  140  175  210  245  280  315  350  385  ...   1435  1470  1505  1540  1575  1610  1645  1680  1715  1750
36   72  108  144  180  216  252  288  324  360  396  ...   1476  1512  1548  1584  1620  1656  1692  1728  1764  1800
37   74  111  148  185  222  259  296  333  370  407  ...   1517  1554  1591  1628  1665  1702  1739  1776  1813  1850
38   76  114  152  190  228  266  304  342  380  418  ...   1558  1596  1634  1672  1710  1748  1786  1824  1862  1900
39   78  117  156  195  234  273  312  351  390  429  ...   1599  1638  1677  1716  1755  1794  1833  1872  1911  1950
40   80  120  160  200  240  280  320  360  400  440  ...   1640  1680  1720  1760  1800  1840  1880  1920  1960  2000
41   82  123  164  205  246  287  328  369  410  451  ...   1681  1722  1763  1804  1845  1886  1927  1968  2009  2050
42   84  126  168  210  252  294  336  378  420  462  ...   1722  1764  1806  1848  1890  1932  1974  2016  2058  2100
43   86  129  172  215  258  301  344  387  430  473  ...   1763  1806  1849  1892  1935  1978  2021  2064  2107  2150
44   88  132  176  220  264  308  352  396  440  484  ...   1804  1848  1892  1936  1980  2024  2068  2112  2156  2200
45   90  135  180  225  270  315  360  405  450  495  ...   1845  1890  1935  1980  2025  2070  2115  2160  2205  2250
46   92  138  184  230  276  322  368  414  460  506  ...   1886  1932  1978  2024  2070  2116  2162  2208  2254  2300
47   94  141  188  235  282  329  376  423  470  517  ...   1927  1974  2021  2068  2115  2162  2209  2256  2303  2350
48   96  144  192  240  288  336  384  432  480  528  ...   1968  2016  2064  2112  2160  2208  2256  2304  2352  2400
49   98  147  196  245  294  343  392  441  490  539  ...   2009  2058  2107  2156  2205  2254  2303  2352  2401  2450
50  100  150  200  250  300  350  400  450  500  550  ...   2050  2100  2150  2200  2250  2300  2350  2400  2450  2500

If you want other functions look at numpy.ufunc.outer and you can use this list of ufunc.  Such:

box_add_outer = pd.DataFrame(np.add.outer(box.index, box.columns), index=box.index, columns=box.columns)

Output:

    2   3   4   5   6   7   8   9   10  11 ...   41  42  43  44  45  46  47  48  49   50
2    4   5   6   7   8   9  10  11  12  13 ...   43  44  45  46  47  48  49  50  51   52
3    5   6   7   8   9  10  11  12  13  14 ...   44  45  46  47  48  49  50  51  52   53
4    6   7   8   9  10  11  12  13  14  15 ...   45  46  47  48  49  50  51  52  53   54
5    7   8   9  10  11  12  13  14  15  16 ...   46  47  48  49  50  51  52  53  54   55
6    8   9  10  11  12  13  14  15  16  17 ...   47  48  49  50  51  52  53  54  55   56
7    9  10  11  12  13  14  15  16  17  18 ...   48  49  50  51  52  53  54  55  56   57
8   10  11  12  13  14  15  16  17  18  19 ...   49  50  51  52  53  54  55  56  57   58
9   11  12  13  14  15  16  17  18  19  20 ...   50  51  52  53  54  55  56  57  58   59
10  12  13  14  15  16  17  18  19  20  21 ...   51  52  53  54  55  56  57  58  59   60
11  13  14  15  16  17  18  19  20  21  22 ...   52  53  54  55  56  57  58  59  60   61
12  14  15  16  17  18  19  20  21  22  23 ...   53  54  55  56  57  58  59  60  61   62
13  15  16  17  18  19  20  21  22  23  24 ...   54  55  56  57  58  59  60  61  62   63
14  16  17  18  19  20  21  22  23  24  25 ...   55  56  57  58  59  60  61  62  63   64
15  17  18  19  20  21  22  23  24  25  26 ...   56  57  58  59  60  61  62  63  64   65
16  18  19  20  21  22  23  24  25  26  27 ...   57  58  59  60  61  62  63  64  65   66
17  19  20  21  22  23  24  25  26  27  28 ...   58  59  60  61  62  63  64  65  66   67
18  20  21  22  23  24  25  26  27  28  29 ...   59  60  61  62  63  64  65  66  67   68
19  21  22  23  24  25  26  27  28  29  30 ...   60  61  62  63  64  65  66  67  68   69
20  22  23  24  25  26  27  28  29  30  31 ...   61  62  63  64  65  66  67  68  69   70
21  23  24  25  26  27  28  29  30  31  32 ...   62  63  64  65  66  67  68  69  70   71
22  24  25  26  27  28  29  30  31  32  33 ...   63  64  65  66  67  68  69  70  71   72
23  25  26  27  28  29  30  31  32  33  34 ...   64  65  66  67  68  69  70  71  72   73
24  26  27  28  29  30  31  32  33  34  35 ...   65  66  67  68  69  70  71  72  73   74
25  27  28  29  30  31  32  33  34  35  36 ...   66  67  68  69  70  71  72  73  74   75
26  28  29  30  31  32  33  34  35  36  37 ...   67  68  69  70  71  72  73  74  75   76
27  29  30  31  32  33  34  35  36  37  38 ...   68  69  70  71  72  73  74  75  76   77
28  30  31  32  33  34  35  36  37  38  39 ...   69  70  71  72  73  74  75  76  77   78
etc....


答:
Heres the working code :-</p>

```<code>PageFreq = function(pf,i,j){

  a = pf %>% filter(Var1 == i) %>% select(Relative_freq);
  b = pf %>% filter(Var1 == j) %>% select(Relative_freq);
  a1 = a$Relative_freq
  b1 = b$Relative_freq
  c = list(a1,b1);
  return (c)

}
k = 21
PF = matrix(data=NA, nrow=k, ncol=k)

for(i in 1:k){
  for(j in 1:k){
    pff = PageFreq(pf,i,j)
    a = pff[[1]]
    b = pff[[2]]
    PF[i,j] = 2 * a *b/(a + b)

  }
}
</code>```

Title: Creating matrix based on a dataframe and storing weights in matrix cells

Body:
I have this dataframe :-

pf = structure(list(Var1 = structure(1:21, .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
"16", "17", "18", "19", "20", "21"), class = "factor"), Freq = c(101L,
61L, 84L, 98L, 56L, 222L, 137L, 103L, 136L, 97L, 77L, 110L, 84L,
88L, 92L, 89L, 86L, 87L, 84L, 71L, 36L), Relative_freq = c(0.0505252626313157,
0.0305152576288144, 0.0420210105052526, 0.0490245122561281, 0.0280140070035018,
0.111055527763882, 0.0685342671335668, 0.0515257628814407, 0.0680340170085043,
0.0485242621310655, 0.0385192596298149, 0.0550275137568784, 0.0420210105052526,
0.0440220110055028, 0.0460230115057529, 0.0445222611305653, 0.0430215107553777,
0.0435217608804402, 0.0420210105052526, 0.0355177588794397, 0.0180090045022511
)), .Names = c("Var1", "Freq", "Relative_freq"), row.names = c(NA,
-21L), class = "data.frame")

Now i want to create a matrix based on this dataframe, which will store these relative_freq as edge(matrix cells) weights.

Heres the code :-

k=5
PF = matrix(data=NA, nrow=k, ncol=k)

for(i in 1:k){
  for(j in 1:k){
    pf = PageFreq(pf,i,j)
    a = pf[[1]]
    b = pf[[2]]
    PF[i,j] = 2 * a *b/(a + b)

  }
}

and here is the PageFreq function which i need to get tweaked in order to work correct :-

PageFreq = function(pf,i,j){

  a = pf %>% filter(Var1 == i) %>% select(Relative_freq);
  b = pf %>% filter(Var1 == j) %>% select(Relative_freq);
  c = list(a,b);
  return (c)

}

Please look whats the correct way ! Thanks

Body:
Heres the working code :-

PageFreq = function(pf,i,j){

  a = pf %>% filter(Var1 == i) %>% select(Relative_freq);
  b = pf %>% filter(Var1 == j) %>% select(Relative_freq);
  a1 = a$Relative_freq
  b1 = b$Relative_freq
  c = list(a1,b1);
  return (c)

}
k = 21
PF = matrix(data=NA, nrow=k, ncol=k)

for(i in 1:k){
  for(j in 1:k){
    pff = PageFreq(pf,i,j)
    a = pff[[1]]
    b = pff[[2]]
    PF[i,j] = 2 * a *b/(a + b)

  }
}


问:
The image not retrieving and show error the input not a valid Base 64 string
I am trying for at least two hours to solve this but all in vein .
I am retrieving the image which is stored in database .

```<code>public Image Base64ToImage(string base64String) {
    // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
    // Convert byte[] to Image
    ms.Write(imageBytes, 0, imageBytes.Length);
    Image image = Image.FromStream(ms, true);
    return image;
}
</code>```

And the code using database as :

```<code>con.Open();
cmd = new SqlCommand("select [s_image] from [2017] where serialno="+serianotext.Text ,con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {

    imagepicturebox.Image = Base64ToImage(dr[0].ToString());
}
con.Close();
</code>```

The error show in image

答:
I don't know the value of your base64 string, so I wrote this example. You can use it to make your own code.</p>

```<code>using System;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        private static string connectionString = "Data Source=localhost;Initial Catalog=my_test_db;Integrated Security=True;";

        public static string ImageToBase64(Image image, ImageFormat imageFormat)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, imageFormat);
                byte[] imageBytes = ms.ToArray();
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }
        public static Image Base64ToImage(string base64String)
        {
            byte[] imageBytes = Convert.FromBase64String(base64String);
            using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
            {
                ms.Write(imageBytes, 0, imageBytes.Length);
                Image image = Image.FromStream(ms, true);
                return image;
            }
        }

        static void Main(string[] args)
        {
            string image1base64;

            using(Bitmap image1 = (Bitmap) Image.FromFile("C:\\test1.png"))
                image1base64 = ImageToBase64((Image)image1, ImageFormat.Png);

            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();

                using (SqlCommand sqlCommand = new SqlCommand("create table #base64test(id int not null, base64image varchar(max));", sqlConnection))
                    sqlCommand.ExecuteNonQuery();

                using (SqlCommand sqlCommand = new SqlCommand("insert #base64test(id, base64image) values(@id, @base64image)", sqlConnection))
                {
                    sqlCommand.Parameters.Add("@id", SqlDbType.Int);
                    sqlCommand.Parameters["@id"].Value = 1;

                    sqlCommand.Parameters.Add("@base64image", SqlDbType.VarChar, -1);
                    sqlCommand.Parameters["@base64image"].Value = image1base64;

                    sqlCommand.ExecuteNonQuery();
                }

                using (SqlCommand sqlCommand = new SqlCommand("select base64image from #base64test where id = @id", sqlConnection))
                {
                    sqlCommand.Parameters.Add("@id", SqlDbType.Int);
                    sqlCommand.Parameters["@id"].Value = 1;

                    using (SqlDataReader rd = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess))
                    {
                        if (rd.Read() == false)
                            throw new ApplicationException("An error occurred ...");

                        object[] temp = new object[rd.FieldCount];//[1]

                        // read BLOB trick
                        if (rd.GetSqlValues(temp) != rd.FieldCount)
                            throw new ApplicationException("An error occurred ...");

                        Image image2 = Base64ToImage(((SqlString)temp[0]).ToString());
                        image2.Save("C:\\test2.png", ImageFormat.Png);
                    }
                }
            }
        }
    }
}
</code>```

Body:
I am trying for at least two hours to solve this but all in vein .
I am retrieving the image which is stored in database .

public Image Base64ToImage(string base64String) {
    // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
    // Convert byte[] to Image
    ms.Write(imageBytes, 0, imageBytes.Length);
    Image image = Image.FromStream(ms, true);
    return image;
}

And the code using database as :

con.Open();
cmd = new SqlCommand("select [s_image] from [2017] where serialno="+serianotext.Text ,con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {

    imagepicturebox.Image = Base64ToImage(dr[0].ToString());
}
con.Close();

The error show in image

Body:
I don't know the value of your base64 string, so I wrote this example. You can use it to make your own code.

using System;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        private static string connectionString = "Data Source=localhost;Initial Catalog=my_test_db;Integrated Security=True;";

        public static string ImageToBase64(Image image, ImageFormat imageFormat)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, imageFormat);
                byte[] imageBytes = ms.ToArray();
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }
        public static Image Base64ToImage(string base64String)
        {
            byte[] imageBytes = Convert.FromBase64String(base64String);
            using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
            {
                ms.Write(imageBytes, 0, imageBytes.Length);
                Image image = Image.FromStream(ms, true);
                return image;
            }
        }

        static void Main(string[] args)
        {
            string image1base64;

            using(Bitmap image1 = (Bitmap) Image.FromFile("C:\\test1.png"))
                image1base64 = ImageToBase64((Image)image1, ImageFormat.Png);

            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();

                using (SqlCommand sqlCommand = new SqlCommand("create table #base64test(id int not null, base64image varchar(max));", sqlConnection))
                    sqlCommand.ExecuteNonQuery();

                using (SqlCommand sqlCommand = new SqlCommand("insert #base64test(id, base64image) values(@id, @base64image)", sqlConnection))
                {
                    sqlCommand.Parameters.Add("@id", SqlDbType.Int);
                    sqlCommand.Parameters["@id"].Value = 1;

                    sqlCommand.Parameters.Add("@base64image", SqlDbType.VarChar, -1);
                    sqlCommand.Parameters["@base64image"].Value = image1base64;

                    sqlCommand.ExecuteNonQuery();
                }

                using (SqlCommand sqlCommand = new SqlCommand("select base64image from #base64test where id = @id", sqlConnection))
                {
                    sqlCommand.Parameters.Add("@id", SqlDbType.Int);
                    sqlCommand.Parameters["@id"].Value = 1;

                    using (SqlDataReader rd = sqlCommand.ExecuteReader(CommandBehavior.SequentialAccess))
                    {
                        if (rd.Read() == false)
                            throw new ApplicationException("An error occurred ...");

                        object[] temp = new object[rd.FieldCount];//[1]

                        // read BLOB trick
                        if (rd.GetSqlValues(temp) != rd.FieldCount)
                            throw new ApplicationException("An error occurred ...");

                        Image image2 = Base64ToImage(((SqlString)temp[0]).ToString());
                        image2.Save("C:\\test2.png", ImageFormat.Png);
                    }
                }
            }
        }
    }
}


问:
Code to find max number from array
I wrote the following code to find the max number from a array of numbers. Apparently there is an error in my code.It is a segmentation error. Please help me identify it.</p>

```<code>#include <stdio.h>
void max(int n,int A[n]);

int main()
{
int n;
int A[n];
max(n,A[n]);
}

void max(int n,int A[n])
{
printf("Enter the number of elements you want in your array\n");
scanf("%d",&n);
int i;
printf("Enter the elements  in your array\n");
for(i=0;i<n;i++)
{
    scanf("%d",&A[i]);
}
int max=A[0];
for(i=1;i<n;i++)
{
    if(A[i]>max)
    {
        max=A[i];
    }
}
printf("%d",max);
}
</code>```

答:
In main() you declare n but it has no value, so likely defaults to 0.  You then declare and define an array A and give it size n, which as I say is likely zero.

Within max() you then read in a value and assign it to n but your array A is size zero.

So change main() to

```<code>/* Get the number of items to store in the array */
int n;
printf("Enter the number of elements you want in your array\n");
scanf("%d",&n);

/* Create the array of the given size */
int A[n];

/* Now find the max value in that array */
max(n,A);
</code>```

And remove the setting of n from max().

Title: Code to find max number from array

Body:
I wrote the following code to find the max number from a array of numbers. Apparently there is an error in my code.It is a segmentation error. Please help me identify it.

#include <stdio.h>
void max(int n,int A[n]);

int main()
{
int n;
int A[n];
max(n,A[n]);
}

void max(int n,int A[n])
{
printf("Enter the number of elements you want in your array\n");
scanf("%d",&n);
int i;
printf("Enter the elements  in your array\n");
for(i=0;i<n;i++)
{
    scanf("%d",&A[i]);
}
int max=A[0];
for(i=1;i<n;i++)
{
    if(A[i]>max)
    {
        max=A[i];
    }
}
printf("%d",max);
}

Body:
In main() you declare n but it has no value, so likely defaults to 0.  You then declare and define an array A and give it size n, which as I say is likely zero.

Within max() you then read in a value and assign it to n but your array A is size zero.

So change main() to

/* Get the number of items to store in the array */
int n;
printf("Enter the number of elements you want in your array\n");
scanf("%d",&n);

/* Create the array of the given size */
int A[n];

/* Now find the max value in that array */
max(n,A);

And remove the setting of n from max().


问:
Should I set my TextView colours if my background colour is not set?
When I comes to specifying colours for an application, I recently came across @android:color. Is it recommended to try to always use predefined system colors?

I changed the colours of some of my labels to something brighter, so that they'll stand out against the black background. But then I start to wonder... would themes/skins (not familiar with those) and such cause the default background colour to be something other than black?

If so... what's the proper way to deal with colouring one's widgets?

答:
You've got 2 options:
1) define explicitly fore/background colors of all of your elements
2) use only default colors, so when the user change its theme, everything will change accordingly. Personally, i prefer this way, but be careful if your UI's got some images

Be consistent, so you'll avoid issues when users change its themes. choose one and back to work!

ContentLicense: CC BY-SA 2.5


问:
NoResourceEntry-x REPL tree output
For some reason for the Xamarin Test app for which I am 100% sure that its elements have Ids, I can only see "NoResourceEntry".

Not sure what is the reason, but either it is related to Emulator, Target Framework or something else.

Did someone have this issue? And do you know what is causing it?
I am running the simple test and just trying to trigger the REPL tree command
Please refer to screenshots below:

REPL tree
DeviceConfiguration

答:
I think you need to add AutomationId to each property.

e.g.    <Button x:Name="Button1" AutomationId="Button1"

This sets the label property, which you should now see in REPL using the tree commnand.

You can then do :

```<code>app.Tap(c => c.Marked("Button1"));
</code>```

See https://forums.xamarin.com/discussion/97202/why-do-views-in-my-app-not-have-ids for more details.

Title: NoResourceEntry-x REPL tree output

Body:
I think you need to add AutomationId to each property.

e.g.    <Button x:Name="Button1" AutomationId="Button1"

This sets the label property, which you should now see in REPL using the tree commnand.

You can then do :

app.Tap(c => c.Marked("Button1"));

See https://forums.xamarin.com/discussion/97202/why-do-views-in-my-app-not-have-ids for more details.


问:
Simple online script minifier for PHP, Javascript & CSS scripts
Mainly looking for PHP minifier. Online copy > paste > output, would be a plus.</p>

答: The only working one I've met is online PHP-Minify tool. But it only works with php.


问:
Finding id's not in other table SQL
Help!

I am trying to find the customer that are in VBSTEST that are not in VMFG9. the tables have identical schema. Whenever i run the query i never get a result returning.

```<code>`SELECT [ROWID]
      ,[ID]
      ,[NAME]
      ,[ADDR_1]
      ,[ADDR_2]
      ,[ADDR_3]
      ,[CITY]
      ,[STATE]
      ,[ZIPCODE]
      ,[COUNTRY]
  FROM [VMFG9].[dbo].[CUSTOMER]
   where NOT EXISTS(
        select v6.[ID]
        from [VBSTEST].[dbo].[CUSTOMER] as v6
        left outer join [VMFG9].[dbo.CUSTOMER] as v9 on  v9.id = v6.[id]
        where v9.id is null);`
</code>```

答:
The subquery that you want doesn't use a join:

```<code>select . . .
from [VMFG9].[dbo].[CUSTOMER] c
where not exists (select 1
                  from [VBSTEST].[dbo].[CUSTOMER] v6
                  where c.id = v6.id
                 );
</code>```

You can use left join/where in the outer query, if you prefer.  But a single table reference is sufficient for the not exists.

Title: Finding id's not in other table SQL

Body:
Help!

I am trying to find the customer that are in VBSTEST that are not in VMFG9. the tables have identical schema. Whenever i run the query i never get a result returning.

`SELECT [ROWID]
      ,[ID]
      ,[NAME]
      ,[ADDR_1]
      ,[ADDR_2]
      ,[ADDR_3]
      ,[CITY]
      ,[STATE]
      ,[ZIPCODE]
      ,[COUNTRY]
  FROM [VMFG9].[dbo].[CUSTOMER]
   where NOT EXISTS(
        select v6.[ID]
        from [VBSTEST].[dbo].[CUSTOMER] as v6
        left outer join [VMFG9].[dbo.CUSTOMER] as v9 on  v9.id = v6.[id]
        where v9.id is null);`

Body:
The subquery that you want doesn't use a join:

select . . .
from [VMFG9].[dbo].[CUSTOMER] c
where not exists (select 1
                  from [VBSTEST].[dbo].[CUSTOMER] v6
                  where c.id = v6.id
                 );

You can use left join/where in the outer query, if you prefer.  But a single table reference is sufficient for the not exists.


问:
Dropdown-menu width changes when other
 is added by jQuery
CODE :

```<code><head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script
    src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"
    integrity="sha256-eEa1kEtgK9ZL6h60VXwDsJ2rxYCwfxi40VZ9E0XwoEA="
    crossorigin="anonymous"></script>
</head>
<body>

<div class="dropdown bigdiv">
  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
    <span class="caret"></span></button>
  <ul class="dropdown-menu bigul">
    <li>
        <a href="#" id="open_input">open_input</a>
    </li>

    <ul class="list-group test">
    </ul>
  </ul>
</div>

</body>
<script>
    $(document).ready(function () {
        var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "Fortran",
        ];

        var ul_text = '    <li class="ui-widget">\n' +
            '<form role="form" style="">\n' +
            '                <div class="input-group input-group-sm" style="">\n' +
            '                  <input type="text" class="form-control" id="tags" placeholder="Enter email">\n' +
            '                </div>\n' +
            '              </form>\n' +
            '    </li>'

        $('#open_input').click(function (e) {
            $('.bigul').append(ul_text)
            $('#tags').autocomplete({
                    search: function(event, ui) {
                        $('.test').empty();
                    },
                    source: availableTags,
                    messages: {
                        noResults: '',
                        results: function() {}
                    }
                }).data('autocomplete')._renderItem = function(ul, item) {
                    return $('<li class="list-group-item"></li>')
                        .data('item.autocomplete', item)
                        .append(item.value)
                        .appendTo($('.test'));
                    };
            e.stopPropagation();
        });
    });
</script>
</code>```

jsfiddle : http://jsfiddle.net/uMqyn/919/

On that code, when I click #open_input, ul.dropdown-menu.bigul's width changes from 160px to 182px. As you can see on , If I click #open_input some
 is added.

Even I gave style="100%" to all elements of var ul_text, it does not works.

Question:

First Question : How can I make width will be the same as initial status? I want it to have the same width - 160px. It's main question.

Second Question : If it is possible, I want to follow width of <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example button. In other words, if width of button is 20px, dropdown-menu and other following
's width will be 20px width also.
But first question is most important to me. Second question is not as important as first one.

答:
you can use .one method:

```<code> $('#open_input').one('click', function(e) {
         $('.bigul').append(ul_text);
 ...
</code>```

Title: Dropdown-menu width changes when other <li> is added by jQuery

Body:
CODE :

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
    </button>

        open_input

jsfiddle : http://jsfiddle.net/uMqyn/919/

On that code, when I click #open_input, ul.dropdown-menu.bigul's width changes from 160px to 182px. As you can see on , If I click #open_input some
 is added.

Even I gave style="100%" to all elements of var ul_text, it does not works.

Question:

First Question : How can I make width will be the same as initial status? I want it to have the same width - 160px. It's main question.

Second Question : If it is possible, I want to follow width of <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example button. In other words, if width of button is 20px, dropdown-menu and other following
's width will be 20px width also.
But first question is most important to me. Second question is not as important as first one.

Body:
you can use .one method:

 $('#open_input').one('click', function(e) {
         $('.bigul').append(ul_text);
 ...


问:
How to find all occurrences of an element in a list
index() will give the first occurrence of an item in a list. Is there a neat trick which returns all indices in a list for an element?

答:
You can create a defaultdict</p>

```<code>from collections import defaultdict
d1 = defaultdict(int)      # defaults to 0 values for keys
unq = set(lst1)              # lst1 = [1, 2, 2, 3, 4, 1, 2, 7]
for each in unq:
      d1[each] = lst1.count(each)
else:
      print(d1)
</code>```

Body:
You can create a defaultdict

from collections import defaultdict
d1 = defaultdict(int)      # defaults to 0 values for keys
unq = set(lst1)              # lst1 = [1, 2, 2, 3, 4, 1, 2, 7]
for each in unq:
      d1[each] = lst1.count(each)
else:
      print(d1)


问:
Use bash variable in mongo eval command to insert data
I'm not an expert, but all I'm trying to do is run a command line command, get the numbers from it, put them in an array, and insert them into a mongo database with the eval option.

```<code>#!/bin/bash

results="$(speedtest-cli --simple | grep -o '[0-9]*')"
echo "${results[@]}"
mongo localhost:27017/ding --eval "db.lloll.insert({date:new Date(),resu:{ping:["${results[0]}","${results[1]}"],down:["${results[2]}","${results[3]}"],uplo:["${results[4]}","${results[5]}"]}})"
</code>```

This is what I'm running, and everytime I run into the error:

```<code>SyntaxError: missing } after property list
</code>```

But when I run it and insert the data using a hardcoded array it works and I don't understand why.

答:
Without going into the details of how you extract the numbers of interest from speedtest-cli output (speedtest-cli on my system maybe has different output than on your system; numbers include decimal point you don't grep), the problem is with splitting those numbers -- i.e. you don't explicitly store them into an array. You should try with array=(e1 e2 ..) construct:

```<code>results=( $(speedtest-cli --simple | grep -o '[0-9]*') )
</code>```

or with declare -a:

```<code>declare -a results=$(speedtest-cli --simple | grep -o '[0-9]*')
</code>```

If you don't store the result into an array, you can not index the numbers with ${results[i]}, as you are trying to do. Namely, what you are running right now with --eval is:

```<code>"db.lloll.insert({date:new Date(),resu:{ping:[46 677 9 18 0 07,],down:[,],uplo:[,]}})"
</code>```

Note the obvious syntax error due to ${results[0] containing all the numbers separated with space, instead of only the first number. But when you use the array, you get something like:

```<code>"db.lloll.insert({date:new Date(),resu:{ping:[46,677],down:[9,18],uplo:[0,07]}})"
</code>```

Your

```<code>echo "${results[@]}"
</code>```

has provided you with a clue -- it outputs one number per line (due to the quoting, newlines were preserved):

```<code>$ echo "${results[@]}"
46
677
9
18
0
07
</code>```

while if the results was really an array (as expected), the elements would have been joined on the first character in IFS, which is a space by default:

```<code>$ echo "${results[@]}"
46 677 9 18 0 07
</code>```

A safer (or more robust) way of inspecting the value of a variable is with declare -p:

```<code>$ declare -p results
declare -a results='([0]="46" [1]="677" [2]="9" [3]="18" [4]="0" [5]="07")'
</code>```

Body:
I'm not an expert, but all I'm trying to do is run a command line command, get the numbers from it, put them in an array, and insert them into a mongo database with the eval option.

#!/bin/bash

results="$(speedtest-cli --simple | grep -o '[0-9]*')"
echo "${results[@]}"
mongo localhost:27017/ding --eval "db.lloll.insert({date:new Date(),resu:{ping:["${results[0]}","${results[1]}"],down:["${results[2]}","${results[3]}"],uplo:["${results[4]}","${results[5]}"]}})"

This is what I'm running, and everytime I run into the error:

SyntaxError: missing } after property list

But when I run it and insert the data using a hardcoded array it works and I don't understand why.

Body:
Without going into the details of how you extract the numbers of interest from speedtest-cli output (speedtest-cli on my system maybe has different output than on your system; numbers include decimal point you don't grep), the problem is with splitting those numbers -- i.e. you don't explicitly store them into an array. You should try with array=(e1 e2 ..) construct:

results=( $(speedtest-cli --simple | grep -o '[0-9]*') )

or with declare -a:

declare -a results=$(speedtest-cli --simple | grep -o '[0-9]*')

If you don't store the result into an array, you can not index the numbers with ${results[i]}, as you are trying to do. Namely, what you are running right now with --eval is:

"db.lloll.insert({date:new Date(),resu:{ping:[46 677 9 18 0 07,],down:[,],uplo:[,]}})"

Note the obvious syntax error due to ${results[0] containing all the numbers separated with space, instead of only the first number. But when you use the array, you get something like:

"db.lloll.insert({date:new Date(),resu:{ping:[46,677],down:[9,18],uplo:[0,07]}})"

Your

echo "${results[@]}"

has provided you with a clue -- it outputs one number per line (due to the quoting, newlines were preserved):

$ echo "${results[@]}"
46
677
9
18
0
07

while if the results was really an array (as expected), the elements would have been joined on the first character in IFS, which is a space by default:

$ echo "${results[@]}"
46 677 9 18 0 07

A safer (or more robust) way of inspecting the value of a variable is with declare -p:

$ declare -p results
declare -a results='([0]="46" [1]="677" [2]="9" [3]="18" [4]="0" [5]="07")'


问:
How to send a two dimensional array over gdbus?
I'm trying to send a two dimendional array of strings over dbus.( I'm using the gdbus api, with gdbus-codegen).

I have defined the dbus interface as follows.

```<code><method name="foo">
            <arg name="count" direction="out" type="i" />
            <arg name="array" direction="out" type="a(ia(s))" />
</method>
</code>```

I'm trying to create the GVariant in the following manner:

```<code>GVariantBuilder *builder;
GVariant *variant;
builder = g_variant_builder_new(G_VARIANT_TYPE("a(ia(s))"));
for (int i = 0; i < count; i++)
{
    g_variant_builder_add(builder, "(ia(s))",
                          options[i].num_supported,
                          pack_string_array(options[i].num_supported, options[i].supported_values));
}

variant = g_variant_new("a(a(s))", builder);
my_interface_complete_foo(interface, invocation, count, variant);
</code>```

where pack_string_array packs an array of c style strings into a gvariant.

```<code>GVariant* pack_string_array(int num_val, char **val)
{
    GVariantBuilder *builder;
    GVariant *values;
    builder = g_variant_builder_new(G_VARIANT_TYPE("a(s)"));
    for (int i = 0; i < num_val; i++)
    {
        g_message("%s", val[i]);
        g_variant_builder_add(builder, "(s)", val[i]);
    }

    if (num_val == 0)
        g_variant_builder_add(builder, "(s)", "NA");

    values = g_variant_new("a(s)", builder);
    return values;
}
</code>```

However when I test it,the program crashes with the following errors:

```<code> GLib-CRITICAL **: g_variant_builder_end: assertion 'ensure_valid_builder (builder)' failed
g_variant_get_type: assertion 'value != NULL' failed
</code>```

How can I send a array of string arrays over the dbus?

答:
```<code>GVariantBuilder* builder = g_variant_builder_new(G_VARIANT_TYPE("a(ia(s))"));

for (int i = 0; i < count; i++) {

    GVariantBuilder* builderStr = g_variant_builder_new(G_VARIANT_TYPE("a(s)"));
    for (int j = 0; j < nr_of_string; j++) {
        g_variant_builder_add(builderStr, "(s)", "Test");
    }
    g_variant_builder_add(builder, "(ia(s))", 32, **builderStr**);
}

GVariant* retVariant = g_variant_builder_end(builder);
</code>```

Body:
I'm trying to send a two dimendional array of strings over dbus.( I'm using the gdbus api, with gdbus-codegen).

I have defined the dbus interface as follows.

<method name="foo">
            <arg name="count" direction="out" type="i" />
            <arg name="array" direction="out" type="a(ia(s))" />
</method>

I'm trying to create the GVariant in the following manner:

GVariantBuilder *builder;
GVariant *variant;
builder = g_variant_builder_new(G_VARIANT_TYPE("a(ia(s))"));
for (int i = 0; i < count; i++)
{
    g_variant_builder_add(builder, "(ia(s))",
                          options[i].num_supported,
                          pack_string_array(options[i].num_supported, options[i].supported_values));
}

variant = g_variant_new("a(a(s))", builder);
my_interface_complete_foo(interface, invocation, count, variant);

where pack_string_array packs an array of c style strings into a gvariant.

GVariant* pack_string_array(int num_val, char **val)
{
    GVariantBuilder *builder;
    GVariant *values;
    builder = g_variant_builder_new(G_VARIANT_TYPE("a(s)"));
    for (int i = 0; i < num_val; i++)
    {
        g_message("%s", val[i]);
        g_variant_builder_add(builder, "(s)", val[i]);
    }

    if (num_val == 0)
        g_variant_builder_add(builder, "(s)", "NA");

    values = g_variant_new("a(s)", builder);
    return values;
}

However when I test it,the program crashes with the following errors:

 GLib-CRITICAL **: g_variant_builder_end: assertion 'ensure_valid_builder (builder)' failed
g_variant_get_type: assertion 'value != NULL' failed

How can I send a array of string arrays over the dbus?


答:
I'm not that familiar with Java, but you can shorten it with for loop:

```<code>import java.util.Scanner;
import java.io.*;

public class score{

    public static void main (String[]args) {

        Scanner scan = new Scanner(System.in);

        int [] arrPlayer = new int[7];

        for(int i=0;i<7;i++) {
            System.out.println("Please Enter Your Score");
            arrPlayer[i]=scan.nextInt();
        }

        for(int i=0;i<7;i++) {
            System.out.println("Player " + i + " : Score: " + arrPlayer[i];
        }
    }
}
</code>```

Title: Using arrays to generate a players score

Body:
I'm trying to use the array method to keep track of scores on my game, I'm having difficulty in doing so when I try to compile and run.

import java.util.Scanner;
import java.io.*;

public class score
{

    public static void main (String[]args)
    {

    Scanner scan = new Scanner(System.in);

    int [] arrPlayer = new int[7];

    System.out.println("Please Enter Your Score");
    arrPlayer[0]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[1]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[2]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[3]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[4]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[5]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[6]=scan.nextInt();

    System.out.println("Player 1 : Score: "arrPlayer[0];
    System.out.println("Player 1 : Score: "arrPlayer[1];
    System.out.println("Player 1 : Score: "arrPlayer[2];
    System.out.println("Player 1 : Score: "arrPlayer[3];
    System.out.println("Player 1 : Score: "arrPlayer[4];
    System.out.println("Player 1 : Score: "arrPlayer[5];
    System.out.println("Player 1 : Score: "arrPlayer[6];

    for(int i=0;i<7;i++);

    }

}

Body:
I'm not that familiar with Java, but you can shorten it with for loop:

import java.util.Scanner;
import java.io.*;

public class score{

    public static void main (String[]args) {

        Scanner scan = new Scanner(System.in);

        int [] arrPlayer = new int[7];

        for(int i=0;i<7;i++) {
            System.out.println("Please Enter Your Score");
            arrPlayer[i]=scan.nextInt();
        }

        for(int i=0;i<7;i++) {
            System.out.println("Player " + i + " : Score: " + arrPlayer[i];
        }
    }
}


问:
Share instance inside local project with different modules
My project strucutred like following

```<code>myproj
   src
      server
         main.go
      helpres
          helper1.go
          helpr2.go
       utils
          utils1.go
          utils2.go
</code>```

This is the code in the main.go function

```<code>import “myproj/utils”
import “myproj/helpers”

var log obj    *obj

func init() {
    log = initLog()
    util.passLog(log)
    helper.passLog(log)
    //And then helper and util can use it ...is it the right way to do it ?
}

func main(){

    log.write()

}
</code>```

Now I was able to use obj1 inside the server -> main.go,
but I want to use the same instance also in helper1.go and utils2.go
instead create the new one on each module,(later on I call to some functiona from helper and util inside the server->main.go)
How should I do it in golfing?

答:
Sharing objects between modules isn't good aproach. In your example you are trying to initialize Logger. Look at implementation of GO built-in package log. Rather provide Api for rest of your modules.

But general approach would be something like this:

```<code>// Assume this is your logging tools package "internal/tools/logging"
package logging

// First you create local object reference in your logger source file:
var logger = NewLoggerInstance()

// Then you provide global api to use this local reference
func Configure(c Myconfig) { std = NewSpecialInstanceFromConfig(c) }

// Then you can provide actual functionality for other modules as part of Api
func Debug(args ...interface{}) {
   std.Debug(args...) // this will cal method of your internal logger reference stored in variable std
}

// Then other modules just import your package
import <PREFIX>/internal/tools/logging

// And use it like this
c := LoadConfigFromEnvironment()
logging.Configure(c)

logging.Debug("Debug log")
logging.Info("something else")
</code>```

And absolutely take a look at this project template.

EDIT:

Example of Configure() method.

```<code>package logging
// lets assume we have package config included, it contains a struct of our application config
func Configure(c config.Config){
   // new logger instance
   l := NewLoggerInstance()

   // check value from config
   if c.GetJsonLogFormat() {
       l.SetFormatter(JsonFormater{})
   }

   // some other settings
   l.SetSomething(c.GetSomething())
   // set global package variable
   logger = l
}
</code>```

Loading config from environment can this do for you.

Body:
My project strucutred like following

myproj
   src
      server
         main.go
      helpres
          helper1.go
          helpr2.go
       utils
          utils1.go
          utils2.go

This is the code in the main.go function

import “myproj/utils”
import “myproj/helpers”

var log obj    *obj

func init() {
    log = initLog()
    util.passLog(log)
    helper.passLog(log)
    //And then helper and util can use it ...is it the right way to do it ?
}

func main(){

    log.write()

}

Now I was able to use obj1 inside the server -> main.go,
but I want to use the same instance also in helper1.go and utils2.go
instead create the new one on each module,(later on I call to some functiona from helper and util inside the server->main.go)
How should I do it in golfing?

Body:
Sharing objects between modules isn't good aproach. In your example you are trying to initialize Logger. Look at implementation of GO built-in package log. Rather provide Api for rest of your modules.

But general approach would be something like this:

// Assume this is your logging tools package "internal/tools/logging"
package logging

// First you create local object reference in your logger source file:
var logger = NewLoggerInstance()

// Then you provide global api to use this local reference
func Configure(c Myconfig) { std = NewSpecialInstanceFromConfig(c) }

// Then you can provide actual functionality for other modules as part of Api
func Debug(args ...interface{}) {
   std.Debug(args...) // this will cal method of your internal logger reference stored in variable std
}

// Then other modules just import your package
import <PREFIX>/internal/tools/logging

// And use it like this
c := LoadConfigFromEnvironment()
logging.Configure(c)

logging.Debug("Debug log")
logging.Info("something else")

And absolutely take a look at this project template.

EDIT:

Example of Configure() method.

package logging
// lets assume we have package config included, it contains a struct of our application config
func Configure(c config.Config){
   // new logger instance
   l := NewLoggerInstance()

   // check value from config
   if c.GetJsonLogFormat() {
       l.SetFormatter(JsonFormater{})
   }

   // some other settings
   l.SetSomething(c.GetSomething())
   // set global package variable
   logger = l
}

Loading config from environment can this do for you.


答:
Your issue is that you are not concatenating the players score with the text:

```<code>System.out.println("Player 1 : Score: " + arrPlayer[0]);
</code>```

Also rather than laboriously typing out the same statement, why not do a loop to gather their scores:

```<code>int [] arrPlayer = new int[7];
for(int i=0; i<arrPlayer.length;i++){
    System.out.println("Please Enter Your Score");
    arrPlayer[i] = scan.nextInt();
}
</code>```

Body:
Your issue is that you are not concatenating the players score with the text:

System.out.println("Player 1 : Score: " + arrPlayer[0]);

Also rather than laboriously typing out the same statement, why not do a loop to gather their scores:

int [] arrPlayer = new int[7];
for(int i=0; i<arrPlayer.length;i++){
    System.out.println("Please Enter Your Score");
    arrPlayer[i] = scan.nextInt();
}


问:
Using MSHTML for the GUI in C++, is there perhaps a tutorial?
I would like to migrate my app to using MHTML for the GUI since it would be much easier to experiment with layouts without rewriting the C++ every time.

What I found is unfortunately not what I need, which are:

Feed it HTML from memory

Receive events such as onclick, etc., back in my C++ code

Manipulate it through the DOM, e.g., set the innerHtml of a particular element

答:
The ugly part is going to be receiving the events. Directly coding to the COM interface of MSHTML in C++ to attach logic to an HTML GUI is going to be pretty ugly if you do it "raw". You'll probably want a thin-ish layer of library code to sit between your application logic and HSHTML, to hide the COM-related plumming.

Ultimately this is a reinvention of things like Firefox's XUL - see http://en.wikipedia.org/wiki/XUL. You may find that more ready for use in this way. You'd be hosting the Gecko engine instead of MSHTML.

Or alternatively you could use WPF, which is again very similar. Given that you're on Windows (as you're happy with a dependency on MSHTML), you could write the GUI stuff in C# and bind it to the C++ code by exposing that with C++/CLI.

OwnerDisplayName: Earwicker


问:
WPF Sorting ItemsControl Binding
I am currently trying to sort a ItemsControl by Name.  Currently I have the list printing out but can't seem to order it on the Views side.  I have the ability to order it on the Control or model side but want it to work from the view.

My ItemsControl has a binding to AllJobTypes (a list of class JobTypes).  JobTypes has a property called Name that I would like to sort in the view.

I have some debug code in the XAML that Prints out the count of each object.  The first 2 print out 'fail' and the last one works correctly.  What can i do to order AllJobTypes on the view side?

```<code><UserControl.Resources>
    <converters:JobTypeCreditUnionCountConverter x:Key="JobTypeCreditUnionCountConverter" />
    <CollectionViewSource x:Key="cvs" Source="{Binding RelativeSource={RelativeSource
                        AncestorType=UserControl}, Path=AllJobTypes}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="Name"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</UserControl.Resources>
<StackPanel>

    <Label Foreground="SteelBlue" FontSize="20" FontWeight="Bold">Job Types</Label>
    <Label Content="{Binding AllJobTypes.Count, FallbackValue='fail'}" />  //Fail
    <Label Content="{Binding cvs.Count, FallbackValue='fail'}" />  //Fail
    <Label Content="{Binding RelativeSource={RelativeSource
                        AncestorType=UserControl}, Path=AllJobTypes}" /> //(Collection
    <ItemsControl ItemsSource="{Binding cvs}" >
        <ItemsControl.ItemTemplate>
        <DataTemplate>
                <Grid Margin="5">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="3*"/>
                        <ColumnDefinition Width="6*"/>
                        <ColumnDefinition Width="2*"/>
                        <ColumnDefinition Width="1*"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" Text="" />
                    <TextBox Grid.Column="1" Text="{Binding Name}" IsEnabled="False" />
</code>```

答:
Try:</p>

```<code><ItemsControl ItemsSource="{Binding Source={StaticResource cvs}}" >
</code>```

Title: WPF Sorting ItemsControl Binding

Body:
I am currently trying to sort a ItemsControl by Name.  Currently I have the list printing out but can't seem to order it on the Views side.  I have the ability to order it on the Control or model side but want it to work from the view.

My ItemsControl has a binding to AllJobTypes (a list of class JobTypes).  JobTypes has a property called Name that I would like to sort in the view.

I have some debug code in the XAML that Prints out the count of each object.  The first 2 print out 'fail' and the last one works correctly.  What can i do to order AllJobTypes on the view side?

<UserControl.Resources>
    <converters:JobTypeCreditUnionCountConverter x:Key="JobTypeCreditUnionCountConverter" />
    <CollectionViewSource x:Key="cvs" Source="{Binding RelativeSource={RelativeSource
                        AncestorType=UserControl}, Path=AllJobTypes}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="Name"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</UserControl.Resources>
<StackPanel>

    Job Types
      //Fail
      //Fail
     //(Collection
    <ItemsControl ItemsSource="{Binding cvs}" >
        <ItemsControl.ItemTemplate>
        <DataTemplate>
                <Grid Margin="5">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="3*"/>
                        <ColumnDefinition Width="6*"/>
                        <ColumnDefinition Width="2*"/>
                        <ColumnDefinition Width="1*"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" Text="" />
                    <TextBox Grid.Column="1" Text="{Binding Name}" IsEnabled="False" />

Body:
Try:

<ItemsControl ItemsSource="{Binding Source={StaticResource cvs}}" >