问:
Cant match a particular pattern in regex using OR
Here is my regex :

```<code>(M|D|MD|A|AM|AD|AMD)?=(0|1|-1|D|A|!D|!A|-D|-A|D\+A)?
</code>```

It matches with

```<code>M=D
M=A
M=1
and so on
</code>```

but it doesnt match with

```<code>M=D+A
</code>```

what am i doing wrong here?

答:
Regex goes from left to right and does not backtrack. And once an earlier part of an 'or' statement is satisfied, it does not look further. So you are capturing the shorter string and the regex never gets to the end of your 'or' statement where the longer string is. Changing your regex to

```<code>(M|D|MD|A|AM|AD|AMD)?=(D\+A|0|1|-1|D|A|!D|!A|-D|-A)?
</code>```

will do the trick. In other words, always order your 'or' statements in a way that you first capture the longer strings and later capture the shorter ones.

demo

Body:
Here is my regex :

(M|D|MD|A|AM|AD|AMD)?=(0|1|-1|D|A|!D|!A|-D|-A|D\+A)?

It matches with

M=D
M=A
M=1
and so on

but it doesnt match with

M=D+A

what am i doing wrong here?

Body:
Regex goes from left to right and does not backtrack. And once an earlier part of an 'or' statement is satisfied, it does not look further. So you are capturing the shorter string and the regex never gets to the end of your 'or' statement where the longer string is. Changing your regex to

(M|D|MD|A|AM|AD|AMD)?=(D\+A|0|1|-1|D|A|!D|!A|-D|-A)?

will do the trick. In other words, always order your 'or' statements in a way that you first capture the longer strings and later capture the shorter ones.

demo


来源: stackexchange

问:
Why does the robot framework add quotation marks to a command string?
Why does the robot framework add quotation marks "" to a string when executing it as a command?

Example: I am trying to execute a command through Run Process keyword. Here is my code:

```<code>*** Settings ***
Documentation    Suite description
Library     Process

*** Test Cases ***
Test1
    ${X}=      Run Process      rm -r     Desktop\\sample.txt
</code>```

When I run the above step in the robot framework, I see that it sends a command as like below (checked in log file):

```<code>"rm -r"  /Desktop/Sample.txt
</code>```

Here rm -r should not get quotation marks in the shell, but the robot framework is adding them between the start and end of any strings with single spaces, which causes the command to fail.

I encounter this issue whenever I want to pass a strings with spaces to the shell.

答:
Robot will not add quotes when running the command. You see quotes because the error adds them to make it easier to understand the error message.

The first argument must be the name of a command. rm -r is not a valid name of a command. The command should be rm because -r is an argument to the command which must be separated from the command with two or more spaces.

```<code>${X}=  Run Process  rm  -r  Desktop\\sample.txt
</code>```

To illustrate that the quotes are only in the log and not in the actual command, create a python script that looks like this:

```<code># example.py
import sys
for arg in sys.argv:
    print(f"arg: {arg}")
</code>```

Next, create a robot script that looks like this:

```<code>*** Settings ***
Library  Process

*** Test Cases ***
Example
    ${result}  Run Process    python  example.py  one  two  three and four
    log  ${result.stdout}
</code>```

When you run the test and examine the log, the following screenshot is what you see in the log. Notice that quotes appear in the log message for Run Process, but the script that you run does not get arguments with any added quotes.

ContentLicense: CC BY-SA 4.0

Body:
Why does the robot framework add quotation marks "" to a string when executing it as a command?

Example: I am trying to execute a command through Run Process keyword. Here is my code:

*** Settings ***
Documentation    Suite description
Library     Process

*** Test Cases ***
Test1
    ${X}=      Run Process      rm -r     Desktop\\sample.txt

When I run the above step in the robot framework, I see that it sends a command as like below (checked in log file):

"rm -r"  /Desktop/Sample.txt

Here rm -r should not get quotation marks in the shell, but the robot framework is adding them between the start and end of any strings with single spaces, which causes the command to fail.

I encounter this issue whenever I want to pass a strings with spaces to the shell.

Body:
Robot will not add quotes when running the command. You see quotes because the error adds them to make it easier to understand the error message.

The first argument must be the name of a command. rm -r is not a valid name of a command. The command should be rm because -r is an argument to the command which must be separated from the command with two or more spaces.

${X}=  Run Process  rm  -r  Desktop\\sample.txt

To illustrate that the quotes are only in the log and not in the actual command, create a python script that looks like this:

# example.py
import sys
for arg in sys.argv:
    print(f"arg: {arg}")

Next, create a robot script that looks like this:

*** Settings ***
Library  Process

*** Test Cases ***
Example
    ${result}  Run Process    python  example.py  one  two  three and four
    log  ${result.stdout}

When you run the test and examine the log, the following screenshot is what you see in the log. Notice that quotes appear in the log message for Run Process, but the script that you run does not get arguments with any added quotes.


问:
Storing large numbers of images in a database? A good experience?
I'm writing an app which will store a large number of image (and possibly video) files. After they're uploaded they will be immediately pushed out to some cloud serving CDN for actual serving to the public. The idea is to have the images stored in a reliable, back-uppable store. I would anticipate of the order of 200,000 objects of up to 10KB each and possibly fewer video files of a few MB.

By default I would go to Postgres which the documentation suggests would be ok.

Is this is a sensible idea?

Will it make backing up the database a complete nightmare. Experiences?

Any reliability issues?

Will this affect the performance for other parts of the db? Bear in mind that the db will only be hit once or twice for each image.

答: My experience is limited to SQL server, but I have several million PDF-files that are larger than 10KB in a database, which is still performing quite nicely. Of course indexes are required. Full database backup takes no longer than expected with such an amount of data. Again, this is for MS-SQL server!</p>

ContentLicense: CC BY-SA 3.0


问:
How to make results above content? Z-index search field issue
This code appears in a siteorigin layout builder in the header widget area. There are four elements, and #4 is a search box. When you type anything into the box, the suggested results appear under the content below.

I tried a z-index on the header, the widget, assigning a special class to the widget with a high z-index, and got nothing.

https://www.carmelchamber.org/

Any thoughts please, because I'm stuck.

Thank you!

Luke

答:
This was a tough one to locate. Please, try adding to Custom CSS:

```<code>.panel-row-style,
.elementor-section {
    -webkit-transform: none !important;
}
</code>```

That's to override a rule in the parent stylesheet.

Body:
This was a tough one to locate. Please, try adding to Custom CSS:

.panel-row-style,
.elementor-section {
    -webkit-transform: none !important;
}

That's to override a rule in the parent stylesheet.


问:
How to make div resize and scrollable between sibling divs
Basically I have this Angular material side nav with expandable navigation items

I want to make the second div scroll able when the items expand beyond the third div and also resizable so when I decrease the window size, it should always resize to fit between div 1 and and div 3.

I managed to implement the scrolling behavior with the following style applied:

```<code>title-div {
    min-height: 10%;
}

items-div {

    height: 80% //To force the info-div to be positioned at the bottom
    max-height: 80%
    overflow: auto;
}

info-div {
    min-height: 10%;
}
</code>```

However the resizing is not working properly. At a certain height the info-div(3) starts to get cut off instead of the item-div(2) resizing smaller for the info-div to fit in. How can I make this work?

答:
You could easily achieve something like this using flexbox:

Title

item

item

item

Information

```

<pre class="lang-css prettyprint-override"><code>#sidenav{
  display: flex;
  flex-direction: column;
  height: 100%;
}
#sidenav .items{
  flex-grow: 1;
  overflow-y: auto;
}
</code>```

https://codepen.io/Ploddy/pen/yLNaLyQ?editors=1100

Body:
Basically I have this Angular material side nav with expandable navigation items

I want to make the second div scroll able when the items expand beyond the third div and also resizable so when I decrease the window size, it should always resize to fit between div 1 and and div 3.

I managed to implement the scrolling behavior with the following style applied:

title-div {
    min-height: 10%;
}

items-div {

    height: 80% //To force the info-div to be positioned at the bottom
    max-height: 80%
    overflow: auto;
}

info-div {
    min-height: 10%;
}

However the resizing is not working properly. At a certain height the info-div(3) starts to get cut off instead of the item-div(2) resizing smaller for the info-div to fit in. How can I make this work?

Body:
You could easily achieve something like this using flexbox:

<div id="sidenav">
  <div>Title</div>
  <div class="items">
    <div>item</div>
    <div>item</div>
    <div>item</div>
  </div>
  <div>Information</div>
</div>

#sidenav{
  display: flex;
  flex-direction: column;
  height: 100%;
}
#sidenav .items{
  flex-grow: 1;
  overflow-y: auto;
}

https://codepen.io/Ploddy/pen/yLNaLyQ?editors=1100


问:
SLO issue with SimpleSAMLphp IDP with 2 SPs : redirected to the wrong login screen
We have set up SimpleSAMLphp as a SAML IDP to which 2 SPs are registered (Liferay and MyWebMethods).

Every SP is registered to the IDP with its own ACS and SLO links in the simplesamlphp/metadata/saml20-sp-remote.php file. Something like :

```<code>// MWS = SP2
$metadata['http://sp2.siteweb.com'] = array(
    'AssertionConsumerService' => 'http://sp2.siteweb.com/',
    'SingleLogoutService' => 'http://sp2.siteweb.com/?method=logout',
);

// LR = SP1
$metadata['http://sp1.siteweb.com/c/portal/saml/metadata'] = array(
    'AssertionConsumerService' => 'http://sp1.siteweb.com/c/portal/saml/acs',
    'SingleLogoutService' => 'http://sp1.siteweb.com/c/portal/saml/sls',
);
</code>```

I have no problem using SSO: after I get authenticated (via the IDP) I can got to the first SP, then I can go to the 2nd SP without the need to login again.

My issue is with the log out (SLO) when the user is connected to each of the 2 SPs in the same time from same session (2 tabs in Google Chrome). If he logs out first from the SP2, whenever he tries to log out from the SP1 he is redirected to the login screen of the SP2 (ie: normal out-of-SSO login screen), instead of being redirected to the IDP login screen.

The logout url is actually captured by our SP filter then we create a saml Auth object that does the logout() :

```<code>Auth auth = new Auth(request, response);
String relayState = sp1_login_url;
auth.logout(relayState);
</code>```

One info is that the SP1 supports SP-initiated and SP2 supports only IDP-initiated.

Any idea please?

答:
After some research, the solution was simply to add a returnUrl parameter to the config for the SP2:

```<code>// MWS = SP2
$metadata['http://sp2.siteweb.com'] = array(
    'AssertionConsumerService' => 'http://sp2.siteweb.com/',
    'SingleLogoutService' => 'http://sp2.siteweb.com/?method=logout&returnUrl=http://idplogin.siteweb.com',
);
</code>```

Body:
We have set up SimpleSAMLphp as a SAML IDP to which 2 SPs are registered (Liferay and MyWebMethods).

Every SP is registered to the IDP with its own ACS and SLO links in the simplesamlphp/metadata/saml20-sp-remote.php file. Something like :

// MWS = SP2
$metadata['http://sp2.siteweb.com'] = array(
    'AssertionConsumerService' => 'http://sp2.siteweb.com/',
    'SingleLogoutService' => 'http://sp2.siteweb.com/?method=logout',
);

// LR = SP1
$metadata['http://sp1.siteweb.com/c/portal/saml/metadata'] = array(
    'AssertionConsumerService' => 'http://sp1.siteweb.com/c/portal/saml/acs',
    'SingleLogoutService' => 'http://sp1.siteweb.com/c/portal/saml/sls',
);

I have no problem using SSO: after I get authenticated (via the IDP) I can got to the first SP, then I can go to the 2nd SP without the need to login again.

My issue is with the log out (SLO) when the user is connected to each of the 2 SPs in the same time from same session (2 tabs in Google Chrome). If he logs out first from the SP2, whenever he tries to log out from the SP1 he is redirected to the login screen of the SP2 (ie: normal out-of-SSO login screen), instead of being redirected to the IDP login screen.

The logout url is actually captured by our SP filter then we create a saml Auth object that does the logout() :

Auth auth = new Auth(request, response);
String relayState = sp1_login_url;
auth.logout(relayState);

One info is that the SP1 supports SP-initiated and SP2 supports only IDP-initiated.

Any idea please?

Body:
After some research, the solution was simply to add a returnUrl parameter to the config for the SP2:

// MWS = SP2
$metadata['http://sp2.siteweb.com'] = array(
    'AssertionConsumerService' => 'http://sp2.siteweb.com/',
    'SingleLogoutService' => 'http://sp2.siteweb.com/?method=logout&returnUrl=http://idplogin.siteweb.com',
);


问:
Convert DFA to RE
I constructed a finite automata  for the language L of all strings made of the symbols 0, 1 and 2 (Σ = {0, 1, 2}) where the last symbol is not smaller than the first symbol. E.g., the strings 0, 2012, 01231 and 102 are in the language, but 10, 2021 and 201 are not in the language.

Then from that an GNFA so I can convert to RE.

My RE looks like this:

```<code>(0(0+1+2)* )(1(0(1+2)+1+2)* )(2((0+1)2+2))*)
</code>```

I have no idea if this is correct, as I think I understand RE but not entirely sure.

Could someone please tell me if it’s correct and if not why?

答:
You can use an algorithm but this DFA might be easy enough to convert as a one-off.

First, note that if the first symbol seen in the initial state is 0, you transition to state A and remain there. A is accepting. This means any string beginning with 0 is accepted. Thus, our regular expression might as well have a term like 0(0+1+2)* in it.

Second, note that if the first symbol seen in the initial state is 1, you transition to state B and remain in states B and D from that point on. You only leave B if you see 0 and you stay out of B as long as you keep seeing 0. The only way to end on D is if the last symbol you saw was 0. Therefore, strings beginning with 1 are accepted if and only if the strings don't end in 0. We can have a term like 1(0+1+2)*(1+2) in our regular expression as well to cover these cases.

Third, note that if the first symbol seen in the initial state is 2, you transition to state C and remain in states C and E from that point on. You leave state C if you see anything but 2 and stay out of B until you see a 2 again. The only way to end up on C is if the last symbol you saw was 2. Therefore, strings beginning with 2 are accepted if and only if the strings end in 2. We can have a term like 2(0+1+2)*(2) in our regular expression as well to cover these cases.

Finally, we see that there are no other cases to consider; our three terms cover all cases and the union of them fully describes our language:

```<code>0(0+1+2)* + 1(0+1+2)*(1+2) + 2(0+1+2)*2
</code>```

It was easy to just write out the answer here because this DFA is sort of like three simple DFAs put together with a start state. More complicated DFAs might be easier to convert to REs using algorithms that don't require you understand or follow what the DFA is doing.

Note that if the start state is accepting (mentioned in a comment on another answer) the RE changes as follows:

```<code>e + 0(0+1+2)* + 1(0+1+2)*(1+2) + 2(0+1+2)*2
</code>```

Basically, we just tack the empty string onto it since it is not already generated by any of the other parts of the aggregate expression.

Title: Convert DFA to RE

Body:
I constructed a finite automata  for the language L of all strings made of the symbols 0, 1 and 2 (Σ = {0, 1, 2}) where the last symbol is not smaller than the first symbol. E.g., the strings 0, 2012, 01231 and 102 are in the language, but 10, 2021 and 201 are not in the language.

Then from that an GNFA so I can convert to RE.

My RE looks like this:

(0(0+1+2)* )(1(0(1+2)+1+2)* )(2((0+1)2+2))*)

I have no idea if this is correct, as I think I understand RE but not entirely sure.

Could someone please tell me if it’s correct and if not why?

Body:
You can use an algorithm but this DFA might be easy enough to convert as a one-off.

First, note that if the first symbol seen in the initial state is 0, you transition to state A and remain there. A is accepting. This means any string beginning with 0 is accepted. Thus, our regular expression might as well have a term like 0(0+1+2)* in it.

Second, note that if the first symbol seen in the initial state is 1, you transition to state B and remain in states B and D from that point on. You only leave B if you see 0 and you stay out of B as long as you keep seeing 0. The only way to end on D is if the last symbol you saw was 0. Therefore, strings beginning with 1 are accepted if and only if the strings don't end in 0. We can have a term like 1(0+1+2)*(1+2) in our regular expression as well to cover these cases.

Third, note that if the first symbol seen in the initial state is 2, you transition to state C and remain in states C and E from that point on. You leave state C if you see anything but 2 and stay out of B until you see a 2 again. The only way to end up on C is if the last symbol you saw was 2. Therefore, strings beginning with 2 are accepted if and only if the strings end in 2. We can have a term like 2(0+1+2)*(2) in our regular expression as well to cover these cases.

Finally, we see that there are no other cases to consider; our three terms cover all cases and the union of them fully describes our language:

0(0+1+2)* + 1(0+1+2)*(1+2) + 2(0+1+2)*2

It was easy to just write out the answer here because this DFA is sort of like three simple DFAs put together with a start state. More complicated DFAs might be easier to convert to REs using algorithms that don't require you understand or follow what the DFA is doing.

Note that if the start state is accepting (mentioned in a comment on another answer) the RE changes as follows:

e + 0(0+1+2)* + 1(0+1+2)*(1+2) + 2(0+1+2)*2

Basically, we just tack the empty string onto it since it is not already generated by any of the other parts of the aggregate expression.


问:
Clean way to access form options in event listener
How can I access $options passed to buildForm() from an event listener in a clean way? Please see below code sample:</p>

```<code>class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'preSetDataListener']);
    }

    public function preSetDataListener(FormEvent $event)
    {
        // how would I access $options from buildFrom here?
    }
</code>```

答:
Don't rely on $event->getForm()->getConfig()->getOptions(). It's not meant to be used by us. I've opened an issue on the Symfony bug tracker with this problem and they told me to inherit variables into the anonymous function instead. See this example.

Pay attention to the use keyword.

```<code>->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options) {
    // here you can use $options
}
</code>```

That gets the $options array from the parent scope and injects it into the event listener function. It's a PHP feature.

Oh, and this means you'll have to either directly pass an anonymous function as an argument to addEventListener() (as in the example above) or define it inside buildForm() as a normal variable, like this:

```<code>$listener = function (FormEvent $event) use ($options) {
    // do something
}

$builder
    ->addEventListener(FormEvents::PRE_SET_DATA, $listener);
</code>```

Body:
How can I access $options passed to buildForm() from an event listener in a clean way? Please see below code sample:

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'preSetDataListener']);
    }

    public function preSetDataListener(FormEvent $event)
    {
        // how would I access $options from buildFrom here?
    }

Body:
Don't rely on $event->getForm()->getConfig()->getOptions(). It's not meant to be used by us. I've opened an issue on the Symfony bug tracker with this problem and they told me to inherit variables into the anonymous function instead. See this example.

Pay attention to the use keyword.

->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options) {
    // here you can use $options
}

That gets the $options array from the parent scope and injects it into the event listener function. It's a PHP feature.

Oh, and this means you'll have to either directly pass an anonymous function as an argument to addEventListener() (as in the example above) or define it inside buildForm() as a normal variable, like this:

$listener = function (FormEvent $event) use ($options) {
    // do something
}

$builder
    ->addEventListener(FormEvents::PRE_SET_DATA, $listener);


问:
How to build dependent dropdown menus in Flutter?
I have three dropdown-menus, and I want a fourth one to be displayed ONLY if certain conditions are met (Favourite Animal = Cat). I also want that fourth dropdown-menu to disappear whenever the conditions are no longer true. Right now the changes are displayed if I manually save the file and execute hot reload, so I'm guessing it has something to do with setState(), which I have not included in the filter.dart-file.

File 1 - filter.dart:

```<code>import 'package:flutter/material.dart';
import './dropdown.dart';

class Filter extends StatefulWidget {
  @override
  _FilterState createState() => _FilterState();
}

class _FilterState extends State<Filter> {
  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 10,
      child: Container(
        height: ((MediaQuery.of(context).size.height) / 2),
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Column(
              children: <Widget>[
                Dropdown('Gender', ['Female', 'Male']),
                Dropdown('Age', ['<15', '15-20', '>20']),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster']),
                (cat) ? Dropdown('Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball']) : Text('')
              ],
            ),
            RaisedButton(
              child: Text('Submit'),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

File 2 - dropdown.dart:

```<code>import 'package:flutter/material.dart';

class Dropdown extends StatefulWidget {
  final String _key;
  final List<String> _values;

  Dropdown(this._key, this._values);

  @override
  _DropdownState createState() => _DropdownState();
}

class _DropdownState extends State<Dropdown> {
  var _chosenValue;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      child: DropdownButton<String> (
        hint: Text(widget._key),
        value: _chosenValue,
        icon: Icon(Icons.arrow_drop_down),
        iconSize: 24,
        isExpanded: true,
        items: widget._values.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
        onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          setState(() {

          });
        },
      ),
    );
  }
}

bool cat = false; //Feels wrong to have this bool out in the open
</code>```

The filter.dart-file is called from main with Filter().

Bonus question: I also want to extract the chosen values and return them to the filter.dart-file and use them in the onPressed-function in the RaisedButton, not quite sure how to do that.

答:
Fix 6 places. How about this?

```<code>class _FilterState extends State<Filter> {
  bool cat = false; // Move here.

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 10,
      child: Container(
        height: ((MediaQuery.of(context).size.height) / 2),
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Column(
              children: <Widget>[
                Dropdown('Gender', ['Female', 'Male']),
                Dropdown('Age', ['<15', '15-20', '>20']),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster'], update: _update), // Fix this line.
                (cat)
                    ? Dropdown(
                        'Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball'])
                    : Text('')
              ],
            ),
            RaisedButton(
              child: Text('Submit'),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }

  // Add this function.
  void _update(bool b) {
    setState(() {
      cat = b;
    });
  }

}
</code>```

```<code>class Dropdown extends StatefulWidget {
  final String _key;
  final List<String> _values;
  final Function update; // Add this line.

  Dropdown(this._key, this._values, {this.update = null}); // Fix this line.

  @override
  _DropdownState createState() => _DropdownState();
}

class _DropdownState extends State<Dropdown> {
  var _chosenValue;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      child: DropdownButton<String>(
        hint: Text(widget._key),
        value: _chosenValue,
        icon: Icon(Icons.arrow_drop_down),
        iconSize: 24,
        isExpanded: true,
        items: widget._values.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
        onChanged: (String value) {
          // Fix start.
          setState(() {
            _chosenValue = value;
          });
          if (widget.update != null) {
            (widget._key == 'Favourite Animal' && _chosenValue == 'Cat')
                ? widget.update(true)
                : widget.update(false);
          }
          // Fix end.
        },
      ),
    );
  }
}
</code>```

Body:
I have three dropdown-menus, and I want a fourth one to be displayed ONLY if certain conditions are met (Favourite Animal = Cat). I also want that fourth dropdown-menu to disappear whenever the conditions are no longer true. Right now the changes are displayed if I manually save the file and execute hot reload, so I'm guessing it has something to do with setState(), which I have not included in the filter.dart-file.

File 1 - filter.dart:

import 'package:flutter/material.dart';
import './dropdown.dart';

class Filter extends StatefulWidget {
  @override
  _FilterState createState() => _FilterState();
}

class _FilterState extends State<Filter> {
  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 10,
      child: Container(
        height: ((MediaQuery.of(context).size.height) / 2),
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Column(
              children: <Widget>[
                Dropdown('Gender', ['Female', 'Male']),
                Dropdown('Age', ['<15', '15-20', '>20']),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster']),
                (cat) ? Dropdown('Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball']) : Text('')
              ],
            ),
            RaisedButton(
              child: Text('Submit'),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }
}

File 2 - dropdown.dart:

import 'package:flutter/material.dart';

class Dropdown extends StatefulWidget {
  final String _key;
  final List<String> _values;

  Dropdown(this._key, this._values);

  @override
  _DropdownState createState() => _DropdownState();
}

class _DropdownState extends State<Dropdown> {
  var _chosenValue;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      child: DropdownButton<String> (
        hint: Text(widget._key),
        value: _chosenValue,
        icon: Icon(Icons.arrow_drop_down),
        iconSize: 24,
        isExpanded: true,
        items: widget._values.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
        onChanged: (String value) {
          _chosenValue = value;
          (widget._key == 'Favourite Animal' && _chosenValue == 'Cat') ? cat = true : cat = false;
          setState(() {

          });
        },
      ),
    );
  }
}

bool cat = false; //Feels wrong to have this bool out in the open

The filter.dart-file is called from main with Filter().

Bonus question: I also want to extract the chosen values and return them to the filter.dart-file and use them in the onPressed-function in the RaisedButton, not quite sure how to do that.

Body:
Fix 6 places. How about this?

class _FilterState extends State<Filter> {
  bool cat = false; // Move here.

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 10,
      child: Container(
        height: ((MediaQuery.of(context).size.height) / 2),
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Column(
              children: <Widget>[
                Dropdown('Gender', ['Female', 'Male']),
                Dropdown('Age', ['<15', '15-20', '>20']),
                Dropdown('Favourite Animal', ['Cat', 'Dog', 'Hamster'], update: _update), // Fix this line.
                (cat)
                    ? Dropdown(
                        'Favourite cat-toy', ['Toy-mouse', 'Ribbon', 'Ball'])
                    : Text('')
              ],
            ),
            RaisedButton(
              child: Text('Submit'),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }

  // Add this function.
  void _update(bool b) {
    setState(() {
      cat = b;
    });
  }

}

class Dropdown extends StatefulWidget {
  final String _key;
  final List<String> _values;
  final Function update; // Add this line.

  Dropdown(this._key, this._values, {this.update = null}); // Fix this line.

  @override
  _DropdownState createState() => _DropdownState();
}

class _DropdownState extends State<Dropdown> {
  var _chosenValue;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      child: DropdownButton<String>(
        hint: Text(widget._key),
        value: _chosenValue,
        icon: Icon(Icons.arrow_drop_down),
        iconSize: 24,
        isExpanded: true,
        items: widget._values.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
        onChanged: (String value) {
          // Fix start.
          setState(() {
            _chosenValue = value;
          });
          if (widget.update != null) {
            (widget._key == 'Favourite Animal' && _chosenValue == 'Cat')
                ? widget.update(true)
                : widget.update(false);
          }
          // Fix end.
        },
      ),
    );
  }
}


问:
performance of fortran matrix operations
I need to use Fortran instead of C somewhere and I am very new to Fortran. I am trying to do some big calculations but it is quite slow comparing to C (maybe 10x or more and I am using Intel's compilers for both). I think the reason is Fortran keeps the matrix in column major format, and I am trying to do operations like sum(matrix(i, j, :)), because it is column major, probably this uses the cache very inefficiently (probably not using at all). However, I am not sure if this is the actual reason (since I know so less about Fortran). Question is, the convention in Fortran is to do operations on column vectors instead of row vectors ?

(BTW: I checked the speed of Fortran already using Intel's LAPACK libraries, and it is quite fast, so it is not related to any compiler or build issue.)

Thanks.

Mete

答:
Try changing the order of your loops when doing matrix operations, e.g. if you have something like this in C:

```<code>for (i = 0; i < M; ++i) // for each row
{
    for (j = 0; j < N; ++j) // for each col
    {
        // matrix operations on e.g. A[i][j]
    }
}
</code>```

then in Fortran you want the j (column) loop as the outer loop and the i (row) loop as the inner loop.

An alternative approach, which achieves the same thing, is to keep the loops as they are but change the definition of the array, e.g. if in C it's A[x][y][z][t] then in FORTRAN make it A[t][z][y][x], assuming that t is the fastest varying loop index, and x the slowest.

Body:
Try changing the order of your loops when doing matrix operations, e.g. if you have something like this in C:

for (i = 0; i < M; ++i) // for each row
{
    for (j = 0; j < N; ++j) // for each col
    {
        // matrix operations on e.g. A[i][j]
    }
}

then in Fortran you want the j (column) loop as the outer loop and the i (row) loop as the inner loop.

An alternative approach, which achieves the same thing, is to keep the loops as they are but change the definition of the array, e.g. if in C it's A[x][y][z][t] then in FORTRAN make it A[t][z][y][x], assuming that t is the fastest varying loop index, and x the slowest.


问:
Update column value that has one or more same values of other column
I have this statement:

```<code>UPDATE `tblAllocatedLeads`
SET tblAllocatedLeads.fldAllocatedStatus = CASE
WHEN tblAllocatedLeads.fldAllocatedStatus = 'Allocated'
AND
(SELECT COUNT(*) FROM (SELECT * FROM `tblAllocatedLeads`) AS tblallocate WHERE AND tblallocate.fldAllocatedLeadId = tblAllocatedLeads.fldAllocatedLeadId) > 1
THEN 'Outstanding'
END

</code>```

What I wanted is that update all rows where fldAllocatedStatus = 'Allocated' to 'Outstanding' that has one or more same value of column fldAllocatedLeadId to other rows.

my data

```<code>ID   fldAllocatedStatus   fldAllocatedLeadId
1    Accepted             123
2    Rejected             123
3    Allocated            123
4    Allocated            321

</code>```

In this case ID = 3 should update fldAllocatedStatus to 'Outstanding' as it has one or more same fldAllocatedLeadId from ID = 1,2

and ID = 4 should stay 'Allocated' as it doesn't have match of fldAllocatedLeadId with other rows.

right now what it does it updates even the "Accepted,Rejected" which is supposedly to update only rows with "Allocated"

答:
You don't need any aggregation, just a self join:

```<code>UPDATE tblAllocatedLeads t
INNER JOIN tblAllocatedLeads tt
ON tt.id <> t.id AND tt.fldAllocatedLeadId = t.fldAllocatedLeadId
SET t.fldAllocatedStatus = 'Outstanding'
WHERE t.fldAllocatedStatus = 'Allocated';
</code>```

See the demo.

Results:

```<code>| ID  | fldAllocatedStatus | fldAllocatedLeadId |
| --- | ------------------ | ------------------ |
| 1   | Accepted           | 123                |
| 2   | Rejected           | 123                |
| 3   | Outstanding        | 123                |
| 4   | Allocated          | 321                |
</code>```

Body:
I have this statement:

UPDATE `tblAllocatedLeads`
SET tblAllocatedLeads.fldAllocatedStatus = CASE
WHEN tblAllocatedLeads.fldAllocatedStatus = 'Allocated'
AND
(SELECT COUNT(*) FROM (SELECT * FROM `tblAllocatedLeads`) AS tblallocate WHERE AND tblallocate.fldAllocatedLeadId = tblAllocatedLeads.fldAllocatedLeadId) > 1
THEN 'Outstanding'
END

What I wanted is that update all rows where fldAllocatedStatus = 'Allocated' to 'Outstanding' that has one or more same value of column fldAllocatedLeadId to other rows.

my data

ID   fldAllocatedStatus   fldAllocatedLeadId
1    Accepted             123
2    Rejected             123
3    Allocated            123
4    Allocated            321

In this case ID = 3 should update fldAllocatedStatus to 'Outstanding' as it has one or more same fldAllocatedLeadId from ID = 1,2

and ID = 4 should stay 'Allocated' as it doesn't have match of fldAllocatedLeadId with other rows.

right now what it does it updates even the "Accepted,Rejected" which is supposedly to update only rows with "Allocated"

Body:
You don't need any aggregation, just a self join:

UPDATE tblAllocatedLeads t
INNER JOIN tblAllocatedLeads tt
ON tt.id <> t.id AND tt.fldAllocatedLeadId = t.fldAllocatedLeadId
SET t.fldAllocatedStatus = 'Outstanding'
WHERE t.fldAllocatedStatus = 'Allocated';

See the demo.

Results:

| ID  | fldAllocatedStatus | fldAllocatedLeadId |
| --- | ------------------ | ------------------ |
| 1   | Accepted           | 123                |
| 2   | Rejected           | 123                |
| 3   | Outstanding        | 123                |
| 4   | Allocated          | 321                |


问:
'import ase' does not load submodule 'ase.io'
I experienced a problem using the 'import module' instead of the 'from module import ...' syntax. This clearly shows that my understanding of loading modules is not sufficient. As far as I find elsewhere, this difference is mainly a style issue, but this does not explains the following situation.

I installed ase using

```<code>sudo apt install python3-ase
</code>```

I tried the following:

```<code>import ase
ase.io.read
</code>```

which outputs

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ase' has no attribute 'io'
</code>```

However, when trying

```<code>from ase.io import read
read
</code>```

or - also possible -

```<code>from ase.io import read
import ase
ase.io.read
</code>```

I get the output

```<code><function read at 0x7f33dc721730>
</code>```

The latter is the desired result as I want to use the ase.io.read function to read a .cif file.

More about the origin of the problem is shown in the following python session:

```<code>import sys
import ase
sys.modules['ase']
</code>```

module 'ase' from '/home/vanbeverj/Programs/anaconda3/envs/abienv/lib/python3.6/site-packages/ase/init.py'

```<code>dir(ase)
</code>```

['Atom', 'Atoms', 'LooseVersion', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'version', 'ase', 'atom', 'atoms', 'calculators', 'cell', 'constraints', 'data', 'dft', 'formula', 'geometry', 'np', 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

```<code>from ase.io import read
dir(ase)
</code>```

['Atom', 'Atoms', 'LooseVersion', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'version', 'ase', 'atom', 'atoms', 'calculators', 'cell', 'constraints', 'data', 'dft', 'formula', 'geometry', 'io', 'np', 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

The 'dir(ase)' commands have clearly different outputs. What happens with e.g. the io submodule? Can someone explains me what is going on under the hood?

答:
It's up to each package whether to expose an imported submodule as an attribute, or whether to import the submodule at all.

os, for example, does import and expose os.path.

In your case, ase does not expose the io submodule as an attribute of ase. (Whether io was imported is another matter; you could check sys.modules.)

Body:
I experienced a problem using the 'import module' instead of the 'from module import ...' syntax. This clearly shows that my understanding of loading modules is not sufficient. As far as I find elsewhere, this difference is mainly a style issue, but this does not explains the following situation.

I installed ase using

sudo apt install python3-ase

I tried the following:

import ase
ase.io.read

which outputs

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ase' has no attribute 'io'

However, when trying

from ase.io import read
read

or - also possible -

from ase.io import read
import ase
ase.io.read

I get the output

<function read at 0x7f33dc721730>

The latter is the desired result as I want to use the ase.io.read function to read a .cif file.

More about the origin of the problem is shown in the following python session:

import sys
import ase
sys.modules['ase']

module 'ase' from '/home/vanbeverj/Programs/anaconda3/envs/abienv/lib/python3.6/site-packages/ase/init.py'

dir(ase)

['Atom', 'Atoms', 'LooseVersion', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'version', 'ase', 'atom', 'atoms', 'calculators', 'cell', 'constraints', 'data', 'dft', 'formula', 'geometry', 'np', 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

from ase.io import read
dir(ase)

['Atom', 'Atoms', 'LooseVersion', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'version', 'ase', 'atom', 'atoms', 'calculators', 'cell', 'constraints', 'data', 'dft', 'formula', 'geometry', 'io', 'np', 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

The 'dir(ase)' commands have clearly different outputs. What happens with e.g. the io submodule? Can someone explains me what is going on under the hood?


问:
Use another property in data element as id
I have data elements:

```<code>{
    'rid': '1',
    'id': '2',
    'name': 'asdw'
},
{
    'rid': '2',
    'id': '2',
    'name': 'dsddf'
},
{
    'rid': '3',
    'id': '2',
    'name': 'fffgg'
}
</code>```

Each data element have the same value of "id" property (slickgrid throws me "Each data element must implement a unique 'id' property"). How can i use another property in data element as id (for example "rid")?
I can not remove props from data object.

答:
You can try setting your items using the setItems(data, objectIdProperty) method defined on DataView in file slick.model.js.</p>

```<code>function setItems(data, objectIdProperty) {
     if (objectIdProperty !== undefined) idProperty = objectIdProperty;
     items = data;
     refreshIdxById();
     refresh();
}
</code>```

Body:
I have data elements:

{
    'rid': '1',
    'id': '2',
    'name': 'asdw'
},
{
    'rid': '2',
    'id': '2',
    'name': 'dsddf'
},
{
    'rid': '3',
    'id': '2',
    'name': 'fffgg'
}

Each data element have the same value of "id" property (slickgrid throws me "Each data element must implement a unique 'id' property"). How can i use another property in data element as id (for example "rid")?
I can not remove props from data object.

Body:
You can try setting your items using the setItems(data, objectIdProperty) method defined on DataView in file slick.model.js.

function setItems(data, objectIdProperty) {
     if (objectIdProperty !== undefined) idProperty = objectIdProperty;
     items = data;
     refreshIdxById();
     refresh();
}


问:
Javascript: Get instance getter and fields names or names and values
I usually use the next sentence to obtain all object fields but I just realized that is skips object getters

```<code>Object.entries(myInstance)
</code>```

I also tried without results:

```<code>Object.keys(myInstance)
Object.values(myInstance)
</code>```

There is any way to traverse the object attributes AND getters? I am interested in the name and value of the getter not the function itself.

答:
```<code>Object.getOwnPropertyNames
</code>```

From MDN web docs: "The Object.getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties except for those which use Symbol)"

Body:
I usually use the next sentence to obtain all object fields but I just realized that is skips object getters

Object.entries(myInstance)

I also tried without results:

Object.keys(myInstance)
Object.values(myInstance)

There is any way to traverse the object attributes AND getters? I am interested in the name and value of the getter not the function itself.

Body:
Object.getOwnPropertyNames

From MDN web docs: "The Object.getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties except for those which use Symbol)"


问:
Need help simplifying batch file
I've got a batch file that copies some files based on user input and I want to simplify it. If a user types the letter A in the prompt, it copies A.txt from C:\ to E:\ Essentially, it goes like this:

```<code>set /p letter="Enter a letter of the alphabet"
if /i [%letter%]==[A] GOTO LetterA
if /i [%letter%]==[B] GOTO LetterB
if /i [%letter%]==[C] GOTO LetterC
:LetterA
robocopy C:\ E:\ A.txt
:LetterB
robocopy C:\ E:\ B.txt
:LetterC
robocopy C:\ E:\ C.txt
:end
</code>```

Would I have to type out/copy each line for every letter of the alphabet, for both the IF statement and the goto command it calls? Can I accomplish this easier with a for loop or if statement and basically say..

```<code>For %letter%
robocopy C:\ E:\ %letter%.txt
</code>```

Or like an IF statement, referring to a list.txt file.. whereas list.txt has all letters of alphabet in it..

```<code>IF %letter% in (C:\list.txt)
then robocopy C:\ E:\ %letter%.txt
</code>```

答:
Basically you look for a way to ensure, the input is within a predefined set. You can do that like:

```<code>@echo off
setlocal
:loop
set /p "letter=Enter a letter of the alphabet: "
echo %letter%|findstr /ix "a b c d e f g h i j k l m n o p q r s t u v w x y z" || goto :loop
ECHO robocopy C:\ E:\ %letter%.txt
</code>```

(remove the uppercase ECHO after testing to actually enable the robocopy command)

Title: Need help simplifying batch file

Body:
I've got a batch file that copies some files based on user input and I want to simplify it. If a user types the letter A in the prompt, it copies A.txt from C:\ to E:\ Essentially, it goes like this:

set /p letter="Enter a letter of the alphabet"
if /i [%letter%]==[A] GOTO LetterA
if /i [%letter%]==[B] GOTO LetterB
if /i [%letter%]==[C] GOTO LetterC
:LetterA
robocopy C:\ E:\ A.txt
:LetterB
robocopy C:\ E:\ B.txt
:LetterC
robocopy C:\ E:\ C.txt
:end

Would I have to type out/copy each line for every letter of the alphabet, for both the IF statement and the goto command it calls? Can I accomplish this easier with a for loop or if statement and basically say..

For %letter%
robocopy C:\ E:\ %letter%.txt

Or like an IF statement, referring to a list.txt file.. whereas list.txt has all letters of alphabet in it..

IF %letter% in (C:\list.txt)
then robocopy C:\ E:\ %letter%.txt

Body:
Basically you look for a way to ensure, the input is within a predefined set. You can do that like:

@echo off
setlocal
:loop
set /p "letter=Enter a letter of the alphabet: "
echo %letter%|findstr /ix "a b c d e f g h i j k l m n o p q r s t u v w x y z" || goto :loop
ECHO robocopy C:\ E:\ %letter%.txt

(remove the uppercase ECHO after testing to actually enable the robocopy command)


问:
How to run WorkManager's work retry every 5 seconds
How to retry work with every 5 seconds?
And if was successful then cancel it?

With the solution below it runs every 10 seconds + Linear growth of time.

```<code>// todo: schedule, and invoke worker every 5 seconds
// todo: if the work is done and there is no more work in queue - cancel worker.

fun scheduleBatchUpload(uniqueWorkName: String) {
    val logBuilder = PeriodicWorkRequest.Builder(StreamLogWorker::class.java, 5, TimeUnit.SECONDS)

    logBuilder.setBackoffCriteria(BackoffPolicy.LINEAR, 5000, TimeUnit.MILLISECONDS) // Custom retry not working

    WorkManager.getInstance().enqueueUniquePeriodicWork(uniqueWorkName, ExistingPeriodicWorkPolicy.REPLACE, logBuilder.build())
}

class StreamLogWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    override fun doWork(): Result {
        Log.e("!!!!!!!!!!", "doWork")
        return Result.retry()
    }
}
</code>```

答:
You can try to schedule your task manually, perhaps it can help to reach your goal.

```<code>private fun WorkManager.launchFrequentTask() {
    val request = OneTimeWorkRequestBuilder<StreamLogWorker>()
            .setInitialDelay(5, TimeUnit.SECONDS)
            .build()
    enqueueUniqueWork(UNIQUE_WORK_NAME, ExistingWorkPolicy.APPEND, request)
}

class StreamLogWorker(private val context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    override fun doWork(): Result {
        try {
            // TODO doWork
        } catch (th: Throwable) {
            // log error
        }
        WorkManager.getInstance(context).launchFrequentTask()
        return Result.success()
    }
}
</code>```

Not sure if this really works as you want (every 5 seconds), it is necessary to check.

Body:
How to retry work with every 5 seconds?
And if was successful then cancel it?

With the solution below it runs every 10 seconds + Linear growth of time.

// todo: schedule, and invoke worker every 5 seconds
// todo: if the work is done and there is no more work in queue - cancel worker.

fun scheduleBatchUpload(uniqueWorkName: String) {
    val logBuilder = PeriodicWorkRequest.Builder(StreamLogWorker::class.java, 5, TimeUnit.SECONDS)

    logBuilder.setBackoffCriteria(BackoffPolicy.LINEAR, 5000, TimeUnit.MILLISECONDS) // Custom retry not working

    WorkManager.getInstance().enqueueUniquePeriodicWork(uniqueWorkName, ExistingPeriodicWorkPolicy.REPLACE, logBuilder.build())
}

class StreamLogWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    override fun doWork(): Result {
        Log.e("!!!!!!!!!!", "doWork")
        return Result.retry()
    }
}

Body:
You can try to schedule your task manually, perhaps it can help to reach your goal.

private fun WorkManager.launchFrequentTask() {
    val request = OneTimeWorkRequestBuilder<StreamLogWorker>()
            .setInitialDelay(5, TimeUnit.SECONDS)
            .build()
    enqueueUniqueWork(UNIQUE_WORK_NAME, ExistingWorkPolicy.APPEND, request)
}

class StreamLogWorker(private val context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    override fun doWork(): Result {
        try {
            // TODO doWork
        } catch (th: Throwable) {
            // log error
        }
        WorkManager.getInstance(context).launchFrequentTask()
        return Result.success()
    }
}

Not sure if this really works as you want (every 5 seconds), it is necessary to check.


问:
Magento Report issue - Only filter option available, no table showing up
I'm new to Magento(V 2.3.1). Got an issue under Reports > Sales > Orders. I see only the filter option and there is no table to display the result. Not sure how this can be solved. Any help would be great.
Screenshot for reference

答: Did you try to refresh your statistics? Admin path: Reports > Statistics > Refresh Statistics


问:
Create Possible Combination in javascript/typescript/nodejs
```<code>let input = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
</code>```

and i want output should be:

```<code>output = {
    first: [[1,2], [3,4], [5,6], [7,8], [9,10]],
    second: [[1,3], [2,4], [5,7], [6,9], [8,10]],
    third: [[1,4], [2,3], [5,8], [7,9], [6,10]],
    fourth: [[1,5], [2,6], [3,7], [8,9], [4,10]],
    fifth: [[1,6], [2,8], [3,5], [4,9], [7,10]],
    sixth: [[1,7], [2,9], [3,6], [4,8], [5,10]],
    seventh: [[1,8], [2,7], [4,6], [5,9], [3,10]],
    eighth: [[1,9], [3,8], [4,5], [6,7], [2,10]],
    ninth: [[1,10], [2,5], [3,9], [4,7], [6,8]],
}
</code>```

I need to write a code in javascript / typescript / nodejs by which i can put number ranges and will get a combinations of given numbers**( n-1 ), i want a code to be written which can return us **all possible combination and the combination will never conflict with other combinations.

Thanks in advance.

答:
You could take a brute force approach with a recursive function for collected pairs and a list of available pairs.

If a new pair is possible to get, take this pair and call the function again.

function getAllPairs(array) {
    var pairs = [];
    for (let i = 0; i < array.length - 1; i++) {
        for (let j = i + 1; j < array.length; j++) {
            pairs.push([array[i], array[j]]);
        }
    }
    return pairs;
}

function fill(pairs, result = []) {
    function check(array) {
        return array.every((s => a => a.every(v => !s.has(v) && s.add(v)))(new Set));
    }

    if (!pairs.length) return result;

    var left = result.slice(Math.floor(result.length / half) * half);

    for (let i = 0; i < pairs.length; i++) {
        if (!check([...left, pairs[i]])) continue;
        var newResult = fill([...pairs.slice(0, i), ...pairs.slice(i + 1)], [...result, pairs[i]]);
        if (newResult) return newResult; // i miss something like returnIf
    }
}

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    half = data.length / 2,
    temp = fill(getAllPairs(data)),
    result = [],
    i = 0;

while (i < temp.length) result.push(temp.slice(i, i += half));

result.forEach(a => console.log(...a.map(a => a.map(v => v.toString().padStart(2, ' ')).join('|'))));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
let input = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

and i want output should be:

output = {
    first: [[1,2], [3,4], [5,6], [7,8], [9,10]],
    second: [[1,3], [2,4], [5,7], [6,9], [8,10]],
    third: [[1,4], [2,3], [5,8], [7,9], [6,10]],
    fourth: [[1,5], [2,6], [3,7], [8,9], [4,10]],
    fifth: [[1,6], [2,8], [3,5], [4,9], [7,10]],
    sixth: [[1,7], [2,9], [3,6], [4,8], [5,10]],
    seventh: [[1,8], [2,7], [4,6], [5,9], [3,10]],
    eighth: [[1,9], [3,8], [4,5], [6,7], [2,10]],
    ninth: [[1,10], [2,5], [3,9], [4,7], [6,8]],
}

I need to write a code in javascript / typescript / nodejs by which i can put number ranges and will get a combinations of given numbers**( n-1 ), i want a code to be written which can return us **all possible combination and the combination will never conflict with other combinations.

Thanks in advance.

Body:
You could take a brute force approach with a recursive function for collected pairs and a list of available pairs.

If a new pair is possible to get, take this pair and call the function again.

function getAllPairs(array) {
    var pairs = [];
    for (let i = 0; i < array.length - 1; i++) {
        for (let j = i + 1; j < array.length; j++) {
            pairs.push([array[i], array[j]]);
        }
    }
    return pairs;
}

function fill(pairs, result = []) {
    function check(array) {
        return array.every((s => a => a.every(v => !s.has(v) && s.add(v)))(new Set));
    }

    if (!pairs.length) return result;

    var left = result.slice(Math.floor(result.length / half) * half);

    for (let i = 0; i < pairs.length; i++) {
        if (!check([...left, pairs[i]])) continue;
        var newResult = fill([...pairs.slice(0, i), ...pairs.slice(i + 1)], [...result, pairs[i]]);
        if (newResult) return newResult; // i miss something like returnIf
    }
}

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    half = data.length / 2,
    temp = fill(getAllPairs(data)),
    result = [],
    i = 0;

while (i < temp.length) result.push(temp.slice(i, i += half));

result.forEach(a => console.log(...a.map(a => a.map(v => v.toString().padStart(2, ' ')).join('|'))));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
error " svn:SSLv3 SSLContext not available on RAD 7.5
I am getting the error " SVN: SSLv3 SSLContext not available    SVN: OPTIONS request failed on ('SVN URL') while trying to connect to SVN repository through RAD 7.5.
I am using web sphere 7.0.
I am able to remote desktop to the server and also can login using the URL directly.
Only problem is through RAD.
Can anyone please help.
Thanks</p>

答: It seems that RAD 7.5 does not support modern TLS/SSL versions, and supports only SSL 3.0 or older. I think that your server does not enable SSL 3.0 for security reasons. SSL 3.0 is deprecated and not secure.</p>


问:
Compare 2 unequal size of maps c++
I have 2 different maps(string, string) of different size. I need to compare and return the different items present in the map.

```<code>eg: map1 contains
"1":"abc"
"2":"xyz"
"3":"abc"
eg: map2 contains
"1":"abcd"
"2":"xyz"
"4":"abc"
"5":"abc"
</code>```

If you compare 2 maps, only "2" is matched. Remaining are unmatched. I need to get all unmatched into another map.

答:
set_symmetric_difference should work fine:

```<code>#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
#include <string>

int main()
{
    std::map<std::string, std::string>
        map1 {
            { "1", "abc" },
            { "2", "xyz" },
            { "3", "abc" }
        },
        map2 {
            { "1", "abcd" },
            { "2", "xyz" },
            { "4", "abc" },
            { "5", "abc" }
        },
        map3;

    std::set_symmetric_difference(map1.cbegin(), map1.cend(), map2.cbegin(), map2.cend(),
        inserter(map3, map3.end()));

    for (auto const& p : map3) {
        std::cout << p.first << " : " << p.second << '\n';
    }
}
</code>```

Output:

```<code>1 : abc
3 : abc
4 : abc
5 : abc
</code>```

As is mentioned in a comment, if you have differing values for a single key, this version will lose one of the values. If this a problem you can make map3 a std::multimap<std::string, std::string> or a std::vector<std::pair<std::string, std::string>> and preserve all values. LIVE

Title: Compare 2 unequal size of maps c++

Body:
I have 2 different maps(string, string) of different size. I need to compare and return the different items present in the map.

eg: map1 contains
"1":"abc"
"2":"xyz"
"3":"abc"
eg: map2 contains
"1":"abcd"
"2":"xyz"
"4":"abc"
"5":"abc"

If you compare 2 maps, only "2" is matched. Remaining are unmatched. I need to get all unmatched into another map.

Body:
set_symmetric_difference should work fine:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
#include <string>

int main()
{
    std::map<std::string, std::string>
        map1 {
            { "1", "abc" },
            { "2", "xyz" },
            { "3", "abc" }
        },
        map2 {
            { "1", "abcd" },
            { "2", "xyz" },
            { "4", "abc" },
            { "5", "abc" }
        },
        map3;

    std::set_symmetric_difference(map1.cbegin(), map1.cend(), map2.cbegin(), map2.cend(),
        inserter(map3, map3.end()));

    for (auto const& p : map3) {
        std::cout << p.first << " : " << p.second << '\n';
    }
}

Output:

1 : abc
3 : abc
4 : abc
5 : abc

As is mentioned in a comment, if you have differing values for a single key, this version will lose one of the values. If this a problem you can make map3 a std::multimap<std::string, std::string> or a std::vector<std::pair<std::string, std::string>> and preserve all values. LIVE


问:
Finding the Stats.max for each hierarchical index in Deedle
If I have a dataset that contains [City, Dealership, Total Cars Sold]. How would I get the top dealer in each city and the number of cars they sold?

The results should look like

```<code>City1 Dealership A 2000
City2 Dealership X 1000
etc.
</code>```

I'm sure it's possible, but I'm not having any luck and it might because i'm approaching the problem the wrong way.

Currently i'm grouping by Dealership and City which creates a Frame<(string*string*int), int> and that gets me

```<code>City1 Dealership A 1 -> 2000
City1 Dealership B 2 -> 1000
City2 Dealership X 3 -> 1000
City2 Dealership Y 4 -> 500
etc.
</code>```

But trying to then get the dealership that does the most deals is where i'm stumped.

Thanks.

答:
I adapted Tomas's answer and output the type as Series<string, (string * int)>

let data = series [
  ("City1", "Dealership A") => 2000
  ("City1", "Dealership B") => 1000
  ("City2", "Dealership X") => 1000
  ("City2", "Dealership Y") => 500 ]

data
|> Series.groupBy (fun k _ -> fst k)
|> Series.mapValues (fun sr ->
  let sorted = sr |> Series.sortBy(fun x -> -x)
  let key = sorted |> Series.firstKey |> snd
  let value = sorted |> Series.firstValue
  key, value )
```

<p>The output looks like</p>

```City1 -> (Dealership A, 2000)
City2 -> (Dealership X, 1000)
```

<p><strong>EDITED</strong></p>

<p>I assume you have a csv file like this</p>

```City,Dealership,TotalCarsSold
City1,Dealership A,2000
City1,Dealership B,1000
City2,Dealership X,1000
City2,Dealership Y,500
```

<p>This is how I'll do it. Read it as <code>Frame</code> and get the column as <code>Series</code> and apply the same code above to get result.</p>

<pre class="lang-ml prettyprint-override"><code>let df =
  Frame.ReadCsv("C:/Temp/dealership.csv")
  |> Frame.indexRowsUsing(fun r -> r.GetAs<string>("City"), r.GetAs<string>("Dealership"))
df?TotalCarsSold
|> Series.groupBy (fun k _ -> fst k)
|> Series.mapValues (fun sr ->
  let sorted = sr |> Series.sortBy(fun x -> -x)
  let key = sorted |> Series.firstKey |> snd
  let value = sorted |> Series.firstValue
  key, value )
</code>```

Body:
If I have a dataset that contains [City, Dealership, Total Cars Sold]. How would I get the top dealer in each city and the number of cars they sold?

The results should look like

City1 Dealership A 2000
City2 Dealership X 1000
etc.

I'm sure it's possible, but I'm not having any luck and it might because i'm approaching the problem the wrong way.

Currently i'm grouping by Dealership and City which creates a Frame<(string*string*int), int> and that gets me

City1 Dealership A 1 -> 2000
City1 Dealership B 2 -> 1000
City2 Dealership X 3 -> 1000
City2 Dealership Y 4 -> 500
etc.

But trying to then get the dealership that does the most deals is where i'm stumped.

Thanks.

Body:
I adapted Tomas's answer and output the type as Series<string, (string * int)>

let data = series [
  ("City1", "Dealership A") => 2000
  ("City1", "Dealership B") => 1000
  ("City2", "Dealership X") => 1000
  ("City2", "Dealership Y") => 500 ]

data
|> Series.groupBy (fun k _ -> fst k)
|> Series.mapValues (fun sr ->
  let sorted = sr |> Series.sortBy(fun x -> -x)
  let key = sorted |> Series.firstKey |> snd
  let value = sorted |> Series.firstValue
  key, value )

The output looks like

City1 -> (Dealership A, 2000)
City2 -> (Dealership X, 1000)

EDITED

I assume you have a csv file like this

City,Dealership,TotalCarsSold
City1,Dealership A,2000
City1,Dealership B,1000
City2,Dealership X,1000
City2,Dealership Y,500

This is how I'll do it. Read it as Frame and get the column as Series and apply the same code above to get result.

let df =
  Frame.ReadCsv("C:/Temp/dealership.csv")
  |> Frame.indexRowsUsing(fun r -> r.GetAs<string>("City"), r.GetAs<string>("Dealership"))
df?TotalCarsSold
|> Series.groupBy (fun k _ -> fst k)
|> Series.mapValues (fun sr ->
  let sorted = sr |> Series.sortBy(fun x -> -x)
  let key = sorted |> Series.firstKey |> snd
  let value = sorted |> Series.firstValue
  key, value )


问:
How to get latest GoogleMaps SDK using pods

I'm trying out the google places sdk sample. I installed it using

pod try GoogleMaps

I installed GoogleMaps (1.10.5) using cocoapods

source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '8.1'

pod 'GoogleMaps'

checking the GoogleMaps in both steps, the one in the sample (1) contains more headers like GMSAutocompleteTableDataSource.h

Why are they different? The one in the sample seems to be a better version but the one given by pods is not the latest? Its not even in the changelog

答: I just ran into this error, and I updated to latest GoogleMaps per the advice above, but had to delete the app on my device and install fresh for it to resolve the error. Error was still present until I did that.</p>


问:
Spring Boot not serving static content
I can't get my Spring-boot project to serve static content.

I've placed a folder named static under src/main/resources. Inside it I have a folder named images. When I package the app and run it, it can't find the images I have put on that folder.

I've tried to put the static files in public, resources and META-INF/resources but nothing works.

If I jar -tvf app.jar I can see that the files are inside the jar on the right folder:
/static/images/head.png for example, but calling: http://localhost:8080/images/head.png, all I get is a 404

Any ideas why spring-boot is not finding this? (I'm using 1.1.4 BTW)

答:
using spring boot 2.*, i have a controller that maps to routes GetMapping({"/{var}", "/{var1}/{var2}", "/{var1}/{var2}/{var3}"}) and boom my app stop serving resources.

i know it is not advisable to have such routes but it all depends on the app you are building (in my case, i have no choice but to have such routes)

so here is my hack to make sure my app serve resources again. I simply have a controller that maps to my resources. since spring will match a direct route first before any that has variable, i decided to add a controller method that maps to /imgaes/{name} and repeated same for other resources

```<code>@GetMapping(value = "/images/{image}", produces = {MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
    public @ResponseBody
    byte[] getImage(@PathVariable String image) {
        ClassPathResource file = new ClassPathResource("static/images/" + image);
        byte[] bytes;
        try {
            bytes = StreamUtils.copyToByteArray(file.getInputStream());
        } catch (IOException e) {
            throw new ResourceNotFoundException("file not found: " + image);
        }
        return bytes;
    }
</code>```

and this solved my issue

Title: Spring Boot not serving static content

Body:
using spring boot 2.*, i have a controller that maps to routes GetMapping({"/{var}", "/{var1}/{var2}", "/{var1}/{var2}/{var3}"}) and boom my app stop serving resources.

i know it is not advisable to have such routes but it all depends on the app you are building (in my case, i have no choice but to have such routes)

so here is my hack to make sure my app serve resources again. I simply have a controller that maps to my resources. since spring will match a direct route first before any that has variable, i decided to add a controller method that maps to /imgaes/{name} and repeated same for other resources

@GetMapping(value = "/images/{image}", produces = {MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
    public @ResponseBody
    byte[] getImage(@PathVariable String image) {
        ClassPathResource file = new ClassPathResource("static/images/" + image);
        byte[] bytes;
        try {
            bytes = StreamUtils.copyToByteArray(file.getInputStream());
        } catch (IOException e) {
            throw new ResourceNotFoundException("file not found: " + image);
        }
        return bytes;
    }

and this solved my issue


问:
COUNT_BIG in Indexed View
```<code>CREATE TABLE test2 (
id INTEGER,
name VARCHAR(10),
family VARCHAR(10),
amount INTEGER)

CREATE VIEW dbo.test2_v WITH SCHEMABINDING
AS
SELECT id, SUM(amount) as amount
-- , COUNT_BIG(*) as tmp
FROM dbo.test2
GROUP BY id

CREATE UNIQUE CLUSTERED INDEX vIdx ON test2_v(id)
</code>```

I have error with this code:

Cannot create index on view
  'test.dbo.test2_v' because its select
  list does not include a proper use of
  COUNT_BIG. Consider adding
  COUNT_BIG(*) to select list.

I can create view like this:

```<code>CREATE VIEW dbo.test2_v WITH SCHEMABINDING
    AS
    SELECT id, SUM(amount) as amount, COUNT_BIG(*) as tmp
    FROM dbo.test2
    GROUP BY id
</code>```

But I'm just wondering what is purpose of this column in this case?

答:
Looks like it's simply a hardcoded performance-related restriction that the SQL Server team had to put in place when they first designed aggregate indexed views in SQL Server  2000.

Until relatively recently you could see this in the SQL 2000 technet documentation at http://msdn.microsoft.com/en-us/library/aa902643(SQL.80).aspx, but the SQL Server 2000 documentation has been definitely retired. You can still download a 92MB PDF file, and find the relevant notes on pages 1146 and 2190: https://www.microsoft.com/en-us/download/details.aspx?id=51958

An explanation for this restriction can be found on the SQLAuthority site - actually an excerpt from Itzik Ben-Gan's "Inside SQL" book: http://blog.sqlauthority.com/2010/09/21/sql-server-count-not-allowed-but-count_big-allowed-limitation-of-the-view-5/

It's worth noting that Oracle has the same restriction/requirement, for the same reasons (for an equivalent fast refreshable materialized view); see http://rwijk.blogspot.com.es/2009/06/fast-refreshable-materialized-view.html for a discussion on this topic.

Summary of the explanation:

Why does sql server logically need a materialized global count column in the indexed aggregate view?

So that it can quickly check / know whether a particular row in the aggregate view needs to change or go, when a given row of an underlying table is updated or deleted.

Why does this count column need to be COUNT_BIG(*)?

So that there is no possible risk of overflow; by forcing the use of the bigint datatype, there is no risk of an indexed view "breaking" when a particular row reaches an overly high count.

It's relatively easy to visualize why a count is critical to efficient aggregate view maintenance - imagine the following situation:

The table structures are as specified in the question

There are 4 rows in the underlying table:

```<code>ID  | name | family | amount
--- | ---- | ------ | ------
1   | a    |        | 10
2   | b    |        | 11
2   | c    |        | 12
3   | d    |        | 13
</code>```

The aggregate view is materialized to something like this:

```<code>ID  | amount | tmp
--- | ------ | ---
1   | 10     | 1
2   | 23     | 2
3   | 13     | 1
</code>```

Simple Case:

The SQL Engine detects a change in the underlying data - the third row in the source data (id 2, name c) is deleted.

The engine needs to:

find and update the relevant row of the aggregate materialized view

reduce the "amount" sum by the amount of the deleted underlying row

reduce the "count" by 1 (if this column exists)

Target/difficult case:

The SQL Engine detects another change in the underlying data - the second row in the source data (id 2, name b) is deleted.

The engine needs to:

find and delete the relevant row of the aggregate materialized view, as there are no more source rows with the same grouping key

Consider that the engine always has the "before" row of the underlying table(s) at view-update time - it knows exactly what changed in both cases.

The notable "step" in the materialized-view-maintenance algorithm is determining whether the target materialized aggregate row needs to be deleted or not

if you have a "count", you don't need to look anywhere beyond the target row - if you're dropping the count to 0, then delete the row. If you're updating to any other value, then leave the row.

if you don't have a count, then the only way for you to figure it out, would be to query the underlying table to check for any other rows with the same aggregation key; such a process would clearly introduce much more onerous restrictions:

it would be implicitly slower, and

in join-aggregation cases would be un-optimizable!

For these reasons, the existence of a count(*) column is a fundamental requirement of the aggregate materialized view implementation. Without a count(*) column, the real-time maintenance of an aggregate materialized view in the face of underlying data changes would carry an unacceptably high performance penalty!

You could still ask "why doesn't SQL Server create/maintain such a count column for me automatically when I create an aggregate materialized view?" - I don't have a particularly good answer for this. In the end, I imagine there would be more questions and confusion about "Why does my aggregate materialized view have a BIGCOUNT column if I didn't add it?" if they did that, so it's simpler to make it a basic requirement of creation of the object, but that's a purely subjective opinion.

Title: COUNT_BIG in Indexed View

Body:
CREATE TABLE test2 (
id INTEGER,
name VARCHAR(10),
family VARCHAR(10),
amount INTEGER)

CREATE VIEW dbo.test2_v WITH SCHEMABINDING
AS
SELECT id, SUM(amount) as amount
-- , COUNT_BIG(*) as tmp
FROM dbo.test2
GROUP BY id

CREATE UNIQUE CLUSTERED INDEX vIdx ON test2_v(id)

I have error with this code:

Cannot create index on view
  'test.dbo.test2_v' because its select
  list does not include a proper use of
  COUNT_BIG. Consider adding
  COUNT_BIG(*) to select list.

I can create view like this:

CREATE VIEW dbo.test2_v WITH SCHEMABINDING
    AS
    SELECT id, SUM(amount) as amount, COUNT_BIG(*) as tmp
    FROM dbo.test2
    GROUP BY id

But I'm just wondering what is purpose of this column in this case?

Body:
Looks like it's simply a hardcoded performance-related restriction that the SQL Server team had to put in place when they first designed aggregate indexed views in SQL Server  2000.

Until relatively recently you could see this in the SQL 2000 technet documentation at http://msdn.microsoft.com/en-us/library/aa902643(SQL.80).aspx, but the SQL Server 2000 documentation has been definitely retired. You can still download a 92MB PDF file, and find the relevant notes on pages 1146 and 2190: https://www.microsoft.com/en-us/download/details.aspx?id=51958

An explanation for this restriction can be found on the SQLAuthority site - actually an excerpt from Itzik Ben-Gan's "Inside SQL" book: http://blog.sqlauthority.com/2010/09/21/sql-server-count-not-allowed-but-count_big-allowed-limitation-of-the-view-5/

It's worth noting that Oracle has the same restriction/requirement, for the same reasons (for an equivalent fast refreshable materialized view); see http://rwijk.blogspot.com.es/2009/06/fast-refreshable-materialized-view.html for a discussion on this topic.

Summary of the explanation:

Why does sql server logically need a materialized global count column in the indexed aggregate view?

So that it can quickly check / know whether a particular row in the aggregate view needs to change or go, when a given row of an underlying table is updated or deleted.

Why does this count column need to be COUNT_BIG(*)?

So that there is no possible risk of overflow; by forcing the use of the bigint datatype, there is no risk of an indexed view "breaking" when a particular row reaches an overly high count.

It's relatively easy to visualize why a count is critical to efficient aggregate view maintenance - imagine the following situation:

The table structures are as specified in the question

There are 4 rows in the underlying table:

ID  | name | family | amount
--- | ---- | ------ | ------
1   | a    |        | 10
2   | b    |        | 11
2   | c    |        | 12
3   | d    |        | 13

The aggregate view is materialized to something like this:

ID  | amount | tmp
--- | ------ | ---
1   | 10     | 1
2   | 23     | 2
3   | 13     | 1

Simple Case:

The SQL Engine detects a change in the underlying data - the third row in the source data (id 2, name c) is deleted.

The engine needs to:

find and update the relevant row of the aggregate materialized view

reduce the "amount" sum by the amount of the deleted underlying row

reduce the "count" by 1 (if this column exists)

Target/difficult case:

The SQL Engine detects another change in the underlying data - the second row in the source data (id 2, name b) is deleted.

The engine needs to:

find and delete the relevant row of the aggregate materialized view, as there are no more source rows with the same grouping key

Consider that the engine always has the "before" row of the underlying table(s) at view-update time - it knows exactly what changed in both cases.

The notable "step" in the materialized-view-maintenance algorithm is determining whether the target materialized aggregate row needs to be deleted or not

if you have a "count", you don't need to look anywhere beyond the target row - if you're dropping the count to 0, then delete the row. If you're updating to any other value, then leave the row.

if you don't have a count, then the only way for you to figure it out, would be to query the underlying table to check for any other rows with the same aggregation key; such a process would clearly introduce much more onerous restrictions:

it would be implicitly slower, and

in join-aggregation cases would be un-optimizable!

For these reasons, the existence of a count(*) column is a fundamental requirement of the aggregate materialized view implementation. Without a count(*) column, the real-time maintenance of an aggregate materialized view in the face of underlying data changes would carry an unacceptably high performance penalty!

You could still ask "why doesn't SQL Server create/maintain such a count column for me automatically when I create an aggregate materialized view?" - I don't have a particularly good answer for this. In the end, I imagine there would be more questions and confusion about "Why does my aggregate materialized view have a BIGCOUNT column if I didn't add it?" if they did that, so it's simpler to make it a basic requirement of creation of the object, but that's a purely subjective opinion.


问:
runtime error after migrating to androidX
I just wanted to build a signed apk, then I got lots of errors which I realized most of them would be solved by migrating to android X, but I get this runtime error after migrating to androidX:

```<code>    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.hamed/com.test.hamed.cups}: android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class android.support.design.widget.AppBarLayout
</code>```

where line #18 that is mentioned is:

 <android.support.design.widget.
     android:id="@+id/cupsAppBar"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:theme="@style/AppTheme.AppBarOverlay">

```

<p>and in Java is this line in onCretae:</p>

<pre class="lang-java prettyprint-override"><code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cups); // <= this line
        .
        .
        .

</code>```

I have searched a lot and some suggest that adding the following line would solve the problem but it didn't:

```<code>    implementation 'com.android.support:design:28.0.0'
</code>```

What is the problem and how can I fix this?
Thanks

答: The correct usage for AppBarLayout is now com.google.android.material.appbar.AppBarLayout

Body:
I just wanted to build a signed apk, then I got lots of errors which I realized most of them would be solved by migrating to android X, but I get this runtime error after migrating to androidX:

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.hamed/com.test.hamed.cups}: android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class android.support.design.widget.AppBarLayout

where line #18 that is mentioned is:

 <android.support.design.widget.
     android:id="@+id/cupsAppBar"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:theme="@style/AppTheme.AppBarOverlay">

and in Java is this line in onCretae:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cups); // <= this line
        .
        .
        .

I have searched a lot and some suggest that adding the following line would solve the problem but it didn't:

    implementation 'com.android.support:design:28.0.0'

What is the problem and how can I fix this?
Thanks


问:
How to construct a lucene search query with multiple parameters
I am new to Lucene.net ,Here I would like to know how to make a lucene search query almost like an sql query .Lemme give more..

I have set of parameter values,Let assume like a stored procedure has set of parameters .Now I want to build a query with all this parameters.

```<code>        searchParams.UseLast = Convert.ToBoolean(base.Arguments["UseLast"]);
        searchParams.LastEditedFrom= Convert.ToDateTime(base.Arguments["LastEditedFrom"]);
        searchParams.LastEditedTo = Convert.ToDateTime(base.Arguments["LastEditedTo"]);
        searchParams.Reviewed = Convert.ToBoolean(base.Arguments["Reviewed"]);
        searchParams.Approved = Convert.ToBoolean(base.Arguments["Approved"]);
        searchParams.Include = Convert.ToBoolean(base.Arguments["Include"]);
        searchParams.IsVisibleToUser = Convert.ToBoolean(base.Arguments["IsVisibleToUser"]);
        searchParams.IsEntry = Convert.ToBoolean(base.Arguments["IsEntry"]);
        searchParams.UserId = Convert.ToInt32(base.Arguments["UserId"]);

        IEnumerable Categories = base.Arguments["Categories"] as IEnumerable;
        IEnumerable Departments = base.Arguments["Departments"] as IEnumerable;

        String mQuery = "How to construct it ....!!!" // Need help in this

        var query = queryParser.Parse(mQuery);
        indexSearcher.Search(query, collector);
</code>```

Here I want to fetch all records from lucene index which has the value for all the above fields.

答:
I'm unclear what you are using searchParams for, however in general you may construct your query string (mQuery) in this cases with any of the features of the Lucene query syntax.  Here is a link to the documentation for Lucene.Net version 4.8 Query Parser Syntax.

In general, when multiple words are listed in the query they are treated with a logical OR but doc matches that contain all terms are ranked higher than docs with only one term.  So for example white dog would match docs containing white dog or white or dog.  You can put and in the statement if you only want docs that match all the terms so for example you could say small and white and dog if you only want docs that contain all three terms.

To specify the specific field to search you list the field name followed by a colon.  So for example you can search UserId:ron and Categories:dogs.  There is much more to the Lucene query syntax but hopefully that will get you started.  For more details see the Lucene query syntax doc I referred to.

Body:
I am new to Lucene.net ,Here I would like to know how to make a lucene search query almost like an sql query .Lemme give more..

I have set of parameter values,Let assume like a stored procedure has set of parameters .Now I want to build a query with all this parameters.

        searchParams.UseLast = Convert.ToBoolean(base.Arguments["UseLast"]);
        searchParams.LastEditedFrom= Convert.ToDateTime(base.Arguments["LastEditedFrom"]);
        searchParams.LastEditedTo = Convert.ToDateTime(base.Arguments["LastEditedTo"]);
        searchParams.Reviewed = Convert.ToBoolean(base.Arguments["Reviewed"]);
        searchParams.Approved = Convert.ToBoolean(base.Arguments["Approved"]);
        searchParams.Include = Convert.ToBoolean(base.Arguments["Include"]);
        searchParams.IsVisibleToUser = Convert.ToBoolean(base.Arguments["IsVisibleToUser"]);
        searchParams.IsEntry = Convert.ToBoolean(base.Arguments["IsEntry"]);
        searchParams.UserId = Convert.ToInt32(base.Arguments["UserId"]);

        IEnumerable Categories = base.Arguments["Categories"] as IEnumerable;
        IEnumerable Departments = base.Arguments["Departments"] as IEnumerable;

        String mQuery = "How to construct it ....!!!" // Need help in this

        var query = queryParser.Parse(mQuery);
        indexSearcher.Search(query, collector);

Here I want to fetch all records from lucene index which has the value for all the above fields.


问:
Is there any way to change the directions left to right in Slick carousel ? Default it goes Right to left directions
When I set rtf fasle then the page goes white and when I set slidesToScroll- 1 it also trhoughs same result.</p>

```<code>$('.demo').slick({
    dots: false,
    slidesToShow: 3,
    slidesToScroll: 1,
    infinite: true,
    cssEase: 'linear',

    accessibility:true,

    autoplay:true,
    autoplaySpeed: 3000,

  });
</code>```

答:
The default for the slideshow is left to right. To enable right to left, you need to set rtl: true and then according to the Slick website:

The HTML tag or the parent of the slider must have the attribute "dir" set to "rtl".

For example:

```<code><div dir="rtl">
    <div class="demo">
    ...
    </div>
</div>
</code>```

Body:
When I set rtf fasle then the page goes white and when I set slidesToScroll- 1 it also trhoughs same result.

$('.demo').slick({
    dots: false,
    slidesToShow: 3,
    slidesToScroll: 1,
    infinite: true,
    cssEase: 'linear',

    accessibility:true,

    autoplay:true,
    autoplaySpeed: 3000,

  });

Body:
The default for the slideshow is left to right. To enable right to left, you need to set rtl: true and then according to the Slick website:

The HTML tag or the parent of the slider must have the attribute "dir" set to "rtl".

For example:

<div dir="rtl">
    <div class="demo">
    ...
    </div>
</div>


问:
plotting a number of specific lines in python
In my plot the x-axis contains dates, but i want to limit it so that they can start from a certain date and not consider the first years of my data
I have tried this:

```<code>plt.figure
f_linear=interp1d(datasurf.iloc[:,0],datasurf.iloc[:,1])
plt.plot(datasurf.iloc[:,0],datasurf.iloc[:,1], label='Surface level')
plt.xlim(pd.Timestamp('2016-01-01'), pd.Timestamp('2019-09-14'))
plt.xlabel('Date')
plt.ylabel('Lake level(m)')
plt.legend()
</code>```

but I have this error:
Failed to convert value(s) to axis units: Timestamp('2016-01-01 00:00:00')

Can someone suggest me something else please

答:
```<code>fig= plt.figure ()
ax= fig.add_subplot (111)
plt.scatter(metadata['Date'], metadata['Offset'], label='Offset')
ax.set_xlim(pd.Timestamp('01/28/2016'), pd.Timestamp('12/09/2019'))
ax.set_title('Offset as a fucntion of time')
ax.set_xlabel('Time')
ax.set_ylabel ('Offset')
ax.legend (loc='lower right')
</code>```

Body:
In my plot the x-axis contains dates, but i want to limit it so that they can start from a certain date and not consider the first years of my data
I have tried this:

plt.figure
f_linear=interp1d(datasurf.iloc[:,0],datasurf.iloc[:,1])
plt.plot(datasurf.iloc[:,0],datasurf.iloc[:,1], label='Surface level')
plt.xlim(pd.Timestamp('2016-01-01'), pd.Timestamp('2019-09-14'))
plt.xlabel('Date')
plt.ylabel('Lake level(m)')
plt.legend()

but I have this error:
Failed to convert value(s) to axis units: Timestamp('2016-01-01 00:00:00')

Can someone suggest me something else please


问:
Need day of week as string (Sunday, Monday ...) in Queryable where clause
I need to check whether the provided keyword is present in the day-name of a date in the db. I have done it by using dynamic query.

```<code>ArrayList paramList = new ArrayList();
int paramCount = 0;
StringBuilder queryString = new StringBuilder();

if (keyword != null)
{
    queryString.Append(" and ClosureDate.Value.DayOfWeek.ToString().ToUpper().Contains(@" + paramCount + ")");
    paramList.Add(this.Keyword.ToUpper());
    paramCount++;
}
var abc= _context.ABC.Where(t => t.RecordStatus == 1).Select(t => t).OrderByDescending(t => t.Created).AsQueryable();
abc= abc.AsQueryable().Where(queryString[0].ToString(), searchArgs.ToArray());
</code>```

This ToString() here is creating problem. I tried in other ways but, no luck. Can anyone help on it?

答:
You can write your SQL Query as below.

```<code>    DECLARE @Dates TABLE
(
  ProductID INT IDENTITY(1,1),
  Dates DATETIME
)

INSERT INTO @Dates (Dates)
VALUES (GETDATE())
      ,(GETDATE()-1)
      ,(GETDATE()-2)
      ,(GETDATE()-3)
      ,(GETDATE()-4)
      ,(GETDATE()-5)

SELECT Dates
FROM @Dates

SELECT Dates,DATENAME(WEEKDAY,Dates) AS DayOfWeek
FROM @Dates
</code>```

Then in C#/MVC/ASP.Net App use the something like  .Where(t => t.DayOfWeek.Contains("Monday"))  to filter the result set.

Body:
I need to check whether the provided keyword is present in the day-name of a date in the db. I have done it by using dynamic query.

ArrayList paramList = new ArrayList();
int paramCount = 0;
StringBuilder queryString = new StringBuilder();

if (keyword != null)
{
    queryString.Append(" and ClosureDate.Value.DayOfWeek.ToString().ToUpper().Contains(@" + paramCount + ")");
    paramList.Add(this.Keyword.ToUpper());
    paramCount++;
}
var abc= _context.ABC.Where(t => t.RecordStatus == 1).Select(t => t).OrderByDescending(t => t.Created).AsQueryable();
abc= abc.AsQueryable().Where(queryString[0].ToString(), searchArgs.ToArray());

This ToString() here is creating problem. I tried in other ways but, no luck. Can anyone help on it?

Body:
You can write your SQL Query as below.

    DECLARE @Dates TABLE
(
  ProductID INT IDENTITY(1,1),
  Dates DATETIME
)

INSERT INTO @Dates (Dates)
VALUES (GETDATE())
      ,(GETDATE()-1)
      ,(GETDATE()-2)
      ,(GETDATE()-3)
      ,(GETDATE()-4)
      ,(GETDATE()-5)

SELECT Dates
FROM @Dates

SELECT Dates,DATENAME(WEEKDAY,Dates) AS DayOfWeek
FROM @Dates

Then in C#/MVC/ASP.Net App use the something like  .Where(t => t.DayOfWeek.Contains("Monday"))  to filter the result set.


问:
How to associate ranges vertically with GAS
I need to draw a chart whose:

X-axis would be a google sheet row

Y-axis another google sheet row.

I don't know why this is not a trivial case in Google sheet but indeed it does expects a column at least apparently.
To do it graphically I need to play a little with the chart settings (TransposeRowsAndColumns and Associate ranges Vertically as you can see in the french (sorry) screenshot).

Unfortunately this trick doesn't allow the reload of values in selected ranges. If I do so I loose my settings.
Anyway I would like to do it programmatically.

I found the setTransposeRowsAndColumns(true|false) function but not the the other one.

So please help me figure out how to perform in Google Apps Script the graphical action "Associate ranges" --> "Vertically"

[

答:
You can use the setMergeStrategy(mergeStrategy) method with the MERGE_ROWS merge type like this:

```<code>function createChart() {
   var sheet = SpreadsheetApp.getActiveSheet();
   var range1 = sheet.getRange("Confirmés!E1:AF1");
   var range2 = sheet.getRange("Confirmés!E77:AF77");
   var chart = sheet.newChart()
       .setChartType(Charts.ChartType.LINE)
       .addRange(range1)
       .addRange(range2)
       .setMergeStrategy(Charts.ChartMergeStrategy.MERGE_ROWS)
       .setTransposeRowsAndColumns(true)
       .setPosition(5, 5, 0, 0)
       .build();
}
</code>```

Reference

EmbeddedChartBuilder Class

Body:
You can use the setMergeStrategy(mergeStrategy) method with the MERGE_ROWS merge type like this:

function createChart() {
   var sheet = SpreadsheetApp.getActiveSheet();
   var range1 = sheet.getRange("Confirmés!E1:AF1");
   var range2 = sheet.getRange("Confirmés!E77:AF77");
   var chart = sheet.newChart()
       .setChartType(Charts.ChartType.LINE)
       .addRange(range1)
       .addRange(range2)
       .setMergeStrategy(Charts.ChartMergeStrategy.MERGE_ROWS)
       .setTransposeRowsAndColumns(true)
       .setPosition(5, 5, 0, 0)
       .build();
}

Reference

EmbeddedChartBuilder Class


问:
Using a 64 bit driver in a 32 bit program. Windows
This is only a half-way programming question. First of all I have a PCI-Express card and 32/64 bit drivers. The target operating system has to be a Windows 64 bit system. I read that under Vista64 all drivers have to be certified 64 bit drivers. Is this a general restriction under 64 bit operating systems and does this also apply to "XP 64" or any Linux system?

So for simplicity let's say I use a 64 bit driver for my PCIe card under Vista64 and have a bunch of 64 bit DLLs to use the cards functionality. On the other side there's a large, legacy 32 bit exe program which needs to use the PCIe device. Converting the program to 64 bit would be a really huge effort.

So what can be done to bring that 32 bit program and the 64 bit driver together? I read that mixing 32/64 bit binaries and DLLs is not possible at all but this is hard to believe for me. I'm sure you can print out a document under Vista64 from within a 32 bit app and Windows will somehow wrap this around to a 64 bit printer driver.

答:
64-bit certification is only required under Vista; there is no certifying authority for non-Windows platforms, and I don't believe that XP or Windows Server checks for certification (not sure though, and it may depend on which service pack you're on).

If you're using the driver via the Windows API, then there shouldn't be any problem; Windows will do the 32<->64-bit translations in the kernel.  If you're trying to load the driver inside your own process, that probably won't be possible.  As Dirk says you'll have to run it inside its own process and communicate through a COM server.  I'm not sure what hoops you'll have to jump through if you have to run your driver in a higher-privilege execution level and want to make calls to it from user mode.

Hopefully your 64-bit DLLs offer a 32-bit API, or Windows offers a standard driver interface (if it's a common I/O device like a display or network card).

OwnerDisplayName: asdrubael

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: asdrubael

OwnerDisplayName: TMN


问:
Zend retrieve router variables
Zend talk.I know this basic difference beetwen getQuery and getParam:

getQuery retrieves values from the query string.

getParam retrieve also variables set by the router.

Question: What if I only want to retrieve variables set by the router(not paying attention to the query string)?

thanks

Luca

答: There's a method getUserParams(). This retrieves only self set params. Maybe this can help you out.

Title: Zend retrieve router variables


问:
boolean values, run time error if not 0 or 1

boolean values, run time error if not 0 or 1

I wanted to hear how you understand this question. Would I be - if using this C variant - allowed to write a codeblock like this:

```<code>int b = 2;
if (b == 2) {
    return 3;
}
</code>```

Is it the return value that cannot be 3? I don't understand the sentence correctly I believe. Could someone give me an example of how an invalid conditional statement would look like in this C variant? Learning about Boolean values.

答:
== always evaluates to 0 or 1 so it can never cause a runtime error in your hypothetical scenario.

if(2) or if(3) would be a runtime error in your hypothetical, in "normal" C these expressions evaluate to true, so the cycle will be executed, in fact any value that is not 0, either positive or negative, evaluates to true.

An example of the advantages of evaluating values other than 0 or 1 would be the strcmp() function:

It will return 0 if the parameter strings (char arrays to be more
  precise) are equal, a negative value if the first parameter appears before the second parameter in lexicographical order, or a positive value if it is  the other way around.

In this case you will want to know if the strings are equal or not, so
  in if(strcmp(a, b)) (being a and b, strings), if strcmp()returns 30 or -2, your expression is still good in "normal" C. The expression will evaluate to true and you  will know the strings are different.

A sample advantage of having errors if the expression evaluates to values other than 0 or 1 would be this case:

If you mistakenly write if(a = 2) when trying to write if(a == 2).
  The mistaken expression will evaluate to 2, a will be assigned the value of 2, and this will evaluate to true regardless of the previous value of a, the mistake will be hard to detect since the code compiles fine. A runtime error would help detect the mistake.*.

* Note that there is a safeguard for these errors if you turn on your compiler warnings, but this would be a direct way, there are languages that do not allow you to evaluate conditional expressions with values other than 1 (true) or 0 (false).

Body:
boolean values, run time error if not 0 or 1

I wanted to hear how you understand this question. Would I be - if using this C variant - allowed to write a codeblock like this:

int b = 2;
if (b == 2) {
    return 3;
}

Is it the return value that cannot be 3? I don't understand the sentence correctly I believe. Could someone give me an example of how an invalid conditional statement would look like in this C variant? Learning about Boolean values.