问:
React Router v4 Modal
I know how to do it in previous versions of React Router but I absolutely do not know how to do it in new React Router v4. Can somebody help me?

What do I want?

When you type /image/1 in browser url, page will appear as normal.

When you click on <Link>Image as modal</Link> with state modal: true, modal with image will appear BUT behind modal must be the previous content + url in browser === /image/1... Then If you press F5, page will appear as normal.

Example: instagram... etc

What do I think I'm doing wrong?

I do not know how to display the previous content. That is all I guess.

Code:

```<code>const Images = (props) => {
  return (
    <div>
      <h2>Images</h2>
      <ul>
        <li><Link to={{
          pathname: '/image/1',
          state: {
            modal: true
          }
        }}>Image as modal</Link></li>
        <li><Link to="/image/2">Image</Link></li>
      </ul>
    </div>
  )
}

const Image = (props) => {
  return (
    <div>
      <h2>Image {props.match.params.id}</h2>
      <ul>
        <li><Link to="/images">Back to Images</Link></li>
      </ul>
    </div>
  )
}

ReactDOM.render(
  <Provider store={store}>
    <Router>
      <div>
        <Route path='/images' component={Images} />
        <Route path='/image/:id' component={Image} />
      </div>
    </Router>
  </Provider>,
  document.getElementById('digital')
)
</code>```

答:
I had the same problem, so I created:

http://npmjs.com/package/react-router-modal

It allows you to attach modals to routes. You would use it as follows:

```<code>import { ModalContainer, ModalRoute } from 'react-router-modal';
// ...
ReactDOM.render(
  <Provider store={store}>
    <Router>
      <div>
        <Route path='/images' component={Images} />
        <ModalRoute path='/image/:id' component={Image} />
      </div>
    </Router>
    <ModalContainer />
  </Provider>,
  document.getElementById('digital')
)
</code>```

There are a few simple examples at https://davidmfoley.github.io/react-router-modal-examples/

Hope it helps.

Title: React Router v4 Modal

Body:
I know how to do it in previous versions of React Router but I absolutely do not know how to do it in new React Router v4. Can somebody help me?

What do I want?

When you type /image/1 in browser url, page will appear as normal.

When you click on <Link>Image as modal</Link> with state modal: true, modal with image will appear BUT behind modal must be the previous content + url in browser === /image/1... Then If you press F5, page will appear as normal.

Example: instagram... etc

What do I think I'm doing wrong?

I do not know how to display the previous content. That is all I guess.

Code:

const Images = (props) => {
  return (

Images

<Link to={{
          pathname: '/image/1',
          state: {
            modal: true
          }
        }}>Image as modal</Link>

<Link to="/image/2">Image</Link>

  )
}

const Image = (props) => {
  return (

Image {props.match.params.id}

<Link to="/images">Back to Images</Link>

  )
}

ReactDOM.render(
  <Provider store={store}>
    <Router>

        <Route path='/images' component={Images} />
        <Route path='/image/:id' component={Image} />

    </Router>
  </Provider>,
  document.getElementById('digital')
)

Body:
I had the same problem, so I created:

http://npmjs.com/package/react-router-modal

It allows you to attach modals to routes. You would use it as follows:

import { ModalContainer, ModalRoute } from 'react-router-modal';
// ...
ReactDOM.render(
  <Provider store={store}>
    <Router>
      <div>
        <Route path='/images' component={Images} />
        <ModalRoute path='/image/:id' component={Image} />
      </div>
    </Router>
    <ModalContainer />
  </Provider>,
  document.getElementById('digital')
)

There are a few simple examples at https://davidmfoley.github.io/react-router-modal-examples/

Hope it helps.


来源: stackexchange

问:
Use Xcode 7 with iOS 10
I want to use Xcode 7 with iOS 10.

As I understand, working with iOS 10 beta requires Xcode 8 beta, so I should upgrade my Xcode. However, my code can't be built by the new compiler, so I want to stay with Xcode 7.

How can I achieve that?

答:
Here it is for XCode 9 and iOS 11 Beta 1:</p>

```<code>sudo ln -s \
/Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0\ \(15A5278f\) \
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0
</code>```

ContentLicense: CC BY-SA 3.0

Title: Use Xcode 7 with iOS 10

Body:
Here it is for XCode 9 and iOS 11 Beta 1:

sudo ln -s \
/Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0\ \(15A5278f\) \
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0


问:
Finding memory violations/leaks
I have an application developed in VC 2008 (C++) which uses axis dlls, which use openssl dlls. And someone in the chain corrupts heap - a situation which ends up giving me "memory access violation" in my application in places where violation shouldn't/couldn't happen. So, someone in the chain axis-ssl corrupts something, but I cannot find who or what.

I tried using DevPartner's tool for memory leaks, but it finds no leaks - no anything.

How should I approach this problem? I looked over axis and ssl documentation a number of times, and implemented and checked all possible memory management issues and fixes, but to no avail.

Thank you very much!
Marin

答: Try using MS application verifier. It integrates with Visual Studio, so you can make "verified" run directly from it.</p>

ContentLicense: CC BY-SA 2.5

Title: Finding memory violations/leaks


问:
Highlight a matched pattern in a DNA sequence with HTML markup using Perl
I am working on generating an HTML page using a CGI script in Perl.

I need filter some sequences in order to check whether they contain a specific pattern; if they contain it I need to print those sequences on my page with 50 bases per line, and highlight the pattern in the sequences. My sequences are in an hash called %hash; the keys are the names, the values are the actual sequences.

```<code>my %hash2;
foreach my $key (keys %hash)  {
    if ($hash{$key} =~ s!(aaagg)!<b>$1</b>!)  {
       $hash2{$key} = $hash{$key}
}
}

foreach my $key (keys %hash2)  {
    print "<p> <b> $key </b> </p>";
    print "<p>$_</p>\n" for unpack '(A50)*', $hash2{$key};
}
</code>```

This method "does" the job however if I highlight the pattern "aaagg" using this method I am messing up the unpacking of the line (for unpack '(A50)*'); because now the sequences contains the extra characters of the bold tags which are included in the unpacking count. This beside making the lines of different length it is also a big problem if the tag falls between 2 lines due to unpacking 50 characters, it basically remains open and everything after that is bold.

答:
The script below uses a single randomly generated DNA sequence of length 243 (generated using http://www.bioinformatics.org/sms2/random_dna.html) and a variable length pattern.

It works by first recording the positions which need to be highlighted instead of changing the sequence string. The highlighting is inserted after the sequence is split into chunks of 50 bases.

The highlighting is done in reverse order to minimize bookkeeping busy work.

```<code>#!/usr/bin/env perl

use utf8;
use strict;
use warnings;
use YAML::XS;

my $PRETTY_WIDTH = 50;

# I am using bold-italic so the highlighting
# is visible on Stackoverflow, but in real
# life, this would be something like:
# my @PRETTY_MARKUP = ('<span class="highlighted-match">', '</span>');

my @PRETTY_MARKUP = ('<b><i>', '</i></b>');

use constant { BAŞ => 0, SON => 1, ROW => 0, COL => 1 };

my $sequence = q{ccggtgagacatccagttagttcactgagccgacttgcatcagtcatgcttttccccgtaatgagggccccatattcaggccgtcgtccggaattgtcttggatccggaatgcagcttttctcaccgcttgatgaacattcactgaatatctgacgccgcgaaaacagggtcactagcctgtttccggtcgcccgagaccggcgagtttgtggtatcgcgagcgcccccgggcggtagggtct};

my $wanted = 'c..?gg';

my @pos;

while ($sequence =~ /($wanted)/g) {
    push @pos, [ pos($sequence) - length($1), pos($sequence) ];
}

print Dump \@pos;

my @output = unpack "(A$PRETTY_WIDTH)*", $sequence;

print Dump \@output;

while (my $pos = pop @pos) {
    my @rc = map pos_to_rc($_, $PRETTY_WIDTH), @$pos;
    substr($output[ $rc[$_][ROW] ], $rc[$_][COL], 0, $PRETTY_MARKUP[$_]) for SON, BAŞ;
}

print Dump \@output;

sub pos_to_rc {
    my $r = int( $_[0] / $_[1] );
    my $c = $_[0] - $r * $_[1];
    [ $r, $c ];
}
</code>```

Output:

```C:\...\Temp> perl s.pl
---
- - 0
  - 4
- - 76
  - 80
- - 87
  - 91
- - 97
  - 102
- - 104
  - 108
- - 165
  - 170
- - 184
  - 188
- - 198
  - 202
- - 226
  - 231
---
- ccggtgagacatccagttagttcactgagccgacttgcatcagtcatgct
- tttccccgtaatgagggccccatattcaggccgtcgtccggaattgtctt
- ggatccggaatgcagcttttctcaccgcttgatgaacattcactgaatat
- ctgacgccgcgaaaacagggtcactagcctgtttccggtcgcccgagacc
- ggcgagtttgtggtatcgcgagcgcccccgggcggtagggtct
---
- <b><i>ccgg</i></b>tgagacatccagttagttcactgagccgacttgcatcagtcatgct
- tttccccgtaatgagggccccatatt<b><i>cagg</i></b>ccgtcgt<b><i>ccgg</i></b>aattgt<b><i>ctt
- gg</i></b>at<b><i>ccgg</i></b>aatgcagcttttctcaccgcttgatgaacattcactgaatat
- ctgacgccgcgaaaa<b><i>caggg</i></b>tcactagcctgttt<b><i>ccgg</i></b>tcgcccgaga<b><i>cc
- gg</i></b>cgagtttgtggtatcgcgagcgcc<b><i>cccgg</i></b>gcggtagggtct```

Especially since this turns out to have been a homework assignment, it is now up to you to take this and apply it to all sequences in your hash table.

Body:
I am working on generating an HTML page using a CGI script in Perl.

I need filter some sequences in order to check whether they contain a specific pattern; if they contain it I need to print those sequences on my page with 50 bases per line, and highlight the pattern in the sequences. My sequences are in an hash called %hash; the keys are the names, the values are the actual sequences.

my %hash2;
foreach my $key (keys %hash)  {
    if ($hash{$key} =~ s!(aaagg)!$1!)  {
       $hash2{$key} = $hash{$key}
}
}

foreach my $key (keys %hash2)  {
    print "
  $key
";
    print "
$_
\n" for unpack '(A50)*', $hash2{$key};
}

This method "does" the job however if I highlight the pattern "aaagg" using this method I am messing up the unpacking of the line (for unpack '(A50)*'); because now the sequences contains the extra characters of the bold tags which are included in the unpacking count. This beside making the lines of different length it is also a big problem if the tag falls between 2 lines due to unpacking 50 characters, it basically remains open and everything after that is bold.

Body:
The script below uses a single randomly generated DNA sequence of length 243 (generated using http://www.bioinformatics.org/sms2/random_dna.html) and a variable length pattern.

It works by first recording the positions which need to be highlighted instead of changing the sequence string. The highlighting is inserted after the sequence is split into chunks of 50 bases.

The highlighting is done in reverse order to minimize bookkeeping busy work.

#!/usr/bin/env perl

use utf8;
use strict;
use warnings;
use YAML::XS;

my $PRETTY_WIDTH = 50;

# I am using bold-italic so the highlighting
# is visible on Stackoverflow, but in real
# life, this would be something like:
# my @PRETTY_MARKUP = ('<span class="highlighted-match">', '</span>');

my @PRETTY_MARKUP = ('<b><i>', '</i></b>');

use constant { BAŞ => 0, SON => 1, ROW => 0, COL => 1 };

my $sequence = q{ccggtgagacatccagttagttcactgagccgacttgcatcagtcatgcttttccccgtaatgagggccccatattcaggccgtcgtccggaattgtcttggatccggaatgcagcttttctcaccgcttgatgaacattcactgaatatctgacgccgcgaaaacagggtcactagcctgtttccggtcgcccgagaccggcgagtttgtggtatcgcgagcgcccccgggcggtagggtct};

my $wanted = 'c..?gg';

my @pos;

while ($sequence =~ /($wanted)/g) {
    push @pos, [ pos($sequence) - length($1), pos($sequence) ];
}

print Dump \@pos;

my @output = unpack "(A$PRETTY_WIDTH)*", $sequence;

print Dump \@output;

while (my $pos = pop @pos) {
    my @rc = map pos_to_rc($_, $PRETTY_WIDTH), @$pos;
    substr($output[ $rc[$_][ROW] ], $rc[$_][COL], 0, $PRETTY_MARKUP[$_]) for SON, BAŞ;
}

print Dump \@output;

sub pos_to_rc {
    my $r = int( $_[0] / $_[1] );
    my $c = $_[0] - $r * $_[1];
    [ $r, $c ];
}

Output:

C:\...\Temp> perl s.pl
---
- - 0
  - 4
- - 76
  - 80
- - 87
  - 91
- - 97
  - 102
- - 104
  - 108
- - 165
  - 170
- - 184
  - 188
- - 198
  - 202
- - 226
  - 231
---
- ccggtgagacatccagttagttcactgagccgacttgcatcagtcatgct
- tttccccgtaatgagggccccatattcaggccgtcgtccggaattgtctt
- ggatccggaatgcagcttttctcaccgcttgatgaacattcactgaatat
- ctgacgccgcgaaaacagggtcactagcctgtttccggtcgcccgagacc
- ggcgagtttgtggtatcgcgagcgcccccgggcggtagggtct
---
- ccggtgagacatccagttagttcactgagccgacttgcatcagtcatgct
- tttccccgtaatgagggccccatattcaggccgtcgtccggaattgtctt
- ggatccggaatgcagcttttctcaccgcttgatgaacattcactgaatat
- ctgacgccgcgaaaacagggtcactagcctgtttccggtcgcccgagacc
- ggcgagtttgtggtatcgcgagcgcccccgggcggtagggtct

Especially since this turns out to have been a homework assignment, it is now up to you to take this and apply it to all sequences in your hash table.


问:
Gluon Home Button Events
I'm using Gluon and have an audio player. When I call the audio and play it all works normally until I press the home button. What I want it to do is to stop the music not to continue playing as it does now. Currently I've tried using an event listener to capture the event and stop the music but it's not recognising the event, I'm thinking either I have assigned the wrong keycode or it simply doesn't work like that. I have a setOnHiding method in the view already and that only works on the back button. I've also tried setOnHidden and setOnCloseRequest as well with no luck. The event listener is below.</p>

```<code>    if (event.getCode().equals(KeyCode.HOME) && KeyEvent.KEY_PRESSED == event.getEventType()) {
    if (service1 != null) {
        service1.backPressed();

    }
</code>```

答:
Add a Listener to LifecycleEvent.Pause:

```<code> Services.get(LifecycleService.class).ifPresent(s -> s.addListener(LifecycleEvent.PAUSE, () -> stopPlayback());
</code>```

The PAUSE event is fired when an application loses focus (e.g. on Android / iOS when the focus is switched out of view (but still running in the background)).

Title: Gluon Home Button Events

Body:
I'm using Gluon and have an audio player. When I call the audio and play it all works normally until I press the home button. What I want it to do is to stop the music not to continue playing as it does now. Currently I've tried using an event listener to capture the event and stop the music but it's not recognising the event, I'm thinking either I have assigned the wrong keycode or it simply doesn't work like that. I have a setOnHiding method in the view already and that only works on the back button. I've also tried setOnHidden and setOnCloseRequest as well with no luck. The event listener is below.

    if (event.getCode().equals(KeyCode.HOME) && KeyEvent.KEY_PRESSED == event.getEventType()) {
    if (service1 != null) {
        service1.backPressed();

    }

Body:
Add a Listener to LifecycleEvent.Pause:

 Services.get(LifecycleService.class).ifPresent(s -> s.addListener(LifecycleEvent.PAUSE, () -> stopPlayback());

The PAUSE event is fired when an application loses focus (e.g. on Android / iOS when the focus is switched out of view (but still running in the background)).


问:
Insert and Splice error in java
I'm trying to Insert some random numbers with the same index in an array but something doesn't work. It says "cannot find symbol". This error is the same with Insert and Splice

the code:

```<code>   Scanner reader = new Scanner(System.in);
   System.out.println("Quina llargada tindrà la taula? ");
   int n = reader.nextInt(); //n=llargada taula
   int[] taula = new int[n];
   int ultims = n-21;

   int fi = 100*n;
   Random rand = new Random();
   //int al = rand.nextInt(fi) + 0;

   for (int i = 0; i < taula.length; i++)
       taula[i] = rand.nextInt(fi);

 Random randGromulls = new Random();
   for (int g = 0; g < 10; g++) {
       g++;
       int k = randGromulls.nextInt(10);
       int igual = k;
       taula.Insert(k, igual);
       //taula.splice(k, 0, igual); this does not work either

   }
</code>```

答:
The code you copied with insert and splice methods was for Javascript, not Java. Java arrays cannot change size. You probably want to use a List<Integer> instead.

If you really need an array, you can simulate insertion by shifting the array data to the next index:

```<code>System.arraycopy(array, i, array, i + 1, array.length - i - 1);
array[i] = value;
</code>```

For example, when you insert the value 5 at index 2, it does this:

```<code> |0|1|2|3|4|0|0|0|
      \ \ \ \ \ x
       \ \ \ \ \
 |0|1|2|2|3|4|0|0| System.arraycopy (shift by 1)
      v
 |0|1|5|2|3|4|0|0| array[2] = 5
</code>```

The last element of the array is dropped, since Java arrays cannot change size. You'll need to create the array with enough extra space to hold the inserted elements.

Alternately, if you aren't worried about memory overhead, you could create a new array for each insert:

```<code>int[] array2 = new int[array.length + 1];
System.arraycopy(array, 0, array2, 0, i);
System.arraycopy(array, i, array2, i + 1, array.length - i);
array2[i] = value;
array = array2; // all references must be updated to the new array!
</code>```

This would give you an array with a larger size, but the original array object won't be changed.

Title: Insert and Splice error in java

Body:
I'm trying to Insert some random numbers with the same index in an array but something doesn't work. It says "cannot find symbol". This error is the same with Insert and Splice

the code:

   Scanner reader = new Scanner(System.in);
   System.out.println("Quina llargada tindrà la taula? ");
   int n = reader.nextInt(); //n=llargada taula
   int[] taula = new int[n];
   int ultims = n-21;

   int fi = 100*n;
   Random rand = new Random();
   //int al = rand.nextInt(fi) + 0;

   for (int i = 0; i < taula.length; i++)
       taula[i] = rand.nextInt(fi);

 Random randGromulls = new Random();
   for (int g = 0; g < 10; g++) {
       g++;
       int k = randGromulls.nextInt(10);
       int igual = k;
       taula.Insert(k, igual);
       //taula.splice(k, 0, igual); this does not work either

   }

Body:
The code you copied with insert and splice methods was for Javascript, not Java. Java arrays cannot change size. You probably want to use a List<Integer> instead.

If you really need an array, you can simulate insertion by shifting the array data to the next index:

System.arraycopy(array, i, array, i + 1, array.length - i - 1);
array[i] = value;

For example, when you insert the value 5 at index 2, it does this:

 |0|1|2|3|4|0|0|0|
      \ \ \ \ \ x
       \ \ \ \ \
 |0|1|2|2|3|4|0|0| System.arraycopy (shift by 1)
      v
 |0|1|5|2|3|4|0|0| array[2] = 5

The last element of the array is dropped, since Java arrays cannot change size. You'll need to create the array with enough extra space to hold the inserted elements.

Alternately, if you aren't worried about memory overhead, you could create a new array for each insert:

int[] array2 = new int[array.length + 1];
System.arraycopy(array, 0, array2, 0, i);
System.arraycopy(array, i, array2, i + 1, array.length - i);
array2[i] = value;
array = array2; // all references must be updated to the new array!

This would give you an array with a larger size, but the original array object won't be changed.


问:
predict day of time series
I am starting to use R to make predictions and I am lost in this new world.

I have this dataset (part of my dataset):

```<code>date                         value

2016-12-27                   85396

2016-12-28                   78573

2016-12-29                   91593

2016-12-30                  196427

2017-01-02                  430301

2017-01-03                  409319

2017-01-04                  330748
</code>```

I want to predict for example the value of 2017-01-05.

I tried to build a timeseries with xts and use the Arime/forecast but the output is a line with values that i dont understand.

Is there another way to try to predict 1 day?

Title: predict day of time series

Body:
I am starting to use R to make predictions and I am lost in this new world.

I have this dataset (part of my dataset):

date                         value

2016-12-27                   85396

2016-12-28                   78573

2016-12-29                   91593

2016-12-30                  196427

2017-01-02                  430301

2017-01-03                  409319

2017-01-04                  330748

I want to predict for example the value of 2017-01-05.

I tried to build a timeseries with xts and use the Arime/forecast but the output is a line with values that i dont understand.

Is there another way to try to predict 1 day?

Body:
You didn't provide the code to reproduce your analysis so basically no one really knows what you did or what you are looking at which is why the question is being downvoted but in the absence of that copy and paste this into R:

Lines <- "date value
2016-12-27 85396
2016-12-28 78573
2016-12-29 91593
2016-12-30 196427
2017-01-02 430301
2017-01-03 409319
2017-01-04 330748"
DF <- read.table(text = Lines, header = TRUE)
library(forecast)
f <- forecast(DF$value)
plot(f)

giving a forecast of 33075.9 for the next point and the indicated 80% and 95% confidence intervals:

> f
   Point Forecast      Lo 80    Hi 80       Lo 95     Hi 95
 8       330755.9  182290.65 479221.1  103697.912  557813.8
 9       330755.9  120804.85 540706.9    9663.502  651848.2
10       330755.9   73623.73 587888.0  -62493.797  724005.5
11       330755.9   33847.73 627664.0 -123325.943  784837.7
12       330755.9   -1195.86 662707.6 -176920.489  838432.2
13       330755.9  -32877.82 694389.5 -225373.861  886885.6
14       330755.9  -62012.47 723524.2 -269931.461  931443.2
15       330755.9  -89130.39 750642.1 -311404.750  972916.5
16       330755.9 -114600.14 776111.9 -350357.376 1011869.1
17       330755.9 -138690.07 800201.8 -387199.732 1048711.5


问:
CSS scrollable-y, visible-x
My question is related to CSS overflow-y:visible, overflow-x:scroll
but I am still not able to solve my problem. I want a scrollable sidebar on y-axis with a visible tag hanging on the x-axis.

My HTML setup:

```<code><div>
   <ul>
     <li>
     </li>
     <li>
       <div> ... //want it to be visible x
       </div>
     </li>
   </ul>
</div>
</code>```

CSS:

I tried to use this:

```<code>.div { overflow-y:scroll; overflow-x:visible; }
.li { position:relative; }
.div { position:absolute; top:0px; left:-100px; display:inline-block; }
</code>```

答:
Generally if you want the to view the scroll in the div you should use

```<code>overflow-x:scroll;
</code>```

Please make sure to add a class otherwise the scroll will appear in the outer div too, Or use the hierarchy.

```<code>div ul li div{ overflow-x:scroll }
.my-div-scroll{ overflow-x:scroll }
</code>```

Title: CSS scrollable-y, visible-x

Body:
My question is related to CSS overflow-y:visible, overflow-x:scroll
but I am still not able to solve my problem. I want a scrollable sidebar on y-axis with a visible tag hanging on the x-axis.

My HTML setup:

 ... //want it to be visible x

CSS:

I tried to use this:

.div { overflow-y:scroll; overflow-x:visible; }
.li { position:relative; }
.div { position:absolute; top:0px; left:-100px; display:inline-block; }

Body:
Generally if you want the to view the scroll in the div you should use

overflow-x:scroll;

Please make sure to add a class otherwise the scroll will appear in the outer div too, Or use the hierarchy.

div ul li div{ overflow-x:scroll }
.my-div-scroll{ overflow-x:scroll }


问:
Adhoc record comparison oracle
So I have some records in excel with 4 pieces of information:

Date, Location, Workstation, Trans_ID.

I need to check these records against an oracle database. If this were sql server, I could just create a temp table & insert them, then join off the temp table and the table I need to check.

Anyone have a good solution for oracle?

答: I load spreadsheet data into Oracle regularly with TOAD [and even SQL*Loader].  I'm sure you can find some tools to help you with this.</p>

Title: Adhoc record comparison oracle


问:
Shifting from turbo to Code::Blocks
I have been using turbo c++ but not I have shifted to Code::Blocks and facing following problems

clrscr() function of conio.h is not working.

Using void main() but it's still asking for return type.

getch() showing some error.

What should I do?

```<code> #include<iostream>
 #include<conio.h>

 Using namespace std;

 void main(){
     clrscr ();
     int x=10;
     cout<<"hi"<<x;
     getch();
 }
</code>```

答:
Turbo C has broken C support since its first release, it added a lot of things that are not standard, like conio.h

Code::Blocks should also not be used because its development has stalled a while ago.

Please, use a modern C++ compiler, and if you need, a modern C++ IDE, below is a list of modern ones that could help you.

CLion

QtCreator

Eclipse CDT

MSVC Express

for C++, please, look into a modern version of any book (look for C++14, your c++ knowledge is from 1992, and I'm saying this not to put you down, but to put you in perspective.)

Title: Shifting from turbo to Code::Blocks

Body:
I have been using turbo c++ but not I have shifted to Code::Blocks and facing following problems

clrscr() function of conio.h is not working.

Using void main() but it's still asking for return type.

getch() showing some error.

What should I do?

 #include<iostream>
 #include<conio.h>

 Using namespace std;

 void main(){
     clrscr ();
     int x=10;
     cout<<"hi"<<x;
     getch();
 }


问:
How to check if connection pools are cleared
I want to rename database file and even I use using with connection every time I have to call:

```<code>FirebirdSql.Data.FirebirdClient.FbConnection.ClearAllPools();
</code>```

The problem is that this method doesn't block the thread and I don't know how to check if all connections are cleared, because if I get value from:

```<code>FirebirdSql.Data.FirebirdClient.FbConnection.ConnectionPoolsCount
</code>```

It is zero immediately after the method, but I am still not able to rename the database file. If I set some timeout after the method (I tried 1s) then the file is not locked and I can rename it. The problem is that this timeout could be certainly different on different machines.

FWIK the only other method how to check if the file is not locked is to try the renaming in the loop with some timeout, but I can not be sure if the lock is made by connections from my application or from somewhere else.

So is there a better way, how I can wait until this method clears the connections?

答:
Making it an answer for the sake of formatting lists.

@Artholl you can not safely rely upon your own disconnection for a bunch of reasons.

There may be other programs connected, not only this your running program. And unless you connect with SYSDBA or database creator or RDB$ADMIN role - you can not query if there are other connections now. However, you can query, from MON$ATTACHMENTS, the connections made with the same user as your CURRENT_CONNECTION. This might help you to check the state of your application's own pool. Just that there is little practical value in it.

in Firebird 3 in SuperServer mode there is the LINGER parameter, it means that server would keep the database open for some time after the last client disconnects, expecting that if some new client might decide to connect again then the PAGE CACHE for DB file is already in place. Like for middle-loaded WWW servers.

even in Firebird 2 every open database has some caches, and it would be installation-specific (firebird.conf) and database specific (gfix/gstat) how large the caches are. After the engine seeing all clients disconnected decided the database is to be closed - it starts with flushing the caches and demanding OS to flush their caches too ( there is no general hardware-independent way to demand RAID controllers and disks themselves to flush caches, or Firebird would try to make it too ). By default Firebird caches are small and preempting them to hardware layer should be fast, but still it is not instant.

Even if you checked that all other clients did disconnected, and then you disconnected yourself, and then you correctly guessed how long to wait for Linger and Caches, even then you still are not safe. You are subject to race conditions. At the very time you start doing something requiring explicit owning of DB there may happen some new client that would concurrently open his new connection.

So the correct approach would be not merely proving there is no database connection right NOW, but also ensuring there CAN NOT be any new connection in future, until you re-enable it.

So, as Mark said above, you have to use Shutdown methods to bring the database into no-connections-allowed state. And after you've done with file renaming and other manipulations - to switch it back to normal mode.

https://www.firebirdsql.org/file/documentation/reference_manuals/user_manuals/html/gfix-dbstartstop.html

Body:
I want to rename database file and even I use using with connection every time I have to call:

FirebirdSql.Data.FirebirdClient.FbConnection.ClearAllPools();

The problem is that this method doesn't block the thread and I don't know how to check if all connections are cleared, because if I get value from:

FirebirdSql.Data.FirebirdClient.FbConnection.ConnectionPoolsCount

It is zero immediately after the method, but I am still not able to rename the database file. If I set some timeout after the method (I tried 1s) then the file is not locked and I can rename it. The problem is that this timeout could be certainly different on different machines.

FWIK the only other method how to check if the file is not locked is to try the renaming in the loop with some timeout, but I can not be sure if the lock is made by connections from my application or from somewhere else.

So is there a better way, how I can wait until this method clears the connections?


问:
Chat server for Rails
As it is evident that AJAX based chats do not scale, so what would you use for chats? Custom servers? Or any other methods?

Since with Rails each chat connection will take lots of memory, it won't be feasible to even have Rails run for each message. What do you recommend for use here?

答: Do you have some data based on quantitative testing (aside from your own qualitative conclusions)?</p>

ContentLicense: CC BY-SA 4.0

Title: Chat server for Rails


问:
ASP.NET RC2 IFormFile file extension and file max size custom validation
I want to have custom jquery unobtrusive validator in MVC-6 RC2

Similar to the the  Old Answer I see some RC2 examples in This one  but I don't know how to implement it for files.

Here is my view mode

```<code>public class FileUploadViewModel
    {
        //TODO [FileType(Validtype="jpeg,png,jif", MaxSize=112222)]// this is what I want
        [Required(ErrorMessage = "Please select a file")]
        public IFormFile File { get; set; }

        [Required(ErrorMessage = "Please select link")]
        public string FileName { get; set; }

        public string ExternalLink { get; set; }

        public string Description { get; set; }
    }
</code>```

答:
I ended up solving my problem by using attributes

Here is how I created it.  (My size and extensions are static the same through our the application thats why I hard coded it in the FileTypeAttribute but you can make it dynamic and pass it to the attribute constructor if you want.

```<code>[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class FileTypeAttribute : ValidationAttribute, IClientModelValidator
    {
        private const int MaxSize = 1048576;
        private const string _DefaultErrorMessage = "Only the following file types are allowed: {0}";
        private IEnumerable<string> _ValidTypes { get; set; }

        public string ValidTypes { get; set; }

        public string ErrorMessageExtension { get; set; }

        public string ErrorMessageSize { get; set; }

        public FileTypeAttribute(string errorExtension, string errorSize)
        {
            ILang lang = ((ContextServiceImpl)ContextService.Instance).HttpContext.RequestServices.GetService(typeof(ILang)) as ILang;
            ErrorMessageExtension = lang[errorExtension];
            ErrorMessageSize = lang[errorSize];

        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            IFormFile file = value as IFormFile;
            if (file != null)
            {

                if (!_ValidTypes.Any(e => file.FileName.EndsWith(e)))
                {
                    return new ValidationResult(ErrorMessageExtension);
                }
                if (file.Length > MaxSize)
                {
                    return new ValidationResult(ErrorMessageSize);
                }
            }

            return ValidationResult.Success;
        }

        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-fileextensions", ErrorMessageExtension);
            MergeAttribute(context.Attributes, "data-val-maxfilesize", ErrorMessageSize);
        }

        private bool MergeAttribute(
        IDictionary<string, string> attributes, string key, string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }

            attributes.Add(key, value);
            return true;
        }
    }
</code>```

Then inside my view model I use the attribute as follows

```<code>public class FileUploadViewModel
    {
         [FileType("invalid format", "invalid size")]
        [Required(ErrorMessage = "Please select a file")]
        public IFormFile File { get; set; }

        [Required(ErrorMessage = "Please select link")]
        public string FileName { get; set; }

        public string ExternalLink { get; set; }

        public string Description { get; set; }
    }
</code>```

Then inside javascript do this

```<code>$.validator.addMethod("fileextensions",
        function (value, element, param) {
            var fileType = $(element)[0].files[0].type;
            var fileTypes = ["image/jpeg", "image/pjpeg", "image/gif", "image/bmp", "image/png", "image/x-png", "image/tiff"]
            var validExtension = $.inArray(type, fileTypes) !== -1;
            return validExtension;
     });

    $.validator.addMethod("maxfilesize",
     function (value, element, param) {

         var fileSize = $(element)[0].files[0].size;
         var maxSize = 1048576;

         var validSize = fileSize < maxSize;
         return validSize;
     });

    $.validator.unobtrusive.adapters.add('fileextensions', [], function (options) {
        var params = {
            fileextensions: $(options.element).data("val-fileextensions").split(',')
        };

        options.rules['fileextensions'] = params;
        options.messages['fileextensions'] = $(options.element).data("val-fileextensions");

    });

    $.validator.unobtrusive.adapters.add('maxfilesize', [], function (options) {

        options.rules['maxfilesize'] = [];
        options.messages['maxfilesize'] = $(options.element).data("val-maxfilesize");

    });
</code>```

Body:
I want to have custom jquery unobtrusive validator in MVC-6 RC2

Similar to the the  Old Answer I see some RC2 examples in This one  but I don't know how to implement it for files.

Here is my view mode

public class FileUploadViewModel
    {
        //TODO [FileType(Validtype="jpeg,png,jif", MaxSize=112222)]// this is what I want
        [Required(ErrorMessage = "Please select a file")]
        public IFormFile File { get; set; }

        [Required(ErrorMessage = "Please select link")]
        public string FileName { get; set; }

        public string ExternalLink { get; set; }

        public string Description { get; set; }
    }

Body:
I ended up solving my problem by using attributes

Here is how I created it.  (My size and extensions are static the same through our the application thats why I hard coded it in the FileTypeAttribute but you can make it dynamic and pass it to the attribute constructor if you want.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class FileTypeAttribute : ValidationAttribute, IClientModelValidator
    {
        private const int MaxSize = 1048576;
        private const string _DefaultErrorMessage = "Only the following file types are allowed: {0}";
        private IEnumerable<string> _ValidTypes { get; set; }

        public string ValidTypes { get; set; }

        public string ErrorMessageExtension { get; set; }

        public string ErrorMessageSize { get; set; }

        public FileTypeAttribute(string errorExtension, string errorSize)
        {
            ILang lang = ((ContextServiceImpl)ContextService.Instance).HttpContext.RequestServices.GetService(typeof(ILang)) as ILang;
            ErrorMessageExtension = lang[errorExtension];
            ErrorMessageSize = lang[errorSize];

        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            IFormFile file = value as IFormFile;
            if (file != null)
            {

                if (!_ValidTypes.Any(e => file.FileName.EndsWith(e)))
                {
                    return new ValidationResult(ErrorMessageExtension);
                }
                if (file.Length > MaxSize)
                {
                    return new ValidationResult(ErrorMessageSize);
                }
            }

            return ValidationResult.Success;
        }

        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-fileextensions", ErrorMessageExtension);
            MergeAttribute(context.Attributes, "data-val-maxfilesize", ErrorMessageSize);
        }

        private bool MergeAttribute(
        IDictionary<string, string> attributes, string key, string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }

            attributes.Add(key, value);
            return true;
        }
    }

Then inside my view model I use the attribute as follows

public class FileUploadViewModel
    {
         [FileType("invalid format", "invalid size")]
        [Required(ErrorMessage = "Please select a file")]
        public IFormFile File { get; set; }

        [Required(ErrorMessage = "Please select link")]
        public string FileName { get; set; }

        public string ExternalLink { get; set; }

        public string Description { get; set; }
    }

Then inside javascript do this

$.validator.addMethod("fileextensions",
        function (value, element, param) {
            var fileType = $(element)[0].files[0].type;
            var fileTypes = ["image/jpeg", "image/pjpeg", "image/gif", "image/bmp", "image/png", "image/x-png", "image/tiff"]
            var validExtension = $.inArray(type, fileTypes) !== -1;
            return validExtension;
     });

    $.validator.addMethod("maxfilesize",
     function (value, element, param) {

         var fileSize = $(element)[0].files[0].size;
         var maxSize = 1048576;

         var validSize = fileSize < maxSize;
         return validSize;
     });

    $.validator.unobtrusive.adapters.add('fileextensions', [], function (options) {
        var params = {
            fileextensions: $(options.element).data("val-fileextensions").split(',')
        };

        options.rules['fileextensions'] = params;
        options.messages['fileextensions'] = $(options.element).data("val-fileextensions");

    });

    $.validator.unobtrusive.adapters.add('maxfilesize', [], function (options) {

        options.rules['maxfilesize'] = [];
        options.messages['maxfilesize'] = $(options.element).data("val-maxfilesize");

    });


问:
How to use JSON variable of GET request in other HTTP request?
I'm really new in JMeter.
Tenant has Multple Environments

I have a test plan to create a Tenant, Get the tenant list. And then i have a JSON Extractor to save the Tenantid in order to create automatly an Environment in the desired tenant.

JSON Extractor:

then I set a Header manager to use the ID of this tenant to create the Environment in the Tenant

My HTTP request is set like this
[enter image description here][3]

But it doesn't work. Can you point me what i'm doing wrong?

答:
Double check that your JSON Extractor works via Debug Sampler and View Results Tree listener combination. You should see tenantId variable value there. See How to Debug your Apache JMeter Script article for more details.

If you really need to send PATH HTTP Header make HTTP Header Manager a child of the next HTTP Request sampler to avoid any clash with other HTTP Header Manager instances. Mind that URL Path is not the same as HTTP Header named PATH

Check jmeter.log file for any suspicious entries.


问:
Better to |> ignore or return ()
So this is just a curiosity question.

If I want to return unit, which is better practice?

```<code>|> ignore
</code>```

or

```<code>()
</code>```

There's probably other ways as well. I just want to know what's best, considering these:

What is most performant

What is best practice for a production environment

What is most readable for long term maintanance

答:
I think you are comparing things that are not quite comparable here. The () value lets you create the unit value, while |> ignore is what you can use to ignore some other result. The two are not exactly the same:

If you are calling a function and you want to ignore the result, you can write just:

```<code>doStuff () |> ignore
</code>```

But doing the same with () would require you to either ignore the warning:

```<code>doStuff () // warning: Result is ignored
()
</code>```

... or you could assign the result to an ignore pattern _ using let binding:

```<code>let _ = doStuff ()
()
</code>```

So, in this case, using ignore is better - it is inlined, so it has no performance implications and it leads to code that is easier to read.

That said, there are cases where you just need to create a unit value and then () is what you need (and there is no obvious way ignore would let you do the same). For example:

```<code>match optMessage with
| Some message -> printfn "ANNOUNCEMENT: %s" message
| None -> ()
</code>```

You could replace () with 42 |> ignore to get the same result, but it would be silly!

Title: Better to |> ignore or return ()

Body:
So this is just a curiosity question.

If I want to return unit, which is better practice?

|> ignore

or

()

There's probably other ways as well. I just want to know what's best, considering these:

What is most performant

What is best practice for a production environment

What is most readable for long term maintanance

Body:
I think you are comparing things that are not quite comparable here. The () value lets you create the unit value, while |> ignore is what you can use to ignore some other result. The two are not exactly the same:

If you are calling a function and you want to ignore the result, you can write just:

doStuff () |> ignore

But doing the same with () would require you to either ignore the warning:

doStuff () // warning: Result is ignored
()

... or you could assign the result to an ignore pattern _ using let binding:

let _ = doStuff ()
()

So, in this case, using ignore is better - it is inlined, so it has no performance implications and it leads to code that is easier to read.

That said, there are cases where you just need to create a unit value and then () is what you need (and there is no obvious way ignore would let you do the same). For example:

match optMessage with
| Some message -> printfn "ANNOUNCEMENT: %s" message
| None -> ()

You could replace () with 42 |> ignore to get the same result, but it would be silly!


问:
If checkboxes are checked angularjs using ng-repeat
Here is my HTML

```<code>    <div ng-controller="Orders">
        <div ng-repeat="order in orders">
          <form>
            <div ng-repeat="item in order.line_items">
                <input type="checkbox" name="order_{{order.id}}_items[]"?> {{item.name}}
            </div>
          </form>
        </div>
    </div>
</code>```

Here is my Controller:

```<code>app.controller("Orders", function($scope, WC) {
    var Woocommerce = WC.WC();
    // get orders from json
    Woocommerce.get('orders?filter[post_status]=wc-processing&?filter[limit]=-1', function(err, data, res){
        var obj = JSON.parse(res);
        console.log(obj.orders);
        $scope.orders = obj.orders;
        $scope.$apply()
    });

});`
</code>```

It outputs this:

Per order I want to know true false if any of the order items has been checked so I can then show a submit button.

On the checkboxes I have tried ng-repeat and ng-model with no success so far.

答:
Create a Directive/Component for each Order item so that you can isolate the scope of each order. Then check for changes for each item.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.orders=[
      {
        id: 1,
        line_items: [
          {
            id: 1,
            "name": "item 1"
          },
          {
            id: 2,
            "name": "item 2"

          }
        ]
      },
      {
        id: 2,
        line_items:[
          {
            id: 3,
            "name": "item 3"
          },
          {
            id: 4,
            "name": "item 4"
          }
        ]
      }
    ]
});

app.component('order', {
  template: '
Order {{$ctrl.order.id}}

<input type="checkbox" ng-model="item.isSelected" ng-change="$ctrl.doChange()"> {{item.name}}

<input type="submit" value="Submit" />
',
  bindings: {
    order: '=ngModel',

  },
  controller: function() {
    this.showButton = false;
    this.doChange = function(){
      var checkedItems = this.order.line_items.filter( (item)=>{
        return item.isSelected;
      });
      this.showButton = (checkedItems && checkedItems.length>0)
    }

  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">

    <section class="orders" ng-repeat="order in orders">
        <Order ng-model="order"></Order>
    </section>

  </body>

</html></code>```

Body:
Here is my HTML

          <form>

                <input type="checkbox" name="order_{{order.id}}_items[]"?> {{item.name}}

          </form>

Here is my Controller:

app.controller("Orders", function($scope, WC) {
    var Woocommerce = WC.WC();
    // get orders from json
    Woocommerce.get('orders?filter[post_status]=wc-processing&?filter[limit]=-1', function(err, data, res){
        var obj = JSON.parse(res);
        console.log(obj.orders);
        $scope.orders = obj.orders;
        $scope.$apply()
    });

});`

It outputs this:

Per order I want to know true false if any of the order items has been checked so I can then show a submit button.

On the checkboxes I have tried ng-repeat and ng-model with no success so far.

Body:
Create a Directive/Component for each Order item so that you can isolate the scope of each order. Then check for changes for each item.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.orders=[
      {
        id: 1,
        line_items: [
          {
            id: 1,
            "name": "item 1"
          },
          {
            id: 2,
            "name": "item 2"

          }
        ]
      },
      {
        id: 2,
        line_items:[
          {
            id: 3,
            "name": "item 3"
          },
          {
            id: 4,
            "name": "item 4"
          }
        ]
      }
    ]
});

app.component('order', {
  template: '<h2>Order {{$ctrl.order.id}}</h2><div ng-repeat="item in $ctrl.order.line_items"><label><input type="checkbox" ng-model="item.isSelected" ng-change="$ctrl.doChange()"> {{item.name}}</label></div><div ng-show="$ctrl.showButton"><input type="submit" value="Submit" /></div>',
  bindings: {
    order: '=ngModel',

  },
  controller: function() {
    this.showButton = false;
    this.doChange = function(){
      var checkedItems = this.order.line_items.filter( (item)=>{
        return item.isSelected;
      });
      this.showButton = (checkedItems && checkedItems.length>0)
    }

  }
});

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">

    <section class="orders" ng-repeat="order in orders">
        <Order ng-model="order"></Order>
    </section>

  </body>

</html>


问:
How to mock a dictionary?
First, I'd better ask if I should mock dictionaries? And if I should how can I achieve that?

I am using Rhino Mocks. I looked through its documentation and saw that it can mock ArrayList. So I tried it on Dictionary but no luck. I got the error that I'm not calling a virtual method bla bla... Will it be a problem if I don't mock it?

答:
Without knowing your specific test scenario I wouldn't mock a .NET framework class, because you can take it as given that they work correctly.

Exceptions to this rule may apply to classes that give access to external ressources (like File or SQLConnection) but this is because you don't want to setup these ressources in your unit test, not because you don't want to test the classes themselves.

Title: How to mock a dictionary?


问:
contiguous date ranges error in Powerpivot
I have a data sales "data" table, and a calendar table with every day in it.  The tables are linked and I have the calendar table marked as a date table and the unique identifier setup as date.

I'm trying to do things like year over year calculations, and for some dates it works, and for others I get the contiguous dates error.

Also, it works sometimes.  For example, I can do 6/1/16 to 5/31/17, but as soon as I add in 5/1/16 to 5/31/17 I get the error.

```<code>=CALCULATE([Total Sales], DATESYTD(Calendar[Date] )  )
</code>```

答:
Looks like the solution is here

https://powerpivotpro.com/2014/01/defanging-the-contiguous-date-selections-error/?nabm=1&utm_referrer=https%3A%2F%2Fwww.google.com%2F

Body:
I have a data sales "data" table, and a calendar table with every day in it.  The tables are linked and I have the calendar table marked as a date table and the unique identifier setup as date.

I'm trying to do things like year over year calculations, and for some dates it works, and for others I get the contiguous dates error.

Also, it works sometimes.  For example, I can do 6/1/16 to 5/31/17, but as soon as I add in 5/1/16 to 5/31/17 I get the error.

=CALCULATE([Total Sales], DATESYTD(Calendar[Date] )  )


问:
Python3 won't recognize a variable in code
All my code is below.

Just started learning to program this week. I'm attempting to make a Monty Hall simulator (text only) where the player chooses a door by selecting 1, 2 or 3. For some reason, though, Python doesn't seem to be recognizing the input!

Here are links to the game for the uninitiated:

Monty Hall wikipedia page

Monty Hall simulation

What my program attempts to do is as follows. First the player chooses a door, either 1, 2 or 3. Then the program checks to make sure that the player did indeed enter one of those three numbers. If not, then the person needs to choose again.

After this, the game randomly chooses a winning door. Then, per the rules of the game, the program needs to reveal a dummy prize (the goat). So the program randomly chooses one of the doors to be the "goat door." The program first makes sure that this door is not the winning door nor is it the chosen door.

Here's the error I get when running my code:

```<code>line 52, in <module>

     doors()

line 14, in doors

     while goatDoor == chosenDoor or goatDoor == winningDoor:

NameError: name 'chosenDoor' is not defined
</code>```

My issue is that I can't tell why it keeps saying that chosenDoor is not defined!

Here's the code:

```<code>import random

def chooseDoor():   # choose a door
    chosenDoor = ''
    while chosenDoor != 1 and chosenDoor != 2 and chosenDoor != 3:
        print('Choose a door. (1, 2 or 3)')
        chosenDoor = input()
        return chosenDoor
    print('You chose door number ' + str(chosenDoor) + '.')

def doors():    # the winning door and the dummy door are randomly selected
    winningDoor = random.randint(1,3)
    goatDoor = ''
    while goatDoor == chosenDoor or goatDoor == winningDoor:
        goatDoor = random.randint(1, 3)

def keepOrSwitch():
    switchDoor = 1
    if switchDoor == chosenDoor or switchDoor == winningDoor:
        switchDoor = 2
        if switchDoor == chosenDoor or switchDoor == winningDoor:
            switchDoor = 3
    print('Do you want to')
    print('KEEP your choice of door number ' + str(chosenDoor) + '?')
    print('...or...')
    print('Do you want to')
    print('SWITCH and choose door number ' + str(switchDoor) + '?')
    print()
    choice = ''
    while True:
        print('Type \'K\' for keep or type \'S\' for switch.')
        choice = input()
        if choice == 'K' or choice == 'k':
            break
        if choice == 'S' or choice == 's':
            chosenDoor = switchDoor
            break

def checkWin():
    if chosenDoor == winningDoor:
        print('You win!')
    if chosenDoor != winningDoor:
        print('You lose!')

# the rest of the code is the actual game
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':

    chooseDoor()

    doors()

    keepOrSwitch()

    checkWin()

    print('Do you want to play again? (yes or no)')
    playAgain = input()
</code>```

答:
Your variables are out of scope, you need to store the variables you're making down in the while loop and return the values from the methods you've made, then pass the values to checkWin

keepOrSwitch should return chosen

chooseDoor should return chosenDoor

doors should return winningdoor/goatdoor

checkwin should take chosenDoor + winnindoor + goatdoor

you'll then be able to reference your variables correctly

Body:
All my code is below.

Just started learning to program this week. I'm attempting to make a Monty Hall simulator (text only) where the player chooses a door by selecting 1, 2 or 3. For some reason, though, Python doesn't seem to be recognizing the input!

Here are links to the game for the uninitiated:

Monty Hall wikipedia page

Monty Hall simulation

What my program attempts to do is as follows. First the player chooses a door, either 1, 2 or 3. Then the program checks to make sure that the player did indeed enter one of those three numbers. If not, then the person needs to choose again.

After this, the game randomly chooses a winning door. Then, per the rules of the game, the program needs to reveal a dummy prize (the goat). So the program randomly chooses one of the doors to be the "goat door." The program first makes sure that this door is not the winning door nor is it the chosen door.

Here's the error I get when running my code:

line 52, in <module>

     doors()

line 14, in doors

     while goatDoor == chosenDoor or goatDoor == winningDoor:

NameError: name 'chosenDoor' is not defined

My issue is that I can't tell why it keeps saying that chosenDoor is not defined!

Here's the code:

import random

def chooseDoor():   # choose a door
    chosenDoor = ''
    while chosenDoor != 1 and chosenDoor != 2 and chosenDoor != 3:
        print('Choose a door. (1, 2 or 3)')
        chosenDoor = input()
        return chosenDoor
    print('You chose door number ' + str(chosenDoor) + '.')

def doors():    # the winning door and the dummy door are randomly selected
    winningDoor = random.randint(1,3)
    goatDoor = ''
    while goatDoor == chosenDoor or goatDoor == winningDoor:
        goatDoor = random.randint(1, 3)

def keepOrSwitch():
    switchDoor = 1
    if switchDoor == chosenDoor or switchDoor == winningDoor:
        switchDoor = 2
        if switchDoor == chosenDoor or switchDoor == winningDoor:
            switchDoor = 3
    print('Do you want to')
    print('KEEP your choice of door number ' + str(chosenDoor) + '?')
    print('...or...')
    print('Do you want to')
    print('SWITCH and choose door number ' + str(switchDoor) + '?')
    print()
    choice = ''
    while True:
        print('Type \'K\' for keep or type \'S\' for switch.')
        choice = input()
        if choice == 'K' or choice == 'k':
            break
        if choice == 'S' or choice == 's':
            chosenDoor = switchDoor
            break

def checkWin():
    if chosenDoor == winningDoor:
        print('You win!')
    if chosenDoor != winningDoor:
        print('You lose!')

# the rest of the code is the actual game
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':

    chooseDoor()

    doors()

    keepOrSwitch()

    checkWin()

    print('Do you want to play again? (yes or no)')
    playAgain = input()


问:
Deserialize xml using C# containing element with an attribute in a different namespace
I am receiving XML in a structure I have no control over and am attempting to deserialize the XML using C#. The XML contains multiple namespaces. Most of the XML is in 1 namespace, but there is a portion that has an attribute in a different namespace. My issue is that the Content node is always being deserialized as null. What do I need to do to correct this?

My XML is given below.

```<code><Documents xmlns="http://mycompany.com/api/v2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Document>
       <Id>100000</Id>
       <Title>Document Title</Title>
       <Locale>en-US</Locale>
       <Status>Archived</Status>
       <PublishDate>2016-06-01T16:40:00</PublishDate>
       <PublishDateUTC>2016-06-01T21:40:00Z</PublishDateUTC>
       <UpdateDateUTC>2016-06-01T21:40:00Z</UpdateDateUTC>
       <Companies>
           <Company>
               <Id>1C000TX2343</Id>
               <Name>Company Name</Name>
               <Status>Public</Status>
               <OperationStatus>N</OperationStatus>
               <Country>USA</Country>
           </Company>
       </Companies>
       <Content i:type="CRCMinute">
           <AssetClass>Corporate</AssetClass>
           <CommitteeAlphaRating>BB+</CommitteeAlphaRating>
           <CommitteeCreditTrend>Negative</CommitteeCreditTrend>
           <CommitteeMeetingDate>2016-06-01T00:00:00</CommitteeMeetingDate>
           <CreditWatch i:nil="true"/>
           <RatingStatus i:nil="true"/>
           <ShortTermRating i:nil="true"/>
           <SignatureDate>2016-06-01T16:40:00</SignatureDate>
           <SignatureText>Alfred Neumann</SignatureText>
       </Content>
    </Document>
</Documents>
</code>```

The class I am using to deserialize the XML is provided as well.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace Morningstar.CreditRatings.CorporateShortTerm
{
[XmlRoot("Documents")]
public class RPSDocuments
{
    [XmlElement("Document")]
    public List<DocumentData> DocumentData { get; set; }
}

[Serializable]
public class DocumentData
{
    [XmlElement]
    public string Id { get; set; }

    [XmlElement]
    public string Title { get; set; }

    [XmlElement]
    public string PublishDate { get; set; }

    [XmlElement]
    public string PublishDateUTC { get; set; }

    [XmlElement]
    public string UpdateDateUTC { get; set; }

    [XmlArray("Companies")]
    [XmlArrayItem("Company")]
    public List<CompanyData> Companies { get; set; }

    [XmlElement("Content", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public DocumentContentData Content { get; set; }
}

[Serializable]
public class CompanyData
{
    [XmlElement]
    public string Id { get; set; }

    public string Name { get; set; }

    [XmlElement]
    public string Status { get; set; }

    [XmlElement]
    public string OperationStatus { get; set; }

    [XmlElement]
    public string Country { get; set; }
}

[Serializable]
public class DocumentContentData
{
    [XmlElement]
    public string Analyst { get; set; }

    [XmlElement]
    public string AssetClass { get; set; }

    [XmlElement]
    public string CommitteeAlphaRating { get; set; }

    [XmlElement]
    public string CommitteeCreditTrend { get; set; }

    [XmlElement]
    public string CommitteeMeetingDate { get; set; }

    [XmlElement]
    public string CreditWatch { get; set; }

    [XmlElement]
    public string RatingStatus { get; set; }

    [XmlElement]
    public string ShortTermRating { get; set; }

    [XmlElement]
    public string SignatureDate { get; set; }

    [XmlElement]
    public string SignatureText { get; set; }
}
</code>```

}

答:
Since the Content element itself is not in a different namespace than its parent (only the type attribute is), remove the Namespace attribute from the Content property. Instead you must decorate RPSDocuments with

```<code>[Namespace = "http://mycompany.com/api/v2"]
</code>```

Edit: You also need to decorate DocumentContentData with

```<code>[XmlType("CRCMinute")]
</code>```

You don't need the Serializable attributes.

Body:
I am receiving XML in a structure I have no control over and am attempting to deserialize the XML using C#. The XML contains multiple namespaces. Most of the XML is in 1 namespace, but there is a portion that has an attribute in a different namespace. My issue is that the Content node is always being deserialized as null. What do I need to do to correct this?

My XML is given below.

<Documents xmlns="http://mycompany.com/api/v2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Document>
       <Id>100000</Id>
       <Title>Document Title</Title>
       <Locale>en-US</Locale>
       <Status>Archived</Status>
       <PublishDate>2016-06-01T16:40:00</PublishDate>
       <PublishDateUTC>2016-06-01T21:40:00Z</PublishDateUTC>
       <UpdateDateUTC>2016-06-01T21:40:00Z</UpdateDateUTC>
       <Companies>
           <Company>
               <Id>1C000TX2343</Id>
               <Name>Company Name</Name>
               <Status>Public</Status>
               <OperationStatus>N</OperationStatus>
               <Country>USA</Country>
           </Company>
       </Companies>
       <Content i:type="CRCMinute">
           <AssetClass>Corporate</AssetClass>
           <CommitteeAlphaRating>BB+</CommitteeAlphaRating>
           <CommitteeCreditTrend>Negative</CommitteeCreditTrend>
           <CommitteeMeetingDate>2016-06-01T00:00:00</CommitteeMeetingDate>
           <CreditWatch i:nil="true"/>
           <RatingStatus i:nil="true"/>
           <ShortTermRating i:nil="true"/>
           <SignatureDate>2016-06-01T16:40:00</SignatureDate>
           <SignatureText>Alfred Neumann</SignatureText>
       </Content>
    </Document>
</Documents>

The class I am using to deserialize the XML is provided as well.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;

namespace Morningstar.CreditRatings.CorporateShortTerm
{
[XmlRoot("Documents")]
public class RPSDocuments
{
    [XmlElement("Document")]
    public List<DocumentData> DocumentData { get; set; }
}

[Serializable]
public class DocumentData
{
    [XmlElement]
    public string Id { get; set; }

    [XmlElement]
    public string Title { get; set; }

    [XmlElement]
    public string PublishDate { get; set; }

    [XmlElement]
    public string PublishDateUTC { get; set; }

    [XmlElement]
    public string UpdateDateUTC { get; set; }

    [XmlArray("Companies")]
    [XmlArrayItem("Company")]
    public List<CompanyData> Companies { get; set; }

    [XmlElement("Content", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public DocumentContentData Content { get; set; }
}

[Serializable]
public class CompanyData
{
    [XmlElement]
    public string Id { get; set; }

    public string Name { get; set; }

    [XmlElement]
    public string Status { get; set; }

    [XmlElement]
    public string OperationStatus { get; set; }

    [XmlElement]
    public string Country { get; set; }
}

[Serializable]
public class DocumentContentData
{
    [XmlElement]
    public string Analyst { get; set; }

    [XmlElement]
    public string AssetClass { get; set; }

    [XmlElement]
    public string CommitteeAlphaRating { get; set; }

    [XmlElement]
    public string CommitteeCreditTrend { get; set; }

    [XmlElement]
    public string CommitteeMeetingDate { get; set; }

    [XmlElement]
    public string CreditWatch { get; set; }

    [XmlElement]
    public string RatingStatus { get; set; }

    [XmlElement]
    public string ShortTermRating { get; set; }

    [XmlElement]
    public string SignatureDate { get; set; }

    [XmlElement]
    public string SignatureText { get; set; }
}

}

Body:
Since the Content element itself is not in a different namespace than its parent (only the type attribute is), remove the Namespace attribute from the Content property. Instead you must decorate RPSDocuments with

[Namespace = "http://mycompany.com/api/v2"]

Edit: You also need to decorate DocumentContentData with

[XmlType("CRCMinute")]

You don't need the Serializable attributes.


问:
How Can I create a restful application on C# in a project with A Soap application without getting a Bad Request 400 code?
I've a Soap application which I want to replicate as a Rest

I've created the following code:

Interface:

```<code>// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IRestfulCardServices" in both code and config file together.
[ServiceContract]
public interface IRestfulCardServices
{
    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
                                               BodyStyle = WebMessageBodyStyle.Bare,
                                               UriTemplate = "ConsultCards/")]
    List<CardInformation> ConsultCards();
}
</code>```

Implementation:

```<code>[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class RestfulCardServices : IRestfulCardServices
{
    public List<CardInformation> ConsultCards()
    {
        return something;
    }
}
</code>```

Web.config

```<code> <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <system.web>
        <compilation debug="true" targetFramework="4.0" />

        <httpRuntime requestValidationMode="2.0" maxRequestLength="9000000" />
      </system.web>
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
      </system.webServer>
      <system.serviceModel>
        <services>

          <service name="ITSCredit.FlowCredit.Services.RestfulCardServices" behaviorConfiguration="serviceBehavior">
            <endpoint address =""
                      binding="webHttpBinding"
                      contract="ITSCredit.FlowCredit.Services.IRestfulCardServices"
                      behaviorConfiguration="web"></endpoint>
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior>
              <dataContractSerializer maxItemsInObjectGraph="2147483647" />
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
            <behavior name="serviceBehavior">
              <dataContractSerializer maxItemsInObjectGraph="2147483647" />
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
            <behavior name="web">
              <webHttp/>
            </behavior>
          </endpointBehaviors>
        </behaviors>
        <protocolMapping>
          <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

 <bindings>
      <basicHttpBinding>
 <binding name="BasicHttpBinding_IRestfulCardServices" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="9999524288" maxBufferSize="999965536" maxReceivedMessageSize="999965536" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true" messageEncoding="Text">
          <readerQuotas maxDepth="32" maxStringContentLength="999998192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
</basicHttpBinding>
    </bindings>
  </system.serviceModel>

  <appSettings>
  </appSettings>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
</code>```

I keep getting a bad Request response as I call it on SoapUi/Postman. If I call the function directly from code behind it works fine. I think the problem might me because of the web config but the examples I've searched seem to be very similar to what I have presently

This is the response error I get:

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content:
  System.Net.Http.StreamContent, Headers: {   Cache-Control: private

  Date: Mon, 05 Jun 2017 16:06:25 GMT   Server: Microsoft-IIS/8.5

  X-AspNet-Version: 4.0.30319   X-Powered-By: ASP.NET   Content-Length:
  0 }}

Any thought about what's missing?

Thanks in advance

答:
Normally I get this kind of error when I  give a wrong service name on the system.serviceModel config.

Check if:

```<code><service name="ITSCredit.FlowCredit.Services.RestfulCardServices" behaviorConfiguration="serviceBehavior">
</code>```

has the correct name (NameSpace.RestfulCardServices)

Body:
I've a Soap application which I want to replicate as a Rest

I've created the following code:

Interface:

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IRestfulCardServices" in both code and config file together.
[ServiceContract]
public interface IRestfulCardServices
{
    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
                                               BodyStyle = WebMessageBodyStyle.Bare,
                                               UriTemplate = "ConsultCards/")]
    List<CardInformation> ConsultCards();
}

Implementation:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class RestfulCardServices : IRestfulCardServices
{
    public List<CardInformation> ConsultCards()
    {
        return something;
    }
}

Web.config

 <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <system.web>
        <compilation debug="true" targetFramework="4.0" />

        <httpRuntime requestValidationMode="2.0" maxRequestLength="9000000" />
      </system.web>
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
      </system.webServer>
      <system.serviceModel>
        <services>

          <service name="ITSCredit.FlowCredit.Services.RestfulCardServices" behaviorConfiguration="serviceBehavior">
            <endpoint address =""
                      binding="webHttpBinding"
                      contract="ITSCredit.FlowCredit.Services.IRestfulCardServices"
                      behaviorConfiguration="web"></endpoint>
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior>
              <dataContractSerializer maxItemsInObjectGraph="2147483647" />
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
            <behavior name="serviceBehavior">
              <dataContractSerializer maxItemsInObjectGraph="2147483647" />
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
            <behavior name="web">
              <webHttp/>
            </behavior>
          </endpointBehaviors>
        </behaviors>
        <protocolMapping>
          <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

 <bindings>
      <basicHttpBinding>
 <binding name="BasicHttpBinding_IRestfulCardServices" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="9999524288" maxBufferSize="999965536" maxReceivedMessageSize="999965536" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true" messageEncoding="Text">
          <readerQuotas maxDepth="32" maxStringContentLength="999998192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
</basicHttpBinding>
    </bindings>
  </system.serviceModel>

  <appSettings>
  </appSettings>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

I keep getting a bad Request response as I call it on SoapUi/Postman. If I call the function directly from code behind it works fine. I think the problem might me because of the web config but the examples I've searched seem to be very similar to what I have presently

This is the response error I get:

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content:
  System.Net.Http.StreamContent, Headers: {   Cache-Control: private

  Date: Mon, 05 Jun 2017 16:06:25 GMT   Server: Microsoft-IIS/8.5

  X-AspNet-Version: 4.0.30319   X-Powered-By: ASP.NET   Content-Length:
  0 }}

Any thought about what's missing?

Thanks in advance

Body:
Normally I get this kind of error when I  give a wrong service name on the system.serviceModel config.

Check if:

<service name="ITSCredit.FlowCredit.Services.RestfulCardServices" behaviorConfiguration="serviceBehavior">

has the correct name (NameSpace.RestfulCardServices)


问:
Spring data JPA. Find by in
I have an usual Spring Data JPA repository in my spring project.

```<code>@Repository
public interface EventRepository extends CrudRepository<Event, Long> {
  List<Event> findByOriginalIdIn(Collection<String> originalEventIds);
  ...
</code>```

I used before method findByOriginalIdIn it was working good. But situation is changed and I need to handle same request using collection of pairs to find and filter correct events.

My alternative method should Handle next logic:
find by (originalId1 AND originalCalendarId1) OR (originalId2 AND originalCalendarId2) OR (originalId..N AND originalCalendarId..N) OR

Is it possible handle this request using Selectively exposing CRUD methods? If yes, could I have an example please?

答:
To not create custom repository I'd recommend to use Spring Data JPA specifications.
Here's an draft example.

```<code>       class Specification1 implements Specification<Event> {
            private final List<Pair<String, String>> pairs;

            public Specification1(List<Pair<String, String>> pairs) {
                this.paris = pairs;
            }

            @Override
            public Predicate toPredicate(Root<Event> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                Predicate[] as = pairs.stream().map(pair -> {
                    return cb.and(cb.equal(root.get("originalId2"), pair.getKey())),cb.equal(root.get("originalCalendarId2"), pair.getKey());
                }).toArray(Predicate[]::new);

                return cb.or(as);
            }
        }

        userRepository.findAll(new Specification1(...));
</code>```

In additional you repository has to extend JpaSpecificationExecutor.

Title: Spring data JPA. Find by in

Body:
I have an usual Spring Data JPA repository in my spring project.

@Repository
public interface EventRepository extends CrudRepository<Event, Long> {
  List<Event> findByOriginalIdIn(Collection<String> originalEventIds);
  ...

I used before method findByOriginalIdIn it was working good. But situation is changed and I need to handle same request using collection of pairs to find and filter correct events.

My alternative method should Handle next logic:
find by (originalId1 AND originalCalendarId1) OR (originalId2 AND originalCalendarId2) OR (originalId..N AND originalCalendarId..N) OR

Is it possible handle this request using Selectively exposing CRUD methods? If yes, could I have an example please?

Body:
To not create custom repository I'd recommend to use Spring Data JPA specifications.
Here's an draft example.

       class Specification1 implements Specification<Event> {
            private final List<Pair<String, String>> pairs;

            public Specification1(List<Pair<String, String>> pairs) {
                this.paris = pairs;
            }

            @Override
            public Predicate toPredicate(Root<Event> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

                Predicate[] as = pairs.stream().map(pair -> {
                    return cb.and(cb.equal(root.get("originalId2"), pair.getKey())),cb.equal(root.get("originalCalendarId2"), pair.getKey());
                }).toArray(Predicate[]::new);

                return cb.or(as);
            }
        }

        userRepository.findAll(new Specification1(...));

In additional you repository has to extend JpaSpecificationExecutor.


问:
stylesheets and mobile browsers
I aint sure if I have asked this question in other threads as well ... but my question have still been unanswered ... what I need to know is that while using Opera mini... or browsing site on the mobile.. are there certain restrictions while using HTML or CSS ?? I got totally confused with certain terms like Screen Stylesheets and Handheld Stylesheets... while getting the media type, there was a mention that we gotta use some screen or handheld stylesheets .... depending upon the media type ...  just not sure how else to ask ....</p>

答:
Mobile browsers may have restrictions on some HTML or CSS rules, just like each browser vendor has it's specifities on this subject. You'll have to check what works or not for the mobile browsers you are developing.

The media types (screen, handheld, etc) is defined by CSS, so you can use different stylesheets to different kinds of media. So, you can display the same content differently to each kind of media. Notice that the types screen, handheld, etc, doesn't define window sizes, only different types of devices. Check the links below, to get a better understanding of it:

http://www.w3.org/TR/CSS2/media.html

http://www.alistapart.com/articles/return-of-the-mobile-stylesheet

Hope it helps!

Title: stylesheets and mobile browsers


问:
How to do segmentation of connected components in openCV?
I have to segment out each individual element in this Image. I have converted the original image to a threshold binary image and then applied some morphological dilation. Then I applied the cv::connectedComponents function to label each connected components. Now I want to crop out them, how can I do it using c++ and openCV ?

答: If instead of using connectedComponents use connectedComponentsWithStats, you should have enough information for cropping each of the objects labeled. </p>


问:
Gradle Java Library Test Jar Using Maven Plugin
In the past, I've had great success in providing test helpers in a core or common project, and having those classes available to other sub-projects using the following:

Common Project A

```<code>task testJar(type: Jar) {
    classifier = "tests"
    from sourceSets.test.output
}

artifacts { testRuntime testJar }
</code>```

Dependent Project B

```<code>testCompile(project(path: ":project-a", configuration: "testRuntime"))
</code>```

However, I have the same requirement between two projects that do NOT share a Gradle multi-project hierarchy.  To clarify, these are completely separate projects.  They are in different repositories, using different build scripts.  They are not sub-modules within a parent project.

To futher complex matters, I'm using the Java Library plugin and the Maven plugin to install libraries locally.  In other words, I'd love for the second project to include a dependency as such:

```<code>testImplementation 'com.mycompany:common-test:1.0.0'
</code>```

What should the first "common" project look like to a) generate that test jar and b) allow it to be installed to Maven?

Many thanks for all help.

答:
I've found that it's best to put any test utilities in their own separate project rather than building a "test" jar from src/test/java and src/test/resources.

It seems that netflix feel the same as me. Previously they mentioned their test-jar plugin as deprecated in their documentation, now it doesn't even get a mention in the readme

Body:
In the past, I've had great success in providing test helpers in a core or common project, and having those classes available to other sub-projects using the following:

Common Project A

task testJar(type: Jar) {
    classifier = "tests"
    from sourceSets.test.output
}

artifacts { testRuntime testJar }

Dependent Project B

testCompile(project(path: ":project-a", configuration: "testRuntime"))

However, I have the same requirement between two projects that do NOT share a Gradle multi-project hierarchy.  To clarify, these are completely separate projects.  They are in different repositories, using different build scripts.  They are not sub-modules within a parent project.

To futher complex matters, I'm using the Java Library plugin and the Maven plugin to install libraries locally.  In other words, I'd love for the second project to include a dependency as such:

testImplementation 'com.mycompany:common-test:1.0.0'

What should the first "common" project look like to a) generate that test jar and b) allow it to be installed to Maven?

Many thanks for all help.


答:
You have posted a lot of code and it looks like a scope issue, the variables in your functions are not visible inside the other functions.

The quick and dirty way to fix this is to make that variable causing the error global like this:

```<code>def chooseDoor():   # choose a door
    global chosenDoor = ''
    while chosenDoor != 1 and chosenDoor != 2 and chosenDoor != 3:
        print('Choose a door. (1, 2 or 3)')
        chosenDoor = input()
        return chosenDoor
    print('You chose door number ' + str(chosenDoor) + '.')
</code>```

I think that will probably fix it but it's not good coding practice.

Title: Python3 won't recognize a variable in code

Body:
You have posted a lot of code and it looks like a scope issue, the variables in your functions are not visible inside the other functions.

The quick and dirty way to fix this is to make that variable causing the error global like this:

def chooseDoor():   # choose a door
    global chosenDoor = ''
    while chosenDoor != 1 and chosenDoor != 2 and chosenDoor != 3:
        print('Choose a door. (1, 2 or 3)')
        chosenDoor = input()
        return chosenDoor
    print('You chose door number ' + str(chosenDoor) + '.')

I think that will probably fix it but it's not good coding practice.


问:
Can I post an inline image using file field in a form
I have an IMG loaded inside the HTML document, and I would like to upload it using the "file" field from a form. The form is in the same document, so I shouldn't have any security issues.

Is it possible to upload the image to a server?

I managed to upload images choosing a file from my hard drive, but I have no clue about doing it using the IMG inside the HTML document.

答:
Using javascript you can grab the 'src' attribute from the inline image (if src is a relative reference, append to the current url location) and post that as a hidden field in your form.

The serverside application would then download the image from the same source, using something like curl in PHP or urllib in python.


问:
Dynamically creating and expanding std::tuple into parameter pack
I'm writing a plugin for software written in C++, here's a snippet where the plugin is defined:

extern "C"
irods::ms_table_entry* plugin_factory() {

    // The number of msParam_t* arguments that it will accept
    int numArguments = 2;

    irods::ms_table_entry* msvc = new irods::ms_table_entry(numArguments);

    msvc->add_operation(
        "my_microservice",
        std::function<int(msParam_t*, msParam_t*, ruleExecInfo_t*)>(MyMicroservice)
    );

    return msvc;
}
```

I'd like to be able to use numArguments to dynamically generate the std::function<int(msParam_t*, msParam_t*, ruleExecInfo_t*)> parameter pack. Where numArguments represents the number of msParam_t* arguments.

I'm not a C++ expert (especially with templating), so after some research I've found that this might be possible by implementing the following:

std::tuple

std::tuple_cat

std::index_sequence

std::make_integer_sequence

But I don't really know how to get started on implementing this. The examples I found were hard to understand, and I couldn't manage to translate them into my own needs. Can anyone provide tips, short examples, or references on how this might work? Any info is greatly appreciated!

答:
I don't know if the following is exactly what you're asking but I think that what you want is being able to generate the right template parameters for the std::function based on the number of arguments that your MyMicroservice takes which is stored into the numParameters variable.

If that is the case you can simply omit writing them at all and use decltypeand let the compiler write them for you.

```<code>int myMicroservice1(int a,int b, int c){
    return a+b+c;
}

int myMicroservice2(int a,int b, int c,int d){
    return a*b*c-d;
}

int myMicroservice3(int a,int b, int c,int d,int e, int f){
    return a*b*c+e+f;
}

template<typename... types_t>
void add_operation(const std::string & _op, std::function< int(types_t...)> _f ){

}

int main() {
    add_operation("blabla",std::function<decltype(myMicroservice1)>(myMicroservice1));
    add_operation("blabla",std::function<decltype(myMicroservice2)>(myMicroservice2));
    add_operation("blabla",std::function<decltype(myMicroservice3)>(myMicroservice3));
    return 0;
}
</code>```

Body:
I'm writing a plugin for software written in C++, here's a snippet where the plugin is defined:

extern "C"
irods::ms_table_entry* plugin_factory() {

    // The number of msParam_t* arguments that it will accept
    int numArguments = 2;

    irods::ms_table_entry* msvc = new irods::ms_table_entry(numArguments);

    msvc->add_operation(
        "my_microservice",
        std::function<int(msParam_t*, msParam_t*, ruleExecInfo_t*)>(MyMicroservice)
    );

    return msvc;
}

I'd like to be able to use numArguments to dynamically generate the std::function<int(msParam_t*, msParam_t*, ruleExecInfo_t*)> parameter pack. Where numArguments represents the number of msParam_t* arguments.

I'm not a C++ expert (especially with templating), so after some research I've found that this might be possible by implementing the following:

std::tuple

std::tuple_cat

std::index_sequence

std::make_integer_sequence

But I don't really know how to get started on implementing this. The examples I found were hard to understand, and I couldn't manage to translate them into my own needs. Can anyone provide tips, short examples, or references on how this might work? Any info is greatly appreciated!

Body:
I don't know if the following is exactly what you're asking but I think that what you want is being able to generate the right template parameters for the std::function based on the number of arguments that your MyMicroservice takes which is stored into the numParameters variable.

If that is the case you can simply omit writing them at all and use decltypeand let the compiler write them for you.

int myMicroservice1(int a,int b, int c){
    return a+b+c;
}

int myMicroservice2(int a,int b, int c,int d){
    return a*b*c-d;
}

int myMicroservice3(int a,int b, int c,int d,int e, int f){
    return a*b*c+e+f;
}

template<typename... types_t>
void add_operation(const std::string & _op, std::function< int(types_t...)> _f ){

}

int main() {
    add_operation("blabla",std::function<decltype(myMicroservice1)>(myMicroservice1));
    add_operation("blabla",std::function<decltype(myMicroservice2)>(myMicroservice2));
    add_operation("blabla",std::function<decltype(myMicroservice3)>(myMicroservice3));
    return 0;
}


问:
How to get Stings from Fragment to Activity
I have an app that works with Stings but I doesn*t know how to send String from a Fragment to an Activity. Somebody help me but I dont understand the code well.So If somebody have questions he could ask me and I could anserd it

Please help me

Fragment:

```<code>public class Fragment_1 extends Fragment {

    String text;
    int zähler = 0;
    String teile[];
    String in = "", in2 = "", in3 = "";
    ListView listView;
    public String [] liste;
    String value = "MIT";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Bundle bundle = new Bundle();
        bundle.putString("Key",value);

        Intent intent = getActivity().getIntent();
        intent.putExtras(bundle);

        View view = inflater.inflate(R.layout.fragment_1, container, false);

        listView = (ListView) view.findViewById(R.id.listView);
       // final Button but = (Button) view.findViewById(R.id.but1) ;

        new doit().execute();

        return view;
    }
</code>```

MainActivity:

```<code>public class MainActivity extends AppCompatActivity {
    String mesg = "MIT";

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        Bundle data = getIntent().getExtras();
        if (data != null) {

            String receivedString = data.getString("Key");

            Log.d("MainActivity", receivedString);
        }

        Log.d("MainActivity", "Bitte nicht" );

    }
</code>```

答:
You have to use an interface in your fragment:

```<code>public class MyFragment extends Fragment
{

private MyInterface mListener;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    return inflater.inflate(R.layout.mylayout, container, false);
}

@Override
public void onActivityCreated(Bundle bundle)
{
    super.onActivityCreated(bundle);
    mListener.passString("Hello from fragment!");
}

@Override
public void onAttach(Context context)
{
    super.onAttach(context);
    if (context instanceof MyFragment.MyInterface)
    {
        mListener = (MyInterface) context;
    }
    else
    {
        throw new RuntimeException(context.toString());
    }
}

@Override
public void onDetach()
{
    super.onDetach();
    mListener = null;
}

public interface MyInterface
{
    void passString(String string);
}

}
</code>```

And in your activity you have to implement the method of the interface:

```<code>public class MyActivity extends AppCompatActivity implements MyFragment.MyInterface
{
String myString;
//other methods like onCreate and so on...

@Override
public void passString(String string)
{
    myString = string;
}

}
</code>```

myString will be the string which you passed from the fragment to the activity.

Body:
I have an app that works with Stings but I doesn*t know how to send String from a Fragment to an Activity. Somebody help me but I dont understand the code well.So If somebody have questions he could ask me and I could anserd it

Please help me

Fragment:

public class Fragment_1 extends Fragment {

    String text;
    int zähler = 0;
    String teile[];
    String in = "", in2 = "", in3 = "";
    ListView listView;
    public String [] liste;
    String value = "MIT";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Bundle bundle = new Bundle();
        bundle.putString("Key",value);

        Intent intent = getActivity().getIntent();
        intent.putExtras(bundle);

        View view = inflater.inflate(R.layout.fragment_1, container, false);

        listView = (ListView) view.findViewById(R.id.listView);
       // final Button but = (Button) view.findViewById(R.id.but1) ;

        new doit().execute();

        return view;
    }

MainActivity:

public class MainActivity extends AppCompatActivity {
    String mesg = "MIT";

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        Bundle data = getIntent().getExtras();
        if (data != null) {

            String receivedString = data.getString("Key");

            Log.d("MainActivity", receivedString);
        }

        Log.d("MainActivity", "Bitte nicht" );

    }

Body:
You have to use an interface in your fragment:

public class MyFragment extends Fragment
{

private MyInterface mListener;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    return inflater.inflate(R.layout.mylayout, container, false);
}

@Override
public void onActivityCreated(Bundle bundle)
{
    super.onActivityCreated(bundle);
    mListener.passString("Hello from fragment!");
}

@Override
public void onAttach(Context context)
{
    super.onAttach(context);
    if (context instanceof MyFragment.MyInterface)
    {
        mListener = (MyInterface) context;
    }
    else
    {
        throw new RuntimeException(context.toString());
    }
}

@Override
public void onDetach()
{
    super.onDetach();
    mListener = null;
}

public interface MyInterface
{
    void passString(String string);
}

}

And in your activity you have to implement the method of the interface:

public class MyActivity extends AppCompatActivity implements MyFragment.MyInterface
{
String myString;
//other methods like onCreate and so on...

@Override
public void passString(String string)
{
    myString = string;
}

}

myString will be the string which you passed from the fragment to the activity.