问:
Gradient color in CSS with percentage
I have only basic knowledge on the CSS. I'm trying to give gradient color for one of my ITEM as per below guidelines and the gradient should be vertical.

I tried the below , but only the first color is coming all over the region. I dont understand that 30% and 50%. How to achieve this?

```<code> .myheader {
  background: linear-gradient(to bottom, #mycolor1 85%, #mycolor2 45%, #mycolor3 10%);
  }
</code>```

答:
The percent values must ascend in order. ( https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient )

```<code>$mycolor1: blue;
$mycolor2: purple;
$mycolor3: red;

.myheader {
background: linear-gradient(to bottom, $mycolor1 0%, $mycolor2 50%, $mycolor3 90%);
height: 200px;
width: 100px;
}
</code>```

https://jsfiddle.net/qa1kLmfc/3/

For your gradient you probably could use just blue and red.

Title: Gradient color in CSS with percentage

Body:
I have only basic knowledge on the CSS. I'm trying to give gradient color for one of my ITEM as per below guidelines and the gradient should be vertical.

I tried the below , but only the first color is coming all over the region. I dont understand that 30% and 50%. How to achieve this?

 .myheader {
  background: linear-gradient(to bottom, #mycolor1 85%, #mycolor2 45%, #mycolor3 10%);
  }

Body:
The percent values must ascend in order. ( https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient )

$mycolor1: blue;
$mycolor2: purple;
$mycolor3: red;

.myheader {
background: linear-gradient(to bottom, $mycolor1 0%, $mycolor2 50%, $mycolor3 90%);
height: 200px;
width: 100px;
}

https://jsfiddle.net/qa1kLmfc/3/

For your gradient you probably could use just blue and red.


来源: stackexchange

问:
Why do Python floats have real and imag attributes?
At least in Python 3, float has attributes real and imag, and a method conjugate(). Since issubclass(float, complex) evaluates to False, what is the reason for these?

答:
It is obviously a design choice and it is very well rooted in Python numeric types (i.e. bool, int, float, complex), as clear from the source code (e.g. for float).

This has been discussed in PEP 3141, which resulted in the numbers module for Numeric abstract base classes module.
As you can see, .real, .imag and .conjugate() are part of the generic Number abstraction.

From a practical perspective, this means that any numeric algorithm can be safely written for complex and it will gracefully work for any Number subtype.

ContentLicense: CC BY-SA 4.0


问:
How to protect global variables (window) from being overwritten
I am currently working on a project where security is very important. By default, all global variables/properties like Promise or even crypto can be overwritten.

Is there a way to protect them from being overwritten?

Example:

```<code>window.crypto.getRandomValues = () => { return [1] }

window.crypto.getRandomValues(new Uint32Array(1))[0] // 1
</code>```

My first thought was to use Object.freeze() to lock the object, but one can simply overwrite the Object.freeze method so it does nothing.

We are already very selective of the dependencies we use, but I would still like to make sure that those variables can not be overwritten. Or at least detect if they were overwritten.

答:
Disclaimer: All this is just a rough outline, not thoroughly tested. I'm sure there are more problems to solve.

freezing the window-object is no option, this would just cause problems, but maybe Objects like window.crypto?

But you can re-define properties to be no longer changeable, even on the window-object

```<code>function freezeProp(target, propertyName) {
  const { value, get = () => value, set = () => void 0, ...desc } = Object.getOwnPropertyDescriptor(target, propertyName);
  Object.defineProperty(target, propertyName, { ...desc, get, set, configurable: false });
}

freezeProp(window, "crypto");
</code>```

But these methods only work out if you can ensure that you are the first script to run.

Detecting if some methods have been changed is also just possible if you have a reference to them; and we're back at being the first script to run.

But if you're not sure wether the global scope has been spoiled, why not get a fresh window-object?

```<code>window.crypto.getRandomValues = () => {
  return [1]
};

const secure = (() => {
  let iframe = document.createElement("iframe");
  document.body.appendChild(iframe);
  const contentWindow = iframe.contentWindow;
  document.body.removeChild(iframe);
  return contentWindow;
})();

var a = window.crypto.getRandomValues(new Uint8Array(1));
console.log(a);

var b = secure.crypto.getRandomValues(new Uint8Array(1));
console.log(b);
</code>```

Body:
I am currently working on a project where security is very important. By default, all global variables/properties like Promise or even crypto can be overwritten.

Is there a way to protect them from being overwritten?

Example:

window.crypto.getRandomValues = () => { return [1] }

window.crypto.getRandomValues(new Uint32Array(1))[0] // 1

My first thought was to use Object.freeze() to lock the object, but one can simply overwrite the Object.freeze method so it does nothing.

We are already very selective of the dependencies we use, but I would still like to make sure that those variables can not be overwritten. Or at least detect if they were overwritten.

Body:
Disclaimer: All this is just a rough outline, not thoroughly tested. I'm sure there are more problems to solve.

freezing the window-object is no option, this would just cause problems, but maybe Objects like window.crypto?

But you can re-define properties to be no longer changeable, even on the window-object

function freezeProp(target, propertyName) {
  const { value, get = () => value, set = () => void 0, ...desc } = Object.getOwnPropertyDescriptor(target, propertyName);
  Object.defineProperty(target, propertyName, { ...desc, get, set, configurable: false });
}

freezeProp(window, "crypto");

But these methods only work out if you can ensure that you are the first script to run.

Detecting if some methods have been changed is also just possible if you have a reference to them; and we're back at being the first script to run.

But if you're not sure wether the global scope has been spoiled, why not get a fresh window-object?

window.crypto.getRandomValues = () => {
  return [1]
};

const secure = (() => {
  let iframe = document.createElement("iframe");
  document.body.appendChild(iframe);
  const contentWindow = iframe.contentWindow;
  document.body.removeChild(iframe);
  return contentWindow;
})();

var a = window.crypto.getRandomValues(new Uint8Array(1));
console.log(a);

var b = secure.crypto.getRandomValues(new Uint8Array(1));
console.log(b);


问:
Flutter showDialog(context) in initState method
I'm trying to use the showDialog(context, builder) to display a greeting message when the user navigates to a certain page.

I tried this by calling the showDialog in the initState method of a stateful widget on that page. While it does work, it appears I don't have access to the actual context.

Is there a way in Flutter to access the context in the initState() method?

If not, is there another way to achieve this behaviour in a better way?

```<code>@override
void initState() {
  super.initState();
  new Future.delayed(Duration.zero, () {
    showDialog(context: context,
    builder: (BuildContext context) {
      return new Container(child: new Text('foo'));
    });
  });
}
</code>```

答:
For newcomers, you have access to context in initState as others said. The only problem here in initState build function is not executed yet. So this context is kind of empty.

To solve this, you can use SchedulerBinding:

```<code>SchedulerBinding.instance.addPostFrameCallback((_) => doSomethingNextFrame(context));
</code>```

addPostFrameCallback: Schedule a callback for the end of this frame.

Future.delayed(Duration.zero) will also work. But I think SchedulerBinding looks cleaner.

Body:
I'm trying to use the showDialog(context, builder) to display a greeting message when the user navigates to a certain page.

I tried this by calling the showDialog in the initState method of a stateful widget on that page. While it does work, it appears I don't have access to the actual context.

Is there a way in Flutter to access the context in the initState() method?

If not, is there another way to achieve this behaviour in a better way?

@override
void initState() {
  super.initState();
  new Future.delayed(Duration.zero, () {
    showDialog(context: context,
    builder: (BuildContext context) {
      return new Container(child: new Text('foo'));
    });
  });
}

Body:
For newcomers, you have access to context in initState as others said. The only problem here in initState build function is not executed yet. So this context is kind of empty.

To solve this, you can use SchedulerBinding:

SchedulerBinding.instance.addPostFrameCallback((_) => doSomethingNextFrame(context));

addPostFrameCallback: Schedule a callback for the end of this frame.

Future.delayed(Duration.zero) will also work. But I think SchedulerBinding looks cleaner.


问:
How to flag items with repeated names and with condition its value less than 20?
Problem

How to return "True" for the repeated items and with both values less than 20?

```<code>=COUNTIF(A:A, A1)>1
</code>```

I am able to detect repeated items, but not sure how to combine another condition.

Expected Results

答:
My data sample is like this:

And the formula I've used is:

```<code>=IF(AND(COUNTIFS($A$2:$A$7;A2;$B$2:$B$7;"<"&20)=COUNTIFS($A$2:$A$7;A2);COUNTIFS($A$2:$A$7;A2)>1);TRUE;FALSE)
</code>```

I've used COUNTIFS.

COUNTIFS function

With COUNTIFS, I've counted how many cells share same letter and value <20, and I compare that count with counting how many cells share same letter only. If equal, it means all letters got value <20. Also, with the AND part, I've added a second condition, and it's checking if the count of cells with same letter is >1, to make sure this applies only to repeated values (X is 15, but not repeated, so it returns FALSE).

Hope you can adapt this to your needs.

Body:
Problem

How to return "True" for the repeated items and with both values less than 20?

=COUNTIF(A:A, A1)>1

I am able to detect repeated items, but not sure how to combine another condition.

Expected Results

Body:
My data sample is like this:

And the formula I've used is:

=IF(AND(COUNTIFS($A$2:$A$7;A2;$B$2:$B$7;"<"&20)=COUNTIFS($A$2:$A$7;A2);COUNTIFS($A$2:$A$7;A2)>1);TRUE;FALSE)

I've used COUNTIFS.

COUNTIFS function

With COUNTIFS, I've counted how many cells share same letter and value <20, and I compare that count with counting how many cells share same letter only. If equal, it means all letters got value <20. Also, with the AND part, I've added a second condition, and it's checking if the count of cells with same letter is >1, to make sure this applies only to repeated values (X is 15, but not repeated, so it returns FALSE).

Hope you can adapt this to your needs.


问:
GET multiselect selected values
I need to get the multiselect selected values:

With a simple select work fine with this method:

```<code>public function championships(Request $request)
{
   $nationId = $request->get('q');
   return Championship::where('nation_id', $nationId)->get(['id', 'name as text']);
}
</code>```

But I need to getall the selected values in the multiselect and pass it to the query using an array with the whereIn.

But I do not know how to capture the values of the multiselect

Thanks

答:
If you want multiselect you must tell laravel it is an array of values what that select box is about. You do that by appending "[]" to the name of the select box.

```<code><select name="q[]">
</code>```

Now, when the controller retrieves the value of this input, it will be in the form of an array, instead of an scalar value.

So, for the sake of clarity in your code, it should be like this:

```<code>$nationIds = $request->get('q');
</code>```

And now you want to choose from an array of values, not a single one, so now you need a "whereIn", instead of "where":

```<code>return Championship::whereIn('nation_id',$nationIds)->get(['id', 'name as text']);
</code>```

Title: GET multiselect selected values

Body:
I need to get the multiselect selected values:

With a simple select work fine with this method:

public function championships(Request $request)
{
   $nationId = $request->get('q');
   return Championship::where('nation_id', $nationId)->get(['id', 'name as text']);
}

But I need to getall the selected values in the multiselect and pass it to the query using an array with the whereIn.

But I do not know how to capture the values of the multiselect

Thanks

Body:
If you want multiselect you must tell laravel it is an array of values what that select box is about. You do that by appending "[]" to the name of the select box.

<select name="q[]">

Now, when the controller retrieves the value of this input, it will be in the form of an array, instead of an scalar value.

So, for the sake of clarity in your code, it should be like this:

$nationIds = $request->get('q');

And now you want to choose from an array of values, not a single one, so now you need a "whereIn", instead of "where":

return Championship::whereIn('nation_id',$nationIds)->get(['id', 'name as text']);


问:
JPA many to many mapping
I am trying to understand JPA many to many mapping from this link.
http://en.wikibooks.org/wiki/Java_Persistence/ManyToMany

However i have a hard time mapping my head around the following line

```<code>employee.getProjects().add(association);
</code>```

what should the method implementation for getProjects look like ?
It looks like there is a method chaining here  ?
Should getProjects return an ArrayList of project/s so we can invoke a add method on it ?

Should the getProjects be implemented in employee class ?

答:
look in this exemple: we consider that "employee" entity has many "projects" so as we represent it in java like ;

```<code> @OneToMany(mappedBy="employee")
 private List<ProjectAssociation> projects;
</code>```

so the function getProject() return list of "projects" associated to an "employee", so then we have to add an "association" to each "project" how ? : like this :

```<code>   employee.getProjects(); // to get "projects" of each "employee"
  employee.getProjects().add(assosiation); //to add an "association" for
   each "project"
</code>```

ContentLicense: CC BY-SA 3.0

Title: JPA many to many mapping

Body:
I am trying to understand JPA many to many mapping from this link.
http://en.wikibooks.org/wiki/Java_Persistence/ManyToMany

However i have a hard time mapping my head around the following line

employee.getProjects().add(association);

what should the method implementation for getProjects look like ?
It looks like there is a method chaining here  ?
Should getProjects return an ArrayList of project/s so we can invoke a add method on it ?

Should the getProjects be implemented in employee class ?

Body:
look in this exemple: we consider that "employee" entity has many "projects" so as we represent it in java like ;

 @OneToMany(mappedBy="employee")
 private List<ProjectAssociation> projects;

so the function getProject() return list of "projects" associated to an "employee", so then we have to add an "association" to each "project" how ? : like this :

   employee.getProjects(); // to get "projects" of each "employee"
  employee.getProjects().add(assosiation); //to add an "association" for
   each "project"


问:
Files with different headers to copy data in azure dwh table
I am new to the Azure Data Warehouse and Azure Data factory V2.

I Have a folder With 10 files in azure blob, Each file is having different headers but there will be a common 5 headers in all files.

Things I have tried,

Created 10 linked servers to the files and using copy data task moved the data to the specific tables.
But I required only 5 columns from those tables

Question

Is there any way that I can have a table with 5 columns and a dynamic file connection to load data from 5 files.

Example:
File1 : 10 headers
File2 : 11 headers
File3 : 7 headers
.
.
.
.
File10 : 15 headers

There will be a common of 5 columns in these files and that data has to be loaded common Table with 5 columns.

答:
You could adopt below idea:

1.Use LookUp Activity to grab the fileName list stored in your specific azure blob storage container or other paths. Please refer to this link.

2.Use ForEach Activity to loop the output of LookUp Activity[@activity('MyLookupActivity').output].

3.Inside the ForEach Activity, use copy activity and configure the source blob storage dataset path as  specific containerName/dynamic fileName.(Like the solution in this case:when try to add dynamic file name (linked server) in azure data factory V2 error encountered)


问:
reuse a calculated field in the same query
I have this query.

```<code>SELECT carte.nome, sum(amount) AS total, (1500-sum(amount)) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
</code>```

The goal of this query is to sum some amounts (sum(amount)) in a period of time. I also set a floor to this amount at 1500 so I want to do the math in the third field. I tried to do

```<code>SELECT carte.nome, sum(amount) AS total, (1500-total) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
</code>```

but mysql complains that totale is not a known field (it is a derived one).
The first query works but it is not efficient. What am I missing for the second one to work?

答:
You can use a Common Table Expression (CTE):

```<code>WITH cte_query AS (
SELECT carte.nome AS nome, sum(amount) AS total
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
)

SELECT nome, total, (1500- total) AS residuo
FROM cte_query
</code>```

Subquery would also work:

```<code>SELECT nome, total, (1500- total) AS residuo
FROM (
SELECT carte.nome AS nome, sum(amount) AS total
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
) A
</code>```

Body:
I have this query.

SELECT carte.nome, sum(amount) AS total, (1500-sum(amount)) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca

The goal of this query is to sum some amounts (sum(amount)) in a period of time. I also set a floor to this amount at 1500 so I want to do the math in the third field. I tried to do

SELECT carte.nome, sum(amount) AS total, (1500-total) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca

but mysql complains that totale is not a known field (it is a derived one).
The first query works but it is not efficient. What am I missing for the second one to work?

Body:
You can use a Common Table Expression (CTE):

WITH cte_query AS (
SELECT carte.nome AS nome, sum(amount) AS total
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
)

SELECT nome, total, (1500- total) AS residuo
FROM cte_query

Subquery would also work:

SELECT nome, total, (1500- total) AS residuo
FROM (
SELECT carte.nome AS nome, sum(amount) AS total
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
) A


问:
Accuracy graph for neural network is fluctuating a lot
I've made a neural network and it's architecture is as follows:

It has two two branches that are merged. One branch takes matrices as an input to a convolutional network and other branch is a fully connected layer that takes a vector as an input. These two branches are merged and send to a fully connected layer followed by a output layer. My network runs, however, I get the following graphs:

For accuracy:

For Loss:

I think my loss graph is alright. But the accuracy fun is fluctuating a lot. My overall accuracy is 60%. Do you think these graphs suggests under-fitting or it's normal?  Insights would be appreciated.

答:
It is a common behaviour to have fluctuations due to batch training. A perfect smooth loss graph/increase in accuracy would be obtained if and only if the neural network would be fed the entire dataset (this is impossible from a computational viewpoint).

When your training loss increases, the validation accuracy decreases, which is a good sign. The last graph together with my previous observation eliminates the possibility of overfitting(at least on the development set).

The graphs do not look out of the ordinary (except for those spikes that I have already mentioned, it is normal to have them during batch training)

It may or may not be the case of underfitting. If using more complex neural networks on both branches(on even on one of the branch) gives you a better result, then this means that it is a case of underfitting.

However, this underfitting phenomenon has nothing to do with the spikes that you see on the graphs.

Hope this helps you with your problem :)


问:
How to do matrix-scalar multiplication in TensorFlow?
What would be the best way to multiply a matrix by a scalar in TensorFlow?
I simply want to scale up the matrix by some scalar value.

Thanks!

Body:
Equivalent variants:

x = tf.constant([[1.0, 0.0], [0.0, 1.0]]
y1 = tf.scalar_mul(-1.0, x)
y2 = tf.multiply(-1.0, x)
y3 = -1.0 * x

Output:

sess.run(y1)
array([[-1., -0.],
       [-0., -1.]], dtype=float32)

sess.run(y2)
array([[-1., -0.],
       [-0., -1.]], dtype=float32)

sess.run(y3)
array([[-1., -0.],
       [-0., -1.]], dtype=float32)


问:
Need to remove unwanted symbols from value using replaceAll method
I am getting the value of a field as ["value"]
I  want to print only the  value removing the [ "from the result value.</p>

答:
The following script should be what you need</p>

```<code>def str = '["value"]'
println(str.replaceAll(/\[|\]/,''))
</code>```

Body:
The following script should be what you need

def str = '["value"]'
println(str.replaceAll(/\[|\]/,''))


问:
How to create a txt file with a String content and download that txt file
I am using java and struts. I have a scenario where there is 'Download' link in the page. After clicking on this link the control goes to the Action class, where I have String content which I need to write to a .txt file and then download that txt file.

Eventually whenever we click on the download link, we should be able to download a txt file having content a particular string.

I used below piece of code,

```<code>FileOutputStream outputStream = new FileOutputStream(fileNameWithDirectory);
outputStream.write(fileContentString.getBytes());
outputStream.close();
ActionForward forward = new ActionForward("doc/" + filename);
forward.setName(filename);
forward.setRedirect(true);
return forward;
</code>```

Also I tried with FileWriter in place of FileOutputStream like,

```<code>FileWriter fileWriter = new FileWriter(fileNameWithDirectory);
fileWriter.write(fileContentString);
fileWriter.flush();
fileWriter.close();
</code>```

But always instead of downloading the txt file, the control opens a new window where the String content is written.
Please suggest me, how would I able to download that .txt file.

答:
You should add Content-Disposition: attachment to say browser, that it should download the file, not to open it.

See more details here

Also Struts has DownloadAction, you may use it as well.

Body:
I am using java and struts. I have a scenario where there is 'Download' link in the page. After clicking on this link the control goes to the Action class, where I have String content which I need to write to a .txt file and then download that txt file.

Eventually whenever we click on the download link, we should be able to download a txt file having content a particular string.

I used below piece of code,

FileOutputStream outputStream = new FileOutputStream(fileNameWithDirectory);
outputStream.write(fileContentString.getBytes());
outputStream.close();
ActionForward forward = new ActionForward("doc/" + filename);
forward.setName(filename);
forward.setRedirect(true);
return forward;

Also I tried with FileWriter in place of FileOutputStream like,

FileWriter fileWriter = new FileWriter(fileNameWithDirectory);
fileWriter.write(fileContentString);
fileWriter.flush();
fileWriter.close();

But always instead of downloading the txt file, the control opens a new window where the String content is written.
Please suggest me, how would I able to download that .txt file.


问:
How to find a key in multidimensional array?
I have a  multidimensional array and i need make a searchCategory($categories, $id) function, which have to return a value of 'title' properties.

it try this code, it work but only for one layer of multidimensional array.

Multidimensional array:

```<code>$categories = array(    array(
    "id" => 1,
    "title" =>  "Обувь",
    'children' => array(
        array(
            'id' => 2,
            'title' => 'Ботинки',
            'children' => array(
                array('id' => 3, 'title' => 'Кожа'),
                array('id' => 4, 'title' => 'Текстиль'),
            ),
        ),
        array('id' => 5, 'title' => 'Кроссовки',),
    )),     array(
    "id" => 6,
    "title" =>  "Спорт",
    'children' => array(
        array(
            'id' => 7,
            'title' => 'Мячи'
        )
    )   ), );
</code>```

Code which i try solve problem:

```<code>function searchCategory($categories, $id) {

    foreach($categories as $category) {

        if($category['id'] == $id) {

            echo $category['title'] . '<br>';

        }
    }
};
</code>```

I need my function to look up the id value in all arrays and return the title in the case of the array found

答:
you need to make your function recursively

Demo : https://3v4l.org/CR7CD

```<code>function searchCategory($categories, $id) {
    foreach($categories as $category) {
        if($category['id'] == $id)
            echo $category['title'] . '<br>';
        if(isset($category['children']))
            searchCategory($category['children'],$id);
    }
}
</code>```

Body:
I have a  multidimensional array and i need make a searchCategory($categories, $id) function, which have to return a value of 'title' properties.

it try this code, it work but only for one layer of multidimensional array.

Multidimensional array:

$categories = array(    array(
    "id" => 1,
    "title" =>  "Обувь",
    'children' => array(
        array(
            'id' => 2,
            'title' => 'Ботинки',
            'children' => array(
                array('id' => 3, 'title' => 'Кожа'),
                array('id' => 4, 'title' => 'Текстиль'),
            ),
        ),
        array('id' => 5, 'title' => 'Кроссовки',),
    )),     array(
    "id" => 6,
    "title" =>  "Спорт",
    'children' => array(
        array(
            'id' => 7,
            'title' => 'Мячи'
        )
    )   ), );

Code which i try solve problem:

function searchCategory($categories, $id) {

    foreach($categories as $category) {

        if($category['id'] == $id) {

            echo $category['title'] . '
';

        }
    }
};

I need my function to look up the id value in all arrays and return the title in the case of the array found

Body:
you need to make your function recursively

Demo : https://3v4l.org/CR7CD

function searchCategory($categories, $id) {
    foreach($categories as $category) {
        if($category['id'] == $id)
            echo $category['title'] . '<br>';
        if(isset($category['children']))
            searchCategory($category['children'],$id);
    }
}


答:
You don't need to write the file and then redirect to it. You can set a http response header called Content-Disposition and then print your data into the http response body.

use it like this

```<code>response.addHeader("Content-Disposition", "Content-Disposition: attachment; filename=\""+filename+"\"");
</code>```

of course this depends on which technology stack you're using.

Title: How to create a txt file with a String content and download that txt file

Body:
You don't need to write the file and then redirect to it. You can set a http response header called Content-Disposition and then print your data into the http response body.

use it like this

response.addHeader("Content-Disposition", "Content-Disposition: attachment; filename=\""+filename+"\"");

of course this depends on which technology stack you're using.


问:
The performance impact of using instanceof in Java
I am working on an application and one design approach involves extremely heavy use of the instanceof operator. While I know that OO design generally tries to avoid using instanceof, that is a different story and this question is purely related to performance. I was wondering if there is any performance impact? Is is just as fast as ==?

For example, I have a base class with 10 subclasses. In a single function that takes the base class, I do checks for if the class is an instance of the subclass and carry out some routine.

One of the other ways I thought of solving it was to use a "type id" integer primitive instead, and use a bitmask to represent categories of the subclasses, and then just do a bit mask comparison of the subclasses "type id" to a constant mask representing the category.

Is instanceof somehow optimized by the JVM to be faster than that? I want to stick to Java but the performance of the app is critical. It would be cool if someone that has been down this road before could offer some advice. Am I nitpicking too much or focusing on the wrong thing to optimize?

答: With regard to Peter Lawrey's note that you don't need instanceof for final classes and can just use a reference equality, be careful!  Even though the final classes cannot be extended, they are not guaranteed to be loaded by the same classloader.  Only use x.getClass() == SomeFinal.class or its ilk if you are absolutely positive that there is only one classloader in play for that section of code.</p>

OwnerDisplayName: Josh

OwnerDisplayName: Miles Elam

ContentLicense: CC BY-SA 2.5


问:
Syntax error "Missing keyword" in case statement in WHERE clause
I am having some syntax error in my case statement where I am checking below condition:

```<code>((RAP10B.CLMSRC = '2', RAP01.EFFDT - 3 years <= RAP10.LOSSDT < RAP01.EFFDT)
       OR
(RAP10B.CLMSRC <> '2', RAP01.EFFDT - 3 years <= RAP10.LOSSDT < RAP01.EFFDT - 60 days)
</code>```

Below is the code what I am using.

```<code>CASE
  WHEN RAP10B.CLMSRC = '2'
  THEN rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND rap01.teffdt_t
  WHEN RAP10B.CLMSRC <> '2'
  THEN rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND (rap01.teffdt_t - 60)
END
</code>```

The error message is  "ORA-00905: missing keyword". But I am not able to find the missing thing.

答:
It's generally much better to use AND/OR constructions in the WHERE clause instead of case expressions:

```<code>WHERE (RAP10B.CLMSRC = '2'
       AND rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND rap01.teffdt_t)
   OR (RAP10B.CLMSRC <> '2'
       AND rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND (rap01.teffdt_t - 60))
</code>```

Body:
I am having some syntax error in my case statement where I am checking below condition:

((RAP10B.CLMSRC = '2', RAP01.EFFDT - 3 years <= RAP10.LOSSDT < RAP01.EFFDT)
       OR
(RAP10B.CLMSRC <> '2', RAP01.EFFDT - 3 years <= RAP10.LOSSDT < RAP01.EFFDT - 60 days)

Below is the code what I am using.

CASE
  WHEN RAP10B.CLMSRC = '2'
  THEN rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND rap01.teffdt_t
  WHEN RAP10B.CLMSRC <> '2'
  THEN rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND (rap01.teffdt_t - 60)
END

The error message is  "ORA-00905: missing keyword". But I am not able to find the missing thing.

Body:
It's generally much better to use AND/OR constructions in the WHERE clause instead of case expressions:

WHERE (RAP10B.CLMSRC = '2'
       AND rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND rap01.teffdt_t)
   OR (RAP10B.CLMSRC <> '2'
       AND rap10.lossdt_t BETWEEN Add_months(rap01.teffdt_t, - 36) AND (rap01.teffdt_t - 60))


问:
Testcafe Wait until an element has a specific text
After uploading an image with TestCafe the server will do some processing. While this time a label on the website will have "Inprogress" as a label. After the server is ready it will change to date. However, I want to tell the Testcafe script to wait until the label is not "Inporgress" anymore.
For this I did:

```<code>    const DeliveryStatus = {
        element: Selector('div.cl-asset-published').with({timeout: 70000}),
        delivered: 'Inprogress'
    };
</code>```

And in the script I have

```<code>await t
     .expect(DeliveryStatus.element).notContains(DeliveryStatus.delivered, { timeout: 70000 })
</code>```

But this step fails. The message I got is "AssertionError: object tested must be an array, a map, an object, a set, a string, or a weakset, but function given" but I do not have any idea why.

Any suggestion to fix this issue?

答:
You pass an element selector that returns the element but not a string to the expect function. Try using the element's innerText property instead as follows:

```<code>await t
 .expect(DeliveryStatus.element.innerText)
 .notContains(DeliveryStatus.delivered, { timeout: 70000 })
</code>```

Body:
After uploading an image with TestCafe the server will do some processing. While this time a label on the website will have "Inprogress" as a label. After the server is ready it will change to date. However, I want to tell the Testcafe script to wait until the label is not "Inporgress" anymore.
For this I did:

    const DeliveryStatus = {
        element: Selector('div.cl-asset-published').with({timeout: 70000}),
        delivered: 'Inprogress'
    };

And in the script I have

await t
     .expect(DeliveryStatus.element).notContains(DeliveryStatus.delivered, { timeout: 70000 })

But this step fails. The message I got is "AssertionError: object tested must be an array, a map, an object, a set, a string, or a weakset, but function given" but I do not have any idea why.

Any suggestion to fix this issue?

Body:
You pass an element selector that returns the element but not a string to the expect function. Try using the element's innerText property instead as follows:

await t
 .expect(DeliveryStatus.element.innerText)
 .notContains(DeliveryStatus.delivered, { timeout: 70000 })


问:
Haskell caught directory not exist but not empty value
With the LambdaCase I am able to filter out if a dir does not exist. However: if a user is prompted and hits enter (empty) I still get an exception.
I think Maybe or Either can help me here, but I have a hard time figuring out how to set this up.

```<code>    {-# LANGUAGE LambdaCase #-}

    import System.Directory
    import System.IO

    dirExist = do
      a <- prompt "Directory:> "
      doesDirectoryExist a >>= \case
        True -> getDirContent a
        _ -> putStrLn "Directory does not exist or invalid value specified."

getDirContent :: FilePath -> IO ()
getDirContent dir = do
  result <- getDirectoryContents dir
  mapM_ putStrLn $ result

    prompt :: String -> IO String
    prompt x = do
      putStr x
      a <- getLine
      return a
</code>```

答:
You can replace the line:

doesDirectoryExist a >>= \case
```

<p>with:</p>

<pre class="lang-hs prettyprint-override"><code>((&&) <$> (pure $ not $ null a) <*> doesDirectoryExist a) >>= \case
</code>```

This is called "applicative style" (in case you didn't know it ;-)); I am combining two IO operations that return a boolean using the AND (&&) operator.

The (pure $ not $ null a) expression checks that the string isn't empty, and uses "pure" to lift a pure operation into an IO (so we can combine it with doesDirectoryExist into an expression that checks for both conditions).

EDIT:

As Joseph noted, the above executes doesDirectoryExist whether it is needed or not; you usually want to avoid that (unless you somehow rely on its side effects); you can avoid it with bradrn's suggestion; you can also do this:

(if null a then pure False else doesDirectoryExist a) >>= \case
```

<p>Alternatively, since you dislike if-then-else notation (as do I):</p>

<pre class="lang-hs prettyprint-override"><code>(case null a of True -> pure False; False -> doesDirectoryExist a) >>= \case
</code>```

Not really cleaner, though; you can import Data.Bool and do this:

-- import Data.Bool
(bool (doesDirectoryExist a) (pure False) $ null a) >>= \case
```

("bool" is just a more functional-like notation for the good old if-then-else)

Body:
With the LambdaCase I am able to filter out if a dir does not exist. However: if a user is prompted and hits enter (empty) I still get an exception.
I think Maybe or Either can help me here, but I have a hard time figuring out how to set this up.

    {-# LANGUAGE LambdaCase #-}

    import System.Directory
    import System.IO

    dirExist = do
      a <- prompt "Directory:> "
      doesDirectoryExist a >>= \case
        True -> getDirContent a
        _ -> putStrLn "Directory does not exist or invalid value specified."

getDirContent :: FilePath -> IO ()
getDirContent dir = do
  result <- getDirectoryContents dir
  mapM_ putStrLn $ result

    prompt :: String -> IO String
    prompt x = do
      putStr x
      a <- getLine
      return a

Body:
You can replace the line:

doesDirectoryExist a >>= \case

with:

((&&) <$> (pure $ not $ null a) <*> doesDirectoryExist a) >>= \case

This is called "applicative style" (in case you didn't know it ;-)); I am combining two IO operations that return a boolean using the AND (&&) operator.

The (pure $ not $ null a) expression checks that the string isn't empty, and uses "pure" to lift a pure operation into an IO (so we can combine it with doesDirectoryExist into an expression that checks for both conditions).

EDIT:

As Joseph noted, the above executes doesDirectoryExist whether it is needed or not; you usually want to avoid that (unless you somehow rely on its side effects); you can avoid it with bradrn's suggestion; you can also do this:

(if null a then pure False else doesDirectoryExist a) >>= \case

Alternatively, since you dislike if-then-else notation (as do I):

(case null a of True -> pure False; False -> doesDirectoryExist a) >>= \case

Not really cleaner, though; you can import Data.Bool and do this:

-- import Data.Bool
(bool (doesDirectoryExist a) (pure False) $ null a) >>= \case

("bool" is just a more functional-like notation for the good old if-then-else)


问:
wrap child div text onto next line when browser resized
How do I get a child's  full text content to move to the next line when the browser is resized and it no longer fits?

so it ends up like this

This text is in - first child

This text is in second child

.child1 {
  display: inline;
  margin-right: 10px;
}

.child2 {
  display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="child1">
    This text is in - first child
  </div>
  <div class="child2">
    This text is in second child
  </div>
</div></code>```

答:
you need to add media query</p>

```<code>.child1 {
  display: inline;
  margin-right: 10px;
}

.child2 {
  display: inline;
}

@media screen and (max-width: 100px) {
  .child2 {
    display: block;
  }
}
</code>```

Body:
How do I get a child's  full text content to move to the next line when the browser is resized and it no longer fits?

so it ends up like this

This text is in - first child

This text is in second child

.child1 {
  display: inline;
  margin-right: 10px;
}

.child2 {
  display: inline;
}

    This text is in - first child

    This text is in second child

Body:
you need to add media query

.child1 {
  display: inline;
  margin-right: 10px;
}

.child2 {
  display: inline;
}

@media screen and (max-width: 100px) {
  .child2 {
    display: block;
  }
}


问:
python re.sub with an integer operation
I currently have a pattern substitution that does the following:

```<code>x = re.sub('(\d+)','\g<1>','100')
=> x = 100
</code>```

I need to be able to divide the integer by 10 in the substitution as the pattern and substitution are inputs from database text fields (so I can't use code). Is there a way to do this so that => x = 10

Thanks,
Richard

答:
you can do this by passing a function as 2nd argument to re.sub. That function will be called with a MatchObject :</p>

```<code>>>> def repl(mo):
...    return mo.group(0)[:-1]
...
>>> import re
>>> re.sub('\d+', repl, '100')
'10'
</code>```

Title: python re.sub with an integer operation

Body:
I currently have a pattern substitution that does the following:

x = re.sub('(\d+)','\g<1>','100')
=> x = 100

I need to be able to divide the integer by 10 in the substitution as the pattern and substitution are inputs from database text fields (so I can't use code). Is there a way to do this so that => x = 10

Thanks,
Richard

Body:
you can do this by passing a function as 2nd argument to re.sub. That function will be called with a MatchObject :

>>> def repl(mo):
...    return mo.group(0)[:-1]
...
>>> import re
>>> re.sub('\d+', repl, '100')
'10'


问:
Return "Error" if no match found by regex
I have a string:

```<code>link = "http://www.this_is_my_perfect_url.com/blah_blah/blah_blah?=trololo"
</code>```

And I have a function which return the domain name from that url or if it not found, returns '':

```<code>def get_domain(url):
    domain_regex = re.compile("\:\/\/(.*?)\/|$")
    return re.findall(domain_regex, str(url))[0].replace('www.', '')

get_domain(link)
</code>```

returned result:

```<code>this_is_my_perfect_url.com
</code>```

|$ returns '' if regex matches nothing.

Is there a way to implement the default value Error inside regex so I do not have to do any check inside the fuction?

So if link = "there_is_no_domain_in_here" then the fuction returns Error instead of ''.

答:
As mentioned in the comments above, you cannot set anything in regex to do that for you, but you can check if the output returned by re.findall after applying the extra formatting is empty or not, and if it is empty, which means that no matches were found, return Error

```<code>import re
link = "http://www.this_is_my_perfect_url.com/blah_blah/blah_blah?=trololo"

def get_domain(url):
    domain_regex = re.compile("\:\/\/(.*?)\/|$")

    #Get regex matches into a list after data massaging
    matches = re.findall(domain_regex, str(url))[0].replace('www.', '')

    #Return the match or Error if output is empty
    return matches or 'Error'

print(get_domain(link))
print(get_domain('there_is_no_domain_in_here'))
</code>```

The output will be

```<code>this_is_my_perfect_url.com
Error
</code>```

Body:
I have a string:

link = "http://www.this_is_my_perfect_url.com/blah_blah/blah_blah?=trololo"

And I have a function which return the domain name from that url or if it not found, returns '':

def get_domain(url):
    domain_regex = re.compile("\:\/\/(.*?)\/|$")
    return re.findall(domain_regex, str(url))[0].replace('www.', '')

get_domain(link)

returned result:

this_is_my_perfect_url.com

|$ returns '' if regex matches nothing.

Is there a way to implement the default value Error inside regex so I do not have to do any check inside the fuction?

So if link = "there_is_no_domain_in_here" then the fuction returns Error instead of ''.

Body:
As mentioned in the comments above, you cannot set anything in regex to do that for you, but you can check if the output returned by re.findall after applying the extra formatting is empty or not, and if it is empty, which means that no matches were found, return Error

import re
link = "http://www.this_is_my_perfect_url.com/blah_blah/blah_blah?=trololo"

def get_domain(url):
    domain_regex = re.compile("\:\/\/(.*?)\/|$")

    #Get regex matches into a list after data massaging
    matches = re.findall(domain_regex, str(url))[0].replace('www.', '')

    #Return the match or Error if output is empty
    return matches or 'Error'

print(get_domain(link))
print(get_domain('there_is_no_domain_in_here'))

The output will be

this_is_my_perfect_url.com
Error


问:
.child-div overflows .parent-div
guys!

I'm making an own portfolio website. The idea is to make full height pages. So regarding this, I got 2 questions.

How can I make .child-div not larger than its .parent-div?

How can I make p-elements height not larger than its .child-div?

Thinking that there is some (maybe the same) solution to both problems.

Overflow is not an option, because it just hide the rest of element.

I tried to set .parent as display: table and .child as display: table-cell but I didn't succeed.
UPD: Also tried to make an table-row div between .parent and. child width width: 100% and height: 33%. Unfortunately without expected result..

Here is the example how it should look like, but .child overflows the .parent.

html {
  height: 100%;
}
body {
  height: 100%;
  max-width: 960px;
  margin: 15px auto;
}
.parent {
  height: 100%;
  border: 1px solid red;
}
.child-30 {
  min-height: calc(100%/3);
  width: 27%;
  margin: 10px;
  border: 1px solid green;
}
.child-70 {
  min-height: calc(100%/3);
  width: 67%;
  margin: 10px;
  border: 1px solid green;
}
.left {
  float: left;
}
.right {
  float: right;
}
@media only screen and (max-width: 750px) {
  .child-30, .child-70 {float: left; width: 100%;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child-30 left"></div>
  <div class="child-70 right"></div>
  <div class="child-70 left"></div>
  <div class="child-30 right"></div>
  <div class="child-30 left"></div>
  <div class="child-70 right"></div>
</div></code>```

And here is the link how it should look like with paragraphs

Same problem here

答:
You assign a relative min-height size to the container to each element.
If you're sure you'll have 3 rows of blocks, you can use the min-height with just a small fix: min-height: calc(100% / 3 - 22px)

Why -22 ?
 - 10 for each margin (top and bottom)
 - 1 for each border (top and bottom) = 22

This is a problem at resize because you will have 6 rows of blocks with 100%/3 (which is 200% instead of 100%). So you need to do a min-height: calc (100% / 6 - 22px) in order to get 100% of the total size of the blocks.

Find bellow the modified code with the Kamil Pikula suggestions for the width.

BUT, if the size of your blocks are dynamic and you do not want to use overflow or ellypsis, it will not work with min-height.  You'll have to use dynamic height and make line breaks for each line with a system like boostrap clearfix.

html {
  height: 100%;
}
body {
  height: 100%;
  max-width: 960px;
  margin: 15px auto;
}
.parent {
  height: 100%;
  border: 1px solid red;
}
.child-30 {
  height: auto;
  min-height: calc(100%/3 - 22px);
  width: 27%;
  margin: 10px;
  border: 1px solid green;
}
.child-70 {
  min-height: calc(100%/3 - 22px);
  width: 67%;
  margin: 10px;
  border: 1px solid green;
}
.left {
  float: left;
}
.right {
  float: right;
}
@media only screen and (max-width: 750px) {
  .child-30, .child-70 {
    float: left;
    width: calc(100% - 22px);
    min-height: calc(100%/6 - 22px);
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child-30 left"></div>
  <div class="child-70 right"></div>
  <div class="child-70 left"></div>
  <div class="child-30 right"></div>
  <div class="child-30 left"></div>
  <div class="child-70 right"></div>
</div></code>```

Title: .child-div overflows .parent-div

Body:
guys!

I'm making an own portfolio website. The idea is to make full height pages. So regarding this, I got 2 questions.

How can I make .child-div not larger than its .parent-div?

How can I make p-elements height not larger than its .child-div?

Thinking that there is some (maybe the same) solution to both problems.

Overflow is not an option, because it just hide the rest of element.

I tried to set .parent as display: table and .child as display: table-cell but I didn't succeed.
UPD: Also tried to make an table-row div between .parent and. child width width: 100% and height: 33%. Unfortunately without expected result..

Here is the example how it should look like, but .child overflows the .parent.

html {
  height: 100%;
}
body {
  height: 100%;
  max-width: 960px;
  margin: 15px auto;
}
.parent {
  height: 100%;
  border: 1px solid red;
}
.child-30 {
  min-height: calc(100%/3);
  width: 27%;
  margin: 10px;
  border: 1px solid green;
}
.child-70 {
  min-height: calc(100%/3);
  width: 67%;
  margin: 10px;
  border: 1px solid green;
}
.left {
  float: left;
}
.right {
  float: right;
}
@media only screen and (max-width: 750px) {
  .child-30, .child-70 {float: left; width: 100%;}
}

And here is the link how it should look like with paragraphs

Same problem here

Body:
You assign a relative min-height size to the container to each element.
If you're sure you'll have 3 rows of blocks, you can use the min-height with just a small fix: min-height: calc(100% / 3 - 22px)

Why -22 ?
 - 10 for each margin (top and bottom)
 - 1 for each border (top and bottom) = 22

This is a problem at resize because you will have 6 rows of blocks with 100%/3 (which is 200% instead of 100%). So you need to do a min-height: calc (100% / 6 - 22px) in order to get 100% of the total size of the blocks.

Find bellow the modified code with the Kamil Pikula suggestions for the width.

BUT, if the size of your blocks are dynamic and you do not want to use overflow or ellypsis, it will not work with min-height.  You'll have to use dynamic height and make line breaks for each line with a system like boostrap clearfix.

html {
  height: 100%;
}
body {
  height: 100%;
  max-width: 960px;
  margin: 15px auto;
}
.parent {
  height: 100%;
  border: 1px solid red;
}
.child-30 {
  height: auto;
  min-height: calc(100%/3 - 22px);
  width: 27%;
  margin: 10px;
  border: 1px solid green;
}
.child-70 {
  min-height: calc(100%/3 - 22px);
  width: 67%;
  margin: 10px;
  border: 1px solid green;
}
.left {
  float: left;
}
.right {
  float: right;
}
@media only screen and (max-width: 750px) {
  .child-30, .child-70 {
    float: left;
    width: calc(100% - 22px);
    min-height: calc(100%/6 - 22px);
    }
}

<div class="parent">
  <div class="child-30 left"></div>
  <div class="child-70 right"></div>
  <div class="child-70 left"></div>
  <div class="child-30 right"></div>
  <div class="child-30 left"></div>
  <div class="child-70 right"></div>
</div>


问:
Passing dynamic object to an angular module's forRoot()
I'm using the package ngx-cookieconsent which imports the module as:

const cookieConfig: NgcCookieConsentConfig = {
  "cookie": {
    "domain": "localhost"
  },
  ...
  "theme": "block",
  "content": {
    "policy": "Cookie Policy"
  }
};
...
@NgModule({
 imports: [
    NgcCookieConsentModule.forRoot(cookieConfig)
  ]

However, the domain property on the config will be set at runtime and so I can't have this defined as a constant. To get round this I have done the following:

Created a ConfigurationService that gets the config and stores it:

```<code>@Injectable()
export class ConfigurationService {

  private configuration: IServerConfiguration;

  constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) { }

  loadConfig() {
    return this.http.get<IServerConfiguration>(this.baseUrl + 'Configuration')
      .pipe(
        tap(config => {
          this.configuration = <IServerConfiguration>(config);
        })
      )
      .toPromise();
  }

  public domain(): string {
    return this.configuration.domain;
  }
}
</code>```

And this is set up as an APP_INITIALIZER so that the config is called first:

```<code>export function loadConfiguration(configService: ConfigurationService) {
  return () => configService.loadConfig();
}

...
 providers: [
    ConfigurationService,
    {
      provide: APP_INITIALIZER,
      useFactory: loadConfiguration,
      multi: true,
      deps: [ConfigurationService]
    }],
</code>```

And then have created a class to create my cookieConsentOptions object using the config:

```<code>@Injectable()
export class CookieConstentService {

  cookieDomain: string;

  constructor(configService: ConfigurationService) {
    this.cookieDomain = configService.domain();
  }

  get cookieConstentOptions(): NgcCookieConsentConfig {
    return {
      "cookie": {
        "domain": this.cookieDomain
      },
      "position": "top-right",
      "content": {
        "message": "This website uses cookies to ensure you get the best experience on our website."
      }
    };
  }
</code>```

Issue

I've got the dependency set up between the configService and the CookieConstentService so that I only create the the cookie options when I have the config values.

However, I am unsure how to pass a dynamic value to the .forRoot() of a module. I should be able to do cookieConsentService.cookieConstentOptions() to get the object but I'm not sure where to instantiate this to be used in he module import. It takes a dependency so can't just create a new instance myself.

Any ideas how I effectively inject a method into a 3rd party module's forRoot()?

Thanks

答:
After posting this question I learnt that the object passed into the forRoot() method is essentially a singleton, so if I set any values before it gets initialised then it will use this. The way I implemented this was:

Create an instance of the options with the constant/default settings (these won't change between environments):

```<code>import { NgcCookieConsentConfig } from "ngx-cookieconsent";

export const cookieConsentOptions: NgcCookieConsentConfig  =
{
  "cookie": {
    "domain": "not-set"
  },
  "position": "bottom-right",
  "theme": "block",
  "palette": {
    "popup": {
      "background": "#df1010",
      "text": "#ffffff",
      "link": "#ffffff"
    },
    "button": {
      "background": "#ffffff",
      "text": "#000000",
      "border": "transparent"
    }
  },
  "type": "info",
  "content": {
    "message": "This website uses cookies to ensure you get the best experience on our website.",
    "dismiss": "Got it!",
    "deny": "Refuse cookies",
    "link": "Learn more",
    "href": "/cookie-policy",
    "policy": "Cookie Policy",
    "target": "_self"
  }
};
</code>```

Add an APP_INITIALIZER to the appModule which injects the NgcCookieConsentConfig object. This will pass in the object created above:

```<code>...
{
      provide: APP_INITIALIZER,
      useFactory: cookieConfigFactory,
      deps: [HttpClient, NgcCookieConsentConfig, ConfigurationService],
      multi: true
    },
...
</code>```

And create the method the used above:

```<code>export function cookieConfigFactory(http: HttpClient, config: NgcCookieConsentConfig, configService: ConfigurationService) {
  return () => configService.loadConfig().then(x => config.cookie.domain = x.domain)
}
</code>```

I'm getting the value for the cookie domain from a custom config service hence why it's being injected in, yours might be different.

Finally in the modules import in appModules, import the CookieConsent module passing in the object created in the first step:

```<code>NgcCookieConsentModule.forRoot(cookieConsentOptions)
</code>```

Body:
I'm using the package ngx-cookieconsent which imports the module as:

const cookieConfig: NgcCookieConsentConfig = {
  "cookie": {
    "domain": "localhost"
  },
  ...
  "theme": "block",
  "content": {
    "policy": "Cookie Policy"
  }
};
...
@NgModule({
 imports: [
    NgcCookieConsentModule.forRoot(cookieConfig)
  ]

However, the domain property on the config will be set at runtime and so I can't have this defined as a constant. To get round this I have done the following:

Created a ConfigurationService that gets the config and stores it:

@Injectable()
export class ConfigurationService {

  private configuration: IServerConfiguration;

  constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) { }

  loadConfig() {
    return this.http.get<IServerConfiguration>(this.baseUrl + 'Configuration')
      .pipe(
        tap(config => {
          this.configuration = <IServerConfiguration>(config);
        })
      )
      .toPromise();
  }

  public domain(): string {
    return this.configuration.domain;
  }
}

And this is set up as an APP_INITIALIZER so that the config is called first:

export function loadConfiguration(configService: ConfigurationService) {
  return () => configService.loadConfig();
}

...
 providers: [
    ConfigurationService,
    {
      provide: APP_INITIALIZER,
      useFactory: loadConfiguration,
      multi: true,
      deps: [ConfigurationService]
    }],

And then have created a class to create my cookieConsentOptions object using the config:

@Injectable()
export class CookieConstentService {

  cookieDomain: string;

  constructor(configService: ConfigurationService) {
    this.cookieDomain = configService.domain();
  }

  get cookieConstentOptions(): NgcCookieConsentConfig {
    return {
      "cookie": {
        "domain": this.cookieDomain
      },
      "position": "top-right",
      "content": {
        "message": "This website uses cookies to ensure you get the best experience on our website."
      }
    };
  }

Issue

I've got the dependency set up between the configService and the CookieConstentService so that I only create the the cookie options when I have the config values.

However, I am unsure how to pass a dynamic value to the .forRoot() of a module. I should be able to do cookieConsentService.cookieConstentOptions() to get the object but I'm not sure where to instantiate this to be used in he module import. It takes a dependency so can't just create a new instance myself.

Any ideas how I effectively inject a method into a 3rd party module's forRoot()?

Thanks

Body:
After posting this question I learnt that the object passed into the forRoot() method is essentially a singleton, so if I set any values before it gets initialised then it will use this. The way I implemented this was:

Create an instance of the options with the constant/default settings (these won't change between environments):

import { NgcCookieConsentConfig } from "ngx-cookieconsent";

export const cookieConsentOptions: NgcCookieConsentConfig  =
{
  "cookie": {
    "domain": "not-set"
  },
  "position": "bottom-right",
  "theme": "block",
  "palette": {
    "popup": {
      "background": "#df1010",
      "text": "#ffffff",
      "link": "#ffffff"
    },
    "button": {
      "background": "#ffffff",
      "text": "#000000",
      "border": "transparent"
    }
  },
  "type": "info",
  "content": {
    "message": "This website uses cookies to ensure you get the best experience on our website.",
    "dismiss": "Got it!",
    "deny": "Refuse cookies",
    "link": "Learn more",
    "href": "/cookie-policy",
    "policy": "Cookie Policy",
    "target": "_self"
  }
};

Add an APP_INITIALIZER to the appModule which injects the NgcCookieConsentConfig object. This will pass in the object created above:

...
{
      provide: APP_INITIALIZER,
      useFactory: cookieConfigFactory,
      deps: [HttpClient, NgcCookieConsentConfig, ConfigurationService],
      multi: true
    },
...

And create the method the used above:

export function cookieConfigFactory(http: HttpClient, config: NgcCookieConsentConfig, configService: ConfigurationService) {
  return () => configService.loadConfig().then(x => config.cookie.domain = x.domain)
}

I'm getting the value for the cookie domain from a custom config service hence why it's being injected in, yours might be different.

Finally in the modules import in appModules, import the CookieConsent module passing in the object created in the first step:

NgcCookieConsentModule.forRoot(cookieConsentOptions)


问:
Parcelable encountered IOException writing serializable object getactivity()
so I am getting this in logcat:

```<code>java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.resources.student_list.Student)
</code>```

I know this means that my student class is not serializable, but it is, here is my student class:

```<code>import java.io.Serializable;

public class Student implements Comparable<Student>,  Serializable{

    private static final long serialVersionUID = 1L;
    private String firstName, lastName;
    private DSLL<Grade> gradeList;

    public Student() {
        firstName = "";
        lastName = "";
        gradeList = new DSLL<Grade>();
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public DSLL<Grade> getGradeList() {
        return gradeList;
    }

    public void setGradeList(DSLL<Grade> gradeList) {
        this.gradeList = gradeList;
    }

    public int compareTo(Student arg0) {
        return this.lastName.compareTo(arg0.getLastName());
    }

}
</code>```

and this is the code that is using the getIntent() method:

```<code>public void onItemClick(AdapterView<?> parent, View viewClicked, int pos,
                                long id) {

                            Student clickedStudent = studentList.get(pos);
                            int position = pos;
                            Intent intent = new Intent(getActivity().getApplicationContext(), ShowStudentActivity.class);
                            Log.e("CINTENT","CREATED!!!");
                            intent.putExtra("clickedStudent",clickedStudent);
                            intent.putExtra("newStudentList",newStudentList);
                            intent.putExtra("position",position);
                            Log.e("putExtra","Passed");
                            Log.e("Start activity","passed");
                            startActivity(intent);

                        }

                    });
</code>```

please help me figure out whats wrong with this.

here is the whole LogCat:

```<code>04-17 16:12:28.890: E/AndroidRuntime(22815): FATAL EXCEPTION: main
04-17 16:12:28.890: E/AndroidRuntime(22815): java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.resources.student_list.Student)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeSerializable(Parcel.java:1181)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeValue(Parcel.java:1135)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeMapInternal(Parcel.java:493)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Bundle.writeToParcel(Bundle.java:1612)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeBundle(Parcel.java:507)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.content.Intent.writeToParcel(Intent.java:6111)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1613)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1422)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.Activity.startActivityForResult(Activity.java:3191)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:848)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.support.v4.app.Fragment.startActivity(Fragment.java:878)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.example.student_lists.MainActivity$DummySectionFragment$2.onItemClick(MainActivity.java:477)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AdapterView.performItemClick(AdapterView.java:292)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView$1.run(AbsListView.java:3168)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Handler.handleCallback(Handler.java:605)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Looper.loop(Looper.java:137)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.ActivityThread.main(ActivityThread.java:4447)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.lang.reflect.Method.invokeNative(Native Method)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.lang.reflect.Method.invoke(Method.java:511)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at dalvik.system.NativeStart.main(Native Method)
04-17 16:12:28.890: E/AndroidRuntime(22815): Caused by: java.io.NotSerializableException: com.resources.student_list.DSLL$DNode
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1364)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeSerializable(Parcel.java:1176)
</code>```

答: The exception occurred due to the fact that any of the inner classes or other referenced classes didn't implement the serializable implementation. So make sure that all the referenced classes must implement the serializable implementation.</p>

Body:
so I am getting this in logcat:

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.resources.student_list.Student)

I know this means that my student class is not serializable, but it is, here is my student class:

import java.io.Serializable;

public class Student implements Comparable<Student>,  Serializable{

    private static final long serialVersionUID = 1L;
    private String firstName, lastName;
    private DSLL<Grade> gradeList;

    public Student() {
        firstName = "";
        lastName = "";
        gradeList = new DSLL<Grade>();
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public DSLL<Grade> getGradeList() {
        return gradeList;
    }

    public void setGradeList(DSLL<Grade> gradeList) {
        this.gradeList = gradeList;
    }

    public int compareTo(Student arg0) {
        return this.lastName.compareTo(arg0.getLastName());
    }

}

and this is the code that is using the getIntent() method:

public void onItemClick(AdapterView<?> parent, View viewClicked, int pos,
                                long id) {

                            Student clickedStudent = studentList.get(pos);
                            int position = pos;
                            Intent intent = new Intent(getActivity().getApplicationContext(), ShowStudentActivity.class);
                            Log.e("CINTENT","CREATED!!!");
                            intent.putExtra("clickedStudent",clickedStudent);
                            intent.putExtra("newStudentList",newStudentList);
                            intent.putExtra("position",position);
                            Log.e("putExtra","Passed");
                            Log.e("Start activity","passed");
                            startActivity(intent);

                        }

                    });

please help me figure out whats wrong with this.

here is the whole LogCat:

04-17 16:12:28.890: E/AndroidRuntime(22815): FATAL EXCEPTION: main
04-17 16:12:28.890: E/AndroidRuntime(22815): java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.resources.student_list.Student)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeSerializable(Parcel.java:1181)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeValue(Parcel.java:1135)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeMapInternal(Parcel.java:493)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Bundle.writeToParcel(Bundle.java:1612)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeBundle(Parcel.java:507)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.content.Intent.writeToParcel(Intent.java:6111)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1613)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1422)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.Activity.startActivityForResult(Activity.java:3191)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:848)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.support.v4.app.Fragment.startActivity(Fragment.java:878)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.example.student_lists.MainActivity$DummySectionFragment$2.onItemClick(MainActivity.java:477)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AdapterView.performItemClick(AdapterView.java:292)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.widget.AbsListView$1.run(AbsListView.java:3168)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Handler.handleCallback(Handler.java:605)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Looper.loop(Looper.java:137)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.app.ActivityThread.main(ActivityThread.java:4447)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.lang.reflect.Method.invokeNative(Native Method)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.lang.reflect.Method.invoke(Method.java:511)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at dalvik.system.NativeStart.main(Native Method)
04-17 16:12:28.890: E/AndroidRuntime(22815): Caused by: java.io.NotSerializableException: com.resources.student_list.DSLL$DNode
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1364)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
04-17 16:12:28.890: E/AndroidRuntime(22815):    at android.os.Parcel.writeSerializable(Parcel.java:1176)


问:
Fluent CRUD with NHibernate ASP.NET MVC
ASP.NET MVC makes it really easy to create editing templates for simple, flat objects. But managing CRUD for complex objects with several indirections when using something like Fluent NHibernate, is not so obvious.

Example

To illustrate my question with a simple Invoice manager, Invoice entities have a Project property:

```<code>public class Invoice
{
    ...
    Project Project { get; set; } // where Project class has an Id and a Name
}
</code>```

...which is mapped to the Projects table via Fluent NHibernate in my InvoiceMap:

```<code>References(x => x.Project).Inverse();
</code>```

In the past, my Invoice entities would have a ProjectId property that referenced a project in my database, which made it easier to render a select list with Project IDs, but harder to output views, e.g.:

```<code>public class Invoice
{
    ...
    Guid ProjectID { get; set; }
}
</code>```

But since I started using Fluent NHibernate, I don't want to dirty up my controller with more IDs.

InvoiceController

```<code>[HttpGet]
public ActionResult Edit(Guid id)
{
    var invoice = _unitOfWork.CurrentSession.Get<Invoice>(id);
    return View(invoice);
}

[HttpPost]
public ActionResult Edit(Invoice invoice)
{
    /* How to deal with invoice.Project mapping here without introducing a second
       action parameter, e.g. Guid projectId ? */

    _unitOfWork.CurrentSession.SaveOrUpdate(invoice);
    _unitOfWork.Commit();

    return RedirectToAction("Details", new { id = invoice.Id });
}
</code>```

The referenced Project should not be editable from my Invoice/Edit.cshtml view, but I want to be able to choose which Project the Invoice should belong to.

How should I design my views and controllers to make CRUD easy without cluttering up my controller action with reference IDs that are not flat entity fields?

答:
I'd suggest you create an action on your ProjectController (assuming you have one) which has a partial view which is simply a list of the projects.

e.g.

```<code> public class ProjectController : Controller
 {
      public ActionResult ProjectsList()
      {
          var projects = GetAllProjects();
          return View(projects);
      }
 }
</code>```

Project/ProjectsList.cshtml

```<code>@model IEnumerable<MyProject.Data.Models.Project>
@{ Layout = null }
<select name="project">
 @foreach(var project in Model)
 {
   <option value="@project.Id">@project.Name</option>
 }
</select>
</code>```

Invoice/Edit.cshtml

```<code><label>Title</label>
<input name="title" />

@Html.Action("ProjectsList","Project")
</code>```

I would then change you Edit invoice to take an input model rather than the straight invoice and look up the project by Id in that action.

HTH

Title: Fluent CRUD with NHibernate ASP.NET MVC

Body:
ASP.NET MVC makes it really easy to create editing templates for simple, flat objects. But managing CRUD for complex objects with several indirections when using something like Fluent NHibernate, is not so obvious.

Example

To illustrate my question with a simple Invoice manager, Invoice entities have a Project property:

public class Invoice
{
    ...
    Project Project { get; set; } // where Project class has an Id and a Name
}

...which is mapped to the Projects table via Fluent NHibernate in my InvoiceMap:

References(x => x.Project).Inverse();

In the past, my Invoice entities would have a ProjectId property that referenced a project in my database, which made it easier to render a select list with Project IDs, but harder to output views, e.g.:

public class Invoice
{
    ...
    Guid ProjectID { get; set; }
}

But since I started using Fluent NHibernate, I don't want to dirty up my controller with more IDs.

InvoiceController

[HttpGet]
public ActionResult Edit(Guid id)
{
    var invoice = _unitOfWork.CurrentSession.Get<Invoice>(id);
    return View(invoice);
}

[HttpPost]
public ActionResult Edit(Invoice invoice)
{
    /* How to deal with invoice.Project mapping here without introducing a second
       action parameter, e.g. Guid projectId ? */

    _unitOfWork.CurrentSession.SaveOrUpdate(invoice);
    _unitOfWork.Commit();

    return RedirectToAction("Details", new { id = invoice.Id });
}

The referenced Project should not be editable from my Invoice/Edit.cshtml view, but I want to be able to choose which Project the Invoice should belong to.

How should I design my views and controllers to make CRUD easy without cluttering up my controller action with reference IDs that are not flat entity fields?

Body:
I'd suggest you create an action on your ProjectController (assuming you have one) which has a partial view which is simply a list of the projects.

e.g.

 public class ProjectController : Controller
 {
      public ActionResult ProjectsList()
      {
          var projects = GetAllProjects();
          return View(projects);
      }
 }

Project/ProjectsList.cshtml

@model IEnumerable<MyProject.Data.Models.Project>
@{ Layout = null }
<select name="project">
 @foreach(var project in Model)
 {
   <option value="@project.Id">@project.Name</option>
 }
</select>

Invoice/Edit.cshtml

<label>Title</label>
<input name="title" />

@Html.Action("ProjectsList","Project")

I would then change you Edit invoice to take an input model rather than the straight invoice and look up the project by Id in that action.

HTH


问:
GET multiselect selected values
I need to get the multiselect selected values:

With a simple select work fine with this method:

```<code>public function championships(Request $request)
{
   $nationId = $request->get('q');
   return Championship::where('nation_id', $nationId)->get(['id', 'name as text']);
}
</code>```

But I need to getall the selected values in the multiselect and pass it to the query using an array with the whereIn.

But I do not know how to capture the values of the multiselect

Thanks

答:
Try this following.

Championship::select('id', 'name as text')->where('nation_id', $nationId)->get();
```

<p>And where statement</p>

<pre class="lang-php prettyprint-override"><code>$users = Championship::select('id', 'name as text')
->where([
    ['nation_id', '=', $nationId],
    ['name', 'like', $name],
])->get();
</code>```

Or where statement

$users =Championship::select('id', 'name as text')
    ->where('nation_id', '=', $nationId)
    ->orWhere('name', 'like', $name)
    ->get();
```

Title: GET multiselect selected values

Body:
I need to get the multiselect selected values:

With a simple select work fine with this method:

public function championships(Request $request)
{
   $nationId = $request->get('q');
   return Championship::where('nation_id', $nationId)->get(['id', 'name as text']);
}

But I need to getall the selected values in the multiselect and pass it to the query using an array with the whereIn.

But I do not know how to capture the values of the multiselect

Thanks

Body:
Try this following.

Championship::select('id', 'name as text')->where('nation_id', $nationId)->get();

And where statement

$users = Championship::select('id', 'name as text')
->where([
    ['nation_id', '=', $nationId],
    ['name', 'like', $name],
])->get();

Or where statement

$users =Championship::select('id', 'name as text')
    ->where('nation_id', '=', $nationId)
    ->orWhere('name', 'like', $name)
    ->get();


问:
Is it possible to insert data into two different tables inside one controller
I have this tables which names are

Users table

and

Pictures Table

whose primary job is to store the picture path and name and user id(Am doing it this way because I want to allow the users of my app to upload more than a picture which if I create a column for the picture in the users table will not allow me to do that).

Now inside the form(Signup form), if a user decide to upload a picture, I want the picture to be save inside the pictures table while still in the

Users_controller create method

This is what I have done so far (new.html.erb)

```<code><% provide(:title, 'Sign up') %>
<h1>Sign up</h1>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <%= form_for(@user, url: signup_path) do |f| %>
          <%= render'shared/error_messages', object: f.object %>
          <%= f.label :name %>
          <%= f.text_field :name, class: 'form-control' %>

          <%= f.label :email %>
          <%= f.email_field :email, class: 'form-control' %>

          <%= f.label :username %>
          <%= f.text_field :username, class: 'form-control' %>

          <%= f.label :password %>
          <%= f.password_field :password, class: 'form-control' %>

          <%= f.label :password_confirmation, "Confirmation" %>
          <%= f.password_field :password_confirmation, class: 'form-control' %>

          <span class="picture">
            <%= f.file_field :picture, accept: 'image/jpeg,image/gif,image/png' %>
          </span>
          <%= f.submit "Create an account", class: "btn btn-primary" %>
        <% end %>
    </div>
</div>
</code>```

and inside the users controller, I have this in the create method

```<code>1. def create
2.  @user = User.new(user_params) # Not the final implementation!
3.
4.  if @user.save
5.      # Save to the picture name to the picture table
6.               if params[:picture].present?
7.                 # How do I save the picture to the picture table from users controller
8.            @user.send_activation_email
9.        flash[:info] = "Please check your email to activate your account."
10.       redirect_to root_url
11. else
12.     #@states = State.all
13.         render 'new'
14. end
15.  end
</code>```

If you look at line 6 and 7, I have these

```<code>if params[:picture].present?
  # How do I save the picture to the picture table from users controller
</code>```

That is where the problem is now, how do I insert the picture name into the database inside user_controller

答:
```<code># new action
def new
  @user = User.new
  @user.pictures.build
end

# create action
def create
  @user = User.new(user_params)
  @user.save
end

private
def user_params
  params.require(:user).permit(:name, pictures_attributes: [:id])
# in addition to the id you need to specify the other required fields.
end
</code>```
```<code># User model
class User
  has_many :pictures
  accepts_nested_attributes_for :pictures, allow_destroy: true
end
</code>```
```<code># form view

<%= form_for @user do |f| %>
  pictures:
    <%= f.fields_for :pictures do |picture_form| %>
    # your code
</code>```

Sometimes in f.fields_for :pictures, you need to write :pictures_attributes by hand, if the first option does not work for you:

```<code><%= f.fields_for :pictures_attributes do |picture_form| %>
</code>```

and write field names by hands:

```<code><%= f.fields_for :pictures_attributes do |picture_form| %>
  <%= picture_form.text_field :name, name: "user[pictures_attributes][][name]" %>
</code>```

Body:
I have this tables which names are

Users table

and

Pictures Table

whose primary job is to store the picture path and name and user id(Am doing it this way because I want to allow the users of my app to upload more than a picture which if I create a column for the picture in the users table will not allow me to do that).

Now inside the form(Signup form), if a user decide to upload a picture, I want the picture to be save inside the pictures table while still in the

Users_controller create method

This is what I have done so far (new.html.erb)

<% provide(:title, 'Sign up') %>

Sign up

        <%= form_for(@user, url: signup_path) do |f| %>
          <%= render'shared/error_messages', object: f.object %>
          <%= f.label :name %>
          <%= f.text_field :name, class: 'form-control' %>

          <%= f.label :email %>
          <%= f.email_field :email, class: 'form-control' %>

          <%= f.label :username %>
          <%= f.text_field :username, class: 'form-control' %>

          <%= f.label :password %>
          <%= f.password_field :password, class: 'form-control' %>

          <%= f.label :password_confirmation, "Confirmation" %>
          <%= f.password_field :password_confirmation, class: 'form-control' %>

            <%= f.file_field :picture, accept: 'image/jpeg,image/gif,image/png' %>

          <%= f.submit "Create an account", class: "btn btn-primary" %>
        <% end %>

and inside the users controller, I have this in the create method

1. def create
2.  @user = User.new(user_params) # Not the final implementation!
3.
4.  if @user.save
5.      # Save to the picture name to the picture table
6.               if params[:picture].present?
7.                 # How do I save the picture to the picture table from users controller
8.            @user.send_activation_email
9.        flash[:info] = "Please check your email to activate your account."
10.       redirect_to root_url
11. else
12.     #@states = State.all
13.         render 'new'
14. end
15.  end

If you look at line 6 and 7, I have these

if params[:picture].present?
  # How do I save the picture to the picture table from users controller

That is where the problem is now, how do I insert the picture name into the database inside user_controller

Body:
# new action
def new
  @user = User.new
  @user.pictures.build
end

# create action
def create
  @user = User.new(user_params)
  @user.save
end

private
def user_params
  params.require(:user).permit(:name, pictures_attributes: [:id])
# in addition to the id you need to specify the other required fields.
end

# User model
class User
  has_many :pictures
  accepts_nested_attributes_for :pictures, allow_destroy: true
end

# form view

<%= form_for @user do |f| %>
  pictures:
    <%= f.fields_for :pictures do |picture_form| %>
    # your code

Sometimes in f.fields_for :pictures, you need to write :pictures_attributes by hand, if the first option does not work for you:

<%= f.fields_for :pictures_attributes do |picture_form| %>

and write field names by hands:

<%= f.fields_for :pictures_attributes do |picture_form| %>
  <%= picture_form.text_field :name, name: "user[pictures_attributes][][name]" %>


Title: Tensorflow tf.metrics.mean_iou returns 0

Body:
I want to use the function tf.metrics.mean_iou for an FCN for semantic segmentation. It only works, if the confusion matrix is calculated before the IoU, otherwise it returns 0.

Here my examples:

This example returns the correct value 0.66071427

import tensorflow as tf
import numpy as np

y_pred0 = np.array([   [ [[0.9,0.1],[0.9,0.1],[0.9,0.1],[0.9,0.1]], [[0.2,0.8],[0.2,0.8],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]] ],   [ [[0.9,0.1],[0.9,0.1],[0.9,0.1],[0.9,0.1]], [[0.2,0.8],[0.2,0.8],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]] ]    ])
y_pred1 = tf.constant(y_pred0)
y_pred2 = tf.argmax(y_pred1, axis=3)

y_label = np.array([[[1,0,1,0],[1,0,1,0],[0,0,1,0],[0,0,1,0]], [[1,0,1,0],[1,0,1,0],[0,0,1,0],[0,0,1,0]]])
y_label2 = tf.constant(y_label)

iou, conf_mat = tf.metrics.mean_iou(y_label2, y_pred2, num_classes=2)

sess = tf.Session()
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())

sess.run(conf_mat)
res = sess.run(iou)

print(res)

.

This example returns 0

import tensorflow as tf
import numpy as np

def intersection_over_union(prediction, labels):
    pred = tf.argmax(prediction, axis=3)
    labl = tf.constant(labels)
    iou, conf_mat = tf.metrics.mean_iou(labl, pred, num_classes=2)
    return iou

y_pred0 = np.array([   [ [[0.9,0.1],[0.9,0.1],[0.9,0.1],[0.9,0.1]], [[0.2,0.8],[0.2,0.8],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]] ],   [ [[0.9,0.1],[0.9,0.1],[0.9,0.1],[0.9,0.1]], [[0.2,0.8],[0.2,0.8],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]] ]    ])
y_pred1 = tf.constant(y_pred0)

y_label = np.array([[[1,0,1,0],[1,0,1,0],[0,0,1,0],[0,0,1,0]], [[1,0,1,0],[1,0,1,0],[0,0,1,0],[0,0,1,0]]])

mean__iou = intersection_over_union(y_pred1, y_label)

sess = tf.Session()
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())

res = sess.run(mean__iou)

print(res)

It would be very nice to have a function calculating mean IoU without initializing all variables in it. Is there any way to fix the second example? I think that the problem is in calculating IoU and confusion matrix simultanously and i didn't found another way for it as by running them separately by Session().

Thanks

Body:
You need to run the update operation that tf.metrics.mean_iou returns before getting the iou value from the tensor.

Here is the fixed code:

import tensorflow as tf
import numpy as np

def intersection_over_union(prediction, labels):
    pred = tf.argmax(prediction, axis=3)
    labl = tf.constant(labels)
    iou, conf_mat = tf.metrics.mean_iou(labl, pred, num_classes=2)
    return iou, conf_mat

y_pred0 = np.array([   [ [[0.9,0.1],[0.9,0.1],[0.9,0.1],[0.9,0.1]], [[0.2,0.8],[0.2,0.8],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]] ],   [ [[0.9,0.1],[0.9,0.1],[0.9,0.1],[0.9,0.1]], [[0.2,0.8],[0.2,0.8],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]], [[0.9,0.1],[0.9,0.1],[0.2,0.8],[0.9,0.1]] ]    ])
y_pred1 = tf.constant(y_pred0)

y_label = np.array([[[1,0,1,0],[1,0,1,0],[0,0,1,0],[0,0,1,0]], [[1,0,1,0],[1,0,1,0],[0,0,1,0],[0,0,1,0]]])

mean__iou, conf_mat = intersection_over_union(y_pred1, y_label)

sess = tf.Session()
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())

sess.run([conf_mat])
res = sess.run(mean__iou)

print(res)

Which returns the correct value: 0.66071427