问:
How to automatically scale down a 100% div without showing browser vertical scrollbars?
I have a table with three rows. I have 1 main #container div (height 100%) and inside it is a table with 3 rows. The first and last row have fixed size content. In the second row is a #content div with 100% height and overflow:auto. (actually the table has a lot more rows and the page has more divs, but for the sake of clarity i scalled it down for this question).

If there is more content in #content than fits, a vertical scrollbar should appear next to that div's content. However, a vertical scrollbar appears at the browser window itself. When i set the #content div to a fixed size however, that vertical scrollbar does appear in the correct place.

I must be doing something wrong, or maybe misinterpreting something :) Any ideas? Maybe there's jquery/javascript out there that can monitor the page and when loading/resizing the browser, scales down that particular div?

EDIT: I just created a small example: http://wierdaonline.com/softest.html

In the ideal situation, the whole thing (table) should always be visible in the browser window, without any window scrollbar other than in the #content div.

答:
Well since you have no choice but to use tables, I modified the HTML, but actually left the CSS the same from the demo I posted in a comment above, check it out here - the only problem I've found is in IE7 where the header and footer table cell doesn't go 100% across:

CSS

```<code>#header, #footer {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 20px;
    border: #000 1px solid;
    margin: 5px;
}
#footer {
    top: auto;
    bottom: 0;
}
#content {
    position: absolute;
    top: 25px;
    left: 0;
    bottom: 25px;
    right: 0;
    overflow-y: auto;
    background: #ddd;
    margin: 5px;
}
</code>```

HTML

```<code><table id="page">
    <thead>
        <tr><td id="header">Header</td></tr>
    </thead>
    <tfoot>
        <tr><td id="footer">Footer</td></tr>
    </tfoot>
    <tbody>
        <tr><td><div id="content">Content goes here</div></td></tr>
    </tbody>
</table>
</code>```

It's still better to not use tables, if you get around to switching the HTML around.

Body:
Well since you have no choice but to use tables, I modified the HTML, but actually left the CSS the same from the demo I posted in a comment above, check it out here - the only problem I've found is in IE7 where the header and footer table cell doesn't go 100% across:

CSS

#header, #footer {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 20px;
    border: #000 1px solid;
    margin: 5px;
}
#footer {
    top: auto;
    bottom: 0;
}
#content {
    position: absolute;
    top: 25px;
    left: 0;
    bottom: 25px;
    right: 0;
    overflow-y: auto;
    background: #ddd;
    margin: 5px;
}

HTML

<table id="page">
    <thead>
        <tr><td id="header">Header</td></tr>
    </thead>
    <tfoot>
        <tr><td id="footer">Footer</td></tr>
    </tfoot>
    <tbody>
        <tr><td><div id="content">Content goes here</div></td></tr>
    </tbody>
</table>

It's still better to not use tables, if you get around to switching the HTML around.


来源: stackexchange

问:
Delete Environment Variable Using Command prompt
Is there a batch file by which i can delete Environment Variable using cmd?? </p>

```<code>setx TEST "C:\"
</code>```

答:
You cannot delete an environment variable using setx, however, you can set it to NULL:

setx TEST ""

However, the variable is still there.

You can delete it using REG

REG DELETE "HKCU\Environment" /v TEST

However, using this approach, changes will not take place immediately.

ContentLicense: CC BY-SA 4.0

Body:
Is there a batch file by which i can delete Environment Variable using cmd??

setx TEST "C:\"


问:
Spring Boot binding and validation error handling in REST controller
When I have the following model with JSR-303 (validation framework) annotations:

```<code>public enum Gender {
    MALE, FEMALE
}

public class Profile {
    private Gender gender;

    @NotNull
    private String name;

    ...
}
</code>```

and the following JSON data:

```<code>{ "gender":"INVALID_INPUT" }
</code>```

In my REST controller, I want to handle both the binding errors (invalid enum value for gender property) and validation errors (name property cannot be null).

The following controller method does NOT work:

```<code>@RequestMapping(method = RequestMethod.POST)
public Profile insert(@Validated @RequestBody Profile profile, BindingResult result) {
    ...
}
</code>```

This gives com.fasterxml.jackson.databind.exc.InvalidFormatException serialization error before binding or validation takes place.

After some fiddling, I came up with this custom code which does what I want:

```<code>@RequestMapping(method = RequestMethod.POST)
public Profile insert(@RequestBody Map values) throws BindException {

    Profile profile = new Profile();

    DataBinder binder = new DataBinder(profile);
    binder.bind(new MutablePropertyValues(values));

    // validator is instance of LocalValidatorFactoryBean class
    binder.setValidator(validator);
    binder.validate();

    // throws BindException if there are binding/validation
    // errors, exception is handled using @ControllerAdvice.
    binder.close();

    // No binding/validation errors, profile is populated
    // with request values.

    ...
}
</code>```

Basically what this code does, is serialize to a generic map instead of model and then use custom code to bind to model and check for errors.

I have the following questions:

Is custom code the way to go here or is there a more standard way of doing this in Spring Boot?

How does the @Validated annotation work? How can I make my own custom annotation that works like @Validated to encapsulate my custom binding code?

答:
I think I should answer your questions in reverse order.

For your second question,
The @Validate annotation throws MethodArgumentNotValidException if there is an error during field validation. The object of this annotation contains two methods, getBindingResult(),getAllErrors() which gives details of validation error. You may create your custom annotation with AspectJ (AOP). But that's not needed here. Because your situation can be solved using the ExceptionHandler of SpringBoot.

Now your first question,

Please go through section 5 of this link Link. Actually it covers whole bean validation in spring boot. Your problem can be solved by section 5. Basic knowledge on general exception handling in spring boot may be good to understand it better. For that, I can share the query link on google for this topic ExceptionHandling.Please go through the first few results of it.

ContentLicense: CC BY-SA 3.0

Body:
When I have the following model with JSR-303 (validation framework) annotations:

public enum Gender {
    MALE, FEMALE
}

public class Profile {
    private Gender gender;

    @NotNull
    private String name;

    ...
}

and the following JSON data:

{ "gender":"INVALID_INPUT" }

In my REST controller, I want to handle both the binding errors (invalid enum value for gender property) and validation errors (name property cannot be null).

The following controller method does NOT work:

@RequestMapping(method = RequestMethod.POST)
public Profile insert(@Validated @RequestBody Profile profile, BindingResult result) {
    ...
}

This gives com.fasterxml.jackson.databind.exc.InvalidFormatException serialization error before binding or validation takes place.

After some fiddling, I came up with this custom code which does what I want:

@RequestMapping(method = RequestMethod.POST)
public Profile insert(@RequestBody Map values) throws BindException {

    Profile profile = new Profile();

    DataBinder binder = new DataBinder(profile);
    binder.bind(new MutablePropertyValues(values));

    // validator is instance of LocalValidatorFactoryBean class
    binder.setValidator(validator);
    binder.validate();

    // throws BindException if there are binding/validation
    // errors, exception is handled using @ControllerAdvice.
    binder.close();

    // No binding/validation errors, profile is populated
    // with request values.

    ...
}

Basically what this code does, is serialize to a generic map instead of model and then use custom code to bind to model and check for errors.

I have the following questions:

Is custom code the way to go here or is there a more standard way of doing this in Spring Boot?

How does the @Validated annotation work? How can I make my own custom annotation that works like @Validated to encapsulate my custom binding code?


问:
Update a List's object using Linq
I would like to assign an object in a list using Linq, but I can't find how to do it.
I tried this:

Items.Where(i => i.Code == line.Code).Single() = line;

But it seems I simply cannot give the statement an object.
I can modify properties of those objects (Like this) :

```<code>Items.Where(i => i.Code == line.Code).Single().name = line.name;
</code>```

But giving it the full item doesn't seem to be accepted.
Is there a reason to prevent this / a way to assign my value to the compatible item ?
Thank you for your answer.

答:
Single() is a method that returns a value. You can't usually assign to the return from an expression. It is ultimately no different to saying:

Math.Max(32, 42) = 14;
```

at which point, Max is going to say "um, no; I was telling you the answer - I wasn't expecting you to tell me".

In theory, what you want here is possible, but only in advanced scenarios involving ref-returns. LINQ does not deal with ref-returns.

Title: Update a List's object using Linq

Body:
I would like to assign an object in a list using Linq, but I can't find how to do it.
I tried this:

Items.Where(i => i.Code == line.Code).Single() = line;

But it seems I simply cannot give the statement an object.
I can modify properties of those objects (Like this) :

Items.Where(i => i.Code == line.Code).Single().name = line.name;

But giving it the full item doesn't seem to be accepted.
Is there a reason to prevent this / a way to assign my value to the compatible item ?
Thank you for your answer.

Body:
Single() is a method that returns a value. You can't usually assign to the return from an expression. It is ultimately no different to saying:

Math.Max(32, 42) = 14;

at which point, Max is going to say "um, no; I was telling you the answer - I wasn't expecting you to tell me".

In theory, what you want here is possible, but only in advanced scenarios involving ref-returns. LINQ does not deal with ref-returns.


问:
Why does my promise chain run concurrently, not sequentially
I'm new to node and promises, so any help would be appreciated!

I'm trying to:

get an access token from an API

send the access token to the same API for a URL

poll the URL for some data

I thought the sensible way to do this would be a promise chain (Note I haven't implemented the polling yet, I just console.log at intervals for now while I'm getting this working. Also the request bodies aren't included below, but aren't a problem):

```<code>const request = require('request');

// get access token
new Promise((resolve, reject) => {
  request.post({
    json_request
  }, (error, response, body) => {
    if (error) console.error(error);
    console.log("got access token"));
    resolve(JSON.parse(body).accessToken);
  });
})

// use access token to get url
.then(
  (accessToken) => {
    request.post({
      json_request_with_access_token
    }, (error, response, body) => {
      if (error) console.error(error);
      console.log("got URL");
      return JSON.parse(body).url;
    })
  }
)

// Poll URL
.then(
  (reportURL) => {
    console.log("I'm here!");
    setInterval(() => {
     console.log("Report URL: ".concat(reportURL));
    }, 10000);    // setInterval waiting time
  }
)
</code>```

The problem is that the last promise in the chain is running before the middle one has finished. So the output to the console is:

```<code>got access token
I'm here!
got URL
report URL: undefined
</code>```

if "I'm here!" is printed before "got URL", then while the 2nd promise is running the code must move on to the last promise. The problem is it doesn't have the URL yet. I don't understand how to run these after one another, rather than concurrently. I've tried making the three promises into 3 separate functions, then wrapping them in one async main() function, where

```<code>async function main() {
  let accessToken = await getAccessToken();
  let url = await getURL(accessToken);
  await pollReport(url);
}
</code>```

but this had the same bug. Does anyone know how to fix this? Have I made a basic error somewhere? Any help would be much appreciated!

答:
Your section // use access token to get url and last section is not returning a promise. It is a callback in then which doesn't return promise. you need to wrap it in new Promise.

I would highly recommend to move from request package as it has now been deperecated. use some modenr day packages which has inbuilt support for promises and will also make your life easier. Like got, axios etc.

Body:
I'm new to node and promises, so any help would be appreciated!

I'm trying to:

get an access token from an API

send the access token to the same API for a URL

poll the URL for some data

I thought the sensible way to do this would be a promise chain (Note I haven't implemented the polling yet, I just console.log at intervals for now while I'm getting this working. Also the request bodies aren't included below, but aren't a problem):

const request = require('request');

// get access token
new Promise((resolve, reject) => {
  request.post({
    json_request
  }, (error, response, body) => {
    if (error) console.error(error);
    console.log("got access token"));
    resolve(JSON.parse(body).accessToken);
  });
})

// use access token to get url
.then(
  (accessToken) => {
    request.post({
      json_request_with_access_token
    }, (error, response, body) => {
      if (error) console.error(error);
      console.log("got URL");
      return JSON.parse(body).url;
    })
  }
)

// Poll URL
.then(
  (reportURL) => {
    console.log("I'm here!");
    setInterval(() => {
     console.log("Report URL: ".concat(reportURL));
    }, 10000);    // setInterval waiting time
  }
)

The problem is that the last promise in the chain is running before the middle one has finished. So the output to the console is:

got access token
I'm here!
got URL
report URL: undefined

if "I'm here!" is printed before "got URL", then while the 2nd promise is running the code must move on to the last promise. The problem is it doesn't have the URL yet. I don't understand how to run these after one another, rather than concurrently. I've tried making the three promises into 3 separate functions, then wrapping them in one async main() function, where

async function main() {
  let accessToken = await getAccessToken();
  let url = await getURL(accessToken);
  await pollReport(url);
}

but this had the same bug. Does anyone know how to fix this? Have I made a basic error somewhere? Any help would be much appreciated!


问:
How to write a step definition that compares a json response to a scenario outline table
I have json response example:

```<code>{
   "colours": ["green","blue", "red"],
   "type" :   ["shoes","socks","t-shirts"],
   "make" :   ["nike", "adidas"],
}
</code>```

I have Scenario outline table:

```<code>    |colours|type    |make  |
    |red    |shoes   |nike  |
    |blue   |socks   |nike  |
    |green  |t-shirts|adidas|
</code>```

I want to use the scenario table to assert against the json response. Now I know how to check this one by one, for example

```<code>* Assert colour is correct: <colours>
* Assert type is correct: <type>
* Assert make is correct: <make>
</code>```

And then perform the step definition like the example below for colour:

```<code>    @Step("Assert colour is correct: <colours>")
    public void assertColourIsCorrect(String colourValue) {
        String responseBody = BridgeTestState.getLastResponse().getBody().toString();
        itemState itemStateResp = new Gson().fromJson(responseBody, itemState.class);

        assertThat("colours", itemStateResp.getColour(), is(equalTo(colourValue.toLowerCase())));
    }
</code>```

Note The getColour() comes from a getter and setter I have set.

Now this works but as you can see it's a bit long winded as I have to create three separate steps to assert against each column.

I want to be a little smarter than this but don't know how to implement. What I would like is a step definition where it will look at the json response and compare it to the table based on its field and then from there view the value.

Something along the lines of:

Assert correct "fields" and "values" are outputted.

I hope that makes sense, basically a smart one step definition to perform the check between the json response and the table row.

答:
Doing what you want to do is counter productive and against the underlying design principles of Cucumber, Scenario Outlines, and probably even data tables in Cucumber.

What the cuke should be doing is explaining WHAT the json response represents and WHY its important. HOW the json response is constructed and the details of exploring its validity and content structure should be pushed down to the step definitions, or better yet helper methods called by the step definitions.

Its really hard to illustrate this with your sample data because its really hard to work out WHAT

```<code>{
   "colours": ["green","blue", "red"],
   "type" :   ["shoes","socks","t-shirts"],
   "make" :   ["nike", "adidas"],
}
</code>```

represents. Its also pretty hard to understand why you want to make the assertions you want to make.

If you gave a real example and explained what the data represents and WHY its important and perhaps also WHY you need to check it and WHAT you would do if it wasn't correct then we might be able to make more progress.

So I'll try with my own example which won't be very good

```<code>Given a set of clothing
When I get a json representation of the clothing
Then the json should be valid clothing
</code>```

and the steps

```<code>Given 'a set of clothing' do
  create_clothing_set
end

When 'I get a json representation of the clothing' do
  @json = make_clothing_request type: :json
end

Then 'the json should be valid clothing' do
  res = validate_clothing json: @json
  expect res ...
end

</code>```

Now your problem is how to write some code to validate your clothing i.e.

```<code>  def validate_clothing(json: )
    ...
  end
</code>```

Which is a much simpler problem being executed in a much more powerful environment. This has nothing to do with cucumber, no interactions with features, scenarios etc. its just a simple programming problem.

In general with Cucumber either push technical problems down, so they become programming problems, or pull problems up, so they are outside Cucumber and become scripting problems. This keeps Cucumber on topic. Its job is describe WHAT and WHY and provide a framework to automate.

Body:
I have json response example:

{
   "colours": ["green","blue", "red"],
   "type" :   ["shoes","socks","t-shirts"],
   "make" :   ["nike", "adidas"],
}

I have Scenario outline table:

    |colours|type    |make  |
    |red    |shoes   |nike  |
    |blue   |socks   |nike  |
    |green  |t-shirts|adidas|

I want to use the scenario table to assert against the json response. Now I know how to check this one by one, for example

* Assert colour is correct: <colours>
* Assert type is correct: <type>
* Assert make is correct: <make>

And then perform the step definition like the example below for colour:

    @Step("Assert colour is correct: <colours>")
    public void assertColourIsCorrect(String colourValue) {
        String responseBody = BridgeTestState.getLastResponse().getBody().toString();
        itemState itemStateResp = new Gson().fromJson(responseBody, itemState.class);

        assertThat("colours", itemStateResp.getColour(), is(equalTo(colourValue.toLowerCase())));
    }

Note The getColour() comes from a getter and setter I have set.

Now this works but as you can see it's a bit long winded as I have to create three separate steps to assert against each column.

I want to be a little smarter than this but don't know how to implement. What I would like is a step definition where it will look at the json response and compare it to the table based on its field and then from there view the value.

Something along the lines of:

Assert correct "fields" and "values" are outputted.

I hope that makes sense, basically a smart one step definition to perform the check between the json response and the table row.

Body:
Doing what you want to do is counter productive and against the underlying design principles of Cucumber, Scenario Outlines, and probably even data tables in Cucumber.

What the cuke should be doing is explaining WHAT the json response represents and WHY its important. HOW the json response is constructed and the details of exploring its validity and content structure should be pushed down to the step definitions, or better yet helper methods called by the step definitions.

Its really hard to illustrate this with your sample data because its really hard to work out WHAT

{
   "colours": ["green","blue", "red"],
   "type" :   ["shoes","socks","t-shirts"],
   "make" :   ["nike", "adidas"],
}

represents. Its also pretty hard to understand why you want to make the assertions you want to make.

If you gave a real example and explained what the data represents and WHY its important and perhaps also WHY you need to check it and WHAT you would do if it wasn't correct then we might be able to make more progress.

So I'll try with my own example which won't be very good

Given a set of clothing
When I get a json representation of the clothing
Then the json should be valid clothing

and the steps

Given 'a set of clothing' do
  create_clothing_set
end

When 'I get a json representation of the clothing' do
  @json = make_clothing_request type: :json
end

Then 'the json should be valid clothing' do
  res = validate_clothing json: @json
  expect res ...
end

Now your problem is how to write some code to validate your clothing i.e.

  def validate_clothing(json: )
    ...
  end

Which is a much simpler problem being executed in a much more powerful environment. This has nothing to do with cucumber, no interactions with features, scenarios etc. its just a simple programming problem.

In general with Cucumber either push technical problems down, so they become programming problems, or pull problems up, so they are outside Cucumber and become scripting problems. This keeps Cucumber on topic. Its job is describe WHAT and WHY and provide a framework to automate.


问:
Binary classifier of words in list
I have extracted text using OCR from a number of stylized documents in Swedish. Now I want formalize the data and extract city names. Due to the OCR working imperfectly, the names are sometimes spelled wrong and shows up at semi-random positions in the text. Therefore regex does not work.

Is it a good procedure/possible to transform the text into bags of words and train an algorithm to binary categorize words as city vs not city?

Consider example data set:

```<code>Col1                                          Col2
['Hi', 'there', 'Haag']                      ['Haag']
[‘Paris, ‘is’, ‘better’, ‘than’, ‘Osloe]     [‘Paris’, ‘Oslo’]
['My', 'hometown', 'is', 'New York']         ['New York']
...
</code>```

I want to use Col1 as X variable and Col2 as Y variable. Is this a good procedure or should I use another method?

答:
One possible way of dealing with spelling mistakes is to first collect your vocabulary (all words in the corpus) and to then select candidate OCR mistakes by their individual term frequencies (assuming that mistakes like "Osloe" are rare). In a second step you could use Edit distance to link candidate spelling mistakes to their correct word forms.

To extract cities you could, for example, take a look at spacy's pretrained models for named entity recognition.

Collocations like "New York" you could identify by contrasting the frequency of the terms to go together in sequence vs the individual term frequencies (depending on your corpus "York" might often go together with "New" much more often than one would assume under a hypothesis of the occurrence of "New" and "York" being independent).

Title: Binary classifier of words in list

Body:
I have extracted text using OCR from a number of stylized documents in Swedish. Now I want formalize the data and extract city names. Due to the OCR working imperfectly, the names are sometimes spelled wrong and shows up at semi-random positions in the text. Therefore regex does not work.

Is it a good procedure/possible to transform the text into bags of words and train an algorithm to binary categorize words as city vs not city?

Consider example data set:

Col1                                          Col2
['Hi', 'there', 'Haag']                      ['Haag']
[‘Paris, ‘is’, ‘better’, ‘than’, ‘Osloe]     [‘Paris’, ‘Oslo’]
['My', 'hometown', 'is', 'New York']         ['New York']
...

I want to use Col1 as X variable and Col2 as Y variable. Is this a good procedure or should I use another method?


问:
Perl If with "+", "-", "*", "/"
I have this code:

```<code>print ("First Value: ");
$valor1 = <STDIN>;
print ("Second Value: ");
$valor2 = <STDIN>;
print ("Operator: ");
$op = <STDIN>;
if ($op == "+")
{
    $total = $valor1 + $valor2;
    print ($total);
}

elsif ($op == "-")
{
    $total = $valor1 - $valor2;
    print ($total);
}

elsif ($op== "*")
{
    $total = $valor1 * $valor2;
    print ($total);
}

elsif ($op == "/")
{
    $total = $valor1 / $valor2;
    print ($total);
}
</code>```

He reads everything correctly, but when he enters the condition if the user types "-", "/" or "*" he always enters the first condition and makes a sum and i wanted to figured out why.

答:
Always use strict; and use warnings;.

This would give you the warning:

Argument "+" isn't numeric in numeric eq (==) at test.pl line 9,  line 3.

And that is why you are getting the behaviour you aren't expecting.

You should be using eq (and accounting for the new line character in the input).

Title: Perl If with "+", "-", "*", "/"

Body:
I have this code:

print ("First Value: ");
$valor1 = <STDIN>;
print ("Second Value: ");
$valor2 = <STDIN>;
print ("Operator: ");
$op = <STDIN>;
if ($op == "+")
{
    $total = $valor1 + $valor2;
    print ($total);
}

elsif ($op == "-")
{
    $total = $valor1 - $valor2;
    print ($total);
}

elsif ($op== "*")
{
    $total = $valor1 * $valor2;
    print ($total);
}

elsif ($op == "/")
{
    $total = $valor1 / $valor2;
    print ($total);
}

He reads everything correctly, but when he enters the condition if the user types "-", "/" or "*" he always enters the first condition and makes a sum and i wanted to figured out why.


问:
MVVMLight toolkit Messenger class causing problems. Firing N times
I have a view named Work.xaml. This Work.xaml contains multiple WorkSkeleton.xaml. The Work.xaml's ViewModel is WorkViewModel.

The Work.xaml is contained in MainPage.xaml which has button to load Work.xaml. I hope I am clear till now. The button's event handler is simple :-

```<code> private void hypMyWork_Click(object sender, RoutedEventArgs e)
        {
            ShowGridContent(new Work());
        }

 private void ShowGridContent(UserControl control)
        {
            gridContent.Children.Clear();
            gridContent.Children.Add(control);
        }
</code>```

In my Work.xaml.cs's Constructor I have registered for Messages of type ObservableCollection:

```<code>    Messenger.Default.Register<ObservableCollection<WorkEducation>>(this, "BindWorkEducationList", collection =>
    {
        foreach (var item in collection)
        {
            if (item.IsEducationInfo == false)
            {
                WorkEducationSkeleton skeleton = new WorkEducationSkeleton();
                skeleton.WorkEducation = item;
                stkPanel.Children.Insert(0,skeleton);

            }
        }
    });
</code>```

The ViewModel is sending this message when the ObservableCollection is loaded like this :-

```<code> Messenger.Default.Send<ObservableCollection<WorkEducation>>(WorkEducation,
                    "BindWorkEducationList");
</code>```

Everything works fine the 1st time. But as soon as I click the Work button in MainPage.xaml to load the Work page 2nd time, the messages are received in my Work.xaml 2 times which adds the same items to stackpanel again and again. This happens N times. If I clicked the button Nth time the message will be received N times in Work.xaml.cs. But how is this possible?

I have clearly specified the recepient in Work.xaml.cs to be this as the 1st parameter which means the message is to be received for this particular instance. On click of Work button the instance is completely new. Then why is it firing N times?

答: Are you sure it's firing N times for the same instance? You probably have N instances lying around (N-1 waiting to be garbage collected) and that's why you're seeing it N times.</p>

Body:
I have a view named Work.xaml. This Work.xaml contains multiple WorkSkeleton.xaml. The Work.xaml's ViewModel is WorkViewModel.

The Work.xaml is contained in MainPage.xaml which has button to load Work.xaml. I hope I am clear till now. The button's event handler is simple :-

 private void hypMyWork_Click(object sender, RoutedEventArgs e)
        {
            ShowGridContent(new Work());
        }

 private void ShowGridContent(UserControl control)
        {
            gridContent.Children.Clear();
            gridContent.Children.Add(control);
        }

In my Work.xaml.cs's Constructor I have registered for Messages of type ObservableCollection:

    Messenger.Default.Register<ObservableCollection<WorkEducation>>(this, "BindWorkEducationList", collection =>
    {
        foreach (var item in collection)
        {
            if (item.IsEducationInfo == false)
            {
                WorkEducationSkeleton skeleton = new WorkEducationSkeleton();
                skeleton.WorkEducation = item;
                stkPanel.Children.Insert(0,skeleton);

            }
        }
    });

The ViewModel is sending this message when the ObservableCollection is loaded like this :-

 Messenger.Default.Send<ObservableCollection<WorkEducation>>(WorkEducation,
                    "BindWorkEducationList");

Everything works fine the 1st time. But as soon as I click the Work button in MainPage.xaml to load the Work page 2nd time, the messages are received in my Work.xaml 2 times which adds the same items to stackpanel again and again. This happens N times. If I clicked the button Nth time the message will be received N times in Work.xaml.cs. But how is this possible?

I have clearly specified the recepient in Work.xaml.cs to be this as the 1st parameter which means the message is to be received for this particular instance. On click of Work button the instance is completely new. Then why is it firing N times?


问:
sed permission denied when overwriting file
I am trying to use sed to overwrite my index.php file, but I am getting an error:

```<code>$ sed -i 's@<head>@<head><script type="text/javascript" src="new.js"></script>@' index.php
sed: couldn't open temporary file ./sedmZNx8T: Permission denied
</code>```

Does anyone know how to fix this?

答:
While editing a file in place, sed creates a temporary file, saves the result and then finally mv the original file with the temporary one.

The problem is that you don't have write permission in the directory where sed is trying to create the temp file.

As the file is /tmp/file, check the permission of the directory where you are running the command.

Body:
I am trying to use sed to overwrite my index.php file, but I am getting an error:

$ sed -i 's@@@' index.php
sed: couldn't open temporary file ./sedmZNx8T: Permission denied

Does anyone know how to fix this?


问:
Have my Spring test slice scan a single class instead of the whole package
I was asked to create integration tests for an existing SpringBoot project, whose organisation is not as modular as I would prefer. For example, there is a package yielding all repositories associated with all services. This became a problem for me when I was attempting to create a @WebMvcTest test slice, because when I use @ComponentScan, @EnableJpaRepositories, @EntityScan to read my target classes it ends up scanning all other unnecessary ones that share the same package.

Since changing the project structure is not really a decision I can make on my own, my question is whether it is possible to have my test scan pick a specific class and disregard all others within the same package?

Thank you for your attention

答:
ComponentScan can work with slices. - It's actually configured on SpringBootApplication annotation itself. The part that makes test slices work with ComponentScan is TypeExcludeFilter:

```<code>@ComponentScan(
    basePackages = "com.mycompany.someotherpackage",
    excludeFilters = {
      @ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    })
</code>```

Body:
ComponentScan can work with slices. - It's actually configured on SpringBootApplication annotation itself. The part that makes test slices work with ComponentScan is TypeExcludeFilter:

@ComponentScan(
    basePackages = "com.mycompany.someotherpackage",
    excludeFilters = {
      @ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    })


问:
IUserRequestBuilder does not contain a definition for FindRooms, HOw to solve it in C#.net using microsoft graph?
I want list name of rooms created.  I got an error at FindingRooms method, IUserRequestBuilder  does not contain a definition for  FindRooms. How to solve it?

```<code> IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
            .Create("****-8d12-45ce-99dc-ee97478abc48")
            .WithTenantId("****-0c15-41f2-9858-b64924a83a6c").WithRedirectUri("http://localhost")
            .Build();

             var password = new SecureString();

            password.AppendChar('<');
            password.AppendChar('T');
            password.AppendChar('N');
            password.AppendChar('>');
            password.AppendChar('7');
 UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);
            Microsoft.Graph.User me = graphClient.Me.Request()
                .WithUsernamePassword("Tej@indica.onmicrosoft.com", password)
                .GetAsync().Result;

            var findRooms = await  graphClient.Me

         .FindRooms("Test@indica.onmicrosoft.com")
            .Request()
               .GetAsync();

</code>```

答: Currently, the findRooms API is in Graph beta version. So, you need to add Microsoft.Graph.Beta package.

Body:
I want list name of rooms created.  I got an error at FindingRooms method, IUserRequestBuilder  does not contain a definition for  FindRooms. How to solve it?

 IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
            .Create("****-8d12-45ce-99dc-ee97478abc48")
            .WithTenantId("****-0c15-41f2-9858-b64924a83a6c").WithRedirectUri("http://localhost")
            .Build();

             var password = new SecureString();

            password.AppendChar('<');
            password.AppendChar('T');
            password.AppendChar('N');
            password.AppendChar('>');
            password.AppendChar('7');
 UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);
            Microsoft.Graph.User me = graphClient.Me.Request()
                .WithUsernamePassword("Tej@indica.onmicrosoft.com", password)
                .GetAsync().Result;

            var findRooms = await  graphClient.Me

         .FindRooms("Test@indica.onmicrosoft.com")
            .Request()
               .GetAsync();


问:
I want to import an external fbx file to a stand alone unity project
Hello how can I import an fbx file to a unity build project without using unity engine.so I can access the new fbx file from the exe that I have built.</p>

答: Use this link It will work for sure. It can handle all formats like fbx, obj, glb, gltf etc.</p>


问:
how to disable the append value in a angular form
I have scenario where iam having the forms  with the name field, where i will pass the default value and i need to make this as read only or disabled  and also i can able to append the value with this.
eg: Room-123
Room-is the default value need to read only or disabled
123-can be append with the room and it can be editable.can anyone give a solution for this.

```<code>public  RoomValue: string='Room';
 public roomDiagForm = this.formBuilder.group({
    id:this.formBuilder.control(''),
    name: this.formBuilder.control(this.RoomValue, Validators.required),
    type: this.formBuilder.control('', Validators.required),
    locationId: this.formBuilder.control(this.location, Validators.required),
  });
</code>```

this is my code.

答:
In Angular reactive forms, you can instantiate a new control in the form group with the disable attribute set to true
Example :

```<code>this.formBuilder.group({
name : new FormControl({value: '', disabled: true})
})
</code>```

you can also conditionally disable using the below code

```<code>this.formBuilder.get('name').disable();

this.formBuilder.get('name').enable();
</code>```

you will also have to use the below code

```<code> "this.formBuilder.updateValueValidity()"
</code>```

after the disabling or enabling to apply the changes.

Body:
I have scenario where iam having the forms  with the name field, where i will pass the default value and i need to make this as read only or disabled  and also i can able to append the value with this.
eg: Room-123
Room-is the default value need to read only or disabled
123-can be append with the room and it can be editable.can anyone give a solution for this.

public  RoomValue: string='Room';
 public roomDiagForm = this.formBuilder.group({
    id:this.formBuilder.control(''),
    name: this.formBuilder.control(this.RoomValue, Validators.required),
    type: this.formBuilder.control('', Validators.required),
    locationId: this.formBuilder.control(this.location, Validators.required),
  });

this is my code.

Body:
In Angular reactive forms, you can instantiate a new control in the form group with the disable attribute set to true
Example :

this.formBuilder.group({
name : new FormControl({value: '', disabled: true})
})

you can also conditionally disable using the below code

this.formBuilder.get('name').disable();

this.formBuilder.get('name').enable();

you will also have to use the below code

 "this.formBuilder.updateValueValidity()"

after the disabling or enabling to apply the changes.


问:
Performance testing for Android application which uses UDP protocol, how to run jmeter script on android device for UDP requests plugin?
Using UDP requests plugin, I created jmeter script to run on desktop application. Now I am trying to run same jmeter script via Android device. I used 'Https Test script Recorder' but still I doesn't able to run UDP requests on android device. Is there any way to Run UDP requests on Android device ?</p>

答:
HTTP(S) Test Script Recorder as per its name can only capture HTTP or HTTPS

UDP is a different beast hence UDP packets cannot be captured by JMeter.

I would suggest using a lower-level sniffer tool like Wireshark which is capable of capturing UDP traffic and once you have the request payload you can simulate the request using UDP Request sampler (can be installed using JMeter Plugins Manager)

Check out Load Testing UDP - The Ultimate Guide article to get more information regarding the specifics of the UDP requests simulation using JMeter


问:
GCC Werror flag leads to "no option" error
I found the Wabsolute-value warning which I want to use as an error. However I get

```<code>cc1.exe:-1: error: error: -Werror=absolute-value: no option -Wabsolute-value
</code>```

When I try the warning itself, I get :

```<code>:-1: error: error: unrecognized command line option '-Wabsolute-value'; did you mean '-Wunused-value'?
</code>```

I am using GCC on Windows 10. Calling gcc --version in cmd gives :

```<code>g++ (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 7.3.0
</code>```

答: The default GCC page on warnings points to a different version of GCC, not 7.3.0 (but rather to the latest, probably). The manual page for warnings for 7.3.0 is here. This page does not speak of the absolute-value warning. It must be missing from 7.3.0 and must have been introduced later.

Body:
I found the Wabsolute-value warning which I want to use as an error. However I get

cc1.exe:-1: error: error: -Werror=absolute-value: no option -Wabsolute-value

When I try the warning itself, I get :

:-1: error: error: unrecognized command line option '-Wabsolute-value'; did you mean '-Wunused-value'?

I am using GCC on Windows 10. Calling gcc --version in cmd gives :

g++ (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 7.3.0


问:
How to setup a Rails integration test for XML methods?
Given a controller method like:

```<code>def show
  @model = Model.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.xml  { render :xml => model }
  end
end
</code>```

What's the best way to write an integration test that asserts that the return has the expected XML?

答:
This is the idiomatic way of testing the xml response from a controller.</p>

```<code>class ProductsControllerTest < ActionController::TestCase
  def test_should_get_index_formatted_for_xml
    @request.env['HTTP_ACCEPT'] = 'application/xml'
    get :index
    assert_response :success
  end
end
</code>```

OwnerDisplayName: Patrick Ritchie

Body:
Given a controller method like:

def show
  @model = Model.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.xml  { render :xml => model }
  end
end

What's the best way to write an integration test that asserts that the return has the expected XML?

Body:
This is the idiomatic way of testing the xml response from a controller.

class ProductsControllerTest < ActionController::TestCase
  def test_should_get_index_formatted_for_xml
    @request.env['HTTP_ACCEPT'] = 'application/xml'
    get :index
    assert_response :success
  end
end

OwnerDisplayName: btandyco


问:
Uniform EditText size
I'm trying to get all edit text views to be the same size without using a hard definition like px or dp, but rather to use a wrap_content and get them all to be the same size. This is what I have, but it doesn't work:

```<code>    enterAge = (EditText) findViewById(R.id.enterAge);
    enterAge.addTextChangedListener(new TextWatcher1());

    enterWeight = (EditText) findViewById(R.id.enterWeight);
    enterWeight.addTextChangedListener(new TextWatcher2());
    enterWeight.setWidth(enterAge.getWidth());

    enterHeight = (EditText) findViewById(R.id.enterHeight);
    enterHeight.addTextChangedListener(new TextWatcher3());
    enterHeight.setWidth(enterAge.getWidth());

    enterMealFrequency = (EditText) findViewById(R.id.enterMealFrequency);
    enterMealFrequency.addTextChangedListener(new TextWatcher4());
    enterMealFrequency.setWidth(enterAge.getWidth());
</code>```

Any suggestions on why this isn't working the way I want it to?

答:
wrap_content is fundamentally the opposite of what you are saying -- it specifies to make the view only as large as it needs to be, regardless of the parent size.

You need to write your UI as a view hierarchy with layouts describing how to position the views.  It is very simple to create a vertical row of text views that are all given them same width by putting them in a LinearLayout.

Title: Uniform EditText size

Body:
I'm trying to get all edit text views to be the same size without using a hard definition like px or dp, but rather to use a wrap_content and get them all to be the same size. This is what I have, but it doesn't work:

    enterAge = (EditText) findViewById(R.id.enterAge);
    enterAge.addTextChangedListener(new TextWatcher1());

    enterWeight = (EditText) findViewById(R.id.enterWeight);
    enterWeight.addTextChangedListener(new TextWatcher2());
    enterWeight.setWidth(enterAge.getWidth());

    enterHeight = (EditText) findViewById(R.id.enterHeight);
    enterHeight.addTextChangedListener(new TextWatcher3());
    enterHeight.setWidth(enterAge.getWidth());

    enterMealFrequency = (EditText) findViewById(R.id.enterMealFrequency);
    enterMealFrequency.addTextChangedListener(new TextWatcher4());
    enterMealFrequency.setWidth(enterAge.getWidth());

Any suggestions on why this isn't working the way I want it to?


问:
SqlServer 2019 using table and scalar function into cursor
I occurred a strange error:

Msg 596, Level 21, State 1, Line 0

Cannot continue the execution because the session is in the kill
  state.

It seems that error is generated when I use a cursor like :

```<code>DECLARE dbCursor CURSOR
            FOR
                SELECT (SELECT TOP 1 VAL FROM dbo.fn_Table('n:',dbo.[fn_Scalar](var)) ORDER BY VAL)
                from table
</code>```

If I taken the select to run it, it is ok.

If in cursor I execute only fn_Table OR fn_Scalar, it is ok.

If in cursor I execute BOTH functions, I have the above error.

In older versions of SQL server (than 2019) the cursor is running properly.

Could you, please, give me an idea?

Thank you.

L.E.
The functions are:
ALTER function [dbo].[UrlDecode](@url nvarchar(max))
returns nvarchar(max)
as
begin
    declare @foo datetime=getdate();

DECLARE @Position INT,
        @Base CHAR(16),
        @High TINYINT,
        @Low TINYINT,
        @Pattern CHAR(21)

```<code>SELECT  @Base = '0123456789abcdef',
    @Pattern = '%[%][0-9a-f][0-9a-f]%',
    @URL = REPLACE(@URL, '+', ' '),
    @Position = PATINDEX(@Pattern, @URL)

WHILE @Position > 0
    SELECT  @High = CHARINDEX(SUBSTRING(@URL, @Position + 1, 1), @Base COLLATE Latin1_General_CI_AS),
        @Low = CHARINDEX(SUBSTRING(@URL, @Position + 2, 1), @Base COLLATE Latin1_General_CI_AS),
        @URL = STUFF(@URL, @Position, 3, CHAR(16 * @High + @Low - 17)),
        @Position = PATINDEX(@Pattern, @URL)

RETURN  @URL
</code>```

end

ALTER FUNCTION [dbo].[Split] (@sep VARCHAR(32), @s VARCHAR(MAX))

RETURNS @t TABLE
    (
        val VARCHAR(MAX)
    )

AS
BEGIN

```<code>--declare @foo datetime=getdate();
--Remove separator if the case
IF RIGHT(LTRIM(RTRIM(@s)),1) = @sep
    SET @s = LEFT(LTRIM(RTRIM(@s)), LEN(LTRIM(RTRIM(@s))) - 1);

DECLARE @xml XML
SET @XML = N'<root><r>' + REPLACE(@s, @sep, '</r><r>') + '</r></root>'

INSERT INTO @t(val)
SELECT r.value('.','VARCHAR(250)') as Item
FROM @xml.nodes('//root/r') AS RECORDS(r)

RETURN
</code>```

END

And the cursor is:
DECLARE cursor_product CURSOR
FOR
select (SELECT TOP 1 VAL FROM dbo.split('n:',dbo.UrlDecode) ORDER BY VAL) from  ABSENTEE

OPEN cursor_product;

FETCH NEXT FROM cursor_product
WHILE @@FETCH_STATUS = 0
    BEGIN

```<code>    FETCH NEXT FROM cursor_product
END;
</code>```

CLOSE cursor_product;
DEALLOCATE cursor_product;

Please, ignore how is defined the cursor, the error occours, anyway.
Thank you.

答:
If the select alone runs well, I propose you to retrieve your data first into a table variable, so you can iterate it later, once the calls to your function are finished, avoiding any kind of weird locking between those calls.</p>

```<code>DECLARE @MyData table (VAL int)

INSERT INTO @MyData (VAL)
       SELECT (SELECT TOP 1 VAL FROM dbo.fn_Table('n:',dbo.[fn_Scalar](var)) ORDER BY VAL)
       FROM table

DECLARE dbCursor CURSOR FOR SELECT VAL FROM @MyData
</code>```

Body:
I occurred a strange error:

Msg 596, Level 21, State 1, Line 0

Cannot continue the execution because the session is in the kill
  state.

It seems that error is generated when I use a cursor like :

DECLARE dbCursor CURSOR
            FOR
                SELECT (SELECT TOP 1 VAL FROM dbo.fn_Table('n:',dbo.[fn_Scalar](var)) ORDER BY VAL)
                from table

If I taken the select to run it, it is ok.

If in cursor I execute only fn_Table OR fn_Scalar, it is ok.

If in cursor I execute BOTH functions, I have the above error.

In older versions of SQL server (than 2019) the cursor is running properly.

Could you, please, give me an idea?

Thank you.

L.E.
The functions are:
ALTER function [dbo].[UrlDecode](@url nvarchar(max))
returns nvarchar(max)
as
begin
    declare @foo datetime=getdate();

DECLARE @Position INT,
        @Base CHAR(16),
        @High TINYINT,
        @Low TINYINT,
        @Pattern CHAR(21)

SELECT  @Base = '0123456789abcdef',
    @Pattern = '%[%][0-9a-f][0-9a-f]%',
    @URL = REPLACE(@URL, '+', ' '),
    @Position = PATINDEX(@Pattern, @URL)

WHILE @Position > 0
    SELECT  @High = CHARINDEX(SUBSTRING(@URL, @Position + 1, 1), @Base COLLATE Latin1_General_CI_AS),
        @Low = CHARINDEX(SUBSTRING(@URL, @Position + 2, 1), @Base COLLATE Latin1_General_CI_AS),
        @URL = STUFF(@URL, @Position, 3, CHAR(16 * @High + @Low - 17)),
        @Position = PATINDEX(@Pattern, @URL)

RETURN  @URL

end

ALTER FUNCTION [dbo].[Split] (@sep VARCHAR(32), @s VARCHAR(MAX))

RETURNS @t TABLE
    (
        val VARCHAR(MAX)
    )

AS
BEGIN

--declare @foo datetime=getdate();
--Remove separator if the case
IF RIGHT(LTRIM(RTRIM(@s)),1) = @sep
    SET @s = LEFT(LTRIM(RTRIM(@s)), LEN(LTRIM(RTRIM(@s))) - 1);

DECLARE @xml XML
SET @XML = N'<root><r>' + REPLACE(@s, @sep, '</r><r>') + '</r></root>'

INSERT INTO @t(val)
SELECT r.value('.','VARCHAR(250)') as Item
FROM @xml.nodes('//root/r') AS RECORDS(r)

RETURN

END

And the cursor is:
DECLARE cursor_product CURSOR
FOR
select (SELECT TOP 1 VAL FROM dbo.split('n:',dbo.UrlDecode) ORDER BY VAL) from  ABSENTEE

OPEN cursor_product;

FETCH NEXT FROM cursor_product
WHILE @@FETCH_STATUS = 0
    BEGIN

    FETCH NEXT FROM cursor_product
END;

CLOSE cursor_product;
DEALLOCATE cursor_product;

Please, ignore how is defined the cursor, the error occours, anyway.
Thank you.

Body:
If the select alone runs well, I propose you to retrieve your data first into a table variable, so you can iterate it later, once the calls to your function are finished, avoiding any kind of weird locking between those calls.

DECLARE @MyData table (VAL int)

INSERT INTO @MyData (VAL)
       SELECT (SELECT TOP 1 VAL FROM dbo.fn_Table('n:',dbo.[fn_Scalar](var)) ORDER BY VAL)
       FROM table

DECLARE dbCursor CURSOR FOR SELECT VAL FROM @MyData


问:
Is there a way to do ask deploy through jenkins?
I want to automate the process of deploying Alexa skill through and want my pipeline to do the following for me:-

ask deploy --target lambda if my lambda has been modified

ask deploy --target model if my models have been modified.

I know I can put an IF condition either to check git log or check changeset in Jenkins and it Will solve my purpose, but since my skill is already in production I don't want to add any risk that by mistake skill gets modified and I will have to send it for re certification again.

答:
I figured out the solution, Thanks to link. I was under a misconception that Amazon discards my production version of skill as soon as I deploy new changes to it.It is rather different.

Now this is what I am doing:-

I am using ask deploy to deploy my lambda as well as skill.

I can send it for re certification whenever I wish and till then develop on my current Dev version.

Using Aliases for Prod deployment of lambda and can re-deploy my lambda on default $LATEST version till I don't decide to publish it to PROD.


问:
For loop is returning only last value
For the below for loop I am able to see all values. But when I assign new object to it, the value returned is only last (Refer last code). can anyone help me here please. Is it not possible to all values displayed with assigning a value?

```<code>for(i in 1:5)
+ {
+     for(j in 1:2)
+     {
+         print(i*j);
+     }
+ }
</code>```

Assigned a object.

```<code>for(i in 1:5)
+ {
+     for(j in 1:2)
+     {
+         as <- i*j
+     }
+ }
</code>```

答:
Here is a canonical R way of doing this:

```<code>as.vector(seq(1:2)%*%t(seq(1:5)))

[1]  1  2  2  4  3  6  4  8  5 10
</code>```

This approach takes the dot product product between [1,2] and t[1,2,3,4,5].  Instead of using explicit loops, it used vectors to represent the bounds of your two original loops.  The intermediate result is a matrix, which we can easily convert to a 1D vector in either column or row order, depending on the bounds of the loops.

Title: For loop is returning only last value

Body:
For the below for loop I am able to see all values. But when I assign new object to it, the value returned is only last (Refer last code). can anyone help me here please. Is it not possible to all values displayed with assigning a value?

for(i in 1:5)
+ {
+     for(j in 1:2)
+     {
+         print(i*j);
+     }
+ }

Assigned a object.

for(i in 1:5)
+ {
+     for(j in 1:2)
+     {
+         as <- i*j
+     }
+ }

Body:
Here is a canonical R way of doing this:

as.vector(seq(1:2)%*%t(seq(1:5)))

[1]  1  2  2  4  3  6  4  8  5 10

This approach takes the dot product product between [1,2] and t[1,2,3,4,5].  Instead of using explicit loops, it used vectors to represent the bounds of your two original loops.  The intermediate result is a matrix, which we can easily convert to a 1D vector in either column or row order, depending on the bounds of the loops.


问:
method is not called inside another method in JUnit
I have a method that calls another mehide inside.
Here is my method:

```<code>    public void unblocUser(BloclistDTO bloclistDTO) {
    blocListRepository.delete(mapper.toModel(bloclistDTO));
      if (blocListRepository.getBlocList(bloclistDTO.getCandidate().getId(), bloclistDTO.getColumnName()).isEmpty()) {
        this.setVisibility(bloclistDTO.getCandidate().getId(), bloclistDTO.getColumnName(), true);
    }
}
</code>```

I've tested the method setVisibility itself, it works. But, when clling unblocUser it doesn't work ;
Here is how am testing it:

```<code>@Test
public void unblocUserLastOne() {
        Company  blockedCompany = new Company ();
        Candidate  candidate = new Candidate ();
        candidate.setId(1L);
        candidate.setPersonalDetailsVisible(false);;
        blockedCompany.setId(2L);
        candidate.setPersonalDetailsVisible(false);
        BloclistDTO bloclist= new BloclistDTO();
        bloclist.setBlockedCandidate(null);
        bloclist.setCandidate(candidate);
        bloclist.setBlockedCompany(blockedCompany);
        bloclist.setColumnName("personal_details_visible");
        bloclist.setId(3L);
        blocListService.unblocUser(bloclist);
         assertEquals(true, candidate.isPersonalDetailsVisible());
}
</code>```

I get an error : expected true but was false.
Any help please ?

答:
first you need to create a mock object for BlocListRepository class

```<code>@InjectMocks
BlocListRepository blocListRepository;
</code>```

Then mock the delete method in BlocListRepository class.

```<code>@Test
public void unblocUserLastOne() {

    Mockito.doNothing().when(blocListRepository).delete(Mockito.any());

    Company  blockedCompany = new Company ();
    Candidate  candidate = new Candidate ();
    candidate.setId(1L);
    candidate.setPersonalDetailsVisible(false);;
    blockedCompany.setId(2L);
    candidate.setPersonalDetailsVisible(false);

    BloclistDTO bloclist= new BloclistDTO();
    bloclist.setBlockedCandidate(null);
    bloclist.setCandidate(candidate);
    bloclist.setBlockedCompany(blockedCompany);
    bloclist.setColumnName("personal_details_visible");
    bloclist.setId(3L);
    blocListService.unblocUser(bloclist);
    assertEquals(true, candidate.isPersonalDetailsVisible());
}
</code>```

Body:
I have a method that calls another mehide inside.
Here is my method:

    public void unblocUser(BloclistDTO bloclistDTO) {
    blocListRepository.delete(mapper.toModel(bloclistDTO));
      if (blocListRepository.getBlocList(bloclistDTO.getCandidate().getId(), bloclistDTO.getColumnName()).isEmpty()) {
        this.setVisibility(bloclistDTO.getCandidate().getId(), bloclistDTO.getColumnName(), true);
    }
}

I've tested the method setVisibility itself, it works. But, when clling unblocUser it doesn't work ;
Here is how am testing it:

@Test
public void unblocUserLastOne() {
        Company  blockedCompany = new Company ();
        Candidate  candidate = new Candidate ();
        candidate.setId(1L);
        candidate.setPersonalDetailsVisible(false);;
        blockedCompany.setId(2L);
        candidate.setPersonalDetailsVisible(false);
        BloclistDTO bloclist= new BloclistDTO();
        bloclist.setBlockedCandidate(null);
        bloclist.setCandidate(candidate);
        bloclist.setBlockedCompany(blockedCompany);
        bloclist.setColumnName("personal_details_visible");
        bloclist.setId(3L);
        blocListService.unblocUser(bloclist);
         assertEquals(true, candidate.isPersonalDetailsVisible());
}

I get an error : expected true but was false.
Any help please ?

Body:
first you need to create a mock object for BlocListRepository class

@InjectMocks
BlocListRepository blocListRepository;

Then mock the delete method in BlocListRepository class.

@Test
public void unblocUserLastOne() {

    Mockito.doNothing().when(blocListRepository).delete(Mockito.any());

    Company  blockedCompany = new Company ();
    Candidate  candidate = new Candidate ();
    candidate.setId(1L);
    candidate.setPersonalDetailsVisible(false);;
    blockedCompany.setId(2L);
    candidate.setPersonalDetailsVisible(false);

    BloclistDTO bloclist= new BloclistDTO();
    bloclist.setBlockedCandidate(null);
    bloclist.setCandidate(candidate);
    bloclist.setBlockedCompany(blockedCompany);
    bloclist.setColumnName("personal_details_visible");
    bloclist.setId(3L);
    blocListService.unblocUser(bloclist);
    assertEquals(true, candidate.isPersonalDetailsVisible());
}


问:
Tensorflow object detection API and images size
I'm practicing with computer vision in general and specifically with the TensorFlow object detection API, and there are a few things I don't really understand yet.

I'm trying to re-train an SSD model to detect one class of custom objects (guitars).

I've been using ssd_mobilenet_v1_coco and ssd_mobilenet_v2_coco models, with a dataset of 1000K pre-labeled images downloaded from the OpenImage dataset. I used the standard configuration file, only modifying the necessary parts.

I'm getting slightly unsatisfactory detections on small objects, which is supposed to be normal when using SSD models. Here on stackoverflow I saw people suggesting to crop the image in smaller frames, but I'm having trouble understanding a few things:

According to the .config file and the SSD papers, images are resized to the fixed dimension of 300x300 pixels (I'm assuming it holds both when training the model and when using it for inference). So, I guess it means that the original size of training and test/evaluation images doesn't matter, because they're always resized to 300x300 anyway? Then, I don't understand why many people suggest using images of the same size of the ones the models has been trained on...does it matter or not?

It's not really clear to me what "small objects" means in the first place.

Is it referred to the size ratio between the object and the whole image? So, a small object is one that covers...say, less than 5% of the total image?

Or is it referred to the number of pixels forming the object?

In the first case, cropping the image around the object would make sense. In the second case, it shouldn't work, because the number of useful pixels identifying the object stays the same.

Thanks!

答:
I am not sure for the answer I am giving below but it worked for me, as you correctly said that images are resized to 300x 300 in the config file of ssd_mobilenet-v2, what this resizing does is compress image to 300 x 300 thus loosing the important features. This adversely effect the object that are small in size as they have much to loose. Depending on the GPU power you have you can make some changes in the config file:
1st- change the following line as
image_resizer {
fixed_shape_resizer {
height: 600
width: 600
}
}
thus now giving double the data(in the config file).
2nd - What the above change will do is throw your GPU out of memory, so you need to reduce the batch size from 24 to 12 or 8, which can lead to over fitting so do check the regularization parameters too.

3rd- optional method is to comment out the following
enter image description here

this helps a lot and reduce the time to train by almost half. the trade off is if the image is not aligned as your train data, the confidence level of the model will drop and it may completely not recognize inverted cat.


问:
How to set UINavigationController as root from UITabBarController.?
I am working on App where Login is shown to user, after successful login user is landed on dashboard. where 4 tabs are shown to navigate to respective use.
I have to use, UITabBarController for four tabs from dashboard and UINavigationController for navigation from LoginView.

I set my UITabBarController to navigationController, when user successfully logged in.
Each view will have one logout button, on click of which I have to set my navigationcontroller back to root.

Here is code sample which I have done.

My UITabBarController

class TabBarVC: UITabBarController {

```<code>let dashboardViewObj = DashboardVC()
let registerViewObj = RegisterVC()
let alertViewObj = AlertVC()
let historyViewObj = HistoryVC()
override func viewDidLoad() {
    super.viewDidLoad()
    self.viewControllers = [dashboardViewObj, registerViewObj,historyViewObj,alertViewObj]
    // Do any additional setup after loading the view.

    dashboardViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .search, tag: 0)
    registerViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 0)
    historyViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 0)
    alertViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .bookmarks, tag: 0)
}
</code>```

In my LoginViewContoller

let tabbarObj = TabBarVC()

```<code>@IBAction func loginBtnClicked(_ sender: Any) {
            self.navigationController?.setViewControllers([tabbarObj], animated: true)
        }
</code>```

Now on click of logout button from any of these views, I need to set navigationController as root.
How to do it...?

Following chart will help to understand what I need.
Any help will be appeciated.

答:
When you are login all you need to put this code in your logout button action and it will redirect you to login page.

```<code>   var window: UIWindow?
   let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate

      let VC = self.appDelegate.storyboard1.instantiateViewController(withIdentifier: "Your controller name") as! loginViewController
            self.appDelegate.navigationController = UINavigationController(rootViewController: VC)
            self.appDelegate.navigationController?.navigationBar.isHidden = true
            self.appDelegate.window?.rootViewController = self.appDelegate.navigationController
            self.appDelegate.window?.makeKeyAndVisible()
</code>```

it will work.

Body:
I am working on App where Login is shown to user, after successful login user is landed on dashboard. where 4 tabs are shown to navigate to respective use.
I have to use, UITabBarController for four tabs from dashboard and UINavigationController for navigation from LoginView.

I set my UITabBarController to navigationController, when user successfully logged in.
Each view will have one logout button, on click of which I have to set my navigationcontroller back to root.

Here is code sample which I have done.

My UITabBarController

class TabBarVC: UITabBarController {

let dashboardViewObj = DashboardVC()
let registerViewObj = RegisterVC()
let alertViewObj = AlertVC()
let historyViewObj = HistoryVC()
override func viewDidLoad() {
    super.viewDidLoad()
    self.viewControllers = [dashboardViewObj, registerViewObj,historyViewObj,alertViewObj]
    // Do any additional setup after loading the view.

    dashboardViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .search, tag: 0)
    registerViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 0)
    historyViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 0)
    alertViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .bookmarks, tag: 0)
}

In my LoginViewContoller

let tabbarObj = TabBarVC()

@IBAction func loginBtnClicked(_ sender: Any) {
            self.navigationController?.setViewControllers([tabbarObj], animated: true)
        }

Now on click of logout button from any of these views, I need to set navigationController as root.
How to do it...?

Following chart will help to understand what I need.
Any help will be appeciated.

Body:
When you are login all you need to put this code in your logout button action and it will redirect you to login page.

   var window: UIWindow?
   let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate

      let VC = self.appDelegate.storyboard1.instantiateViewController(withIdentifier: "Your controller name") as! loginViewController
            self.appDelegate.navigationController = UINavigationController(rootViewController: VC)
            self.appDelegate.navigationController?.navigationBar.isHidden = true
            self.appDelegate.window?.rootViewController = self.appDelegate.navigationController
            self.appDelegate.window?.makeKeyAndVisible()

it will work.


问:
input type file in Opera
I have tried to fire onkeydown, onkeypress and onkeyup events on file input(e.g. when the element is on focus and a key is pressed the events are not fired), but they doesn't work in Opera. Firing 'click' with jQuery , doesn't work too (e.g. $('#myFileinput').Click() or $('#myFileinput').trigger('click')).

Is there a way to trigger these events in Opera ?

Here is my code:

```<code> <input type="file" class="foo" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript">
    debugger;
    window.onload = onPageLoad;
    function onPageLoad() {

        var input = $(".foo");
        debugger;
        input.keydown(function () {
            //doesn't work in Opera
            alert("keydown");
        });

        input.keypress(function () {
            //doesn't work in Opera
            alert("keypress");
        });

        input.keyup(function () {
            //doesn't work in Opera
            alert("keyup");
        })
    }

    window.onkeydown = function () {
        //when the focus is on the input the code bellow doesn't fire
        alert("window key down")

    }

</script>
</code>```

答: Due to security policies, it is limited what events Opera fires on an input type=file. Also, in new Opera versions focusing the input will bring up a file dialog, so no key events would ever fire on the input anyway. If you need to know when the value changes, listen for the change event.</p>

Title: input type file in Opera

Body:
I have tried to fire onkeydown, onkeypress and onkeyup events on file input(e.g. when the element is on focus and a key is pressed the events are not fired), but they doesn't work in Opera. Firing 'click' with jQuery , doesn't work too (e.g. $('#myFileinput').Click() or $('#myFileinput').trigger('click')).

Is there a way to trigger these events in Opera ?

Here is my code:

 <input type="file" class="foo" />


问:
A constraint with function that contains Select is never satisfied
I have a table like this:

```<code>CREATE TABLE CarRentSchedule
(
    carId INTEGER NOT NULL,
    rent_start INTEGER NOT NULL,
    rent_end INTEGER NOT NULL,
    personId INTEGER NOT NULL,
    tariff INTEGER NOT NULL,
    PRIMARY KEY carId,
    FOREIGN KEY (personId) REFERENCES Persons(PersonID)
    CONSTRAINT CHK_CR_AVLBL CHECK (dbo.CarCheck(carId , rent_start , rent_end ) = 1))
</code>```

And I need to forbid any rent time intersection for the same car.
I found that, when a function is used (example below) inside the constraint, the value it returns is different from whent it is used outside the constraint.

```<code>if exists (select * from dbo.CarRentSchedule rt
               where rt.carId = @id
                 and ((rt.rent_Start >= @startTime and rt.rent_end < @endTime)
                      or
                      (rt.rent_end <= @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start < @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start >= @startTime and rt.rent_end <= @endTime)))
        return 0
</code>```

So when I'm trying to insert data into the table, the constraint would never allow me to for some reason.

I have checked, when called from the constraint the function seems to return NULL, however calling the function like

```<code>select dbo.CheckFunc(1, 10, 15, 1, 1)
</code>```

would return 0/1 as it is supposed to. I have also checked and found out that if there is no SELECT in the function (a simple comparison operation, for example) it would work just fine in the constraint too.

Could anybody explain why does this work this way? Is it some restriction forbidding using SELECT's inside the constraints or is it because the SELECT references to the same table the constraint applied to?

答:
Can you try below if that works :</p>

```<code>Alter function AvailableCar
    (@car integer, @startTime integer, @endTime integer)
returns integer
as
begin
declare @value int
    set @value = (select max(1) from dbo.CarRentSchedule as rt
               where rt.roomId = @car
                 and ((rt.rent_Start >= @startTime and p.occ_start < @endTime)
                      or
                      (rt.rent_end <= @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start < @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start >= @startTime and rt.rent_end <= @endTime)))
       if (@value is NULL)
       set @value = 0

       return @value

end
</code>```

Body:
I have a table like this:

CREATE TABLE CarRentSchedule
(
    carId INTEGER NOT NULL,
    rent_start INTEGER NOT NULL,
    rent_end INTEGER NOT NULL,
    personId INTEGER NOT NULL,
    tariff INTEGER NOT NULL,
    PRIMARY KEY carId,
    FOREIGN KEY (personId) REFERENCES Persons(PersonID)
    CONSTRAINT CHK_CR_AVLBL CHECK (dbo.CarCheck(carId , rent_start , rent_end ) = 1))

And I need to forbid any rent time intersection for the same car.
I found that, when a function is used (example below) inside the constraint, the value it returns is different from whent it is used outside the constraint.

if exists (select * from dbo.CarRentSchedule rt
               where rt.carId = @id
                 and ((rt.rent_Start >= @startTime and rt.rent_end < @endTime)
                      or
                      (rt.rent_end <= @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start < @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start >= @startTime and rt.rent_end <= @endTime)))
        return 0

So when I'm trying to insert data into the table, the constraint would never allow me to for some reason.

I have checked, when called from the constraint the function seems to return NULL, however calling the function like

select dbo.CheckFunc(1, 10, 15, 1, 1)

would return 0/1 as it is supposed to. I have also checked and found out that if there is no SELECT in the function (a simple comparison operation, for example) it would work just fine in the constraint too.

Could anybody explain why does this work this way? Is it some restriction forbidding using SELECT's inside the constraints or is it because the SELECT references to the same table the constraint applied to?

Body:
Can you try below if that works :

Alter function AvailableCar
    (@car integer, @startTime integer, @endTime integer)
returns integer
as
begin
declare @value int
    set @value = (select max(1) from dbo.CarRentSchedule as rt
               where rt.roomId = @car
                 and ((rt.rent_Start >= @startTime and p.occ_start < @endTime)
                      or
                      (rt.rent_end <= @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start < @endTime and rt.rent_end > @startTime)
                      or
                      (rt.rent_Start >= @startTime and rt.rent_end <= @endTime)))
       if (@value is NULL)
       set @value = 0

       return @value

end


问:
Could not display TreeView in Python
Trying out a really simple TreeView control for Qt in Python, but for some reason the GUI is just blank.

main.qml

```<code>import QtQuick 2.14
import QtQuick.Controls 2.14
import QtQuick.Controls 1.4 as OldControls

ApplicationWindow {
    visible: true
    title: qsTr("Simple Tree View")

    OldControls.TreeView {
        anchors.fill: parent
        model: simpleModel
        OldControls.TableViewColumn {
            role: "display"
            title: "Name"
            width: 100
        }
    }
}
</code>```

main.py

```<code>import sys
from os.path import abspath, dirname, join

from PySide2.QtGui import QGuiApplication, QStandardItemModel, QStandardItem
from PySide2.QtQml import QQmlApplicationEngine

class SimpleTreeView(QStandardItemModel):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setColumnCount(1)

        root = self.invisibleRootItem()
        group1 = QStandardItem("group1")
        group1.setText("group1")
        value1 = QStandardItem("value1")
        value1.setText("value1")
        group1.appendRow(value1)
        root.appendRow(group1)

if __name__ == '__main__':
    app = QGuiApplication(sys.argv)

    engine = QQmlApplicationEngine()
    qmlFile = join(dirname(__file__), 'main.qml')
    engine.rootContext().setContextProperty("simpleModel", SimpleTreeView())
    engine.load(abspath(qmlFile))

    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
</code>```

Output in Linux

答:
The problem is that since the SimpleTreeView object is not assigned to a variable then it is destroyed, that can be verified using the destroyed signal.

```<code>class SimpleTreeView(QStandardItemModel):
    def __init__(self, parent=None):
        super().__init__(parent)

        <b>self.destroyed.connect(lambda o : print("destroyed:", o))</b>
        # ...</code>```

Output:

```<code>destroyed: <PySide2.QtCore.QObject(0x56377cf050f0) at 0x7ffa20deac40>
</code>```

The solution is to assign a variable to that object so that the life cycle is greater:

```<code>qmlFile = join(dirname(__file__), 'main.qml')
<b>model = SimpleTreeView()</b>
engine.rootContext().setContextProperty("simpleModel", <b>model</b>)
# ...</code>```

Title: Could not display TreeView in Python

Body:
Trying out a really simple TreeView control for Qt in Python, but for some reason the GUI is just blank.

main.qml

import QtQuick 2.14
import QtQuick.Controls 2.14
import QtQuick.Controls 1.4 as OldControls

ApplicationWindow {
    visible: true
    title: qsTr("Simple Tree View")

    OldControls.TreeView {
        anchors.fill: parent
        model: simpleModel
        OldControls.TableViewColumn {
            role: "display"
            title: "Name"
            width: 100
        }
    }
}

main.py

import sys
from os.path import abspath, dirname, join

from PySide2.QtGui import QGuiApplication, QStandardItemModel, QStandardItem
from PySide2.QtQml import QQmlApplicationEngine

class SimpleTreeView(QStandardItemModel):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setColumnCount(1)

        root = self.invisibleRootItem()
        group1 = QStandardItem("group1")
        group1.setText("group1")
        value1 = QStandardItem("value1")
        value1.setText("value1")
        group1.appendRow(value1)
        root.appendRow(group1)

if __name__ == '__main__':
    app = QGuiApplication(sys.argv)

    engine = QQmlApplicationEngine()
    qmlFile = join(dirname(__file__), 'main.qml')
    engine.rootContext().setContextProperty("simpleModel", SimpleTreeView())
    engine.load(abspath(qmlFile))

    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())

Output in Linux

Body:
The problem is that since the SimpleTreeView object is not assigned to a variable then it is destroyed, that can be verified using the destroyed signal.

class SimpleTreeView(QStandardItemModel):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.destroyed.connect(lambda o : print("destroyed:", o))
        # ...

Output:

destroyed: <PySide2.QtCore.QObject(0x56377cf050f0) at 0x7ffa20deac40>

The solution is to assign a variable to that object so that the life cycle is greater:

qmlFile = join(dirname(__file__), 'main.qml')
model = SimpleTreeView()
engine.rootContext().setContextProperty("simpleModel", model)
# ...


问:
Unable to click parameters tab in Jmeter 5.2.1
I am trying to pass an authorization header along with a request body to an HTTP request in Jmeter. When i pass a parameterized body, I am not able to click on the parameters tab to pass a header, and if I add the header first, the body data tab becomes non-clickable. Please help.</p>

答:
Parameters are being used for the URL Parameters or for the Query String.

Use HTTP Header Manager to pass an authorization header along with your request body in JMeter.

Just right click on your HTTP sampler and then add HTTP Header Manager from the config element.

In Header Manager, You can add multiple header information along with the request.


答:
So, the for loop is very inefficient here. You should multiply vectors instead. E.g.

```<code> rep(1:5, each = 2)
</code>```

gives you

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

and if you multiply this with

```<code>1:2
</code>```

the shorter vector gets recycled and you get this:

```<code>rep(1:5, each = 2) * 1:2
[1]  1  2  2  4  3  6  4  8  5 10
</code>```

Title: For loop is returning only last value

Body:
So, the for loop is very inefficient here. You should multiply vectors instead. E.g.

 rep(1:5, each = 2)

gives you

[1] 1 1 2 2 3 3 4 4 5 5

and if you multiply this with

1:2

the shorter vector gets recycled and you get this:

rep(1:5, each = 2) * 1:2
[1]  1  2  2  4  3  6  4  8  5 10


问:
Unable to add custom settings file to Asp.Net Core 3.1 WebApi
I am writing a WebApi for tracking my puppy's doings (potty breaks, crate training etc). The api has a front-end component written in Blazor, but that is not part of this question.

On my github projects, I never use the file appsettings.json in fear of accidentally commiting it and thus exposing any secrets. Instead, I wanted to add my own appsettings file as such:

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(config => {
                    var basePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    var fileName = "puppytrackersettings.json";
                    var fullPath = Path.Combine(basePath, fileName);

                    if(File.Exists(fullPath))
                    {
                        config.SetBasePath(basePath);
                        config.AddJsonFile(fileName, optional: true);
                    }
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
```

This way, the settings file can be maintained in the "My Documents" folder ("/" on linux), safely tucked away far from the source code.

PROBLEM

The problem is that the config is only updated with this added json file while in the CreateHostBuilder() method. Once the configuration gets activated in Startup.cs the configuration is back to it's default config. I see that the configurationproviders are 5 before entering CreateHostBuilder(), then it jumps up to 6 once I add my json file, but then when Startup.ConfigureServices() runs, the configuration is back to 5 again.

I've tried numerous ways of creating a configuration for the webapi, but none work.

WORKAROUND

So far, my workaround is to use application secrets in VS, but since some of the settings, such as Application Insights Telemetry Key are shared, it is a pain to replicate across all the microservices, since I can't point to an existing app secret.

Does anyone know what I am doing wrong, or how to do this correctly?

Version of .Net Core is 3.1.101
Visual Studio: 16.4.5

答:
Is I correctly understand that you want to store some configs (like passwords or API-keys) in separate folder? So, it's very reasonable to not  store such data in the git-repository.

FIRST SOLUTION

Do you know  about AddInMemoryCollection or AddEFConfiguration or AddCommandLine or AddEnvironmentVariables?

By this methods you can extend your settings file by values from Database, Commandline Parameters or Environment variables.

If I were you I will use AddEnvironmentVariables.

See more information here https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

ONE MORE SOLUTION

You can add file with specific data to you code and ignore it in GIT. So, if this file will be optional then your application will not fail but you will have posibility to changle configuration.

To do this make something like this:

```<code>public IConfiguration Configuration { get; set; }
public IHostingEnvironment Environment { get; set; }

public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
   Environment = environment;
   Configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.secrets.json")
            .Build();
}
</code>```

and add appsettings.secrets.json to you git ignore

ONE MORE SOLUTION

So, why you use SetBasePath?
Why you not use  AddJsonFile  with full path? Like this:

```<code>if(File.Exists(fullPath))
{
    config.AddJsonFile(fileName, optional: true);
}
</code>```

Body:
I am writing a WebApi for tracking my puppy's doings (potty breaks, crate training etc). The api has a front-end component written in Blazor, but that is not part of this question.

On my github projects, I never use the file appsettings.json in fear of accidentally commiting it and thus exposing any secrets. Instead, I wanted to add my own appsettings file as such:

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(config => {
                    var basePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    var fileName = "puppytrackersettings.json";
                    var fullPath = Path.Combine(basePath, fileName);

                    if(File.Exists(fullPath))
                    {
                        config.SetBasePath(basePath);
                        config.AddJsonFile(fileName, optional: true);
                    }
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

This way, the settings file can be maintained in the "My Documents" folder ("/" on linux), safely tucked away far from the source code.

PROBLEM

The problem is that the config is only updated with this added json file while in the CreateHostBuilder() method. Once the configuration gets activated in Startup.cs the configuration is back to it's default config. I see that the configurationproviders are 5 before entering CreateHostBuilder(), then it jumps up to 6 once I add my json file, but then when Startup.ConfigureServices() runs, the configuration is back to 5 again.

I've tried numerous ways of creating a configuration for the webapi, but none work.

WORKAROUND

So far, my workaround is to use application secrets in VS, but since some of the settings, such as Application Insights Telemetry Key are shared, it is a pain to replicate across all the microservices, since I can't point to an existing app secret.

Does anyone know what I am doing wrong, or how to do this correctly?

Version of .Net Core is 3.1.101
Visual Studio: 16.4.5

Body:
Is I correctly understand that you want to store some configs (like passwords or API-keys) in separate folder? So, it's very reasonable to not  store such data in the git-repository.

FIRST SOLUTION

Do you know  about AddInMemoryCollection or AddEFConfiguration or AddCommandLine or AddEnvironmentVariables?

By this methods you can extend your settings file by values from Database, Commandline Parameters or Environment variables.

If I were you I will use AddEnvironmentVariables.

See more information here https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

ONE MORE SOLUTION

You can add file with specific data to you code and ignore it in GIT. So, if this file will be optional then your application will not fail but you will have posibility to changle configuration.

To do this make something like this:

public IConfiguration Configuration { get; set; }
public IHostingEnvironment Environment { get; set; }

public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
   Environment = environment;
   Configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.secrets.json")
            .Build();
}

and add appsettings.secrets.json to you git ignore

ONE MORE SOLUTION

So, why you use SetBasePath?
Why you not use  AddJsonFile  with full path? Like this:

if(File.Exists(fullPath))
{
    config.AddJsonFile(fileName, optional: true);
}


问:
get view id from oncontextitemselected
I've several buttons registered for context menu

how do I know which button was clicked for the menu to appear?

below is the pseudocode that i'll be using. I need to do something related to which button clicked (I have few more buttons to be declared), how do I know that the context menu is activated from which button click.

EDIT: I think i didn't make myself clear, I wanted to know which button was clicked for the menu to appear. Not which menu item is clicked. Anyways, I've a solution which I'll add in pretty soon.

thanks

```<code>private static final int SEND_AS_TEXT = Menu.FIRST;
private static final int SEND_AS_IMAGE = Menu.FIRST + 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        sendAllBtn = (Button)findViewById(R.id.sendAllBtn);
        sendAllBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        registerForContextMenu(v);
        openContextMenu(v);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch(item.getItemId()){
        case SEND_AS_TEXT:
            //do sth related to the button clicked
            break;

        }
        return super.onContextItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        // TODO Auto-generated method stub
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(Menu.NONE, SEND_AS_TEXT, SEND_AS_TEXT, "Send As Text");
        menu.add(Menu.NONE, SEND_AS_IMAGE, SEND_AS_IMAGE, "Send As Image");
    }
</code>```

答:
try this...</p>

```<code>@Override
public boolean onContextItemSelected(MenuItem item)
 {
    if(item.getItemId()==SEND_AS_TEXT)
    {
        //code for send text
    }
    else if(item.getItemId()==SEND_AS_IMAGE)
    {
       //code for send image
    }
    return super.onContextItemSelected(item);
}
</code>```

Title: get view id from oncontextitemselected

Body:
I've several buttons registered for context menu

how do I know which button was clicked for the menu to appear?

below is the pseudocode that i'll be using. I need to do something related to which button clicked (I have few more buttons to be declared), how do I know that the context menu is activated from which button click.

EDIT: I think i didn't make myself clear, I wanted to know which button was clicked for the menu to appear. Not which menu item is clicked. Anyways, I've a solution which I'll add in pretty soon.

thanks

private static final int SEND_AS_TEXT = Menu.FIRST;
private static final int SEND_AS_IMAGE = Menu.FIRST + 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        sendAllBtn = (Button)findViewById(R.id.sendAllBtn);
        sendAllBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        registerForContextMenu(v);
        openContextMenu(v);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch(item.getItemId()){
        case SEND_AS_TEXT:
            //do sth related to the button clicked
            break;

        }
        return super.onContextItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        // TODO Auto-generated method stub
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(Menu.NONE, SEND_AS_TEXT, SEND_AS_TEXT, "Send As Text");
        menu.add(Menu.NONE, SEND_AS_IMAGE, SEND_AS_IMAGE, "Send As Image");
    }

Body:
try this...

@Override
public boolean onContextItemSelected(MenuItem item)
 {
    if(item.getItemId()==SEND_AS_TEXT)
    {
        //code for send text
    }
    else if(item.getItemId()==SEND_AS_IMAGE)
    {
       //code for send image
    }
    return super.onContextItemSelected(item);
}


问:
Update a List's object using Linq
I would like to assign an object in a list using Linq, but I can't find how to do it.
I tried this:

Items.Where(i => i.Code == line.Code).Single() = line;

But it seems I simply cannot give the statement an object.
I can modify properties of those objects (Like this) :

```<code>Items.Where(i => i.Code == line.Code).Single().name = line.name;
</code>```

But giving it the full item doesn't seem to be accepted.
Is there a reason to prevent this / a way to assign my value to the compatible item ?
Thank you for your answer.

答:
Will below linq address your requirement?</p>

```<code>      items.Where(i => i.Code== line.code)?.ToList()?.ForEach(i => i.name= line.name);
</code>```

Title: Update a List's object using Linq

Body:
I would like to assign an object in a list using Linq, but I can't find how to do it.
I tried this:

Items.Where(i => i.Code == line.Code).Single() = line;

But it seems I simply cannot give the statement an object.
I can modify properties of those objects (Like this) :

Items.Where(i => i.Code == line.Code).Single().name = line.name;

But giving it the full item doesn't seem to be accepted.
Is there a reason to prevent this / a way to assign my value to the compatible item ?
Thank you for your answer.

Body:
Will below linq address your requirement?

      items.Where(i => i.Code== line.code)?.ToList()?.ForEach(i => i.name= line.name);


问:
Execute javascript on html partial render in Ruby on Rails
I am trying to get some elements of a partial whenever it is rendered. The problem is that I can use document.addEventListener('DOMContentLoaded', () => {}); when the whole page is rendered but I am not able to figure out how to get the elements everytime the html partial is rendered.

js code

```<code>window.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('answer_choices');
});
</code>```

How can I call this event whenever the partial is rendered. I can include the javascript file in the partial itself but it creates a lot of overhead. So this javascript file is included in the main html file but I want the querySelectorAll function to be triggered whenever the html partial is rendered. How can I do the same?

答:
If you use Jquery - you can do it in that way:

$(function() {
   document.querySelectorAll('answer_choices');
})
```

Body:
I am trying to get some elements of a partial whenever it is rendered. The problem is that I can use document.addEventListener('DOMContentLoaded', () => {}); when the whole page is rendered but I am not able to figure out how to get the elements everytime the html partial is rendered.

js code

window.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('answer_choices');
});

How can I call this event whenever the partial is rendered. I can include the javascript file in the partial itself but it creates a lot of overhead. So this javascript file is included in the main html file but I want the querySelectorAll function to be triggered whenever the html partial is rendered. How can I do the same?


问:
Select the IDs using group by condition
I have a dataset where I need to find the diseased patients in consecutive rows.

I'll share my sample dataset with a clear explanation.

```<code>ID Normal Des1 Des2 Des3 Des4
12 0      1    0    0    0
12 1      0    1    0    0
12 1      0    1    0    0
12 1      0    1    0    0
14 0      1    0    1    0
18 1      0    0    0    0
18 1      0    0    0    0
18 1      0    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
22 1      0    0    0    0
</code>```

Here I specified the Diseased list of the dataset. I required the IDs for those who are in the same Disease in all the period.
Assume that I need an output for Patients who never fall in any Diseased criteria(IDs 18, 22) I stored it as a new set(Undiseased), Later I need to get the same model for Des1 patients (IDs 11). I tried the below code to fetch the data. but It returns partial output.

```<code>select ID from tablename where
(normal = '1' and Des1 = '0' and Des2 = '0' and Des3 = '0' and Des4 = '0')
group by ID
</code>```

答:
You can use use apply :

```<code>select t.id
from table t cross apply
     ( values (Des1, 'Des1'), (Des2, 'Des2'), (Des3, 'Des3'), (Des4, 'Des4')
     ) tt(DiseasFlag, DiseasName)
where DiseasFlag = 1
group by t.id
having count(distinct DiseasName) = 1;
</code>```

Title: Select the IDs using group by condition

Body:
I have a dataset where I need to find the diseased patients in consecutive rows.

I'll share my sample dataset with a clear explanation.

ID Normal Des1 Des2 Des3 Des4
12 0      1    0    0    0
12 1      0    1    0    0
12 1      0    1    0    0
12 1      0    1    0    0
14 0      1    0    1    0
18 1      0    0    0    0
18 1      0    0    0    0
18 1      0    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
22 1      0    0    0    0

Here I specified the Diseased list of the dataset. I required the IDs for those who are in the same Disease in all the period.
Assume that I need an output for Patients who never fall in any Diseased criteria(IDs 18, 22) I stored it as a new set(Undiseased), Later I need to get the same model for Des1 patients (IDs 11). I tried the below code to fetch the data. but It returns partial output.

select ID from tablename where
(normal = '1' and Des1 = '0' and Des2 = '0' and Des3 = '0' and Des4 = '0')
group by ID

Body:
You can use use apply :

select t.id
from table t cross apply
     ( values (Des1, 'Des1'), (Des2, 'Des2'), (Des3, 'Des3'), (Des4, 'Des4')
     ) tt(DiseasFlag, DiseasName)
where DiseasFlag = 1
group by t.id
having count(distinct DiseasName) = 1;


问:
Hiding span under div in CSS
Below is the code for my WP post. I'm trying to hide the span for comment. So that it doesn't appear on the blog post.

```<code><div class="blog-stats">
    <span class="clock">
        <i class="fa fa-calendar stats-item"></i>
        <span class="text-center text-light stats-item">February 15, 2020</span>
    </span>
    <span class="comment">
        <i class="fa fa-comment stats-item"></i>
        <span class="text-center text-light stats-item">no comments</span>
    </span>
    <span class="user">
        <i class="fa fa-user stats-item"></i>
        <span class="text-content text-light stats-item">Wayne John</span>
    </span>
</div>
</code>```

I tried a few below and it didn't work.

```<code>.blog-stats.comment {
    display: none;
}

span .comment {
    display: none;
}

span.comment {
    display: none;
}
</code>```

Any idea how to fix it?

答:
In case if you don't want to use !important try the below version.

```<code>.blog-stats .comment.comment {
   display: none;
}
</code>```

Note: You can increase the .comment class x number of times to get higher precedence.

Example:

```<code>.blog-stats .comment.comment.comment {
   display: none;
}
</code>```

Title: Hiding span under div in CSS

Body:
Below is the code for my WP post. I'm trying to hide the span for comment. So that it doesn't appear on the blog post.

        February 15, 2020

        no comments

        Wayne John

I tried a few below and it didn't work.

.blog-stats.comment {
    display: none;
}

span .comment {
    display: none;
}

span.comment {
    display: none;
}

Any idea how to fix it?

Body:
In case if you don't want to use !important try the below version.

.blog-stats .comment.comment {
   display: none;
}

Note: You can increase the .comment class x number of times to get higher precedence.

Example:

.blog-stats .comment.comment.comment {
   display: none;
}