问:
Tarantool - AUTOINCREMENT equivalent?
During my first steps with Tarantool I am wondering how to do basic things.

Imagine that I am storing the following registers:

```<code>s:insert(1,'{"name": "foo name", "phone": "foo phone"}')
s:insert(2,'{"name": "barname", "phone": "bar phone"}')
</code>```

Is there something similar to autoincrement primary key in SQL databases so I do not need to enumerate the indexes?

Something like not specifying the primary index at all in Tarantool 1.6.

Thanks,

答:
There is a (deprecated) auto_increment function, which you could use like:box.space.bigspace:auto_increment{'Fld#1', 'Fld#2'}.

Fld#1 and Fld#2 are the contents to place into a new tuple.
See here. Since Tarantool 1.7.5, it is recommended to use sequences though, which are interesting in that they let you specify how you'd like your keys generated. Basically once you set up a sequence, you assign it to a space, and it autoincrements whenever you add a new tuple.

Title: Tarantool - AUTOINCREMENT equivalent?

Body:
During my first steps with Tarantool I am wondering how to do basic things.

Imagine that I am storing the following registers:

s:insert(1,'{"name": "foo name", "phone": "foo phone"}')
s:insert(2,'{"name": "barname", "phone": "bar phone"}')

Is there something similar to autoincrement primary key in SQL databases so I do not need to enumerate the indexes?

Something like not specifying the primary index at all in Tarantool 1.6.

Thanks,


来源: stackexchange

问:
How to use an array data in node js from a javascript file?
I have some data stored in an array in javascript and want to use that array in node js. I tried this:

JS:

```<code>let myArray = ['data1', 'data2'];
</code>```

Node js:

```<code>let myArray = require('scripts.js').myArray;
</code>```

But I get Error: Cannot find module error.

What should I do?

答:
You are using the syntax to import a node module:
e.g.

```<code>const app = require('express')
</code>```

Node is looking for a node module named script.js

If you want to require local files you need to use the syntax

```<code>let myArray = require('./scripts').myArray;
</code>```

No need to put the .js on the end require does this for you.  The full details in the documentation are here: https://nodejs.org/api/modules.html#modules_modules

ContentLicense: CC BY-SA 3.0

Body:
I have some data stored in an array in javascript and want to use that array in node js. I tried this:

JS:

let myArray = ['data1', 'data2'];

Node js:

let myArray = require('scripts.js').myArray;

But I get Error: Cannot find module error.

What should I do?

Body:
You are using the syntax to import a node module:
e.g.

const app = require('express')

Node is looking for a node module named script.js

If you want to require local files you need to use the syntax

let myArray = require('./scripts').myArray;

No need to put the .js on the end require does this for you.  The full details in the documentation are here: https://nodejs.org/api/modules.html#modules_modules


问:
Wrap callback function to include extra argument when caller verifies exact callback signature
I'm trying to bind multiple callback functions across multiple properties with code that looks something like:

```<code>for key in keys:
    def callback(self, value):
        #Do stuff...
        return None

    doSomething(callback)
</code>```

This works because the calling code (that calls callback) expect exactly two parameters and the callback to return None. The issue is now I want to wrap the callback such that I can also pass the key in something like:

```<code>for key in keys:
    def wrappedCallback(self, value):
        #How do I get key in here???
        realCallback(self, key, value)
        return None

    doSomething(wrapperCallback)
</code>```

But I have no idea how to get key inside of wrapperCallback. I can't add an extra default parameter like:

```<code>...
#This throws with "expected a function taking 2 arguments, not 3"
def wrappedCallback(self, value, key=key):
    realCallback(self, key, value)
    ...
</code>```

because this will throw an error from the caller (it's C code that expects a very strict callback). I've also tried functools.partial but then I get expected a function, not a functools.partial

How do I wrap the passed callback function to include the external parameter key (from the for loop) while keeping the exact signature described?

答:
Minutes after I figured out that I can create a function inside the for loop to get a new stack frame. This unfortunately does not seem at all Pythonic...</p>

```<code>for key in keys:
    def dummyForStackFrame(key): #Extra function to get a new stack frame with key
        def wrappedCallback(self, value):
            realCallback(self, key, value)
            return None
        doSomething(wrappedCallback
    dummyForStackFrame(key)
</code>```

Body:
I'm trying to bind multiple callback functions across multiple properties with code that looks something like:

for key in keys:
    def callback(self, value):
        #Do stuff...
        return None

    doSomething(callback)

This works because the calling code (that calls callback) expect exactly two parameters and the callback to return None. The issue is now I want to wrap the callback such that I can also pass the key in something like:

for key in keys:
    def wrappedCallback(self, value):
        #How do I get key in here???
        realCallback(self, key, value)
        return None

    doSomething(wrapperCallback)

But I have no idea how to get key inside of wrapperCallback. I can't add an extra default parameter like:

...
#This throws with "expected a function taking 2 arguments, not 3"
def wrappedCallback(self, value, key=key):
    realCallback(self, key, value)
    ...

because this will throw an error from the caller (it's C code that expects a very strict callback). I've also tried functools.partial but then I get expected a function, not a functools.partial

How do I wrap the passed callback function to include the external parameter key (from the for loop) while keeping the exact signature described?

Body:
Minutes after I figured out that I can create a function inside the for loop to get a new stack frame. This unfortunately does not seem at all Pythonic...

for key in keys:
    def dummyForStackFrame(key): #Extra function to get a new stack frame with key
        def wrappedCallback(self, value):
            realCallback(self, key, value)
            return None
        doSomething(wrappedCallback
    dummyForStackFrame(key)


问:
How do I extract surnames with spaces in them as 'one' name/'en bloc'?
Could anyone please advise on a way to extract surnames that have spaces in them, as a single block of names?

I have names in a dataset that look like this

```<code>clear
input str40 name
"R. P. de la Espriella Guerrero"
"J. de Carvalho Ponce"
"E. De Freitas Drumond"
"R. de la Fuente and M. E. Medina-Mora"
"C. Van Heyningen and I. D. Watson"
"A. Z. van de Wiel and D. W. de Lange"
end
</code>```

I only want the first surname (so only the first author and excluding other authors) but I want those names that have spaces to be extracted 'en bloc'. So, ultimately resulting in a dataset as follows, for instance:

```<code>clear
input str40 name
"de la Espriella Guerrero"
"de Carvalho Ponce"
"De Freitas Drumond"
"de la Fuente"
"Van Heyningen"
"van de Wiel"
end
</code>```

I'd be grateful for any help.

答:
Here is code that implements the two rules given in my comment above. It assumes the version of Stata used supports the unicode character string functions.</p>

```<code>clear
input str40 name
"R. P. de la Espriella Guerrero"
"J. de Carvalho Ponce"
"E. De Freitas Drumond"
"R. de la Fuente and M. E. Medina-Mora"
"C. Van Heyningen and I. D. Watson"
"A. Z. van de Wiel and D. W. de Lange"
end
generate surname = name
replace surname = usubstr(surname,1,ustrpos(surname+" and "," and ")-1)
list, clean noobs
replace surname = usubstr(surname,ustrrpos(surname,". ")+1,.)
list, clean noobs
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Could anyone please advise on a way to extract surnames that have spaces in them, as a single block of names?

I have names in a dataset that look like this

clear
input str40 name
"R. P. de la Espriella Guerrero"
"J. de Carvalho Ponce"
"E. De Freitas Drumond"
"R. de la Fuente and M. E. Medina-Mora"
"C. Van Heyningen and I. D. Watson"
"A. Z. van de Wiel and D. W. de Lange"
end

I only want the first surname (so only the first author and excluding other authors) but I want those names that have spaces to be extracted 'en bloc'. So, ultimately resulting in a dataset as follows, for instance:

clear
input str40 name
"de la Espriella Guerrero"
"de Carvalho Ponce"
"De Freitas Drumond"
"de la Fuente"
"Van Heyningen"
"van de Wiel"
end

I'd be grateful for any help.

Body:
Here is code that implements the two rules given in my comment above. It assumes the version of Stata used supports the unicode character string functions.

clear
input str40 name
"R. P. de la Espriella Guerrero"
"J. de Carvalho Ponce"
"E. De Freitas Drumond"
"R. de la Fuente and M. E. Medina-Mora"
"C. Van Heyningen and I. D. Watson"
"A. Z. van de Wiel and D. W. de Lange"
end
generate surname = name
replace surname = usubstr(surname,1,ustrpos(surname+" and "," and ")-1)
list, clean noobs
replace surname = usubstr(surname,ustrrpos(surname,". ")+1,.)
list, clean noobs


问:
React-Native FlatList render a zero state when data is empty
Is it possible to render an alternate component when the data is empty?  The only reason I would not just render the list or not render the list is that the ListHeaderComponent is necessary in both scenarios (data.length and !data.length)...

```<code>const data = []
<FlatList
  contentContainerStyle={styles.list}
  data={data} // if empty or !data.length render <ZeroComponent/>
</code>```

答:
UPDATE
react-native recently added ListEmptyComponent

const data = []
_listEmptyComponent = () => {
    return (
        <View>
            // any activity indicator or error component
        </View>
    )
}

<FlatList
    data={data}
    ListEmptyComponent={this._listEmptyComponent}
    contentContainerStyle={styles.list}
/>
```

<pre class="lang-js prettyprint-override"><code>const data = []

renderFooter = () => {
  if (data.length != 0) return null;

  return (
    <View>
      // any activity indicator or error component
    </View>
   );
};

<FlatList
    contentContainerStyle={styles.list}
    data={data}
    ListFooterComponent={this.renderFooter}
/>
</code>```

Hope this helps

Body:
Is it possible to render an alternate component when the data is empty?  The only reason I would not just render the list or not render the list is that the ListHeaderComponent is necessary in both scenarios (data.length and !data.length)...

const data = []
<FlatList
  contentContainerStyle={styles.list}
  data={data} // if empty or !data.length render <ZeroComponent/>

Body:
UPDATE
react-native recently added ListEmptyComponent

const data = []
_listEmptyComponent = () => {
    return (
        <View>
            // any activity indicator or error component
        </View>
    )
}

<FlatList
    data={data}
    ListEmptyComponent={this._listEmptyComponent}
    contentContainerStyle={styles.list}
/>

const data = []

renderFooter = () => {
  if (data.length != 0) return null;

  return (
    <View>
      // any activity indicator or error component
    </View>
   );
};

<FlatList
    contentContainerStyle={styles.list}
    data={data}
    ListFooterComponent={this.renderFooter}
/>

Hope this helps


问:
Phantomjs browser incorrectly computing css calc() function in Nightwatch tests
I am building Nightwatch tests (uses Phantomjs) for functioning front ends, and one of my tasks is to make sure banner images' heights are dynamic and their heights are being calculated correctly per the screen size.

I have some page elements that look something like this:

```<code>//html
<div class="bannerImg"></div>

//css
.bannerImg {
    background-image: url('someImgUrl');
    height: calc(100vh - 200); //some calculation here
    min-height: 600px; //some minimum height
}
</code>```

For example, a viewport of 1080 should yield a height of 880px.

However when I run my test, Nightwatch is reporting the element's size to be 600px (essentially, bellow 600).

From my research on this, others have had other/similar difficulties with calc() and testing with the Phantom.js browser
https://github.com/ariya/phantomjs/issues/13547

Is there any plans on adding support for this function?

答: PhantomJS is no longer in active development, if possible you should migrate to puppeteer which was heavily inspired by PhantomJS.</p>

Body:
I am building Nightwatch tests (uses Phantomjs) for functioning front ends, and one of my tasks is to make sure banner images' heights are dynamic and their heights are being calculated correctly per the screen size.

I have some page elements that look something like this:

//html

//css
.bannerImg {
    background-image: url('someImgUrl');
    height: calc(100vh - 200); //some calculation here
    min-height: 600px; //some minimum height
}

For example, a viewport of 1080 should yield a height of 880px.

However when I run my test, Nightwatch is reporting the element's size to be 600px (essentially, bellow 600).

From my research on this, others have had other/similar difficulties with calc() and testing with the Phantom.js browser
https://github.com/ariya/phantomjs/issues/13547

Is there any plans on adding support for this function?


问:
geospatial queries in javascript
I'm looking for a library in javascript that would allow me to make geospatial queries.  I know about OpenLayers and GoogleMaps, but this two do not support things like union intersection and so on.

```<code>+----+
|    |
|  +-+--+
+--+-+  |
   |    |
   +----+
</code>```

to

```<code>    +----+
    |    |
    |    +--+
    +--+    |
       |    |
       +----+
</code>```

答:
Did you look at geoUtils?

I am not sure whether it supports the union op, but might be worth giving a try.

ContentLicense: CC BY-SA 2.5

Title: geospatial queries in javascript

Body:
I'm looking for a library in javascript that would allow me to make geospatial queries.  I know about OpenLayers and GoogleMaps, but this two do not support things like union intersection and so on.

+----+
|    |
|  +-+--+
+--+-+  |
   |    |
   +----+

to

    +----+
    |    |
    |    +--+
    +--+    |
       |    |
       +----+


问:
How do I pull the thumbprint out of a SSL certificate FILE (not the windows cert store)?
I understand how to get the thumbprint of a certificate that's installed to a certificate store, however I'm hoping there is a way to get that information from a certificate FILE.

So for example I'd have c:\temp\mycert.com.cer... how would I get the thumbprint from that file? Is it even possible? Google isn't being very helpful. I've been doing this in powershell as such to get this from the certificate store, but again - I need to get this info from a certificate FILE.

```<code>$certCN = mysite.com
$cert = Get-ChildItem cert:\LocalMachine\My -Recurse |
  where {$_.subject -like "*CN=$certCN*"} |
  where {$_.ExpiringInDays -lt "91"}
$thumbprint = $cert.thumbprint
</code>```

Thank you in advance!!

答:
Without using a third party library you can rely on x509certificate2 cryptography class of .NET framework:

```<code>$content = [System.IO.File]::ReadAllBytes("D:\mycertificate.cer")
$cer = [system.security.cryptography.x509certificates.x509certificate2]::new($content)

$cer.SignatureAlgorithm.FriendlyName
$cer.Thumbprint
$cer.Subject
</code>```

Then you will receive a result like:

```<code>sha1RSA
5A6008B61ABADE6412BEE4704C2407D5DE5DAA34
C=GB, O=University College London, OU=Computer Science, CN=FTAM Service
</code>```

Body:
I understand how to get the thumbprint of a certificate that's installed to a certificate store, however I'm hoping there is a way to get that information from a certificate FILE.

So for example I'd have c:\temp\mycert.com.cer... how would I get the thumbprint from that file? Is it even possible? Google isn't being very helpful. I've been doing this in powershell as such to get this from the certificate store, but again - I need to get this info from a certificate FILE.

$certCN = mysite.com
$cert = Get-ChildItem cert:\LocalMachine\My -Recurse |
  where {$_.subject -like "*CN=$certCN*"} |
  where {$_.ExpiringInDays -lt "91"}
$thumbprint = $cert.thumbprint

Thank you in advance!!

Body:
Without using a third party library you can rely on x509certificate2 cryptography class of .NET framework:

$content = [System.IO.File]::ReadAllBytes("D:\mycertificate.cer")
$cer = [system.security.cryptography.x509certificates.x509certificate2]::new($content)

$cer.SignatureAlgorithm.FriendlyName
$cer.Thumbprint
$cer.Subject

Then you will receive a result like:

sha1RSA
5A6008B61ABADE6412BEE4704C2407D5DE5DAA34
C=GB, O=University College London, OU=Computer Science, CN=FTAM Service


问:
r - add filename in first column of many csv files with irregular column type
I have many csv files in a folder and their names are in the same format ending with a date (xys 01.12.2017). I need to add the date to each data in the first column.
I found many examples to do that but in all examples files have same the column format. However my files do not contain same number of columns.
Is it possible to add the date even the columns numbers vary?
Appreciate your help in advance.</p>

答:
If all of the files are in a specific subdirectory you can list the files, and then use an apply() function to read the data and add the date as the first column.

```<code># list the files
fileList <- list.files(...,full.names=TRUE)
theDataFrames <- lapply(fileList,function(x) {
   data <- read.csv(x,header=TRUE)
   # extract all characters after 'xls' in 'xys01.01.2017'
   date <-rep(substr(x,4,nchar(x)),nrow(data))
   # bind date to data frame and return
  cbind(date, data)
})
</code>```

Body:
If all of the files are in a specific subdirectory you can list the files, and then use an apply() function to read the data and add the date as the first column.

# list the files
fileList <- list.files(...,full.names=TRUE)
theDataFrames <- lapply(fileList,function(x) {
   data <- read.csv(x,header=TRUE)
   # extract all characters after 'xls' in 'xys01.01.2017'
   date <-rep(substr(x,4,nchar(x)),nrow(data))
   # bind date to data frame and return
  cbind(date, data)
})


问:
ORA-02253: constraint specification not allowed here - foreign key
I'm new to this sql and I wanted to know what the problem is in this case.

"constraint specification not allowed here"
  Cause:    Constraint specification is not allowed here in the statement.

```<code>CREATE TABLE CLIENTE(
RUT VARCHAR2(10) CONSTRAINT CLIENTE_PK PRIMARY KEY,
NOMBRE VARCHAR2(20) CONSTRAINT NOMBRE_CLIENTE NOT NULL,
APELLIDOP VARCHAR2(30) CONSTRAINT APELLIDOP_CLIENTE NOT NULL,
APELLIDOM VARCHAR2(30) CONSTRAINT APPELIDOM_CLIENTE NOT NULL,
DIRECCION VARCHAR2(100) CONSTRAINT DIRECCION_CLIENTE NOT NULL,
TELEFONO NUMBER(8) CONSTRAINT TELEFONO_CLIENTE NOT NULL,
EMAIL VARCHAR2(255) CONSTRAINT EMAIL_CLIENTE NOT NULL,
FECHA_NACIMIENTO DATE CONSTRAINT FECHA_NACIMIENTO_CLIENTE NOT NULL,
SEXO CHAR(1) CONSTRAINT SEXO_CLIENTE NOT NULL,
COD_CIUDAD NUMBER(3) CONSTRAINT CLIENTE_CIUDAD_FK FOREIGN KEY (COD_CIUDAD)
REFERENCES CIUDAD (COD_CIUDAD)
);
</code>```

答:
In the last line of code, you define column cod_ciudad and you add a foreign key constraint.

There are two categories of constraints: IN-LINE constraints, defined right after the column name and data type (they can only affect "that" column) and OUT-OF-LINE constraints, which come at the bottom of the table, after all the column definitions. Constraints that involve more than one column can only be out-of-line constraints.

The constraint you define in your code is on one column only, and moreover, it is on cod_ciudad. You did NOT add a comma between the column definition (name and data type); that is the correct syntax for IN-LINE constraints. But an IN-LINE foreign key constraint does not need the keywords FOREIGN KEY, and they don't need to repeat the column name in parentheses. The constraint, being IN-LINE, can only refer to the "current" column. So: One way to fix your code is to REMOVE FOREIGN KEY (COD_CIUDAD) from the code.

Another way to fix it is to make the constraint into an OUT-OF-LINE constraint. Then the syntax is correct, but you must add a comma (,) before the keyword CONSTRAINT.

Body:
I'm new to this sql and I wanted to know what the problem is in this case.

"constraint specification not allowed here"
  Cause:    Constraint specification is not allowed here in the statement.

CREATE TABLE CLIENTE(
RUT VARCHAR2(10) CONSTRAINT CLIENTE_PK PRIMARY KEY,
NOMBRE VARCHAR2(20) CONSTRAINT NOMBRE_CLIENTE NOT NULL,
APELLIDOP VARCHAR2(30) CONSTRAINT APELLIDOP_CLIENTE NOT NULL,
APELLIDOM VARCHAR2(30) CONSTRAINT APPELIDOM_CLIENTE NOT NULL,
DIRECCION VARCHAR2(100) CONSTRAINT DIRECCION_CLIENTE NOT NULL,
TELEFONO NUMBER(8) CONSTRAINT TELEFONO_CLIENTE NOT NULL,
EMAIL VARCHAR2(255) CONSTRAINT EMAIL_CLIENTE NOT NULL,
FECHA_NACIMIENTO DATE CONSTRAINT FECHA_NACIMIENTO_CLIENTE NOT NULL,
SEXO CHAR(1) CONSTRAINT SEXO_CLIENTE NOT NULL,
COD_CIUDAD NUMBER(3) CONSTRAINT CLIENTE_CIUDAD_FK FOREIGN KEY (COD_CIUDAD)
REFERENCES CIUDAD (COD_CIUDAD)
);


问:
how to extract the result of an AngularFirestoreCollection into an array
The app I am trying to develop allows the choice of language using a Material2 Select input field. The available languages are held in a Firestore collection of documents. I use an AngularFirestoreCollection to retrieve them but cannot find out how to extract the language names from the result and put them into an array.

I have googled for examples and tutorials, read and re-read pages of documentation and found many examples using ‘*ngFor’ but I cannot find any using ‘map’ which I suspect is what I need to use.

Thank you in advance.

```<code>  languageid: string;
  languageName: string;
  languageCollection: AngularFirestoreCollection<any> = this.afs.collection('Countries/AU/cLanguage');
  languagecollection = this.languageCollection.valueChanges();
  languages: string[];
</code>```

I want to map "languagecollection = this.languageCollection.valueChanges();" to an array.

答:
I think you can try something like: (untested. comment if it's wrong)</p>

```<code>let languages: string[];
let collection = this.afs.collection('Countries/AU/cLanguage').valueChanges();

//if you want to Firebase's .once(), use take(1)
let storeTask = collection.subscribe((langs) => {
    languages = langs;

    //Or
    /*Object.keys(langs).map(function(key, index) {
       languages.push(langs[key].name)
    });*/
});
</code>```

Body:
The app I am trying to develop allows the choice of language using a Material2 Select input field. The available languages are held in a Firestore collection of documents. I use an AngularFirestoreCollection to retrieve them but cannot find out how to extract the language names from the result and put them into an array.

I have googled for examples and tutorials, read and re-read pages of documentation and found many examples using ‘*ngFor’ but I cannot find any using ‘map’ which I suspect is what I need to use.

Thank you in advance.

  languageid: string;
  languageName: string;
  languageCollection: AngularFirestoreCollection<any> = this.afs.collection('Countries/AU/cLanguage');
  languagecollection = this.languageCollection.valueChanges();
  languages: string[];

I want to map "languagecollection = this.languageCollection.valueChanges();" to an array.

Body:
I think you can try something like: (untested. comment if it's wrong)

let languages: string[];
let collection = this.afs.collection('Countries/AU/cLanguage').valueChanges();

//if you want to Firebase's .once(), use take(1)
let storeTask = collection.subscribe((langs) => {
    languages = langs;

    //Or
    /*Object.keys(langs).map(function(key, index) {
       languages.push(langs[key].name)
    });*/
});


问:
Find maximum non contiguous subarray that respect a specific rule
Given these two arrays:

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

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

Find the maximum subsequence in both arrays that the index of the elements are in a crescent order:

Example: [3, 4] it's an answer because the indexes are in a crescent way in both arrays. (same as [1, 2]). Therefore, the subsequence the answer [3, 4, 1] is wrong, because the indexes are the crescent in the first array, but not on the second one.

The output of the program should be the length of the max non-contiguous subarray.

This is the code I wrote for solving this, but it only takes the first subarray, and I'm having difficulty to generate the other possibilities

```<code>vector<pair<int, double>> esq;
vector<pair<int, double>> dir;
// N is the size of esq and dir
// pair<int, double> where int is the key (show in the example array) and double is the value, used for sort previously.
int cont = 1;
for (int i = 0; i < N - 1; i++)
{
    int cont_aux = 1;
    pair<int, double> pivot = esq[i];
    auto it_dir = find_if(dir.begin(), dir.end(), [&pivot](const pair<int, double> &p) { return p.first == pivot.first; });
    int last_index = it_dir - dir.begin();

    for (int j = 0; j < N; j++)
    {
        pair<int, double> actual = esq[j];
        auto it = find_if(dir.begin(), dir.end(), [&actual](const pair<int, double> &p) { return p.first == actual.first; });
        int pos = it - dir.begin();

        if (pos >= last_index) {
            last_index = pos;
            cont_aux++;
        }
    }

    cont = max(cont, cont_aux);
}

cout << cont << endl;
</code>```

答:
```<code>lista_test = [5,3, 4,1,7, 2]
lista2_test = [5,1,3, 2, 4,7]

def max_nocontigoous(list_a,list_b):
    #lets suppose that the list is ordered.
    count_i = 0
    count_j_previous = 0
    count_j = 0
    counter_exclusive = 0
    listDouble = list()
    indice_real = 0
    for i in range(len(list_a)):
        try:
            element_a = list_a[i]
            if element_a in list_b and list_b.index(element_a)>=count_j:
                if count_j_previous != count_j:
                    listDouble[len(listDouble)-1].append(element_a)
                    count_j_previous = count_j
                else:
                    if(i == 0):
                        count_j_previous  -= 1
                    listDouble.append([element_a])
            else:
                listDouble.append([element_a])
                count_j_previous = count_j
                count_j = list_b.index(element_a)
        except IndexError:
            print("Error in: " +str(i) + " iteration")
    return listDouble

print(max_nocontigoous(lista_test,lista2_test))
</code>```

Notice that i have considered the first array or list in my case only can be a list whose values are in order and consecutively. I have just considered it because i have followed your example where you have an array with consecutively values ordered and the next array could be not necessarily consecutively.
Good Look!

Body:
Given these two arrays:

[5, 3, 4, 1, 2]

[1, 3, 2, 4, 5]

Find the maximum subsequence in both arrays that the index of the elements are in a crescent order:

Example: [3, 4] it's an answer because the indexes are in a crescent way in both arrays. (same as [1, 2]). Therefore, the subsequence the answer [3, 4, 1] is wrong, because the indexes are the crescent in the first array, but not on the second one.

The output of the program should be the length of the max non-contiguous subarray.

This is the code I wrote for solving this, but it only takes the first subarray, and I'm having difficulty to generate the other possibilities

vector<pair<int, double>> esq;
vector<pair<int, double>> dir;
// N is the size of esq and dir
// pair<int, double> where int is the key (show in the example array) and double is the value, used for sort previously.
int cont = 1;
for (int i = 0; i < N - 1; i++)
{
    int cont_aux = 1;
    pair<int, double> pivot = esq[i];
    auto it_dir = find_if(dir.begin(), dir.end(), [&pivot](const pair<int, double> &p) { return p.first == pivot.first; });
    int last_index = it_dir - dir.begin();

    for (int j = 0; j < N; j++)
    {
        pair<int, double> actual = esq[j];
        auto it = find_if(dir.begin(), dir.end(), [&actual](const pair<int, double> &p) { return p.first == actual.first; });
        int pos = it - dir.begin();

        if (pos >= last_index) {
            last_index = pos;
            cont_aux++;
        }
    }

    cont = max(cont, cont_aux);
}

cout << cont << endl;

Body:
lista_test = [5,3, 4,1,7, 2]
lista2_test = [5,1,3, 2, 4,7]

def max_nocontigoous(list_a,list_b):
    #lets suppose that the list is ordered.
    count_i = 0
    count_j_previous = 0
    count_j = 0
    counter_exclusive = 0
    listDouble = list()
    indice_real = 0
    for i in range(len(list_a)):
        try:
            element_a = list_a[i]
            if element_a in list_b and list_b.index(element_a)>=count_j:
                if count_j_previous != count_j:
                    listDouble[len(listDouble)-1].append(element_a)
                    count_j_previous = count_j
                else:
                    if(i == 0):
                        count_j_previous  -= 1
                    listDouble.append([element_a])
            else:
                listDouble.append([element_a])
                count_j_previous = count_j
                count_j = list_b.index(element_a)
        except IndexError:
            print("Error in: " +str(i) + " iteration")
    return listDouble

print(max_nocontigoous(lista_test,lista2_test))

Notice that i have considered the first array or list in my case only can be a list whose values are in order and consecutively. I have just considered it because i have followed your example where you have an array with consecutively values ordered and the next array could be not necessarily consecutively.
Good Look!


问:
Checking data in Spring Boot Test Controller
I wrote a test for my UserController which based on info from http://www.baeldung.com/spring-boot-testing
In during version test passes. How can I change commented line to check which user and records were received? Or where can I read about this case?
Templates based on JSP.

```<code>@RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
    model.addAttribute("user", userService.findByUsername(SecurityContextHolder.getContext().getAuthentication().getName()));
    model.addAttribute("records", recordService.findAll());
    return "welcome";
}
</code>```

```<code>package pavelkuropatin.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import pavelkuropatin.WebApplicationClass;
import pavelkuropatin.entities.Record;
import pavelkuropatin.entities.User;
import pavelkuropatin.service.RecordService;
import pavelkuropatin.service.SecurityService;
import pavelkuropatin.service.UserService;
import pavelkuropatin.validator.UserValidator;
import java.util.Arrays;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(
    classes = WebApplicationClass.class)
@AutoConfigureMockMvc
@TestPropertySource(
    locations = "classpath:application.properties")
public class UserControllerTest {

    @MockBean
    public UserService userService;
    @MockBean
    public RecordService recordService;
    @MockBean
    public SecurityService securityService;
    @MockBean
    public UserValidator userValidator;
    @Autowired
    private MockMvc mvc;

    @Test
    public void welcome() throws Exception {
        Record record1 = new Record();
        record1.setId(1L);
        record1.setTopic("Topic1");
        record1.setText("Text1");
        Record record2 = new Record();
        record2.setId(2L);
        record2.setTopic("Topic2");
        record2.setText("Text2");
        User user = new User();
        user.setUsername("pavelkuropatin");
        when(userService.findByUsername(anyString())).thenReturn(user);
        when(recordService.findAll()).thenReturn(Arrays.asList(record1,     record2));
        this.mvc.perform(get("/")
            .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk())
            //.andExpect( jsonPath("$.ModelAndView.user.username", is("pavelkuropatin")))
            //.andExpect(jsonPath("$", hasSize(3)))
        ;
    }
}
</code>```

this info shows in the console.

```<code>MockHttpServletRequest:
  HTTP Method = GET
  Request URI = /
   Parameters = {}
      Headers = {Content-Type=[application/json;charset=UTF-8]}

Handler:
         Type = pavelkuropatin.web.UserController
       Method = public java.lang.String pavelkuropatin.web.UserController.welcome(org.springframework.ui.Model)

Async:
Async started = false
 Async result = null

Resolved Exception:
         Type = null

ModelAndView:
    View name = welcome
         View = null
    Attribute = user
        value = User{id=null, fio='null', username='pavelkuropatin', password='null', passwordConfirm='null', roles=null}
       errors = []
    Attribute = records
        value = [Record{id=1, text='Text1', topic='Topic1', date=null, author='null'}, Record{id=2, text='Text2', topic='Topic2', date=null, author='null'}]

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
     Content type = null
             Body =
    Forwarded URL = /welcome.jsp
   Redirected URL = null
          Cookies = []
</code>```

答:
You can check that model attribute is present and has expected values using org.hamcrest.Matchers

```<code>public void welcome() throws Exception {
        // Mock required services

        this.mvc.perform(get("/")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())
                .andExpect(model().attribute("user", Matchers.hasProperty("username", Matchers.equalTo("pavelkuropatin"))))
                .andExpect(model().attribute("records", Matchers.hasSize(3)))
        ;
    }
</code>```

Body:
I wrote a test for my UserController which based on info from http://www.baeldung.com/spring-boot-testing
In during version test passes. How can I change commented line to check which user and records were received? Or where can I read about this case?
Templates based on JSP.

@RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
    model.addAttribute("user", userService.findByUsername(SecurityContextHolder.getContext().getAuthentication().getName()));
    model.addAttribute("records", recordService.findAll());
    return "welcome";
}

package pavelkuropatin.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import pavelkuropatin.WebApplicationClass;
import pavelkuropatin.entities.Record;
import pavelkuropatin.entities.User;
import pavelkuropatin.service.RecordService;
import pavelkuropatin.service.SecurityService;
import pavelkuropatin.service.UserService;
import pavelkuropatin.validator.UserValidator;
import java.util.Arrays;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(
    classes = WebApplicationClass.class)
@AutoConfigureMockMvc
@TestPropertySource(
    locations = "classpath:application.properties")
public class UserControllerTest {

    @MockBean
    public UserService userService;
    @MockBean
    public RecordService recordService;
    @MockBean
    public SecurityService securityService;
    @MockBean
    public UserValidator userValidator;
    @Autowired
    private MockMvc mvc;

    @Test
    public void welcome() throws Exception {
        Record record1 = new Record();
        record1.setId(1L);
        record1.setTopic("Topic1");
        record1.setText("Text1");
        Record record2 = new Record();
        record2.setId(2L);
        record2.setTopic("Topic2");
        record2.setText("Text2");
        User user = new User();
        user.setUsername("pavelkuropatin");
        when(userService.findByUsername(anyString())).thenReturn(user);
        when(recordService.findAll()).thenReturn(Arrays.asList(record1,     record2));
        this.mvc.perform(get("/")
            .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk())
            //.andExpect( jsonPath("$.ModelAndView.user.username", is("pavelkuropatin")))
            //.andExpect(jsonPath("$", hasSize(3)))
        ;
    }
}

this info shows in the console.

MockHttpServletRequest:
  HTTP Method = GET
  Request URI = /
   Parameters = {}
      Headers = {Content-Type=[application/json;charset=UTF-8]}

Handler:
         Type = pavelkuropatin.web.UserController
       Method = public java.lang.String pavelkuropatin.web.UserController.welcome(org.springframework.ui.Model)

Async:
Async started = false
 Async result = null

Resolved Exception:
         Type = null

ModelAndView:
    View name = welcome
         View = null
    Attribute = user
        value = User{id=null, fio='null', username='pavelkuropatin', password='null', passwordConfirm='null', roles=null}
       errors = []
    Attribute = records
        value = [Record{id=1, text='Text1', topic='Topic1', date=null, author='null'}, Record{id=2, text='Text2', topic='Topic2', date=null, author='null'}]

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
     Content type = null
             Body =
    Forwarded URL = /welcome.jsp
   Redirected URL = null
          Cookies = []

Body:
You can check that model attribute is present and has expected values using org.hamcrest.Matchers

public void welcome() throws Exception {
        // Mock required services

        this.mvc.perform(get("/")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())
                .andExpect(model().attribute("user", Matchers.hasProperty("username", Matchers.equalTo("pavelkuropatin"))))
                .andExpect(model().attribute("records", Matchers.hasSize(3)))
        ;
    }


问:
Parsing xml using python not working as expected
```<code><?xml version="1.0" ?>
<Data>
    <Channels>
        <channel0 ChannelName="Name1" />
        <channel1 ChannelName="Name2" />
        <channel2 ChannelName="Name3" />
    </Channels>
</Data>
</code>```

For some reason when I parse this from the xml file which has the above data in it, I only get it to print out channel0 Name1, it skips out the rest of the channels. Not sure if I'm missing something, or if I made a mistake. Could someone help me out? Thanks!

```<code>root = et.parse(path).getroot()
for child in root:
    for element in child:
        print element.tag, element.attrib['ChannelName']
</code>```

答:
I tried this in Python 3.6 and it printed out all three channels

```<code>import xml.etree.cElementTree as et

path = 'test.xml'

root = et.parse(path).getroot()
for child in root:
    for element in child:
        print(element.tag, element.attrib['ChannelName'])
</code>```

output

```<code>channel0 Name1
channel1 Name2
channel2 Name3
</code>```

Body:
<?xml version="1.0" ?>
<Data>
    <Channels>
        <channel0 ChannelName="Name1" />
        <channel1 ChannelName="Name2" />
        <channel2 ChannelName="Name3" />
    </Channels>
</Data>

For some reason when I parse this from the xml file which has the above data in it, I only get it to print out channel0 Name1, it skips out the rest of the channels. Not sure if I'm missing something, or if I made a mistake. Could someone help me out? Thanks!

root = et.parse(path).getroot()
for child in root:
    for element in child:
        print element.tag, element.attrib['ChannelName']

Body:
I tried this in Python 3.6 and it printed out all three channels

import xml.etree.cElementTree as et

path = 'test.xml'

root = et.parse(path).getroot()
for child in root:
    for element in child:
        print(element.tag, element.attrib['ChannelName'])

output

channel0 Name1
channel1 Name2
channel2 Name3


问:
System.out.print keeps looping error
Hello there guys I've been trying to help my friend with this code that almost works. It's a simple Blackjack game which asks the user if they want another card write yes and if user writes no then his turn is ended and it should be the dealer's turn. The problem I'm having is that when I write no to end my turn it just keeps asking me the question if I want another card in the console. Thank you for you help.
Ex.

```<code>Another Card (yes/no)?: nO
Another Card (yes/no)?: no
Another Card (yes/no)?: no
Another Card (yes/no)?: no
Another Card (yes/no)?: nO
Another Card (yes/no)?: no
</code>```

this is my code below:

```<code>while (playing == true ){
        System.out.print("Another Card (yes/no)?: ");
        anotherCard = keyboard.nextLine();

        if (anotherCard.equals("yes")) {

            nextCard = random.nextInt(10) + 1;
            cardTotal += nextCard;
            System.out.println("Card: " + nextCard);
            System.out.println("Total: " + cardTotal);

            if (cardTotal > 21) {
            System.out.println("You busted, Dealer Wins");
            playing = false;
            }
            if (cardTotal == 21) {
            System.out.println("Player Wins");
            playing = false;
            }

            }
           if (anotherCard.equals("no")) {
           dealerturn = true;

           if ((dealerturn == true) && (dTotal < 17)) {
                nextCard = random.nextInt(10) + 1;
                dTotal += nextCard;

                if (dTotal > 21) {
                System.out.println("Dealer Busts, You Win!");
                playing = false;

                }
            }
            else if ((dealerturn == true) && (dTotal > 17))  {
             if (dTotal > 21) {
                System.out.println("Dealer Busts, You Win!");
                playing = false;
                }
             }
           }
        }
     }
</code>```

答:
Your problem is that you have no condition set to your "another card" prompt, and therefore it will prompt the user no matter what. To fix this, first verify dealerturn is false before printing the prompt along with the input.

so, change this:

```<code>System.out.print("Another Card (yes/no)?: ");
anotherCard = keyboard.nextLine();
</code>```

into this:

```<code>if (dealerturn == false) {
    System.out.print("Another Card (yes/no)?: ");
    anotherCard = keyboard.nextLine();
}
</code>```

PS. Next time you have a problem, post your code with the appropriate variable declarations and imports, so it's easier for people to help you faster.

Title: System.out.print keeps looping error

Body:
Hello there guys I've been trying to help my friend with this code that almost works. It's a simple Blackjack game which asks the user if they want another card write yes and if user writes no then his turn is ended and it should be the dealer's turn. The problem I'm having is that when I write no to end my turn it just keeps asking me the question if I want another card in the console. Thank you for you help.
Ex.

Another Card (yes/no)?: nO
Another Card (yes/no)?: no
Another Card (yes/no)?: no
Another Card (yes/no)?: no
Another Card (yes/no)?: nO
Another Card (yes/no)?: no

this is my code below:

while (playing == true ){
        System.out.print("Another Card (yes/no)?: ");
        anotherCard = keyboard.nextLine();

        if (anotherCard.equals("yes")) {

            nextCard = random.nextInt(10) + 1;
            cardTotal += nextCard;
            System.out.println("Card: " + nextCard);
            System.out.println("Total: " + cardTotal);

            if (cardTotal > 21) {
            System.out.println("You busted, Dealer Wins");
            playing = false;
            }
            if (cardTotal == 21) {
            System.out.println("Player Wins");
            playing = false;
            }

            }
           if (anotherCard.equals("no")) {
           dealerturn = true;

           if ((dealerturn == true) && (dTotal < 17)) {
                nextCard = random.nextInt(10) + 1;
                dTotal += nextCard;

                if (dTotal > 21) {
                System.out.println("Dealer Busts, You Win!");
                playing = false;

                }
            }
            else if ((dealerturn == true) && (dTotal > 17))  {
             if (dTotal > 21) {
                System.out.println("Dealer Busts, You Win!");
                playing = false;
                }
             }
           }
        }
     }

Body:
Your problem is that you have no condition set to your "another card" prompt, and therefore it will prompt the user no matter what. To fix this, first verify dealerturn is false before printing the prompt along with the input.

so, change this:

System.out.print("Another Card (yes/no)?: ");
anotherCard = keyboard.nextLine();

into this:

if (dealerturn == false) {
    System.out.print("Another Card (yes/no)?: ");
    anotherCard = keyboard.nextLine();
}

PS. Next time you have a problem, post your code with the appropriate variable declarations and imports, so it's easier for people to help you faster.


问:
Does being trivially copyable imply being nothrow copyable?
Alternatively, is there an example of a type with a copy constructor that can throw, but is nontheless trivial?
And if not, does that imply that the is_nothrow_copy_constructible_v<T> should be true whenever is_trivially_copy_constructible_v<T> is true?

Note that according to the standard (latest draft [23.15.4.3]), for a type T to be nothrow copyable, we need the expression T t(declval<const T&>()); to be a well-formed variable definition that is known not to throw any exceptions. This wording seems to be somewhat vauge to me - what does it mean for something to be known? Should the noexcept specifier be sufficient to establish that knowledge? or maybe the determination is left to the implementation?

Edit: I realize there's a difference between being trivially copyable, and being trivially copy constructible. My focus is on the latter.

答:
On a compiler that implements DR2171:</p>

```<code>struct X {
    X(X&) = default;
    template<class U> X(U&&){ throw 1; }
};

static_assert(std::is_trivially_copyable_v<X>, "");
static_assert(std::is_copy_constructible_v<X>, "");
static_assert(!std::is_nothrow_copy_constructible_v<X>, "");
static_assert(!std::is_trivially_copy_constructible_v<X>, "");
</code>```

Body:
On a compiler that implements DR2171:

struct X {
    X(X&) = default;
    template<class U> X(U&&){ throw 1; }
};

static_assert(std::is_trivially_copyable_v<X>, "");
static_assert(std::is_copy_constructible_v<X>, "");
static_assert(!std::is_nothrow_copy_constructible_v<X>, "");
static_assert(!std::is_trivially_copy_constructible_v<X>, "");


问:
How to count words in a textarea if the word has a space
I have a text input and a text area.  I want to count the number of times the text input value occurs in the text area.  The following code works fine when the text input value doesn't have any spaces before or after.  But when it has spaces, I'm getting a null even if it occurs in the text area.  For example:

```<code>text input value: "dog"
text area value: "dog"
I get "1" in the console log.
</code>```

However

```<code>text input value: "dog_"
text area value: "dog_"
I get "null" in the console log.
</code>```

How do I get it so if I type  "dog_" in the text input and there is a  "dog_" in the text area, the count will be "1"

```<code>function testCount() {

var textVal = document.getElementById("textInput").value;
var textArea = document.getElementById("textArea").value;
var regex = new RegExp("\\b" + textVal + "\\b",'gi');
var count = textArea.match(regex).length;

console.log(count);

}
</code>```

I've tried various RegExp but they didn't solve the problem.  Thanks.

答:
function testCount() {

  var textVal = document.getElementById("textInput").value;
  var textArea = document.getElementById("textArea").value;
  var regex = new RegExp("(^|\\b)" + textVal + "(\\b|\\W|$)",'gi');  // UPDATE: Added "\\W"
  var count = textArea.match(regex);

  // To stop function if input is empty
  if (!textVal) return;

  // To prevent no-match cases from generating error
  if (!count)
    count = 0;
  else
    count = count.length;

  console.log(count);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="textInput" type="text" oninput="testCount()">
<textarea id="textArea"></textarea></code>```

UPDATE

@rockstar suggested an even better RegExp.

```<code>new RegExp("(^|[^\\w ])(" + textVal + ")([^\\w ]|$)",'gi')
</code>```

Unlike the previous implementation, this RegExp ensures perfect match (including trailing spaces).

If you feel confused with the complicated symbols, feel free to look at a very simple reference here.

UPDATE 2

@rockstar again suggested an even better RegExp.

```<code>new RegExp("(^|[^\\w ])" + textVal + "(?=[^\\w ]|$)",'gi');
</code>```

Body:
I have a text input and a text area.  I want to count the number of times the text input value occurs in the text area.  The following code works fine when the text input value doesn't have any spaces before or after.  But when it has spaces, I'm getting a null even if it occurs in the text area.  For example:

text input value: "dog"
text area value: "dog"
I get "1" in the console log.

However

text input value: "dog_"
text area value: "dog_"
I get "null" in the console log.

How do I get it so if I type  "dog_" in the text input and there is a  "dog_" in the text area, the count will be "1"

function testCount() {

var textVal = document.getElementById("textInput").value;
var textArea = document.getElementById("textArea").value;
var regex = new RegExp("\\b" + textVal + "\\b",'gi');
var count = textArea.match(regex).length;

console.log(count);

}

I've tried various RegExp but they didn't solve the problem.  Thanks.

Body:
function testCount() {

  var textVal = document.getElementById("textInput").value;
  var textArea = document.getElementById("textArea").value;
  var regex = new RegExp("(^|\\b)" + textVal + "(\\b|\\W|$)",'gi');  // UPDATE: Added "\\W"
  var count = textArea.match(regex);

  // To stop function if input is empty
  if (!textVal) return;

  // To prevent no-match cases from generating error
  if (!count)
    count = 0;
  else
    count = count.length;

  console.log(count);

}

<input id="textInput" type="text" oninput="testCount()">
<textarea id="textArea"></textarea>

UPDATE

@rockstar suggested an even better RegExp.

new RegExp("(^|[^\\w ])(" + textVal + ")([^\\w ]|$)",'gi')

Unlike the previous implementation, this RegExp ensures perfect match (including trailing spaces).

If you feel confused with the complicated symbols, feel free to look at a very simple reference here.

UPDATE 2

@rockstar again suggested an even better RegExp.

new RegExp("(^|[^\\w ])" + textVal + "(?=[^\\w ]|$)",'gi');


问:
Store value of session key then unset?

I'm trying to imitate the behavior of flash messages in native PHP, for one-time display of error messages.

Displaying the Login page:

```<code>public function showLoginAndRegistrationPage()
{
    $session = new Session();

    $data['errors']['login']['account'] = $session->getFormErrorFlashData('login', 'account');

    $this->viewPresenter->display('basic', 'customer/login-registration', $data, 'Login/Register');
}
</code>```

Verifying the login details:

```<code>public function processLogin()
{
    // Some code
    $session        = new Session();

    if($this->formInputFilter->isValid()) {

    // Some code

        if(true) {
    // Some code
        } else {
            $errors = array(
                'account' => 'Account does not exist.'
            );
            $session->setFormErrorFlashData('login', $errors);

            header('Location: /login');
        }
    } else {
            header('Location: /login');
    }
}
</code>```

For setting the error messages:

```<code>public function setFormErrorFlashData($form, $errors = array())
{
    foreach($errors As $field => $message) {
        $_SESSION['errors']["{$form}"]["{$field}"] = $message;
    }
}
</code>```

For getting the error messages stored in the session:

```<code>public function getFormErrorFlashData($form, $field)
{
    if(isset($_SESSION['errors']["{$form}"]["{$field}"])) {
        $message = $_SESSION['errors']["{$form}"]["{$field}"];

        unset($_SESSION['errors']["{$form}"]["{$field}"]);

        return $message;
    }
}
</code>```

Basically for an invalid attempt, after redirect, it should now display the 'Account does not exist' message, and then when the user refreshes the page, it should no longer be there.

What happens is when I comment out the unset() line in getFormErrorFlashData(), the $_SESSION contains the errors, but of course as expected they do persist even after countless page refreshes.

But when it's not commented out, I get a NULL. It seems that $message is also unset, even after attempting to store in it the value of that session key.

I have a bootstrap file that has the session_start() line, it's loaded for every page so I doubt that's the cause?

UPDATE:

index.php (bootstrap file)

```<code><?php

session_start();
date_default_timezone_set('Asia/Taipei');

require_once 'core/Autoloader.php';

use core\Autoloader As Autoloader;
use core\Router As Router;
use core\Dispatcher As Dispatcher;

spl_autoload_register('core\Autoloader::loadClass');
$request_uri    = trim($_SERVER['REQUEST_URI']);
$router         = new Router();
$route          = $router->handleRequest($request_uri);

if (!$route) {
    require_once ('./views/errors/404.php');
} else {
    $dispatcher     = new Dispatcher($route);

    $isDispatched   = $dispatcher->dispatch();
    if (!$isDispatched) {
        echo '<div>' .$route['class'] .'/' . $route['action'] . ' not found </div>';
        require_once ('./views/errors/404.php');
    }
}
</code>```

答:
I've found the culprit.

When I traced the request logs, showLoginAndRegistrationPage() was being called twice because I didn't realize I also had a .js file attached in the html file with a submit event handler that gets fired too, thus the double page requests.

I removed the file and now it's working.

Thanks for the help!

Title: Store value of session key then unset?

Body:
I'm trying to imitate the behavior of flash messages in native PHP, for one-time display of error messages.

Displaying the Login page:

public function showLoginAndRegistrationPage()
{
    $session = new Session();

    $data['errors']['login']['account'] = $session->getFormErrorFlashData('login', 'account');

    $this->viewPresenter->display('basic', 'customer/login-registration', $data, 'Login/Register');
}

Verifying the login details:

public function processLogin()
{
    // Some code
    $session        = new Session();

    if($this->formInputFilter->isValid()) {

    // Some code

        if(true) {
    // Some code
        } else {
            $errors = array(
                'account' => 'Account does not exist.'
            );
            $session->setFormErrorFlashData('login', $errors);

            header('Location: /login');
        }
    } else {
            header('Location: /login');
    }
}

For setting the error messages:

public function setFormErrorFlashData($form, $errors = array())
{
    foreach($errors As $field => $message) {
        $_SESSION['errors']["{$form}"]["{$field}"] = $message;
    }
}

For getting the error messages stored in the session:

public function getFormErrorFlashData($form, $field)
{
    if(isset($_SESSION['errors']["{$form}"]["{$field}"])) {
        $message = $_SESSION['errors']["{$form}"]["{$field}"];

        unset($_SESSION['errors']["{$form}"]["{$field}"]);

        return $message;
    }
}

Basically for an invalid attempt, after redirect, it should now display the 'Account does not exist' message, and then when the user refreshes the page, it should no longer be there.

What happens is when I comment out the unset() line in getFormErrorFlashData(), the $_SESSION contains the errors, but of course as expected they do persist even after countless page refreshes.

But when it's not commented out, I get a NULL. It seems that $message is also unset, even after attempting to store in it the value of that session key.

I have a bootstrap file that has the session_start() line, it's loaded for every page so I doubt that's the cause?

UPDATE:

index.php (bootstrap file)

<?php

session_start();
date_default_timezone_set('Asia/Taipei');

require_once 'core/Autoloader.php';

use core\Autoloader As Autoloader;
use core\Router As Router;
use core\Dispatcher As Dispatcher;

spl_autoload_register('core\Autoloader::loadClass');
$request_uri    = trim($_SERVER['REQUEST_URI']);
$router         = new Router();
$route          = $router->handleRequest($request_uri);

if (!$route) {
    require_once ('./views/errors/404.php');
} else {
    $dispatcher     = new Dispatcher($route);

    $isDispatched   = $dispatcher->dispatch();
    if (!$isDispatched) {
        echo '
' .$route['class'] .'/' . $route['action'] . ' not found
';
        require_once ('./views/errors/404.php');
    }
}


问:
Remove row from pandas dataframe if it has 2 strings
Im looking for a way to remove a row from a pandas data frame if it contains both of the 2 strings. I can do it if it has one, but havent been able to get both to work. Below is the code i used to remove records based on 1 string, looking to change that to include another keyword

code:

```<code>Vikings_dataframe_cleaned2=Vikings_dataframe_cleaned[Vikings_dataframe_cleaned.TweetText.str.contains("RT") == False]
</code>```

Strings to be excluded:
I want to check to text to make sure that it doesnt contain both @teddyb_h20 and @casekeenum7.

Example:

```<code>['@teddyb_h2o test test','@casekeenum7 and @teddyb_h2o are test','@casekeenum7 is the best right now']
</code>```

The code should then produce a dataframe that looks like this:

```<code>['@teddyb_h2o test test','@casekeenum7 is the best right now']
</code>```

答:
Sample df

```<code>df = pd.DataFrame({'col': ['@teddyb_h2o test test','@casekeenum7 and @teddyb_h2o are test','@casekeenum7 is the best right now','test test']})

    col
0   @teddyb_h2o test test
1   @casekeenum7 and @teddyb_h2o are test
2   @casekeenum7 is the best right now
3   test test
</code>```

Solution:

```<code>df[~(df.col.str.contains('@teddyb_h2o') & df.col.str.contains('@casekeenum7'))]

    col
0   @teddyb_h2o test test
2   @casekeenum7 is the best right now
3   test test
</code>```

@Wen's suggestion, more elegant

```<code>df[~df['col'].str.contains(r'^(?=.*@teddyb_h2o)(?=.*@casekeenum7)')]
</code>```

Body:
Im looking for a way to remove a row from a pandas data frame if it contains both of the 2 strings. I can do it if it has one, but havent been able to get both to work. Below is the code i used to remove records based on 1 string, looking to change that to include another keyword

code:

Vikings_dataframe_cleaned2=Vikings_dataframe_cleaned[Vikings_dataframe_cleaned.TweetText.str.contains("RT") == False]

Strings to be excluded:
I want to check to text to make sure that it doesnt contain both @teddyb_h20 and @casekeenum7.

Example:

['@teddyb_h2o test test','@casekeenum7 and @teddyb_h2o are test','@casekeenum7 is the best right now']

The code should then produce a dataframe that looks like this:

['@teddyb_h2o test test','@casekeenum7 is the best right now']

Body:
Sample df

df = pd.DataFrame({'col': ['@teddyb_h2o test test','@casekeenum7 and @teddyb_h2o are test','@casekeenum7 is the best right now','test test']})

    col
0   @teddyb_h2o test test
1   @casekeenum7 and @teddyb_h2o are test
2   @casekeenum7 is the best right now
3   test test

Solution:

df[~(df.col.str.contains('@teddyb_h2o') & df.col.str.contains('@casekeenum7'))]

    col
0   @teddyb_h2o test test
2   @casekeenum7 is the best right now
3   test test

@Wen's suggestion, more elegant

df[~df['col'].str.contains(r'^(?=.*@teddyb_h2o)(?=.*@casekeenum7)')]


问:
How to run once function on scroll up and scroll down event?
How to run doSomething() once when scrolling up or scrolling down?

```<code>window.onscroll = function(e) {
   // scrolling up
   if(this.oldScroll > this.scrollY){
      doSomething();
   // scrolling down
   } else {
      doSomething();
   }
   this.oldScroll = this.scrollY;
};
</code>```

The doSomething() bind some elements and I don't want to do repeat binds. I Just want when on scrolling up, bind once and when on scrolling down bind once.

答:
You can have an option of defining the closure function and using it in a way like described in this post

Apart from the above post I came across this situation and i used the following method to check if the event is already registered or not see below function where I needed to bind the click once only I used typeof $._data ( elementClose.get ( 0 ), 'events' ) === 'undefined' to get the events registered with the element, $._data is used to retrieve event handlers registered to an element/

```<code>this.closeButtonPreview = () => {
  let elementClose = $("a.close-preview");
  if (typeof $._data(elementClose.get(0), 'events') === 'undefined') {
    elementClose.on('click', function(e) {
      e.preventDefault();
      let container = $(this).parent();
      container.find('video').remove();
      $("#overlay,.window").effect("explode", {}, 500);
    });
  }
  return;
};
</code>```

EDIT

Just to get the concept clear for you about the logic I used with $._data(). i created an example below.

What i am doing is binding event click to anchor with id=unique inside the condition if (typeof $._data(uniqueBind.get(0), 'events') == 'undefined') { which determines if an event is assigned to the element and binding the event click to the anchor id=multi outside the condition without checking binded events on the element.

What you have to do.

Initially the button unique and multi won't log anything to console, click on EVENT BINDER once and then click on both unique and mutli they both will log text once in console, but as you keep clicking on the EVENT BINDER notice that clicking the multi button will start logging the text as many times as you have clicked the EVENT BINDER button but the unique  button will only log once no matter how many times you click on the EVENT BINDER button.

$(document).ready(function() {
  $('#binder').on('click', bindEvents);
  $('#clear').on('click', function() {
    console.clear();

  })
});

function bindEvents() {
  var uniqueBind = $('#unique-bind');
  var multiBind = $('#multi-bind');

  //will bind only once as many times you click on the EVENT BINDER BUTTON
  //check if any event is assigned to the element
  if (typeof $._data(uniqueBind.get(0), 'events') == 'undefined') {
    uniqueBind.on('click', function() {
      console.log('clicked unique bind');
    });
  }

  //will log the text EVENT BINDER * TIMES_EVENT_BINDER_CLICKED button
  multiBind.on('click', function() {
    console.log('clicked multi bind');
  });

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  text-align: center;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
EVENT BINDER
CLEAR CONSOLE

UNIQUE
MULTI```

Body:
How to run doSomething() once when scrolling up or scrolling down?

window.onscroll = function(e) {
   // scrolling up
   if(this.oldScroll > this.scrollY){
      doSomething();
   // scrolling down
   } else {
      doSomething();
   }
   this.oldScroll = this.scrollY;
};

The doSomething() bind some elements and I don't want to do repeat binds. I Just want when on scrolling up, bind once and when on scrolling down bind once.

Body:
You can have an option of defining the closure function and using it in a way like described in this post

Apart from the above post I came across this situation and i used the following method to check if the event is already registered or not see below function where I needed to bind the click once only I used typeof $._data ( elementClose.get ( 0 ), 'events' ) === 'undefined' to get the events registered with the element, $._data is used to retrieve event handlers registered to an element/

this.closeButtonPreview = () => {
  let elementClose = $("a.close-preview");
  if (typeof $._data(elementClose.get(0), 'events') === 'undefined') {
    elementClose.on('click', function(e) {
      e.preventDefault();
      let container = $(this).parent();
      container.find('video').remove();
      $("#overlay,.window").effect("explode", {}, 500);
    });
  }
  return;
};

EDIT

Just to get the concept clear for you about the logic I used with $._data(). i created an example below.

What i am doing is binding event click to anchor with id=unique inside the condition if (typeof $._data(uniqueBind.get(0), 'events') == 'undefined') { which determines if an event is assigned to the element and binding the event click to the anchor id=multi outside the condition without checking binded events on the element.

What you have to do.

Initially the button unique and multi won't log anything to console, click on EVENT BINDER once and then click on both unique and mutli they both will log text once in console, but as you keep clicking on the EVENT BINDER notice that clicking the multi button will start logging the text as many times as you have clicked the EVENT BINDER button but the unique  button will only log once no matter how many times you click on the EVENT BINDER button.

$(document).ready(function() {
  $('#binder').on('click', bindEvents);
  $('#clear').on('click', function() {
    console.clear();

  })
});

function bindEvents() {
  var uniqueBind = $('#unique-bind');
  var multiBind = $('#multi-bind');

  //will bind only once as many times you click on the EVENT BINDER BUTTON
  //check if any event is assigned to the element
  if (typeof $._data(uniqueBind.get(0), 'events') == 'undefined') {
    uniqueBind.on('click', function() {
      console.log('clicked unique bind');
    });
  }

  //will log the text EVENT BINDER * TIMES_EVENT_BINDER_CLICKED button
  multiBind.on('click', function() {
    console.log('clicked multi bind');
  });

}

body {
  text-align: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<a href="#." class="btn btn-success" id="binder">EVENT BINDER</a>
<a href="#." class="btn btn-success" id="clear">CLEAR CONSOLE</a>
<br /><br /><br /><br />
<a href="#." class="btn btn-info" id="unique-bind">UNIQUE</a>
<a href="#." class="btn btn-danger" id="multi-bind">MULTI</a>


问:
Django 1.8 IntegrityError when adding new user
I moved an old Django app from 1.4 to 1.8 and everything in the main application ran fine. I then needed to copy everything from server 1 to server 2, and in the process just dumped the mysql data for the admin database and installed to the new database.

Everything came up fine, however when creating a new user I get:
IntegrityError at /admin/auth/user/add/
(1048, "Column 'last_login' cannot be null")

This is a live system with 30 accounts. I found a variety of solutions to this online but I want to make sure it doesn't trash my database.

I only need the admin database fixed up. My business side database and tables are not managed by Django, but is a custom schema (that I inherited).

btw, deleting a user works fine.

答:
This is described in the release notes, along with the steps to migrate your database to allow null values:

The AbstractUser.last_login field now allows null values. Previously, it defaulted to the time when the user was created which was misleading if the user never logged in. If you are using the default user (django.contrib.auth.models.User), run the database migration included in contrib.auth.

If you are using a custom user model that inherits from AbstractUser, you’ll need to run makemigrations and generate a migration for your app that contains that model. Also, if wish to set last_login to NULL for users who haven’t logged in, you can run this query:

from django.db import models
     from django.contrib.auth import get_user_model
     from django.contrib.auth.models import AbstractBaseUser

```<code>UserModel = get_user_model()
if issubclass(UserModel, AbstractBaseUser):
    UserModel._default_manager.filter(
        last_login=models.F('date_joined')
    ).update(last_login=None)
</code>```

Your error suggests that you haven't run the migration that will allow null values for that column.

Body:
This is described in the release notes, along with the steps to migrate your database to allow null values:

The AbstractUser.last_login field now allows null values. Previously, it defaulted to the time when the user was created which was misleading if the user never logged in. If you are using the default user (django.contrib.auth.models.User), run the database migration included in contrib.auth.

If you are using a custom user model that inherits from AbstractUser, you’ll need to run makemigrations and generate a migration for your app that contains that model. Also, if wish to set last_login to NULL for users who haven’t logged in, you can run this query:

from django.db import models
     from django.contrib.auth import get_user_model
     from django.contrib.auth.models import AbstractBaseUser

UserModel = get_user_model()
if issubclass(UserModel, AbstractBaseUser):
    UserModel._default_manager.filter(
        last_login=models.F('date_joined')
    ).update(last_login=None)

Your error suggests that you haven't run the migration that will allow null values for that column.


问:
IE8 Height 100% Bug
Has anyone heard of a bug that occurs with IE8 when applying height as a percentage to the html and body using CSS? I'm seeing a white background when a tile pattern should be applied.</p>

```<code>html, body {
    margin: 0;
    padding: 0;
    height: 100%;
}

body {
    background-color: #666;
    background-image: url('../images/body/bg_pattern.gif');
}
</code>```

答:
IE8 interprets the height element closer to the standards than IE7 did. The statement

`Height: 100%

Is pretty much ignored. Percentage heights are based upon the height of their parent element. If the parent element doesn't have an explicit height, the percentage is ignored and set to Auto. You can see more about this on w3.org.

If the page you are displaying is empty, body will have a height of 0 and you will see the default background.

Title: IE8 Height 100% Bug

Body:
Has anyone heard of a bug that occurs with IE8 when applying height as a percentage to the html and body using CSS? I'm seeing a white background when a tile pattern should be applied.

html, body {
    margin: 0;
    padding: 0;
    height: 100%;
}

body {
    background-color: #666;
    background-image: url('../images/body/bg_pattern.gif');
}


问:
How to correctly use UUID.fromString method?
I am trying to read/write these ble characteristics:

Right now, I'm trying to read AA01*

I am using this library to do it.

Here's my code:

```<code>private void connectToSensorTag(RxBleDevice rxBleDevice) {
    rxBleDevice.establishConnection(getApplicationContext(), false)
            .doOnError(new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    int i = 0;
                }
            })
            .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString("AA01*")))
            .subscribe(new Subscriber<byte[]>() {
                @Override
                public void onCompleted() {
                    int i = 0;
                }

                @Override
                public void onError(Throwable e) {
                    int i = 0;
                }

                @Override
                public void onNext(byte[] bytes) {
                    int i = 0;
                }
            });
</code>```

I get this error:

java.lang.IllegalArgumentException: Invalid UUID: AA01*

I also tried the solutions from this similar question but nothing works. Same error.

答:
If you need a faster java.util.UUID.fromString(), you can use Fast-UUID-Parser
 instead. It returns java.util.UUID and it's 4 times faster than java.util.UUID.fromString().

Body:
I am trying to read/write these ble characteristics:

Right now, I'm trying to read AA01*

I am using this library to do it.

Here's my code:

private void connectToSensorTag(RxBleDevice rxBleDevice) {
    rxBleDevice.establishConnection(getApplicationContext(), false)
            .doOnError(new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    int i = 0;
                }
            })
            .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString("AA01*")))
            .subscribe(new Subscriber<byte[]>() {
                @Override
                public void onCompleted() {
                    int i = 0;
                }

                @Override
                public void onError(Throwable e) {
                    int i = 0;
                }

                @Override
                public void onNext(byte[] bytes) {
                    int i = 0;
                }
            });

I get this error:

java.lang.IllegalArgumentException: Invalid UUID: AA01*

I also tried the solutions from this similar question but nothing works. Same error.


问:
Right-aligning an image to the page border in a r-markdown PDF document
I'm looking to create a cover page for a PDF document rendered via rmarkdown, with an image cover.png that I'd have right-aligned right up against the page border. In my YAML below, I currently have it centered on the page. How do I move it to the right?

```<code>---
title: \vspace{3cm} \fontsize{1.5cm}{2cm}\selectfont Report Title
header-includes:
- \usepackage{titling}
- \pretitle{\begin{center}\includegraphics[width=20cm]{cover.png}\\[\bigskipamount]}
- \posttitle{\end{center}}
- \pagenumbering{gobble}
output:
  pdf_document:
    latex_engine: xelatex
mainfont: Calibri
editor_options:
  chunk_output_type: console
---
</code>```

答:
You could include raw latex in your Rmd doc that will situate the picture where you want it. For example:

```<code>---
title: Dogs are the best
output:
  pdf_document:
header-includes:
  - \usepackage{graphicx}
---

```{r include = FALSE}
library(httr)
dog <- "https://www.cesarsway.com/sites/newcesarsway/files/styles/large_article_preview/public/Common-dog-behaviors-explained.jpg"
GET(dog, write_disk("dog.jpg", overwrite = TRUE))
```

\begin{figure}
  \raggedleft
  \begin{minipage}{5cm}
  \includegraphics[width = 5cm]{dog.jpg}
  \end{minipage}
\end{figure}

\pagebreak

## Introduction

Dogs dogs dogs
</code>```

Which results in:

Body:
I'm looking to create a cover page for a PDF document rendered via rmarkdown, with an image cover.png that I'd have right-aligned right up against the page border. In my YAML below, I currently have it centered on the page. How do I move it to the right?

---
title: \vspace{3cm} \fontsize{1.5cm}{2cm}\selectfont Report Title
header-includes:
- \usepackage{titling}
- \pretitle{\begin{center}\includegraphics[width=20cm]{cover.png}\\[\bigskipamount]}
- \posttitle{\end{center}}
- \pagenumbering{gobble}
output:
  pdf_document:
    latex_engine: xelatex
mainfont: Calibri
editor_options:
  chunk_output_type: console
---

Body:
You could include raw latex in your Rmd doc that will situate the picture where you want it. For example:

---
title: Dogs are the best
output:
  pdf_document:
header-includes:
  - \usepackage{graphicx}
---

```{r include = FALSE}
library(httr)
dog <- "https://www.cesarsway.com/sites/newcesarsway/files/styles/large_article_preview/public/Common-dog-behaviors-explained.jpg"
GET(dog, write_disk("dog.jpg", overwrite = TRUE))
```

\begin{figure}
  \raggedleft
  \begin{minipage}{5cm}
  \includegraphics[width = 5cm]{dog.jpg}
  \end{minipage}
\end{figure}

\pagebreak

## Introduction

Dogs dogs dogs

Which results in:


问:
Trying to display all posts in given category - getting error
I'm building my first laravel app.

I'm trying to display all posts in x category.

My routes:

```<code>Route::get('/', 'PostsController@index')->name('home');
Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
Route::get('/categories/{category}', 'CategoriesController@index')->name('category');
</code>```

My category model:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}
</code>```

My category controller:

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Category;

class CategoriesController extends Controller
{
    public function index(Category $category)
    {
        $posts = $category->posts;

        return view('index', compact('posts'));
    }
}
</code>```

Getting: "Sorry, the page you are looking for could not be found."

Works if I change:

```<code>Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
</code>```

To:

```<code>Route::get('/{post}', 'PostsController@show')->name('show');
</code>```

Thank you in advance!

答:
Your route /{id}/{slug?} regex is capturing the word categories of your other route and preventing it to work as expected. You have 2 options here:

Move the categories/{category} up to the post route. Laravel routes stops on first match.

Define what {id} can be

```<code>Route::get('/{id}/{slug?}', 'PostsController@show')->name('show')->where('id', '[0-9]*');
</code>```

Anyway, if that post id route is a backend route, I shall recommend to you to prefix it like posts/{id}/{slug?}. If it's a frontend, choose one of the previous solutions (or even both).

Body:
I'm building my first laravel app.

I'm trying to display all posts in x category.

My routes:

Route::get('/', 'PostsController@index')->name('home');
Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');
Route::get('/categories/{category}', 'CategoriesController@index')->name('category');

My category model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}

My category controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Category;

class CategoriesController extends Controller
{
    public function index(Category $category)
    {
        $posts = $category->posts;

        return view('index', compact('posts'));
    }
}

Getting: "Sorry, the page you are looking for could not be found."

Works if I change:

Route::get('/{id}/{slug?}', 'PostsController@show')->name('show');

To:

Route::get('/{post}', 'PostsController@show')->name('show');

Thank you in advance!

Body:
Your route /{id}/{slug?} regex is capturing the word categories of your other route and preventing it to work as expected. You have 2 options here:

Move the categories/{category} up to the post route. Laravel routes stops on first match.

Define what {id} can be

Route::get('/{id}/{slug?}', 'PostsController@show')->name('show')->where('id', '[0-9]*');

Anyway, if that post id route is a backend route, I shall recommend to you to prefix it like posts/{id}/{slug?}. If it's a frontend, choose one of the previous solutions (or even both).


问:
Trying to break up the users string into my function for a decimal return - Python
So I am trying to chop the user input of 1s and 0s to print out their decimal counterpart, but no matter what when I enter: "10000000111111110000001100001111" I get 256 for the second set of 8 numbers instead of 255. I am stumped. I get 128 for value 1, but 256 for value 2. I don't think I understand what (number[6:10]) is even doing. </p>

```<code>def convert(bits):
    answer = 0
    keeper = 128
    for i in bits:
        if(i == '1'):
            answer = answer + keeper
            keeper / 2
    return answer

number = str(input("Please enter a 32-bit integer: "))

value1 = convert(number[0:7])
value2 = convert(number[6:10])

print(value1, value2)
</code>```

答:
The value of keeper isn't being updated when you do keeper / 2.

You have to catch the value of that statement and assign it to keeper:

keeper = keeper // 2 or keeper //= 2

Since you want to split the user's input into 8 bit blocks, you should also change the indexes in your slicing. In your case you would want:

```<code>value1 = convert(number[0:8])
value2 = convert(number[8:16])
</code>```

I don't think I understand what (number[6:10]) is even doing.

number is being set to a string of the number the user inputs, in your case "10000000111111110000001100001111".

By saying number[6:10], you're slicing the string meaning you're getting a specific piece of the string. The first number 6 is the starting point and 10 is the endpoint -- but note that 10 is exclusive meaning you will get the string starting at index 6 and ending at but not including the character at index 10. Also note that the very first index of the string is 0, and not 1. There are some helpful examples here.

Body:
So I am trying to chop the user input of 1s and 0s to print out their decimal counterpart, but no matter what when I enter: "10000000111111110000001100001111" I get 256 for the second set of 8 numbers instead of 255. I am stumped. I get 128 for value 1, but 256 for value 2. I don't think I understand what (number[6:10]) is even doing.

def convert(bits):
    answer = 0
    keeper = 128
    for i in bits:
        if(i == '1'):
            answer = answer + keeper
            keeper / 2
    return answer

number = str(input("Please enter a 32-bit integer: "))

value1 = convert(number[0:7])
value2 = convert(number[6:10])

print(value1, value2)

Body:
The value of keeper isn't being updated when you do keeper / 2.

You have to catch the value of that statement and assign it to keeper:

keeper = keeper // 2 or keeper //= 2

Since you want to split the user's input into 8 bit blocks, you should also change the indexes in your slicing. In your case you would want:

value1 = convert(number[0:8])
value2 = convert(number[8:16])

I don't think I understand what (number[6:10]) is even doing.

number is being set to a string of the number the user inputs, in your case "10000000111111110000001100001111".

By saying number[6:10], you're slicing the string meaning you're getting a specific piece of the string. The first number 6 is the starting point and 10 is the endpoint -- but note that 10 is exclusive meaning you will get the string starting at index 6 and ending at but not including the character at index 10. Also note that the very first index of the string is 0, and not 1. There are some helpful examples here.


问:
Queing notification in PHP using AJAX with beep sound
I am building now a Queuing system for my helpdesk system. i have problem in detecting the changes of input value. I want to play the play_sound() function sound when the value of input is incremented. the curent value of input is coming from the rowCount in my SQL Query stored in variable.
screenshot picture link

Input

```<code>  <input disabled type="text" id="needapproval"  id="approval" value="0" class="center" />
</code>```

My Script

```<code> <script type="text/javascript">
  function play_sound() {
    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', 'Kalimba.mp3');
    audioElement.setAttribute('autoplay', 'autoplay');
    audioElement.load();
    audioElement.play();
  }
  activateMagic();
  function activateMagic() {
    setInterval(realTimeData, 1000);
        function realTimeData() {
            $.ajax({
                url: './includes/needapproval.php',
                method: 'GET',
                  dataType: "json",
                success: function(res) {
                    $("#needapproval").val(res.data_count);
                },
                error: function(err) {
                    console.log(err);
                }
            });
        }
    }
   </script>
</code>```

PHP

```<code>require_once "connection.php";
    class NeedApprovalStatus extends Connection{
            public function needApproval() {
              $count_approval = "SELECT * FROM job_request WHERE approval_status LIKE '%Need Approval%' ";
              $stmt_count_approval = $this->db->prepare($count_approval);
              $stmt_count_approval->execute();
              $count = $stmt_count_approval->rowCount();
              $data_count = [];
                if ($count == 0) {
                    $data_count = [
                          'data_count'  => 0
                      ];
                } else {
                    $data_count = [
                          'data_count' => $count
                      ];
                }
                  echo json_encode($data_count);
            }

   }
    $need_approval = new NeedApprovalStatus;
    $need_approval->needApproval();
</code>```

I tried to use onchange event in jquery but it doesn't work. because i think onchange only trigger when you change value on input manually. Any ideas guys?

答:
It would be easier to check the value inside the success function and call play_sound() from there.

```<code>function activateMagic() {

    var value = 0;

    setInterval(realTimeData, 1000);
    function realTimeData() {
        $.ajax({
            url: './includes/needapproval.php',
            method: 'GET',
            dataType: "json",
            success: function(res) {
                var newValue = res.data_count;

                if(newValue != value) {
                    play_sound()
                    $("#needapproval").val(value);
                    value = newValue;
                }
            }
         ...
</code>```

Body:
I am building now a Queuing system for my helpdesk system. i have problem in detecting the changes of input value. I want to play the play_sound() function sound when the value of input is incremented. the curent value of input is coming from the rowCount in my SQL Query stored in variable.
screenshot picture link

Input

  <input disabled type="text" id="needapproval"  id="approval" value="0" class="center" />

My Script

PHP

require_once "connection.php";
    class NeedApprovalStatus extends Connection{
            public function needApproval() {
              $count_approval = "SELECT * FROM job_request WHERE approval_status LIKE '%Need Approval%' ";
              $stmt_count_approval = $this->db->prepare($count_approval);
              $stmt_count_approval->execute();
              $count = $stmt_count_approval->rowCount();
              $data_count = [];
                if ($count == 0) {
                    $data_count = [
                          'data_count'  => 0
                      ];
                } else {
                    $data_count = [
                          'data_count' => $count
                      ];
                }
                  echo json_encode($data_count);
            }

   }
    $need_approval = new NeedApprovalStatus;
    $need_approval->needApproval();

I tried to use onchange event in jquery but it doesn't work. because i think onchange only trigger when you change value on input manually. Any ideas guys?

Body:
It would be easier to check the value inside the success function and call play_sound() from there.

function activateMagic() {

    var value = 0;

    setInterval(realTimeData, 1000);
    function realTimeData() {
        $.ajax({
            url: './includes/needapproval.php',
            method: 'GET',
            dataType: "json",
            success: function(res) {
                var newValue = res.data_count;

                if(newValue != value) {
                    play_sound()
                    $("#needapproval").val(value);
                    value = newValue;
                }
            }
         ...


问:
How to use database with React native?
I am building my first app with react native.
I am, for now, storing locally with AsyncStorage the user data.
This app is going to make users interact with each other, I am looking at realm.io but for my understanding all the mobile apps save the data locally then sync it to a database.
I am not sure if this is the way and I am doing correct. Basically what I want to do is :

Open the app, load the user data from AsyncStorage

Call the database (from a server) download other users data

Store user and users data in to the state of the app (I use redux)

Sync with the live database at each interaction.

Is this the correct way? For example if is a chat and I want to store the data for both users in to the database, how do I do?
So to recap, how do I store the app data for all users in a live database that is on a server?

答:
What you're looking for is redux-persist https://github.com/rt2zz/redux-persist

What redux persist does is handle all the local storage things on its own any time it changes. So when you reopen the app everything that you want is there. You handle the database loading as you would normally and send it to your redux store and replace the old data.

Persist also has a black and white list for some of the things that you may or may not want to be saved. If you want to save everything in the store though it does it by default.

If you have important things that you want to be saved, you'll want to move it into the store if you have it in the state, because it does not save state.

Title: How to use database with React native?


问:
Reshape matrix using Matlab
I work using Matlab and I have a matrix in 400x400x3x3 shape. I need to reshape it into 1200x1200. How do I do that?

I know there's a command called reshape and I've tried using it, but I'm missing something that I'm not seeing it.

答:
I'm going to guess that you want dimensions 1 and 3 to collapse into a new first dimension, and dimensions 2 and 4 to collapse into a new second dimension.

In that case, you need permute before reshape so that the dimensions to be collapsed appear together:

```<code>x = rand(400, 400, 3, 3); % random data
y = reshape(permute(x, [1 3 2 4]), size(x,1)*size(x,3), size(x,2)*size(x,4));
</code>```

Title: Reshape matrix using Matlab

Body:
I'm going to guess that you want dimensions 1 and 3 to collapse into a new first dimension, and dimensions 2 and 4 to collapse into a new second dimension.

In that case, you need permute before reshape so that the dimensions to be collapsed appear together:

x = rand(400, 400, 3, 3); % random data
y = reshape(permute(x, [1 3 2 4]), size(x,1)*size(x,3), size(x,2)*size(x,4));


问:
Check URL parameter in php
I want to check a parameter in a url variable, for example:

```<code>$var2join = 'en'; // can be anything else
$url = 'https://www.example.com/hello/parameter2';
$url2 = 'https://www.example.com/hello2';
$url3 = 'https://www.example.com/en/hey';
</code>```

first check if the $url vars have the $var2join into $var as parameter if have it, leave it intact and if not add it.

Wanted output:

```<code>$url = 'https://www.example.com/en/hello/parameter2';
$url2 = 'https://www.example.com/en/hello2';
$url3 = 'https://www.example.com/en/hey';
</code>```

I tried:

```<code>$url = (!preg_match('~^/[a-z]{2}(?:/|$)~', $location)) ? '/' . $var2join . $url : $url;
</code>```

答:
Use parse_url(), it is specifically for analysing URLs and their various elements.

Note this code assumes your parameters are path segments, as you describe above.  If you ever use query string parameters like ?foo=bar, you'd need to adjust.

```<code>$var2join = 'en';
$url = 'https://www.example.com/hello/parameter2';

// Split URL into each of its parts
$url_parts = parse_url($url);

// Create an array of all the path parts, which correspond to
// parameters in your scheme
$params = explode('/', $url_parts['path']);

// Check if your var is in there
if (!in_array($var2join, $params)) {

    // If not, reconstruct the same URL, but with your var inserted.
    // NOTE this assumes a pretty simple URL, you'll need to adjust if
    // you ever have other elements like port number, u/p, query strings
    // etc.  @Jason-rush links to something in the PHP docs to handle
    // such cases.
    $url = $url_parts['scheme'] . '://' . $url_parts['host'] . '/' . $var2join . $url_parts['path'];
}

// Check your result - https://www.example.com/en/hello/parameter2
echo $url;
</code>```

Title: Check URL parameter in php

Body:
I want to check a parameter in a url variable, for example:

$var2join = 'en'; // can be anything else
$url = 'https://www.example.com/hello/parameter2';
$url2 = 'https://www.example.com/hello2';
$url3 = 'https://www.example.com/en/hey';

first check if the $url vars have the $var2join into $var as parameter if have it, leave it intact and if not add it.

Wanted output:

$url = 'https://www.example.com/en/hello/parameter2';
$url2 = 'https://www.example.com/en/hello2';
$url3 = 'https://www.example.com/en/hey';

I tried:

$url = (!preg_match('~^/[a-z]{2}(?:/|$)~', $location)) ? '/' . $var2join . $url : $url;

Body:
Use parse_url(), it is specifically for analysing URLs and their various elements.

Note this code assumes your parameters are path segments, as you describe above.  If you ever use query string parameters like ?foo=bar, you'd need to adjust.

$var2join = 'en';
$url = 'https://www.example.com/hello/parameter2';

// Split URL into each of its parts
$url_parts = parse_url($url);

// Create an array of all the path parts, which correspond to
// parameters in your scheme
$params = explode('/', $url_parts['path']);

// Check if your var is in there
if (!in_array($var2join, $params)) {

    // If not, reconstruct the same URL, but with your var inserted.
    // NOTE this assumes a pretty simple URL, you'll need to adjust if
    // you ever have other elements like port number, u/p, query strings
    // etc.  @Jason-rush links to something in the PHP docs to handle
    // such cases.
    $url = $url_parts['scheme'] . '://' . $url_parts['host'] . '/' . $var2join . $url_parts['path'];
}

// Check your result - https://www.example.com/en/hello/parameter2
echo $url;


问:
How to stream a video file for html5 video tag
I was wondering what's the best way to stream a video file (mpg4/avi - or any other format) in Go. Possibly, I'd like to be able to play it using a simple  tag.

I've tried playing the famous Big Buck Bunny file with this code:

```<code>package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "time"
)

func serveHTTP(w http.ResponseWriter, r *http.Request) {
    video, err := os.Open("./bunny.avi")
    if err != nil {
        log.Fatal(err)
    }
    http.ServeContent(w, r, "bunny.avi", time.Now(), video)
    defer video.Close()
}

func main() {
    http.HandleFunc("/", serveHTTP)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println(err.Error())
    }
}
</code>```

But when loading the html page in my browser nothing plays and only one http request is actually triggered and only one response with 206 Partial content is sent to the page.

The html page contains the following code in the body:

```<code><video width="320" height="240" controls autoplay>
    <source src="http://localhost:8080">
    Your browser does not support the video tag.
</video>
</code>```

Thank you!

答:
Your go code looks fine, leading me to think this is probably a problem with your video.
avi is usually not supported for html5, see here for more details on containers/codecs for html5.

I would try with a known working video. eg: https://www.quirksmode.org/html5/videos/big_buck_bunny.mp4

Maybe even simplify your code and just use http.ServeFile, although the important part of video serving (range requests) is in ServeContent anyway.

Body:
I was wondering what's the best way to stream a video file (mpg4/avi - or any other format) in Go. Possibly, I'd like to be able to play it using a simple  tag.

I've tried playing the famous Big Buck Bunny file with this code:

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "time"
)

func serveHTTP(w http.ResponseWriter, r *http.Request) {
    video, err := os.Open("./bunny.avi")
    if err != nil {
        log.Fatal(err)
    }
    http.ServeContent(w, r, "bunny.avi", time.Now(), video)
    defer video.Close()
}

func main() {
    http.HandleFunc("/", serveHTTP)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println(err.Error())
    }
}

But when loading the html page in my browser nothing plays and only one http request is actually triggered and only one response with 206 Partial content is sent to the page.

The html page contains the following code in the body:

<video width="320" height="240" controls autoplay>
    <source src="http://localhost:8080">
    Your browser does not support the video tag.
</video>

Thank you!