问:
Inserting JavaScript inside components in Angular
I would like to insert a  inside a .html component in an Angular project and I was wondering how it can be done.

It seems like any Javascript I insert into this component is just ignored.

答:
Yeah sure you can add javascript in Angular.You can make one external Javascript file and put all your code inside that file.For example you file is external.js in /app folder.And now you can access that file functions in Angular component.This is the easiest way I found. You can use import to include your external file. Code for that will be following.

```<code>import './external.js';
declare var myExtObject: any;
</code>```

Now use one variable here I named myExtObject to call External.js file function like following any where you want :

```<code>myExtObject.func1();
</code>```

Body:
Yeah sure you can add javascript in Angular.You can make one external Javascript file and put all your code inside that file.For example you file is external.js in /app folder.And now you can access that file functions in Angular component.This is the easiest way I found. You can use import to include your external file. Code for that will be following.

import './external.js';
declare var myExtObject: any;

Now use one variable here I named myExtObject to call External.js file function like following any where you want :

myExtObject.func1();


来源: stackexchange

问:
List all “.csv” filename and then enter corresponding the code to plot the graph
There is a folder which contains lot of data for example the folder contains ".html" files , ".jpeg" files, ".pdf"files, ".csv" files(There are plenty of ".csv" excel sheets in the folder containing different file names). Here is the code which list only csv files.

```<code>import os
path = "F:\\Users\\Desktop\\Data\\Summary"
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.csv' in file:
            files.append(os.path.join(r, file))
            test_folders = os.listdir(path)
for f in files:
    print(f)
file_code = int(input("Enter Corresponding code to plot: "))
</code>```

When i run the above code i get output as:

```<code>F:\\Users\\Desktop\\Data\\Summary\Test_Summary_1.csv
F:\\Users\\Desktop\\Data\\Summary\Test_Summary_2.csv
F:\\Users\\Desktop\\Data\\Summary\Test_Summary_3.csv
</code>```

Actually i want Output to be displayed as:

```<code>0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc
</code>```

How do i modify it to get as said above?? i will later use that code num to plot

答:
You can skip joining the paths.

import os
path = "F:\\Users\\Desktop\\Data\\Summary"
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.csv' in file:
            files.append(file)
for i, f in enumerate(files):
    print("%d-%s"%( i,f))
    csv_code = int(input("Enter corresponding code to plot: "))
    csv_path = os.path.join(path, files[csv_code])

    df = pd.read_csv(csv_path, header=None)
    #df1 = df[0:2]
    df1 = df.iloc[:,0:2]
    plt.plot(df1[0], df1[1])
```

ContentLicense: CC BY-SA 4.0

Body:
There is a folder which contains lot of data for example the folder contains ".html" files , ".jpeg" files, ".pdf"files, ".csv" files(There are plenty of ".csv" excel sheets in the folder containing different file names). Here is the code which list only csv files.

import os
path = "F:\\Users\\Desktop\\Data\\Summary"
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.csv' in file:
            files.append(os.path.join(r, file))
            test_folders = os.listdir(path)
for f in files:
    print(f)
file_code = int(input("Enter Corresponding code to plot: "))

When i run the above code i get output as:

F:\\Users\\Desktop\\Data\\Summary\Test_Summary_1.csv
F:\\Users\\Desktop\\Data\\Summary\Test_Summary_2.csv
F:\\Users\\Desktop\\Data\\Summary\Test_Summary_3.csv

Actually i want Output to be displayed as:

0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc

How do i modify it to get as said above?? i will later use that code num to plot


问:
How to extract lower and upper bound in numeric format from a confidence interval string?
Suppose a vector including some confidence intervals as below

```<code>confint <- c("[0.741 ; 2.233]", "[263.917 ; 402.154]", "[12.788 ; 17.975]", "[0.680 ; 2.450]", "[0.650 ; 1.827]", "[0.719 ; 2.190]")
</code>```

I want to have two new vectors one including the lower Limits in numeric format as

```<code>lower <- c(0.741, 263.917, 12.788, 0.680, 0.650 , 0.719)
</code>```

and othe including the upper Limits in numeric format like

```<code>upper <- c(2.233, 402.154, 17.975, 2.450, 1.827, 2.190)
</code>```

答:
```<code>mypattern <- '\\[(\\d+\\.\\d+) ; (\\d+\\.\\d+)\\]'
as.numeric(gsub(mypattern, '\\1', confint))
as.numeric(gsub(mypattern, '\\2', confint))
</code>```

Body:
Suppose a vector including some confidence intervals as below

confint <- c("[0.741 ; 2.233]", "[263.917 ; 402.154]", "[12.788 ; 17.975]", "[0.680 ; 2.450]", "[0.650 ; 1.827]", "[0.719 ; 2.190]")

I want to have two new vectors one including the lower Limits in numeric format as

lower <- c(0.741, 263.917, 12.788, 0.680, 0.650 , 0.719)

and othe including the upper Limits in numeric format like

upper <- c(2.233, 402.154, 17.975, 2.450, 1.827, 2.190)


问:
Notification with workManager
I'm creating application using PeriodicWorkRequest to execute or fire notification with content changing every day.
it work smoothly but i want to  test the content of next day, i search in this case but does not arrive to the best solution. i try to change the day in device but it still does not work</p>

```<code> val notificationWorkBuilderRepeated = PeriodicWorkRequest
            .Builder(Notification::class.java, 1, TimeUnit.DAYS)
            .setInputData(inputData)
            .build()

    WorkManager.getInstance().enqueue(notificationWorkBuilderRepeated)
</code>```

答:
As I have worked for first time with Work Manager I also got this problem for testing.

I have just decreased interval for 15 minutes and tested.

Currently its working fine for every hour.

You can also test it by giving 15 minutes (minimum interval) to test it.

Hope it will helps you. Thank you.

Title: Notification with workManager

Body:
I'm creating application using PeriodicWorkRequest to execute or fire notification with content changing every day.
it work smoothly but i want to  test the content of next day, i search in this case but does not arrive to the best solution. i try to change the day in device but it still does not work

 val notificationWorkBuilderRepeated = PeriodicWorkRequest
            .Builder(Notification::class.java, 1, TimeUnit.DAYS)
            .setInputData(inputData)
            .build()

    WorkManager.getInstance().enqueue(notificationWorkBuilderRepeated)


问:
Arrow key not working in component
I use the Gecko SDK, a component that allows you to view web pages.

I use this component to create an html editor.

This problem happens when going off editing web pages.

The problem is that the arrow keys and the tab does not work with my component. I tried to find an answer to this problem, but I didn't find one. I found a track here, but the function does not work.

Function Movement (dx, dy) does not exist. Thank you for helping me solve this problem.

```<code>Procedure Tform1.TraiteMessages(Var msg : TMsg; Var Handled: boolean);
var
  dx, dy : integer;
begin   dx: 0; dy := 0;
  With msg do
  begin
    IF Message = WM_KEYDOWN then
    Case  wparam of
      VK_LEFT  : dx := -1;
      VK_RIGHT : dx :=  1;
      VK_UP    : dy := -1;
      VK_DOWN  : dy :=  1;
    end;
  end;
  IF (dy = 0) AND (Dx = 0) then Handled := false else
  begin
    handled := true;     // message traité
    Mouvement(dx, dy)    // exécution du tracé
  end;
end;
</code>```

答:
```<code>Procedure Tform1.TraiteMessages(Var msg : TMsg; Var Handled: boolean);
var
  dx, dy : integer;
begin
  dx := 0;
  dy := 0;
  With msg do
  begin
    IF Message = WM_KEYDOWN then
    begin
      Case  wparam of
        VK_LEFT  : dx := -1;
        VK_RIGHT : dx :=  1;
        VK_UP    : dy := -1;
        VK_DOWN  : dy :=  1;
      end;
    end;
  end;
  Mouvement(dx, dy);
  Handled := ((dy <> 0) or (dx <> 0));
end;
</code>```

That cleans up your method... now, you should place a breakpoint on your IF statement, and another on your Case conditions to determine first and foremost if your message hook is ever being triggered, but also if the message being handled is what you would expect.

Does your component properly catch Key events? Do you have another visual component focused? Have you set your form's "KeyPreview" property to True?

You may also want to try using a TApplicationEvents control to deal with your key message hook (if your component is non-visual).

Take a look at this unit on my SVN repository (username and password are both "anon" without quotes) as it demonstrates how to intercept and handle key inputs even on non-visual components.

Hope this helps, and good luck!

ContentLicense: CC BY-SA 3.0

Title: Arrow key not working in component

Body:
I use the Gecko SDK, a component that allows you to view web pages.

I use this component to create an html editor.

This problem happens when going off editing web pages.

The problem is that the arrow keys and the tab does not work with my component. I tried to find an answer to this problem, but I didn't find one. I found a track here, but the function does not work.

Function Movement (dx, dy) does not exist. Thank you for helping me solve this problem.

Procedure Tform1.TraiteMessages(Var msg : TMsg; Var Handled: boolean);
var
  dx, dy : integer;
begin   dx: 0; dy := 0;
  With msg do
  begin
    IF Message = WM_KEYDOWN then
    Case  wparam of
      VK_LEFT  : dx := -1;
      VK_RIGHT : dx :=  1;
      VK_UP    : dy := -1;
      VK_DOWN  : dy :=  1;
    end;
  end;
  IF (dy = 0) AND (Dx = 0) then Handled := false else
  begin
    handled := true;     // message traité
    Mouvement(dx, dy)    // exécution du tracé
  end;
end;

Body:
Procedure Tform1.TraiteMessages(Var msg : TMsg; Var Handled: boolean);
var
  dx, dy : integer;
begin
  dx := 0;
  dy := 0;
  With msg do
  begin
    IF Message = WM_KEYDOWN then
    begin
      Case  wparam of
        VK_LEFT  : dx := -1;
        VK_RIGHT : dx :=  1;
        VK_UP    : dy := -1;
        VK_DOWN  : dy :=  1;
      end;
    end;
  end;
  Mouvement(dx, dy);
  Handled := ((dy <> 0) or (dx <> 0));
end;

That cleans up your method... now, you should place a breakpoint on your IF statement, and another on your Case conditions to determine first and foremost if your message hook is ever being triggered, but also if the message being handled is what you would expect.

Does your component properly catch Key events? Do you have another visual component focused? Have you set your form's "KeyPreview" property to True?

You may also want to try using a TApplicationEvents control to deal with your key message hook (if your component is non-visual).

Take a look at this unit on my SVN repository (username and password are both "anon" without quotes) as it demonstrates how to intercept and handle key inputs even on non-visual components.

Hope this helps, and good luck!


问:
How to Do 10-fold cross-validation with a test set size of in python
How to build a machine learning model for predicting the expected SpendValue for a customer Using the LinearRegression() function

Also measure the performance of the model using 10-fold cross-validation with a test set size of 20%.

```<code>X = sales.drop(['SpendValue'], axis=1).values
y = sales.SpendValue.values
print("The training dataset has {} examples and {} features.".format(X.shape[0], X.shape[1]))
lr = LinearRegression()
kfolds = KFold(n_splits=10, random_state=42, shuffle=False)
for train, test in kfolds.split(X):
    print("Train Index: ", train, "\n")
    print("Test Index: ", test)
</code>```

I am not sure where to mention the test Size and how to proceed further to Predict the expected Spendvalue for the customer and also to display the various performance measures

答:
I would like to start the explanation of cross validation and train & test splitting, which was explained here.

First, you have to do the train-test splitting (something like the following)

```<code>>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, test_size=0.20, random_state=42)
</code>```

Then do a cross validation of training dataset and also you have a test dataset of size 20% of the original dataset.

```<code>kfolds = KFold(n_splits=10, random_state=42, shuffle=False)
for train, test in kfolds.split(X_train):
    print("Train Index: ", train, "\n")
    print("Test Index: ", test)
</code>```

Body:
How to build a machine learning model for predicting the expected SpendValue for a customer Using the LinearRegression() function

Also measure the performance of the model using 10-fold cross-validation with a test set size of 20%.

X = sales.drop(['SpendValue'], axis=1).values
y = sales.SpendValue.values
print("The training dataset has {} examples and {} features.".format(X.shape[0], X.shape[1]))
lr = LinearRegression()
kfolds = KFold(n_splits=10, random_state=42, shuffle=False)
for train, test in kfolds.split(X):
    print("Train Index: ", train, "\n")
    print("Test Index: ", test)

I am not sure where to mention the test Size and how to proceed further to Predict the expected Spendvalue for the customer and also to display the various performance measures

Body:
I would like to start the explanation of cross validation and train & test splitting, which was explained here.

First, you have to do the train-test splitting (something like the following)

>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, test_size=0.20, random_state=42)

Then do a cross validation of training dataset and also you have a test dataset of size 20% of the original dataset.

kfolds = KFold(n_splits=10, random_state=42, shuffle=False)
for train, test in kfolds.split(X_train):
    print("Train Index: ", train, "\n")
    print("Test Index: ", test)


问:
Using sparse matrices with Keras and Tensorflow
My data can be viewed as a matrix of 10B entries (100M x 100), which is very sparse (< 1/100 * 1/100 of entries are non-zero).  I would like to feed the data into into a Keras Neural Network model which I have made, using a Tensorflow backend.

My first thought was to expand the data to be dense, that is, write out all 10B entries into a series of CSVs, with most entries zero.  However, this is quickly overwhelming my resources (even doing the ETL overwhelmed pandas and is causing postgres to struggle).  So I need to use true sparse matrices.

How can I do that with Keras (and Tensorflow)? While numpy doesn't support sparse matrices, scipy and tensorflow both do.  There's lots of discussion (e.g.  https://github.com/fchollet/keras/pull/1886 https://github.com/fchollet/keras/pull/3695/files https://github.com/pplonski/keras-sparse-check https://groups.google.com/forum/#!topic/keras-users/odsQBcNCdZg ) about this idea - either using scipy's sparse matrixcs or going directly to Tensorflow's sparse matrices.  But I can't find a clear conclusion, and I haven't been able to get anything to work (or even know clearly which way to go!).

How can I do this?

I believe there are two possible approaches:

Keep it as a scipy sparse matrix, then, when giving Keras a minibatch, make it dense

Keep it sparse all the way through, and use Tensorflow Sparse Tensors

I also think #2 is preferred, because you'll get much better performance all the way through (I believe), but #1 is probably easier and will be adequate.  I'll be happy with either.

How can either be implemented?

答:
This answer addresses the second approach mentioned in the question.
It is possible to use sparse matrices as inputs to a Keras model with the Tensorflow backend if you write a custom training loop. In the example below, the model takes a sparse matrix as an input and outputs a dense matrix.

from keras.layers import Dense, Input
from keras.models import Model
import scipy
import numpy as np

trainX = scipy.sparse.random(1024, 1024)
trainY = np.random.rand(1024, 1024)

inputs = Input(shape=(trainX.shape[1],), sparse=True)
outputs = Dense(trainY.shape[1], activation='softmax')(inputs)
model = Model(inputs=inputs, outputs=outputs)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

steps = 10
for i in range(steps):
  # For simplicity, we directly use trainX and trainY in this example
  # Usually, this is where batches are prepared
  print(model.train_on_batch(trainX, trainY))
# [3549.2546, 0.0]
# ...
# [3545.6448, 0.0009765625]
```

However, the usefulness of this approach depends on whether your model needs to densify the sparse matrix.
Indeed, the above model has one layer which transforms the sparse matrix into a dense one. This can be a problem if your sparse matrix doesn't fit in memory.

Body:
This answer addresses the second approach mentioned in the question.
It is possible to use sparse matrices as inputs to a Keras model with the Tensorflow backend if you write a custom training loop. In the example below, the model takes a sparse matrix as an input and outputs a dense matrix.

from keras.layers import Dense, Input
from keras.models import Model
import scipy
import numpy as np

trainX = scipy.sparse.random(1024, 1024)
trainY = np.random.rand(1024, 1024)

inputs = Input(shape=(trainX.shape[1],), sparse=True)
outputs = Dense(trainY.shape[1], activation='softmax')(inputs)
model = Model(inputs=inputs, outputs=outputs)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

steps = 10
for i in range(steps):
  # For simplicity, we directly use trainX and trainY in this example
  # Usually, this is where batches are prepared
  print(model.train_on_batch(trainX, trainY))
# [3549.2546, 0.0]
# ...
# [3545.6448, 0.0009765625]

However, the usefulness of this approach depends on whether your model needs to densify the sparse matrix.
Indeed, the above model has one layer which transforms the sparse matrix into a dense one. This can be a problem if your sparse matrix doesn't fit in memory.


问:
How to console.log number in the following format?
I'm trying to display numbers in the following format can you please tell me what is wrong?
Can not use div. As i'm printing this in the console.

I for n = 5:

```<code>           1

         1 2 1

       1 2 3 2 1

     1 2 3 4 3 2 1

   1 2 3 4 5 4 3 2 1
</code>```

I have tried the following code:

```<code>n = 10
for (var i = 1; i <= n; i++) {
  for (var j = 1; j <= i; j++) {
    console.log("0" + j + " ");
  }
  console.log("<br />");
}
</code>```

n = 10
for (var i = 1; i <= n; i++) {
  for (var j = 1; j <= i; j++) {
    console.log("0" + j + " ");
  }
  console.log("
");
}```
</div>
</div>
</p>

<p>But it displays something like this:</p>

```1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

1 2 3 4 5 6

1 2 3 4 5 6 7

1 2 3 4 5 6 7 8

1 2 3 4 5 6 7 8 9

1 2 3 4 5 6 7 8 9 10
```

答:
Here is the code for your Task. It takes numbers from 1 to declared. Also puts some space at the beginning of each row. You need to declare a string at the beginning of each row and then add all elements to it. When all loops are done, you can print it in console with console.log.

var n = 10 // Declaring number of rows

for (var i = 1; i <= n; i++) {
  var row = ''; //declaring text variable for current row

  for (var x = n - i; x >= 1; x--) {
    row += '  '; //adding spaces in begining of the row
  }

  for (var j = 1; j <= i; j++) {
    row += ' ' + j; // numbers which increase up to middle
  }

  for (var k = i - 1; k >= 1; k--) {
    row += ' ' + k; // adding rest of the numbers to the row
  }

  console.log(row); //displaying whole row
}```

Body:
I'm trying to display numbers in the following format can you please tell me what is wrong?
Can not use div. As i'm printing this in the console.

I for n = 5:

           1

         1 2 1

       1 2 3 2 1

     1 2 3 4 3 2 1

   1 2 3 4 5 4 3 2 1

I have tried the following code:

n = 10
for (var i = 1; i <= n; i++) {
  for (var j = 1; j <= i; j++) {
    console.log("0" + j + " ");
  }
  console.log("
");
}

n = 10
for (var i = 1; i <= n; i++) {
  for (var j = 1; j <= i; j++) {
    console.log("0" + j + " ");
  }
  console.log("
");
}

But it displays something like this:

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

1 2 3 4 5 6

1 2 3 4 5 6 7

1 2 3 4 5 6 7 8

1 2 3 4 5 6 7 8 9

1 2 3 4 5 6 7 8 9 10


问:
Top 10 records with sum of remaining records in others in SQL server
I have one table which consists of 4 Columns - (id int, location varchar (max), [date] datetime, Total_Sales Money) which consist of 20 records in output I want 11 rows in which top 10 rows as it is and 11th row should be sum of remaining rows i.e. from 11 to 20 in Other_Location. Please help me to get the query.

I want 11 rows in which top 10 rows as it is and 11th row should be sum of remaining rows

答:
I would use row_number() and conditional aggregation.  That way, you can do this with one group by:

```<code>select (case when seqnum <= 10 then id end) as id,
       max(case when seqnum <= 10 then location else 'All else' end) as location,
       max(case when seqnum <= 10 then datetime end) as datetime,
       sum(amount)
from (select t.*,
             row_number() over (order by amount desc) as seqnum
      from t
     ) t
group by (case when seqnum <= 10 then id end);
</code>```

Body:
I would use row_number() and conditional aggregation.  That way, you can do this with one group by:

select (case when seqnum <= 10 then id end) as id,
       max(case when seqnum <= 10 then location else 'All else' end) as location,
       max(case when seqnum <= 10 then datetime end) as datetime,
       sum(amount)
from (select t.*,
             row_number() over (order by amount desc) as seqnum
      from t
     ) t
group by (case when seqnum <= 10 then id end);


问:
One EBJ project include another EJB project, then javax.naming.NameAlreadyBoundException
I have deployed an EJB project (named A, having an ejb and an war modules) on my server (glassfish 3.0 on Redhat). Then my another EJB project (named B) needs to use functions of A's xxx-ejb module, so I included A's ejb module. While I deployed B on server, exceptions came:

```<code>
Exception while invoking class org.glassfish.ejb.startup.EjbDeployer load method
java.lang.RuntimeException: EJB Container initialization error
    at org.glassfish.ejb.startup.EjbApplication.loadContainers(EjbApplication.java:219)
    at org.glassfish.ejb.startup.EjbDeployer.load(EjbDeployer.java:197)
    at org.glassfish.ejb.startup.EjbDeployer.load(EjbDeployer.java:63)
    at org.glassfish.internal.data.ModuleInfo.load(ModuleInfo.java:175)
    at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:216)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:338)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:183)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:272)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:305)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:320)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1176)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$900(CommandRunnerImpl.java:83)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1224)
    at org.glassfish.admingui.common.util.LocalDeploymentFacility$LocalDFCommandRunner.run(LocalDeploymentFacility.java:138)
    at org.glassfish.deployment.client.AbstractDeploymentFacility.deploy(AbstractDeploymentFacility.java:350)
    at org.glassfish.admingui.common.util.DeployUtil.invokeDeploymentFacility(DeployUtil.java:89)
    at org.glassfish.admingui.common.util.DeployUtil.deploy(DeployUtil.java:66)
    at org.glassfish.admingui.common.handlers.DeploymentHandler.deploy(DeploymentHandler.java:186)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at com.sun.jsftemplating.layout.descriptors.handler.Handler.invoke(Handler.java:442)
    at com.sun.jsftemplating.layout.descriptors.LayoutElementBase.dispatchHandlers(LayoutElementBase.java:420)
    at com.sun.jsftemplating.layout.descriptors.LayoutElementBase.dispatchHandlers(LayoutElementBase.java:394)
    at com.sun.jsftemplating.layout.event.CommandActionListener.invokeCommandHandlers(CommandActionListener.java:150)
    at com.sun.jsftemplating.layout.event.CommandActionListener.processAction(CommandActionListener.java:98)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:772)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at com.sun.webui.jsf.component.WebuiCommand.broadcast(WebuiCommand.java:166)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
    at com.sun.webui.jsf.util.UploadFilter.doFilter(UploadFilter.java:223)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:239)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
    at java.lang.Thread.run(Thread.java:636)
Caused by: java.lang.RuntimeException: Error while binding JNDI name maintree.util.GetHourlyTrendRemote for EJB : GetHourlyTrend
    at com.sun.ejb.containers.BaseContainer.initializeHome(BaseContainer.java:1530)
    at com.sun.ejb.containers.StatelessSessionContainer.initializeHome(StatelessSessionContainer.java:197)
    at com.sun.ejb.containers.ContainerFactoryImpl.createContainer(ContainerFactoryImpl.java:161)
    at org.glassfish.ejb.startup.EjbApplication.loadContainers(EjbApplication.java:207)
    ... 66 more
Caused by: javax.naming.NameAlreadyBoundException: Use rebind to override
    at com.sun.enterprise.naming.impl.TransientContext.doBindOrRebind(TransientContext.java:275)
    at com.sun.enterprise.naming.impl.TransientContext.bind(TransientContext.java:214)
    at com.sun.enterprise.naming.impl.SerialContextProviderImpl.bind(SerialContextProviderImpl.java:79)
    at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.bind(LocalSerialContextProviderImpl.java:81)
    at com.sun.enterprise.naming.impl.SerialContext.bind(SerialContext.java:586)
    at com.sun.enterprise.naming.impl.SerialContext.bind(SerialContext.java:602)
    at javax.naming.InitialContext.bind(InitialContext.java:421)
    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.publishObject(GlassfishNamingManagerImpl.java:206)
    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.publishObject(GlassfishNamingManagerImpl.java:187)
    at com.sun.ejb.containers.BaseContainer$JndiInfo.publish(BaseContainer.java:5533)
    at com.sun.ejb.containers.BaseContainer.initializeHome(BaseContainer.java:1515)
    ... 69 more

</code>```

Thus the problem should be: how can I deploy the same EJB modules on a same glassfish server twice. Or how can I let B use A's ejb module without including it explicitly?

Thanks a lot,
Peter

答: You should not include EJBs of project A to Project B. You should only include Remote classes of Project A.</p>

Body:
I have deployed an EJB project (named A, having an ejb and an war modules) on my server (glassfish 3.0 on Redhat). Then my another EJB project (named B) needs to use functions of A's xxx-ejb module, so I included A's ejb module. While I deployed B on server, exceptions came:

Exception while invoking class org.glassfish.ejb.startup.EjbDeployer load method
java.lang.RuntimeException: EJB Container initialization error
    at org.glassfish.ejb.startup.EjbApplication.loadContainers(EjbApplication.java:219)
    at org.glassfish.ejb.startup.EjbDeployer.load(EjbDeployer.java:197)
    at org.glassfish.ejb.startup.EjbDeployer.load(EjbDeployer.java:63)
    at org.glassfish.internal.data.ModuleInfo.load(ModuleInfo.java:175)
    at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:216)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:338)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:183)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:272)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:305)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:320)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1176)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$900(CommandRunnerImpl.java:83)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1224)
    at org.glassfish.admingui.common.util.LocalDeploymentFacility$LocalDFCommandRunner.run(LocalDeploymentFacility.java:138)
    at org.glassfish.deployment.client.AbstractDeploymentFacility.deploy(AbstractDeploymentFacility.java:350)
    at org.glassfish.admingui.common.util.DeployUtil.invokeDeploymentFacility(DeployUtil.java:89)
    at org.glassfish.admingui.common.util.DeployUtil.deploy(DeployUtil.java:66)
    at org.glassfish.admingui.common.handlers.DeploymentHandler.deploy(DeploymentHandler.java:186)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at com.sun.jsftemplating.layout.descriptors.handler.Handler.invoke(Handler.java:442)
    at com.sun.jsftemplating.layout.descriptors.LayoutElementBase.dispatchHandlers(LayoutElementBase.java:420)
    at com.sun.jsftemplating.layout.descriptors.LayoutElementBase.dispatchHandlers(LayoutElementBase.java:394)
    at com.sun.jsftemplating.layout.event.CommandActionListener.invokeCommandHandlers(CommandActionListener.java:150)
    at com.sun.jsftemplating.layout.event.CommandActionListener.processAction(CommandActionListener.java:98)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:772)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at com.sun.webui.jsf.component.WebuiCommand.broadcast(WebuiCommand.java:166)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
    at com.sun.webui.jsf.util.UploadFilter.doFilter(UploadFilter.java:223)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:239)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
    at java.lang.Thread.run(Thread.java:636)
Caused by: java.lang.RuntimeException: Error while binding JNDI name maintree.util.GetHourlyTrendRemote for EJB : GetHourlyTrend
    at com.sun.ejb.containers.BaseContainer.initializeHome(BaseContainer.java:1530)
    at com.sun.ejb.containers.StatelessSessionContainer.initializeHome(StatelessSessionContainer.java:197)
    at com.sun.ejb.containers.ContainerFactoryImpl.createContainer(ContainerFactoryImpl.java:161)
    at org.glassfish.ejb.startup.EjbApplication.loadContainers(EjbApplication.java:207)
    ... 66 more
Caused by: javax.naming.NameAlreadyBoundException: Use rebind to override
    at com.sun.enterprise.naming.impl.TransientContext.doBindOrRebind(TransientContext.java:275)
    at com.sun.enterprise.naming.impl.TransientContext.bind(TransientContext.java:214)
    at com.sun.enterprise.naming.impl.SerialContextProviderImpl.bind(SerialContextProviderImpl.java:79)
    at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.bind(LocalSerialContextProviderImpl.java:81)
    at com.sun.enterprise.naming.impl.SerialContext.bind(SerialContext.java:586)
    at com.sun.enterprise.naming.impl.SerialContext.bind(SerialContext.java:602)
    at javax.naming.InitialContext.bind(InitialContext.java:421)
    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.publishObject(GlassfishNamingManagerImpl.java:206)
    at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.publishObject(GlassfishNamingManagerImpl.java:187)
    at com.sun.ejb.containers.BaseContainer$JndiInfo.publish(BaseContainer.java:5533)
    at com.sun.ejb.containers.BaseContainer.initializeHome(BaseContainer.java:1515)
    ... 69 more

Thus the problem should be: how can I deploy the same EJB modules on a same glassfish server twice. Or how can I let B use A's ejb module without including it explicitly?

Thanks a lot,
Peter


问:
Not able to write SQL query
I have a restriction table that stores coupon_id, restriction_value, and restriction_type.

```<code>coupon_id     restriction_value     restriction_type
-----------------------------------------
1             delhi                 city
2             delhi                 city
1             india                 country
</code>```

I want to return a query which gives me the coupon which is applicable for country India and for city Delhi.

答:
Select the coupons for city 'delhi' for which a record with country 'india' exists.

Something like this:

```<code>SELECT city.*
FROM   my_table city
WHERE  city.restriction_type = 'city'
  AND  city.restriction_value = 'delhi'
  AND  EXISTS (SELECT *
               FROM   my_table country
               WHERE  city.coupon_id = country.coupon_id
                 AND  country.restriction_type = 'country'
                 AND  country.restriction_value = 'india');
</code>```

Title: Not able to write SQL query

Body:
I have a restriction table that stores coupon_id, restriction_value, and restriction_type.

coupon_id     restriction_value     restriction_type
-----------------------------------------
1             delhi                 city
2             delhi                 city
1             india                 country

I want to return a query which gives me the coupon which is applicable for country India and for city Delhi.

Body:
Select the coupons for city 'delhi' for which a record with country 'india' exists.

Something like this:

SELECT city.*
FROM   my_table city
WHERE  city.restriction_type = 'city'
  AND  city.restriction_value = 'delhi'
  AND  EXISTS (SELECT *
               FROM   my_table country
               WHERE  city.coupon_id = country.coupon_id
                 AND  country.restriction_type = 'country'
                 AND  country.restriction_value = 'india');


问:
How can I use findstr with newline regular expression
I'm on windows dos prompt. I have log file which contains log like:

```<code>Timestamp: Order received for Item No. 26551
Timestamp: Exception: OutOfRangeException
Timestamp: Message: Inventory Item is not stock. Item No. 23423
Timestamp: Order received for Item No. 23341
</code>```

I want to extract all the item number who has give some sort of exception. I'm using findstr command for this. how can I use newline in my regular expression? I want to all lines which have Exception word and from next line the item no.

any help?

答:
If you can download tools, here's a Ruby for Windows command you can use.</p>

```<code>C:\work>ruby -ne "print gets.split.last if /Exception/" file
23423
C:\work>type file
Timestamp: Order received for Item No. 26551
Timestamp: Exception: OutOfRangeException
Timestamp: Message: Inventory Item is not stock. Item No. 23423
Timestamp: Order received for Item No. 23341

C:\work>ruby -ne "print gets.split.last if /Exception/" file
23423
</code>```

Body:
I'm on windows dos prompt. I have log file which contains log like:

Timestamp: Order received for Item No. 26551
Timestamp: Exception: OutOfRangeException
Timestamp: Message: Inventory Item is not stock. Item No. 23423
Timestamp: Order received for Item No. 23341

I want to extract all the item number who has give some sort of exception. I'm using findstr command for this. how can I use newline in my regular expression? I want to all lines which have Exception word and from next line the item no.

any help?

Body:
If you can download tools, here's a Ruby for Windows command you can use.

C:\work>ruby -ne "print gets.split.last if /Exception/" file
23423
C:\work>type file
Timestamp: Order received for Item No. 26551
Timestamp: Exception: OutOfRangeException
Timestamp: Message: Inventory Item is not stock. Item No. 23423
Timestamp: Order received for Item No. 23341

C:\work>ruby -ne "print gets.split.last if /Exception/" file
23423


问:
How to use Expanded in SingleChildScrollView?
How to use Expanded in SingleChildScrollView? I have a screen with Image.network, ListView.builder and Row (TextFormField and IconButton). I wrapped ListView with Expanded. How to wrap this column with SingleChildScrollView? I need to move screen when the keyboard is open to see what I am writing. When I wrap my column I have this error.

      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              child: GestureDetector(
                child:
                Image.network(
                  postOne.imageUrl,
                  fit: BoxFit.fitWidth,
                  height: MediaQuery
                      .of(context)
                      .size
                      .width,
                  width: MediaQuery
                      .of(context)
                      .size
                      .width,
                ),
                onLongPress: () {},
                onDoubleTap: () {},
              ),
            ),
            Expanded(
              //height: MediaQuery.of(context).size.width*0.33,
              child: ListView.builder(
                  itemCount: commentList.length,
                  itemBuilder: (context, position) {
                    return GestureDetector(
                        onLongPress: () {},
                        child: Card(
                          child: Padding(
                            padding: EdgeInsets.all(5.0),
                            child: new CheckboxListTile(
                                title: new Text(commentList
                                    .elementAt(position)
                                    .coment,
                                  style: TextStyle(fontSize: 18.0),),
                                value: values[commentList
                                    .elementAt(position)
                                    .coment],
                                onChanged: (bool value) {}),
                          ),
                        )
                    );
                  }
              ),
            ),
            Container(
              child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    new Flexible(
                      child: Theme(
                        data: new ThemeData(
                            brightness: Brightness.light,
                            primarySwatch: Colors.grey,
                            inputDecorationTheme: new InputDecorationTheme(
                              labelStyle: new TextStyle(
                                  color: Colors.black45, fontSize: 18.0
                              ),
                            )
                        ),
                        child: new Form(
                          key: _formKey,
                          child: new TextFormField(
                            validator: (value) {
                              if (value.isEmpty) {
                                return 'Please enter the comment';
                              }
                            },
                            controller: commentController,
                            decoration: new InputDecoration(
                              labelText: "Add comment",
                              //hintText: 'Add comment'
                            ),
                            keyboardType: TextInputType.text,
                          ),
                        ),
                      ),
                    ),
                    new Container(
                        margin: EdgeInsets.only(left: 10.0, top: 12.0),
                        child: new IconButton(
                            icon: new Icon(Icons.send, color: Colors.black,),
                            onPressed: () {}
                        )
                    ),
                  ]),
            ),
          ],
        ),
      ),
```
```I/flutter ( 6816): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 6816): The following assertion was thrown during performLayout():
I/flutter ( 6816): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I/flutter ( 6816): When a column is in a parent that does not provide a finite height constraint, for example if it is
I/flutter ( 6816): in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
I/flutter ( 6816): flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
I/flutter ( 6816): space in the vertical direction.
I/flutter ( 6816): These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
I/flutter ( 6816): cannot simultaneously expand to fit its parent.
I/flutter ( 6816): Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
I/flutter ( 6816): children (using Flexible rather than Expanded). This will allow the flexible children to size
I/flutter ( 6816): themselves to less than the infinite remaining space they would otherwise be forced to take, and
I/flutter ( 6816): then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
I/flutter ( 6816): constraints provided by the parent.
I/flutter ( 6816): The affected RenderFlex is:
I/flutter ( 6816):   RenderFlex#9f534 relayoutBoundary=up11 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816): The creator information is set to:
I/flutter ( 6816):   Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816):   _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816):   Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816):   ⋯
I/flutter ( 6816): The nearest ancestor providing an unbounded width constraint is:
I/flutter ( 6816):   _RenderSingleChildViewport#155d8 relayoutBoundary=up10 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816):   creator: _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816):   _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816):   Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816):   RepaintBoundary ← ⋯
I/flutter ( 6816):   parentData: <none> (can use size)
I/flutter ( 6816):   constraints: BoxConstraints(0.0<=w<=440.8, 0.0<=h<=649.3)
I/flutter ( 6816):   size: MISSING
I/flutter ( 6816): See also: https://flutter.dev/layout/
I/flutter ( 6816): If this message did not help you determine the problem, consider using debugDumpRenderTree():
I/flutter ( 6816):   https://flutter.dev/debugging/#rendering-layer
I/flutter ( 6816):   http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html
I/flutter ( 6816): If none of the above helps enough to fix this problem, please don't hesitate to file a bug:
I/flutter ( 6816):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 6816):

```

答:
The answer is in the error itself. When the column is inside a view that is scrollable, the column is trying to shrink-wrap its content but since you used Expanded as a child of the column it is working opposite to the column trying to shrink-wrap its children. This is causing this error because these two directives are completely opposite to each other.

As mentioned in the error logs try the following:

Consider setting mainAxisSize to MainAxisSize.min (for column) and using FlexFit.loose fits for the flexible(use Flexible rather than Expanded).

Body:
How to use Expanded in SingleChildScrollView? I have a screen with Image.network, ListView.builder and Row (TextFormField and IconButton). I wrapped ListView with Expanded. How to wrap this column with SingleChildScrollView? I need to move screen when the keyboard is open to see what I am writing. When I wrap my column I have this error.

      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              child: GestureDetector(
                child:
                Image.network(
                  postOne.imageUrl,
                  fit: BoxFit.fitWidth,
                  height: MediaQuery
                      .of(context)
                      .size
                      .width,
                  width: MediaQuery
                      .of(context)
                      .size
                      .width,
                ),
                onLongPress: () {},
                onDoubleTap: () {},
              ),
            ),
            Expanded(
              //height: MediaQuery.of(context).size.width*0.33,
              child: ListView.builder(
                  itemCount: commentList.length,
                  itemBuilder: (context, position) {
                    return GestureDetector(
                        onLongPress: () {},
                        child: Card(
                          child: Padding(
                            padding: EdgeInsets.all(5.0),
                            child: new CheckboxListTile(
                                title: new Text(commentList
                                    .elementAt(position)
                                    .coment,
                                  style: TextStyle(fontSize: 18.0),),
                                value: values[commentList
                                    .elementAt(position)
                                    .coment],
                                onChanged: (bool value) {}),
                          ),
                        )
                    );
                  }
              ),
            ),
            Container(
              child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    new Flexible(
                      child: Theme(
                        data: new ThemeData(
                            brightness: Brightness.light,
                            primarySwatch: Colors.grey,
                            inputDecorationTheme: new InputDecorationTheme(
                              labelStyle: new TextStyle(
                                  color: Colors.black45, fontSize: 18.0
                              ),
                            )
                        ),
                        child: new Form(
                          key: _formKey,
                          child: new TextFormField(
                            validator: (value) {
                              if (value.isEmpty) {
                                return 'Please enter the comment';
                              }
                            },
                            controller: commentController,
                            decoration: new InputDecoration(
                              labelText: "Add comment",
                              //hintText: 'Add comment'
                            ),
                            keyboardType: TextInputType.text,
                          ),
                        ),
                      ),
                    ),
                    new Container(
                        margin: EdgeInsets.only(left: 10.0, top: 12.0),
                        child: new IconButton(
                            icon: new Icon(Icons.send, color: Colors.black,),
                            onPressed: () {}
                        )
                    ),
                  ]),
            ),
          ],
        ),
      ),

I/flutter ( 6816): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 6816): The following assertion was thrown during performLayout():
I/flutter ( 6816): RenderFlex children have non-zero flex but incoming height constraints are unbounded.
I/flutter ( 6816): When a column is in a parent that does not provide a finite height constraint, for example if it is
I/flutter ( 6816): in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
I/flutter ( 6816): flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining
I/flutter ( 6816): space in the vertical direction.
I/flutter ( 6816): These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
I/flutter ( 6816): cannot simultaneously expand to fit its parent.
I/flutter ( 6816): Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
I/flutter ( 6816): children (using Flexible rather than Expanded). This will allow the flexible children to size
I/flutter ( 6816): themselves to less than the infinite remaining space they would otherwise be forced to take, and
I/flutter ( 6816): then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
I/flutter ( 6816): constraints provided by the parent.
I/flutter ( 6816): The affected RenderFlex is:
I/flutter ( 6816):   RenderFlex#9f534 relayoutBoundary=up11 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816): The creator information is set to:
I/flutter ( 6816):   Column ← _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816):   _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816):   Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816):   ⋯
I/flutter ( 6816): The nearest ancestor providing an unbounded width constraint is:
I/flutter ( 6816):   _RenderSingleChildViewport#155d8 relayoutBoundary=up10 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 6816):   creator: _SingleChildViewport ← IgnorePointer-[GlobalKey#3670d] ← Semantics ← Listener ←
I/flutter ( 6816):   _GestureSemantics ← RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#4878e] ←
I/flutter ( 6816):   Listener ← _ScrollableScope ← _ScrollSemantics-[GlobalKey#c5885] ← RepaintBoundary ← CustomPaint ←
I/flutter ( 6816):   RepaintBoundary ← ⋯
I/flutter ( 6816):   parentData: <none> (can use size)
I/flutter ( 6816):   constraints: BoxConstraints(0.0<=w<=440.8, 0.0<=h<=649.3)
I/flutter ( 6816):   size: MISSING
I/flutter ( 6816): See also: https://flutter.dev/layout/
I/flutter ( 6816): If this message did not help you determine the problem, consider using debugDumpRenderTree():
I/flutter ( 6816):   https://flutter.dev/debugging/#rendering-layer
I/flutter ( 6816):   http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html
I/flutter ( 6816): If none of the above helps enough to fix this problem, please don't hesitate to file a bug:
I/flutter ( 6816):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 6816):


问:
Including multiple non defined variables
I'm trying to make a simple Discord bot that will take input from users and output it as a new nickname for another user. It works, but the new nickname needs 3 words in it. Is there a way to make it work with any number of input variables?

It first only worked with 1 word, but now I'm trying to add several words with spaces between them. And that now works too, unless the new nickname consists of more or less than 3 words. I dont really know what I'm doing, and I'm rather surprised I even got this far

```<code>function navnCommand(arguments, message) {
if (message.content.startsWith(".navn")){
    let args = message.content.split(" ");
    let userMention = message.mentions.users.first();
    let userNick = args[2]+' '+args[3]+' '+args[4]
    if (userMention == null){
        message.channel.send("Ey, bruk .navn @person nyttnavn din jævel")
    } else {
        let userID = userMention.id
        message.guild.members.get(userID).setNickname(userNick);
</code>```

If the nickname lacks a variable, I get an "undefined" in the new nickname, and any more than 3 is then not included.

答:
Check your arguments not the concat. result</p>

```<code>   if (args.length < 3){
        message.channel.send("Ey, bruk .navn @person nyttnavn din jævel")
    } else {
        let userID = userMention.id
        message.guild.members.get(userID).setNickname(userNick);
}
</code>```

Body:
I'm trying to make a simple Discord bot that will take input from users and output it as a new nickname for another user. It works, but the new nickname needs 3 words in it. Is there a way to make it work with any number of input variables?

It first only worked with 1 word, but now I'm trying to add several words with spaces between them. And that now works too, unless the new nickname consists of more or less than 3 words. I dont really know what I'm doing, and I'm rather surprised I even got this far

function navnCommand(arguments, message) {
if (message.content.startsWith(".navn")){
    let args = message.content.split(" ");
    let userMention = message.mentions.users.first();
    let userNick = args[2]+' '+args[3]+' '+args[4]
    if (userMention == null){
        message.channel.send("Ey, bruk .navn @person nyttnavn din jævel")
    } else {
        let userID = userMention.id
        message.guild.members.get(userID).setNickname(userNick);

If the nickname lacks a variable, I get an "undefined" in the new nickname, and any more than 3 is then not included.

Body:
Check your arguments not the concat. result

   if (args.length < 3){
        message.channel.send("Ey, bruk .navn @person nyttnavn din jævel")
    } else {
        let userID = userMention.id
        message.guild.members.get(userID).setNickname(userNick);
}


问:
Clickhouse Kafka Engine: Materialized View benefits
In the documentation it shows a way to use a materialized view consuming from a KafkaEngine sending the data to a *MergeTree family table.

This has the benefit of, in case of changing of transformation logic, detach the table, make changes, and reattach.

However, if you're not applying logic to it (e.g. field type conversions) , does it make more sense to use the materialized view as destination, applying *MergeTree engine? i.e. removing the TO table part and sending queries to the materialized view.

I don't see this approach anywhere, though. I can see the loss in the flexibility, however, does this approach make sense at all? and what are the limitations of this approach?

答:
I'd say that it is basicaly the same.

The only difference is that without TO
 clause, ClickHouse creates table .inner.<mv name> and stores data there instead of storing it in
. Otherwise the behavior is the same AFAIK.

So to sum it up, I suppose it's better to use TO
 clause because you have better control over that table created. Also MVs in ClickHouse are not views nor tables but triggers. So I prefer to treat them that way and not expect them to be used to read data from them.

Body:
I'd say that it is basicaly the same.

The only difference is that without TO <table> clause, ClickHouse creates table .inner.<mv name> and stores data there instead of storing it in <table>. Otherwise the behavior is the same AFAIK.

So to sum it up, I suppose it's better to use TO <table> clause because you have better control over that table created. Also MVs in ClickHouse are not views nor tables but triggers. So I prefer to treat them that way and not expect them to be used to read data from them.


问:
Customising socket/close syscalls in boost::asio
I have a library which communicates with TCP and UDP sockets using boost::asio. This library is cross-platform and delegates some operations to the application using it via callbacks. In the case of sockets, the following must occur:

Library opens a socket (for an outbound connection).

Application receives a callback allowing it to customise behaviour

Library connects a socket and uses it

Application receives a callback allowing it to do any necessary cleanup

Library closes the socket

Here's how I thought I can achieve this:

class CustomizableTcpSocket {
public:
  template <typename T, typename U>
  auto async_connect(T&& endpoint, U&& handler) {
    boost::system::error_code ec;
    socket_.open(endpoint.protocol(), ec);
    native_code_.socket_did_open(socket_.native_handle());
    return socket_.async_connect(std::forward(handler));
  }

  // same for async_write_some as well
  template <typename... Args>
  auto async_read_some(Args&&... args) {
    return socket_.async_read_some(std::forward<Args>(args)...);
  }

  ~CustomizableTcpSocket() {
    if (socket_.is_open()) {
      native_code_.socket_will_close(socket_.native_handle());
    }
  }

private:
  NativeCode native_code_;
  boost::asio::ip::tcp::socket socket_;
};
```

What I'm finding is that asio is sometimes closing the socket (at the OS level) before my destructor fires.

Is there a way I can be notified of a socket closing before asio actually does it?

答:
ASIO has a debugging feature called handler tracking.

You could use it to intercept socket closures which are invoked as:

```<code>  BOOST_ASIO_HANDLER_OPERATION((reactor_.context(), "socket", &impl, impl.socket_, "close"));
</code>```

Just #define BOOST_ASIO_HANDLER_OPERATION(...) to whatever function you want called and in there check that arg 5 == "close".

Here's an example of how to use handler tracking.

For reference: the actual close() operation is not straightforward. Better to leave that as it is.

Body:
I have a library which communicates with TCP and UDP sockets using boost::asio. This library is cross-platform and delegates some operations to the application using it via callbacks. In the case of sockets, the following must occur:

Library opens a socket (for an outbound connection).

Application receives a callback allowing it to customise behaviour

Library connects a socket and uses it

Application receives a callback allowing it to do any necessary cleanup

Library closes the socket

Here's how I thought I can achieve this:

class CustomizableTcpSocket {
public:
  template <typename T, typename U>
  auto async_connect(T&& endpoint, U&& handler) {
    boost::system::error_code ec;
    socket_.open(endpoint.protocol(), ec);
    native_code_.socket_did_open(socket_.native_handle());
    return socket_.async_connect(std::forward(handler));
  }

  // same for async_write_some as well
  template <typename... Args>
  auto async_read_some(Args&&... args) {
    return socket_.async_read_some(std::forward<Args>(args)...);
  }

  ~CustomizableTcpSocket() {
    if (socket_.is_open()) {
      native_code_.socket_will_close(socket_.native_handle());
    }
  }

private:
  NativeCode native_code_;
  boost::asio::ip::tcp::socket socket_;
};

What I'm finding is that asio is sometimes closing the socket (at the OS level) before my destructor fires.

Is there a way I can be notified of a socket closing before asio actually does it?

Body:
ASIO has a debugging feature called handler tracking.

You could use it to intercept socket closures which are invoked as:

  BOOST_ASIO_HANDLER_OPERATION((reactor_.context(), "socket", &impl, impl.socket_, "close"));

Just #define BOOST_ASIO_HANDLER_OPERATION(...) to whatever function you want called and in there check that arg 5 == "close".

Here's an example of how to use handler tracking.

For reference: the actual close() operation is not straightforward. Better to leave that as it is.


问:
Getting "Cannot call a class as a function" in my React Project
I'm trying to add a React map component to my project but run into an error. I'm using Fullstack React's blog post as a reference. I tracked down where the error gets thrown in google_map.js line 83:

```<code>function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
    }
  }
</code>```

Here is my map component so far. The page loads just fine (without a map) when I comment out lines 58-60, the last three lines. edit: I made the changes that @Dmitriy Nevzorov suggested and it still gives me the same error.

```<code>import React from 'react'
import GoogleApiComponent from 'google-map-react'

export class LocationsContainer extends React.Component {
    constructor() {
        super()
    }
  render() {
    const style = {
        width: '100vw',
        height: '100vh'
    }
    return (
      <div style={style}>
        <Map google={this.props.google} />
      </div>
    )
  }
}

export class Map extends React.Component {
    componentDidUpdate(prevProps, prevState){
        if (prevProps.google !== this.props.google){
            this.loadMap();
        }
    }
    componentDidMount(){
        this.loadMap();
    }
    loadMap(){
        if (this.props && this.props.google){
            const {google} = this.props;
            const maps = google.maps;

            const mapRef = this.refs.map;
            const node = ReactDOM.findDOMNode(mapRef);

            let zoom = 14;
            let lat = 37.774929
            let lng = 122.419416
            const center = new maps.LatLng(lat, lng);
            const mapConfig = Object.assign({}, {
                center: center,
                zoom: zoom
            })
            this.map = new maps.Map(node, mapConfig)
        }
    }
    render() {
        return (
            <div ref='map'>
                Loading map...
            </div>
        )
    }
}

export default GoogleApiComponent({
  apiKey: MY_API_KEY
})(LocationsContainer)
</code>```

And here is where this map component gets routed in main.js:

```<code>import {render} from 'react-dom';
import React from 'react';
import Artists from './components/Artists'
import { Router, Route, Link, browserHistory } from 'react-router'
import Home from './components/HomePage'
import Gallery from './components/ArtGallery'
import ArtistPage from './components/ArtistPage'
import FavsPage from './components/FavsPage'
import LocationsContainer from './components/Locations'

//Create the route configuration
render((
  <Router history={browserHistory}>
    <Route path="/" component={Home} />
        <Route path="locations" component={LocationsContainer} />
        <Route path="artists" component={Artists} />
        <Route path="gallery" component={Gallery} />
      <Route path="favorites" component={FavsPage} />
      <Route path=":artistName" component={ArtistPage} />
  </Router>
), document.getElementById('app'))
</code>```

答:
Actually all the problem redux connect. solutions:

Correct:

```<code>export default connect(mapStateToProps, mapDispatchToProps)(PageName)
</code>```

Wrong & Bug:

```<code>export default connect(PageName)(mapStateToProps, mapDispatchToProps)
</code>```

Body:
I'm trying to add a React map component to my project but run into an error. I'm using Fullstack React's blog post as a reference. I tracked down where the error gets thrown in google_map.js line 83:

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
    }
  }

Here is my map component so far. The page loads just fine (without a map) when I comment out lines 58-60, the last three lines. edit: I made the changes that @Dmitriy Nevzorov suggested and it still gives me the same error.

import React from 'react'
import GoogleApiComponent from 'google-map-react'

export class LocationsContainer extends React.Component {
    constructor() {
        super()
    }
  render() {
    const style = {
        width: '100vw',
        height: '100vh'
    }
    return (

        <Map google={this.props.google} />

    )
  }
}

export class Map extends React.Component {
    componentDidUpdate(prevProps, prevState){
        if (prevProps.google !== this.props.google){
            this.loadMap();
        }
    }
    componentDidMount(){
        this.loadMap();
    }
    loadMap(){
        if (this.props && this.props.google){
            const {google} = this.props;
            const maps = google.maps;

            const mapRef = this.refs.map;
            const node = ReactDOM.findDOMNode(mapRef);

            let zoom = 14;
            let lat = 37.774929
            let lng = 122.419416
            const center = new maps.LatLng(lat, lng);
            const mapConfig = Object.assign({}, {
                center: center,
                zoom: zoom
            })
            this.map = new maps.Map(node, mapConfig)
        }
    }
    render() {
        return (

                Loading map...

        )
    }
}

export default GoogleApiComponent({
  apiKey: MY_API_KEY
})(LocationsContainer)

And here is where this map component gets routed in main.js:

import {render} from 'react-dom';
import React from 'react';
import Artists from './components/Artists'
import { Router, Route, Link, browserHistory } from 'react-router'
import Home from './components/HomePage'
import Gallery from './components/ArtGallery'
import ArtistPage from './components/ArtistPage'
import FavsPage from './components/FavsPage'
import LocationsContainer from './components/Locations'

//Create the route configuration
render((
  <Router history={browserHistory}>
    <Route path="/" component={Home} />
        <Route path="locations" component={LocationsContainer} />
        <Route path="artists" component={Artists} />
        <Route path="gallery" component={Gallery} />
      <Route path="favorites" component={FavsPage} />
      <Route path=":artistName" component={ArtistPage} />
  </Router>
), document.getElementById('app'))

Body:
Actually all the problem redux connect. solutions:

Correct:

export default connect(mapStateToProps, mapDispatchToProps)(PageName)

Wrong & Bug:

export default connect(PageName)(mapStateToProps, mapDispatchToProps)


问:
JMeter Post request - JSON parse error: Invalid UTF-8 start byte 0xb0
I am sending a post request with JSON as a body using JMeter.

I am getting Success response When I executed the same request using postman.

But using JMeter I am getting "JSON parse error: Invalid UTF-8 start byte 0xb0".

Based on the similar questions asked, It seems -(hyphen) causing problems but not 100% sure about that.

These are the Combination of headers I tried:

First

Content-type : application/json ;  charset=utf-8

Second

Content-type : application/json

Content-Encoding : utf-8

Below is JSON Body

```<code>{
   "note":"Test item note",
   "externalIds":[
      {
         "sourceId":"external-0",
         "value":"0003869",
         "type":{
            "key":"33501",
            "value":"Item #",
            "id":3686074
         },
         "_operation":0
      }
   ],
   "description":"TEST 16700654 ROTIS FC 2/5 LB",
   "country":"USA",
   "specialConditions":{
      "isHazmat":true,
      "isOdorSensitive":true
   },
   "status":{
      "code":{
         "id":538663,
         "key":"35001",
         "value":"active"
      }
   },
   "catchWeightType":{
      "id":538674,
      "key":"35051",
      "value":"Inbound"
   },
   "weights":[
      {
         "sourceId":"weights-0",
         "value":10,
         "type":{
            "key":"35301",
            "value":"Net Weight",
            "id":538701
         },
         "unit":{
            "key":"1520",
            "value":"lb"
         },
         "_operation":0
      }
   ],
   "packages":[
      {
         "sourceId":"package-0",
         "maxStackCount":25,
         "nmfc":"123",
         "nmfcSub":"chk87",
         "freightClass":{
            "id":100218,
            "value":"50",
            "key":"5100"
         },
         "value":{
            "value":100.5,
            "currency":{
               "id":100065,
               "value":"USD",
               "key":"1550"
            }
         },
         "temperature":{
            "unit":{
               "key":"1510",
               "value":"°F",
               "id":100058
            },
            "max":78,
            "min":-29.6
         },
         "weights":[
            {
               "unit":{
                  "key":"1520",
                  "value":"lb",
                  "id":100060
               },
               "value":100,
               "type":{
                  "key":"35303",
                  "value":"Tare Weight",
                  "id":538703
               },
               "sourceId":"weight-0",
               "_operation":0
            },
            {
               "unit":{
                  "key":"1520",
                  "value":"lb",
                  "id":100060
               },
               "value":298.7,
               "type":{
                  "key":"35301",
                  "value":"Net Weight",
                  "id":538701
               },
               "sourceId":"weight-1",
               "_operation":0
            }
         ],
         "packageUnit":{
            "key":"6022",
            "value":"cases",
            "id":114043
         },
         "isBaseUnit":true,
         "units":{
            "key":"1530",
            "value":"in",
            "id":100062
         },
         "height":8.813,
         "length":14.938,
         "width":9.438,
         "isStackable":true,
         "ti":13,
         "high":7,
         "_operation":0
      }
   ],
   "customId":"0006686",
   "is_odor_sensitive":true,
   "name":"TEST 16700654 ROTIS FC 2/5 LB",
   "location":{
      "id":632804
   },
   "shelfLife":{
      "value":365,
      "type":{
         "key":"35351",
         "value":"days",
         "id":538705
      }
   },
   "category":{
      "key":"22300",
      "value":"Other",
      "id":139708
   },
   "customer":{
      "id":476093
   }
}

</code>```

答:
Maybe you have a space or special character added. The following should work:

Add HTTP Header Manager under HTTP Request

Add in Name column: Content-Type

Add in Value column: application/json;charset=UTF-8

Body:
I am sending a post request with JSON as a body using JMeter.

I am getting Success response When I executed the same request using postman.

But using JMeter I am getting "JSON parse error: Invalid UTF-8 start byte 0xb0".

Based on the similar questions asked, It seems -(hyphen) causing problems but not 100% sure about that.

These are the Combination of headers I tried:

First

Content-type : application/json ;  charset=utf-8

Second

Content-type : application/json

Content-Encoding : utf-8

Below is JSON Body

{
   "note":"Test item note",
   "externalIds":[
      {
         "sourceId":"external-0",
         "value":"0003869",
         "type":{
            "key":"33501",
            "value":"Item #",
            "id":3686074
         },
         "_operation":0
      }
   ],
   "description":"TEST 16700654 ROTIS FC 2/5 LB",
   "country":"USA",
   "specialConditions":{
      "isHazmat":true,
      "isOdorSensitive":true
   },
   "status":{
      "code":{
         "id":538663,
         "key":"35001",
         "value":"active"
      }
   },
   "catchWeightType":{
      "id":538674,
      "key":"35051",
      "value":"Inbound"
   },
   "weights":[
      {
         "sourceId":"weights-0",
         "value":10,
         "type":{
            "key":"35301",
            "value":"Net Weight",
            "id":538701
         },
         "unit":{
            "key":"1520",
            "value":"lb"
         },
         "_operation":0
      }
   ],
   "packages":[
      {
         "sourceId":"package-0",
         "maxStackCount":25,
         "nmfc":"123",
         "nmfcSub":"chk87",
         "freightClass":{
            "id":100218,
            "value":"50",
            "key":"5100"
         },
         "value":{
            "value":100.5,
            "currency":{
               "id":100065,
               "value":"USD",
               "key":"1550"
            }
         },
         "temperature":{
            "unit":{
               "key":"1510",
               "value":"°F",
               "id":100058
            },
            "max":78,
            "min":-29.6
         },
         "weights":[
            {
               "unit":{
                  "key":"1520",
                  "value":"lb",
                  "id":100060
               },
               "value":100,
               "type":{
                  "key":"35303",
                  "value":"Tare Weight",
                  "id":538703
               },
               "sourceId":"weight-0",
               "_operation":0
            },
            {
               "unit":{
                  "key":"1520",
                  "value":"lb",
                  "id":100060
               },
               "value":298.7,
               "type":{
                  "key":"35301",
                  "value":"Net Weight",
                  "id":538701
               },
               "sourceId":"weight-1",
               "_operation":0
            }
         ],
         "packageUnit":{
            "key":"6022",
            "value":"cases",
            "id":114043
         },
         "isBaseUnit":true,
         "units":{
            "key":"1530",
            "value":"in",
            "id":100062
         },
         "height":8.813,
         "length":14.938,
         "width":9.438,
         "isStackable":true,
         "ti":13,
         "high":7,
         "_operation":0
      }
   ],
   "customId":"0006686",
   "is_odor_sensitive":true,
   "name":"TEST 16700654 ROTIS FC 2/5 LB",
   "location":{
      "id":632804
   },
   "shelfLife":{
      "value":365,
      "type":{
         "key":"35351",
         "value":"days",
         "id":538705
      }
   },
   "category":{
      "key":"22300",
      "value":"Other",
      "id":139708
   },
   "customer":{
      "id":476093
   }
}


问:
Hosted .Net application not able to access Google cloud VPC hosted Solr search
I have hosted the standalone version of Solr search on Google cloud VPC. When I am accessing the search from my .Net code, I am getting the result in these 3 scenarios:

From visual studio in debug mode.

From my site locally hosted on IIS.

From hitting the search URL in browser.

But when I am hosting my .Net code to cloud (Hostgator, Smarterasp) then I am not able to connect to google cloud. I am using RestSharp to consume the search API and No authentication is used in google VPC.

I have tried WebClient and HttpWebRequest in place of RestSharp but getting the same issue again.

答:
Can you clarify what do you mean when you are talking about hosted software on a Google Cloud VPC? Are you talking about a GCE instance using a VPC network with 'Solr search' standalone software installed? What do you mean when you are saying that you are not able to connect to google cloud when you are 'hosting' your .NET code to cloud? Are you trying to connect to a specific resource in GCP (e.g.: GCE instance, APP engine, Cloud SQL)? Are you using a Cloud VPN and you want to access from your on-premise site to a GCP service?

'The Virtual Private Cloud (VPC) provides networking functionality to
  Compute Engine virtual machine (VM) instances, GKE containers and App
  Engine Flex. VPC provides global, scalable, flexible networking for
  your cloud-based services.'

The VPC networks route, allow or deny network traffic, it's difficult to install software on it. Try to describe better your issue,e.g.: instance not accessible by API through Cloud VPN. If you are using an instance for your software:

Check if the instance has the correct configuration to use the API.

The firewall rules are allowing the network traffic to the correct IPs and Ports.

Check the routes from your on-premise site to the VPC network where the Solr instance is.


问:
Change the delete icon for material ui chip to a custom svg?
I would like to use a custom svg icon instead of the default delete icon for the material ui chip element.
Is this possible or would it be a new feature request?

I was only able to change the color of the icon but not the icon itself...

答:
```<code>import IconSVG from @materialui/icons/IconSVG

<Chip
  label="delete me"
  deleteIcon={<IconSVG />}
  onDelete={this.deleteMethod}
/>
</code>```

In the chip api of material ui there is a props : deleteIcon it allows to change the delete icon using onDelete

Body:
import IconSVG from @materialui/icons/IconSVG

<Chip
  label="delete me"
  deleteIcon={<IconSVG />}
  onDelete={this.deleteMethod}
/>

In the chip api of material ui there is a props : deleteIcon it allows to change the delete icon using onDelete


问:
Remote ipython kernel not displaying plots
My setup is that I run an ipython notebook remotely on a linux server and I connect to it from OSX via an ssh tunnel.

I can confirm that X forwarding works fine and from the same terminal where ipython is started from I can use gnuplot etc.

In the ipython session on my local machine when trying to do something like

```<code>import matplotlib as mpl
mpl.use("GTK3cairo")
import matplotlib.pyplot as plt
plt.plot([1,2,3,4],'*-')
</code>```

all I get is [<matplotlib.lines.Line2D at 0x54bcc90>]. I have tried various other backends, with the same results. When using %pylab inline the plots appear, but I'd like them in separate windows.

I suppose something is wrong with X forwarding still - what would be the best way to debug this? All suggestions welcome.

答:
When connecting to the server, use -L (which does local port forwarding) instead of -X (which does graphical output forwarding) like this:

```<code>ssh -L 8000:localhost:8888 your_user_name@your_server_ip
</code>```

In your code, use %matplotlib inline before you import the pyplot to load the backend upfront and end with ; like this:

```<code>%matplotlib inline
from matplotlib import pyplot as plt

plt.figure()
plt.imshow(sample_image)
plt.show();
</code>```

Body:
My setup is that I run an ipython notebook remotely on a linux server and I connect to it from OSX via an ssh tunnel.

I can confirm that X forwarding works fine and from the same terminal where ipython is started from I can use gnuplot etc.

In the ipython session on my local machine when trying to do something like

import matplotlib as mpl
mpl.use("GTK3cairo")
import matplotlib.pyplot as plt
plt.plot([1,2,3,4],'*-')

all I get is [<matplotlib.lines.Line2D at 0x54bcc90>]. I have tried various other backends, with the same results. When using %pylab inline the plots appear, but I'd like them in separate windows.

I suppose something is wrong with X forwarding still - what would be the best way to debug this? All suggestions welcome.

Body:
When connecting to the server, use -L (which does local port forwarding) instead of -X (which does graphical output forwarding) like this:

ssh -L 8000:localhost:8888 your_user_name@your_server_ip

In your code, use %matplotlib inline before you import the pyplot to load the backend upfront and end with ; like this:

%matplotlib inline
from matplotlib import pyplot as plt

plt.figure()
plt.imshow(sample_image)
plt.show();


问:
Java: Thread.currentThread().getName() returns "NO_THREAD_YET"
I have a webservice which runs a Thread pool on service startup like this:

```<code>ExecutorService threadPool = Executors.newFixedThreadPool(30);
threadPool.execute(new WorkerThread());
</code>```

The Workerthread class looks like this:

```<code>    class WorkerThread implements Runnable {

    public WorkerThread () {
    }

    @Override
    public void run() {
        String threadName = Thread.currentThread().getName()
    }
}
</code>```

Problem: Sometimes the threadname is NO_THREAD_YET and i cannot figured out the circumstances under which that happens.I guess the ExecutorService just does not have any free threats available,but why doesn't the pool throw an Exception when it is full and i try to add a new WorkerThread?

How can i make sure that Thread.currentThread().getName() always returns the id of a valid thread from the pool?

Edit: The class WorkerThread is my own implementation. This is just a reduced example code, as other arguments i pass to WorkerThread e.g. String variables are not connected to this problem.

答:
The reason is very likely that you rename a thread manually somewhere in your code, e.g. during some other task which runs in the same thread pool:

```<code>@Override
public void run() {
    // ...
    Thread.currentThread().setName("NO_THREAD_YET");
    // ...
}
</code>```

after that task is completed, the thread "returns" to the pool becoming available for other tasks, and when eventually requested, is produced such an output.

To get a unmodifiable thread id, use Thread#getId

Body:
I have a webservice which runs a Thread pool on service startup like this:

ExecutorService threadPool = Executors.newFixedThreadPool(30);
threadPool.execute(new WorkerThread());

The Workerthread class looks like this:

    class WorkerThread implements Runnable {

    public WorkerThread () {
    }

    @Override
    public void run() {
        String threadName = Thread.currentThread().getName()
    }
}

Problem: Sometimes the threadname is NO_THREAD_YET and i cannot figured out the circumstances under which that happens.I guess the ExecutorService just does not have any free threats available,but why doesn't the pool throw an Exception when it is full and i try to add a new WorkerThread?

How can i make sure that Thread.currentThread().getName() always returns the id of a valid thread from the pool?

Edit: The class WorkerThread is my own implementation. This is just a reduced example code, as other arguments i pass to WorkerThread e.g. String variables are not connected to this problem.

Body:
The reason is very likely that you rename a thread manually somewhere in your code, e.g. during some other task which runs in the same thread pool:

@Override
public void run() {
    // ...
    Thread.currentThread().setName("NO_THREAD_YET");
    // ...
}

after that task is completed, the thread "returns" to the pool becoming available for other tasks, and when eventually requested, is produced such an output.

To get a unmodifiable thread id, use Thread#getId


问:
Cosmos DB internal error when fetching documents
Using the Azure Cosmos DB Data Explorer shows me no values, even though I know there's data in it. When using my web app, I can see it inserts data. I can also verify this by querying db.files.stats().count from a local GUI. However at  any point in the UI where I try to read from the DB, it breaks -- seemingly the same issue as what I see in the GUIs I've tried to use.

Looking at the network tab in Chrome, I can see a failed request being sent to the https://portal-prod-northeurope-mongo.portal-prod-northeurope.p.azurewebsites.net endpoint whenever I try to refresh the result set.
The response it comes back with is

Command find failed: Unknown server error occurred when processing this request..

I get the same error when I query the db with a local GUI so I assume it's not directly related to the Azure Portal.
I have tried to delete and recreate the collections but to no avail.
When I run all this locally on the Cosmos DB emulator, it works just fine.

Collections are defined as such:

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'files' `
                                  --db-name $db `
                                  --partition-key-path '/p'

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'users' `
                                  --db-name $db

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'projects' `
                                  --db-name $db `
                                  --partition-key-path '/cb'
```

<p>and an example object is the following:</p>

<pre class="lang-cs prettyprint-override"><code>internal class File
{
    [JsonProperty(PropertyName = "id")]
    public Guid Id { get; set; }

    [JsonProperty(PropertyName = "of")]
    public string OriginalFilename { get; set; }

    [JsonProperty(PropertyName = "if")]
    public string InternalFilename { get; set; }

    [JsonProperty(PropertyName = "ua")]
    public DateTime UploadedAt { get; set; }

    [JsonProperty(PropertyName = "p")]
    public Guid ProjectId { get; set; }

    [JsonProperty(PropertyName = "su")]
    public string StorageUri { get; set; }

    [JsonProperty(PropertyName = "t")]
    public byte Type { get; set; }

    public override string ToString() => JsonConvert.SerializeObject(this);
}
</code>```

答:
Is there a data migration involved here...how is the data being created in Cosmos DB? Can you please provide a Json document example with all the system generated properties.
The Data Explorer issues tend to exist this migrated data where a predefined ID value is provided but doesn't match the format required by Cosmos DB. </p>

Body:
Using the Azure Cosmos DB Data Explorer shows me no values, even though I know there's data in it. When using my web app, I can see it inserts data. I can also verify this by querying db.files.stats().count from a local GUI. However at  any point in the UI where I try to read from the DB, it breaks -- seemingly the same issue as what I see in the GUIs I've tried to use.

Looking at the network tab in Chrome, I can see a failed request being sent to the https://portal-prod-northeurope-mongo.portal-prod-northeurope.p.azurewebsites.net endpoint whenever I try to refresh the result set.
The response it comes back with is

Command find failed: Unknown server error occurred when processing this request..

I get the same error when I query the db with a local GUI so I assume it's not directly related to the Azure Portal.
I have tried to delete and recreate the collections but to no avail.
When I run all this locally on the Cosmos DB emulator, it works just fine.

Collections are defined as such:

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'files' `
                                  --db-name $db `
                                  --partition-key-path '/p'

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'users' `
                                  --db-name $db

    az cosmosdb collection create --resource-group $resourceGroup `
                                  --name $dbService `
                                  --collection-name 'projects' `
                                  --db-name $db `
                                  --partition-key-path '/cb'

and an example object is the following:

internal class File
{
    [JsonProperty(PropertyName = "id")]
    public Guid Id { get; set; }

    [JsonProperty(PropertyName = "of")]
    public string OriginalFilename { get; set; }

    [JsonProperty(PropertyName = "if")]
    public string InternalFilename { get; set; }

    [JsonProperty(PropertyName = "ua")]
    public DateTime UploadedAt { get; set; }

    [JsonProperty(PropertyName = "p")]
    public Guid ProjectId { get; set; }

    [JsonProperty(PropertyName = "su")]
    public string StorageUri { get; set; }

    [JsonProperty(PropertyName = "t")]
    public byte Type { get; set; }

    public override string ToString() => JsonConvert.SerializeObject(this);
}


问:
Why does slides[i].frame print a different value than SlideScrollView.subviews[i].frame
I was trying to calculate the current visible "Slide" in my UIScrollView when I noticed this. I couldn't figure out why I am getting these values. Especially frame 2 & 3 show strange values.

can anyone tell me if and where I am wrong and how do I get the bottom values to match that of the top?

Here is my code :

```<code>{...}
for i in 0 ..< slides.count
        {
            slides[i].frame = CGRect(x:CONSTwid * CGFloat(i),y:0,width:CONSTwid+20,height : view.frame.height)
            print("slide \(i) frame : \(slides[i].frame)")
            SlideScrollView.addSubview(slides[i])
        }
        let container = CGRect(x: SlideScrollView.contentOffset.x, y: SlideScrollView.contentOffset.y, width: SlideScrollView.frame.size.width, height: SlideScrollView.frame.size.height)

//this was just to see the result (do not ask me to loop it...I know :-P)

        print("sr \(container)")
        print("srcz\(SlideScrollView.contentSize)")
        print("slide 0 frame \(SlideScrollView.subviews[0].frame)")
        print("slide 1 frame \(SlideScrollView.subviews[1].frame)")
        print("slide 2 frame \(SlideScrollView.subviews[2].frame)")

{...}
</code>```

here is the output :

Console Output :

Thanks in advance

答:
Since slides is an array of views you wan't to check then that is the array you need to use. Although subviews is opened property it can still hold views you should not be looking into. Basically any view can have any number of subviews for any reason. This may even vary between devices or OS versions.

In your case you seem to have an extra view of size 2.5 x 7 that looks like a very small view. Perhaps a scroll indicator?

Body:
I was trying to calculate the current visible "Slide" in my UIScrollView when I noticed this. I couldn't figure out why I am getting these values. Especially frame 2 & 3 show strange values.

can anyone tell me if and where I am wrong and how do I get the bottom values to match that of the top?

Here is my code :

{...}
for i in 0 ..< slides.count
        {
            slides[i].frame = CGRect(x:CONSTwid * CGFloat(i),y:0,width:CONSTwid+20,height : view.frame.height)
            print("slide \(i) frame : \(slides[i].frame)")
            SlideScrollView.addSubview(slides[i])
        }
        let container = CGRect(x: SlideScrollView.contentOffset.x, y: SlideScrollView.contentOffset.y, width: SlideScrollView.frame.size.width, height: SlideScrollView.frame.size.height)

//this was just to see the result (do not ask me to loop it...I know :-P)

        print("sr \(container)")
        print("srcz\(SlideScrollView.contentSize)")
        print("slide 0 frame \(SlideScrollView.subviews[0].frame)")
        print("slide 1 frame \(SlideScrollView.subviews[1].frame)")
        print("slide 2 frame \(SlideScrollView.subviews[2].frame)")

{...}

here is the output :

Console Output :

Thanks in advance


问:
How to return && object from function?
I have TTempTable class with move symantics. I wrote

```<code>TTempTable&& MyFunction() {
   TTempTable tmp = f(...);
   ...
   return std::move(tmp);
}
</code>```

and got no compiler errors.

Was this correct?

答:
No, it is not correct.

You're returning a reference to a local variable. That reference is dangling.

Like any dangling thing, the compiler won't [always] diagnose it for you.

Return by value, and remove the std::move (it's redundant and inhibits elision).

Title: How to return && object from function?

Body:
I have TTempTable class with move symantics. I wrote

TTempTable&& MyFunction() {
   TTempTable tmp = f(...);
   ...
   return std::move(tmp);
}

and got no compiler errors.

Was this correct?