问:
Why is this mode function returning null?
In the below function, when I call

```<code>mmmr(array(1,2,3,3,4,3), 'mode', 'ceil'); // null
</code>```

it returns null. Works fine if I don't set the third ($round) argument.

```<code>mmmr(array(1,2,3,3,4,3), 'mode'); // 3
</code>```

What am I missing? Coffee?

```<code>function mmmr( array $array, $output = 'mean', $round = false ) {

        switch( $output ) {

                case 'mode':

                if( $round == "ceil" ) {
                    foreach( $array as $key => $value ) {
                        $array[$key] = ceil( $value );
                    }
                } elseif( $round == "floor" ) {
                    foreach( $array as $key => $value ) {
                        $array[$key] = floor( $value );
                    }
                } elseif( $round == "normal" ) {
                    foreach( $array as $key => $value ) {
                        $array[$key] = round( $value );
                    }
                }

                $v = array_count_values( $array );
                arsort( $v );
                foreach( $v as $k => $v ) {
                    $total = $k;
                    break;
                }
                break;

        }

        return $total;

    }
</code>```

答:
array_count_values() can only count STRING and INTEGER values. ceil(), floor(), and round() return a float. Casting it to an int fixes your problem:

```<code><?php

function mmmr( array $array, $output = 'mean', $round = false ) {

    switch( $output ) {

            case 'mode':

            if( $round == "ceil" ) {
                foreach( $array as $key => $value ) {
                    $array[$key] = (int) ceil( $value ); // (int)
                }
            } elseif( $round == "floor" ) {
                foreach( $array as $key => $value ) {
                    $array[$key] = (int) floor( $value ); // (int)
                }
            } elseif( $round == "normal" ) {
                foreach( $array as $key => $value ) {
                    $array[$key] = (int) round( $value ); // (int)
                }
            }

            $v = array_count_values( $array );
            arsort( $v );
            foreach( $v as $k => $v ) {
                $total = $k;
                break;
            }
            break;

    }

    return $total;

}

echo mmmr(array(1,2,3,3,4,3), 'mode', 'ceil'); // Returns 3
</code>```

Body:
In the below function, when I call

mmmr(array(1,2,3,3,4,3), 'mode', 'ceil'); // null

it returns null. Works fine if I don't set the third ($round) argument.

mmmr(array(1,2,3,3,4,3), 'mode'); // 3

What am I missing? Coffee?

function mmmr( array $array, $output = 'mean', $round = false ) {

        switch( $output ) {

                case 'mode':

                if( $round == "ceil" ) {
                    foreach( $array as $key => $value ) {
                        $array[$key] = ceil( $value );
                    }
                } elseif( $round == "floor" ) {
                    foreach( $array as $key => $value ) {
                        $array[$key] = floor( $value );
                    }
                } elseif( $round == "normal" ) {
                    foreach( $array as $key => $value ) {
                        $array[$key] = round( $value );
                    }
                }

                $v = array_count_values( $array );
                arsort( $v );
                foreach( $v as $k => $v ) {
                    $total = $k;
                    break;
                }
                break;

        }

        return $total;

    }

Body:
array_count_values() can only count STRING and INTEGER values. ceil(), floor(), and round() return a float. Casting it to an int fixes your problem:

<?php

function mmmr( array $array, $output = 'mean', $round = false ) {

    switch( $output ) {

            case 'mode':

            if( $round == "ceil" ) {
                foreach( $array as $key => $value ) {
                    $array[$key] = (int) ceil( $value ); // (int)
                }
            } elseif( $round == "floor" ) {
                foreach( $array as $key => $value ) {
                    $array[$key] = (int) floor( $value ); // (int)
                }
            } elseif( $round == "normal" ) {
                foreach( $array as $key => $value ) {
                    $array[$key] = (int) round( $value ); // (int)
                }
            }

            $v = array_count_values( $array );
            arsort( $v );
            foreach( $v as $k => $v ) {
                $total = $k;
                break;
            }
            break;

    }

    return $total;

}

echo mmmr(array(1,2,3,3,4,3), 'mode', 'ceil'); // Returns 3


来源: stackexchange

问:
Google External Login Fails with no Error Message - But Facebook Works
I'm using MVC External Authentication providers for both Google and Facebook.  I have easily gotten both working many times before.

For some reason today, on a brand new project (File | New Project | MVC 5 Web App) in VS 2015 - it is the completely default project.  The only thing I have done is provide the App Keys and Secrets for both Google and facebook.

Facebook works all the way through, calls back - asks me to register as a new user - and then logs me in as that user.

Google gets all the way to the point where it WOULD call back to the OAuth Callback url - but that never happens, and instead I'm just redirected back to the login page with no further explanation.  There are no errors, no messages are logged anywhere that I can find, and no exceptions are thrown.

If instead, I register as a password user, and then try to link the account - I am able to do so without any trouble with facebook.  However, again, with the Google external provider, it gets to the point where the OAuth callback uri WOULD Be triggered, but instead, it just take me back to the "/ManageLogins" page with the generic error "An Error has Occurred".

I have enabled every type of exception that I could possible trap - but I get absolutely no feedback from the process except that it didn't work.  And since I literally have not yet had a chance to write a single line of code, I'm not sure what else to try.

I have spent almost 6 hours now trying to get this basic identity management part of the project completed - and while it usually only takes 10-15 minutes, I am completely blocked.  And since there is so little feedback from the code itself, I'm hoping that someone has run into this before and might be able to help.

Thanks.

Other Things I've tried:
1) it was original http - I thought that might be the problem, so I got an ssl certificate - and have converted it to https.  Same problem.

2) I have cleared my cookies, tried incognito, tried in many browsers - always the same result.

3) Original it was a new project in a larger solution - so I have now just created a new web project in it's own solution. Same problem.

4) I have switched to 2 different domains, and tried it from localhost of course.

Running out fo things to try....

EJ

答: I know its an old thread, but I ran into the exact same issue. You have to make sure that Google+ API is enabled in Google Developers Console.</p>

ContentLicense: CC BY-SA 3.0


问:
Write a function in R containing an if/else statement and rowSums(), defining how to handle NAs
I've been searching for answers and trying all I can think of, but nothing works:

I want to write a function to add the values across rows in a dataframe. It's easiest to write a function since I have so many columns and don't always have to add the same ones. Here an example of a dataframe:

```<code>ExampleData <- data.frame(Participant = 1:7,
                   Var1 = c(2, NA, 13, 15, 0, 2, NA),
                   Var2 = c(NA, NA, 1, 0, NA, 4, 2),
                   Var3 = c(6, NA, 1, 0, 1, 5, 3),
                   Var4 = c(12, NA, NA, 4, 10, 1, 4),
                   Var5 = c(10, NA, 3, 5, NA, 4, 4))
</code>```

The conditions: If all values across a row are NA, the sum should be NA. If there is at least one value across a row that is a number (>= 0, or not NA), then rowSums should ignore NA's and add the values.

The best solution I've reached so far is:

```<code>addition <- function(x) {
  if(all(is.na(x))){
       NA
  }else{
       rowSums(x, na.rm = TRUE)
  }
}
addition(ExampleData[, c("Var1", "Var2", "Var3")])
</code>```

The output is:  [1]  8  0 15 15  1 11  5

But it should be: [1] 8 NA 15 15 1 11 5

Does anyone know how to do this?
Thank you.

答:
The reason is the all(is.na(x)) is checking whether all the elements of the dataset are NA instead of by rows.   If we check the output of is.na(data), it is a logical matrix.  A matrix is basically a vector with dimension attributes.  So, wrapping with all checks if all the elements are NA or not.

For example,

```<code>all(is.na(matrix(c(1:9, NA), 5, 2)))
#[1] FALSE
</code>```

We can change the function to

```<code> addition <- function(x) {
     rowSums(x, na.rm = TRUE) *  NA^(rowSums(!is.na(x))==0)

 }
addition(ExampleData[, c("Var1", "Var2", "Var3")])
#[1]  8 NA 15 15  1 11  5
</code>```

Body:
I've been searching for answers and trying all I can think of, but nothing works:

I want to write a function to add the values across rows in a dataframe. It's easiest to write a function since I have so many columns and don't always have to add the same ones. Here an example of a dataframe:

ExampleData <- data.frame(Participant = 1:7,
                   Var1 = c(2, NA, 13, 15, 0, 2, NA),
                   Var2 = c(NA, NA, 1, 0, NA, 4, 2),
                   Var3 = c(6, NA, 1, 0, 1, 5, 3),
                   Var4 = c(12, NA, NA, 4, 10, 1, 4),
                   Var5 = c(10, NA, 3, 5, NA, 4, 4))

The conditions: If all values across a row are NA, the sum should be NA. If there is at least one value across a row that is a number (>= 0, or not NA), then rowSums should ignore NA's and add the values.

The best solution I've reached so far is:

addition <- function(x) {
  if(all(is.na(x))){
       NA
  }else{
       rowSums(x, na.rm = TRUE)
  }
}
addition(ExampleData[, c("Var1", "Var2", "Var3")])

The output is:  [1]  8  0 15 15  1 11  5

But it should be: [1] 8 NA 15 15 1 11 5

Does anyone know how to do this?
Thank you.

Body:
The reason is the all(is.na(x)) is checking whether all the elements of the dataset are NA instead of by rows.   If we check the output of is.na(data), it is a logical matrix.  A matrix is basically a vector with dimension attributes.  So, wrapping with all checks if all the elements are NA or not.

For example,

all(is.na(matrix(c(1:9, NA), 5, 2)))
#[1] FALSE

We can change the function to

 addition <- function(x) {
     rowSums(x, na.rm = TRUE) *  NA^(rowSums(!is.na(x))==0)

 }
addition(ExampleData[, c("Var1", "Var2", "Var3")])
#[1]  8 NA 15 15  1 11  5


问:
Migrating Data In Wagtail
I was wondering is there is any documentation or good resources on migrating Page models, Streamfields, and Blocks in wagtail CMS. All of this seems to not be documented much.</p>

答:
The official documentation has a page about StreamField, which has a section about migrations. It gives a fairly detailed description of how StreamField definitions differ from normal model fields, and the fact that migrations have been specially catered for in StreamField's design. I know that this was the biggest headache that the author faced when developing the feature.

There is also a handy guide on how to convert an existing RichTextField to a StreamField, and just yesterday, Wagtail pull request #3014 was merged, extending that documentation example.

Title: Migrating Data In Wagtail

ContentLicense: CC BY-SA 4.0


问:
How can I find the maximum value and its index in array in MATLAB?
Suppose I have an array, a = [2 5 4 7]. What is the function returning the maximum value and its index?

For example, in my case that function should return 7 as the maximum value and 4 as the index.

答:
For a matrix you can use this:

```<code>[M,I] = max(A(:))
</code>```

I is the index of A(:) containing the largest element.

Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.

```<code>[I_row, I_col] = ind2sub(size(A),I)
</code>```

source: https://www.mathworks.com/help/matlab/ref/max.html

Body:
For a matrix you can use this:

[M,I] = max(A(:))

I is the index of A(:) containing the largest element.

Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.

[I_row, I_col] = ind2sub(size(A),I)

source: https://www.mathworks.com/help/matlab/ref/max.html


问:
Inno Setup: how to use {app} in InitializeWizard Procedure
How can I gain access to the {app} variable in the InitializeWizard procedure ?

When I use ExpandConstant('{app}'); I get the next error message:

An attempt to expand the {app} constant was made before it was initialized

答:
Found the answer :)

Prototype:

function WizardDirValue: String;
```

Description:

Returns the current contents of the edit control on the Select Destination Location page of the wizard.

Unlike ExpandConstant('{app}'), this function will not fail if called after the wizard is shown but prior to the user selecting a directory. Rather, it will return the default directory name.

Body:
Found the answer :)

Prototype:

function WizardDirValue: String;

Description:

Returns the current contents of the edit control on the Select Destination Location page of the wizard.

Unlike ExpandConstant('{app}'), this function will not fail if called after the wizard is shown but prior to the user selecting a directory. Rather, it will return the default directory name.


问:
Remove all punctuation from string, except if it's between digits
I have a text that contains words and numbers. I'll give a representative example of the text:

```<code>string = "This is a 1example of the text. But, it only is 2.5 percent of all data"
</code>```

I'd like to convert it to something like:

```<code>"This is a  1 example of the text But it only is  2.5  percent of all data"
</code>```

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

```<code>item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item
</code>```

The result is :

```<code> >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"
</code>```

I'm almost there but can't figure out that last peace.

答:
This is a regex approach

([^ ]?)(?:[^\P{punct}.]|(?<!\d)\.(?!\d))([^ ]?)

Replace in a callback:

if $1 length > 0 and $2 length > 0

replace with  $1 + space + $2

else
replace with  $1$2

Expanded

```<code> ( [^ ]? )                     # (1)
 (?:
      [^\P{punct}.]
   |
      (?<! \d )
      \.
      (?! \d )
 )
 ( [^ ]? )                     # (2)
</code>```

If you don't want to use  logic for chars adjacent to punct

Use (?:[^\P{punct}.]|(?<!\d)\.(?!\d)) and replace with nothing.

Body:
I have a text that contains words and numbers. I'll give a representative example of the text:

string = "This is a 1example of the text. But, it only is 2.5 percent of all data"

I'd like to convert it to something like:

"This is a  1 example of the text But it only is  2.5  percent of all data"

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item

The result is :

 >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"

I'm almost there but can't figure out that last peace.

Body:
This is a regex approach

([^ ]?)(?:[^\P{punct}.]|(?<!\d)\.(?!\d))([^ ]?)

Replace in a callback:

if $1 length > 0 and $2 length > 0

replace with  $1 + space + $2

else
replace with  $1$2

Expanded

 ( [^ ]? )                     # (1)
 (?:
      [^\P{punct}.]
   |
      (?<! \d )
      \.
      (?! \d )
 )
 ( [^ ]? )                     # (2)

If you don't want to use  logic for chars adjacent to punct

Use (?:[^\P{punct}.]|(?<!\d)\.(?!\d)) and replace with nothing.


问:
Auto update Google Map from database
I have a MySQL database populated with latitude and longitude.

The data is plotted like a polyline on Google Maps.
Everything is working, but i don't know how to auto update the polyline when there is new data added.

I've tried to set interval on the function initmap, but that did not work.
I would appriciate if someone could help me with this.

```<code>  <!DOCTYPE html >
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <style>
      #map {
        height: 100%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>

   function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: new google.maps.LatLng(59.913063,10.750923),
      zoom: 10,
      mapTypeId : 'terrain'
    });

    var flightPlanCoordinates = [
        <?php
            require("dbcred.php");
            $connection = mysqli_connect($host, $username, $password, $database);

            mysqli_select_db($connection, $database);
            $query = mysqli_query($connection,"SELECT latitude, longitude FROM geografi");
            while($row = mysqli_fetch_assoc($query)){
                $lat = $row['latitude'];
                $lon = $row['longitude'];
                echo 'new google.maps.LatLng('.$lat.', '.$lon.'),';
            }
        ?>
    ];

   var flightPath = new google.maps.Polyline({
       path: flightPlanCoordinates,
       geodesic: true,
       strokeColor: '#FF0000',
       strokeOpacity: 1.0,
       strokeWeight: 2
       });
       flightPath.setMap(map);
   }

    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=GoogleKey&callback=initMap">
    </script>
  </body>
  </html>
</code>```

答:
I found the solution how to do it.

First i did like suggested by Ahmad - put the php in a different file, and made a ajax call. The ajax returned latitude and longitude.

Then I made a function that removed the existing polylines.
After that, I made a update function, that was called by ajax.

In the end, I made a interval function that called the remove function and the update function, by a set interval.

Title: Auto update Google Map from database

Body:
I have a MySQL database populated with latitude and longitude.

The data is plotted like a polyline on Google Maps.
Everything is working, but i don't know how to auto update the polyline when there is new data added.

I've tried to set interval on the function initmap, but that did not work.
I would appriciate if someone could help me with this.

  <!DOCTYPE html >

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>


问:
Why does this code (Python) only return one line?
I recently started programming and I wanted to sort a file, but in the end, this code only returns one line, even though the text file has 65 lines...</p>

```<code>f = open(".\\test.txt")
g, u = [], []
a = 0

for i, line in enumerate(f):
    a += 1
    if i%2 == 0:
        g.append(f.readlines()[i])
        print(i),
    elif i%2 == 1:
        u.append(f.readlines()[i])
        print(i),

print(u),
print(g)
</code>```

答:
You have to do</p>

```<code>lines = f.readlines()
for i, line in enumerate(lines):
    a += 1
    if i%2 == 0:
        g.append(lines[i])
        print(i),
    elif i%2 == 1:
        u.append(lines[i])
        print(i),
</code>```

Body:
I recently started programming and I wanted to sort a file, but in the end, this code only returns one line, even though the text file has 65 lines...

f = open(".\\test.txt")
g, u = [], []
a = 0

for i, line in enumerate(f):
    a += 1
    if i%2 == 0:
        g.append(f.readlines()[i])
        print(i),
    elif i%2 == 1:
        u.append(f.readlines()[i])
        print(i),

print(u),
print(g)

Body:
You have to do

lines = f.readlines()
for i, line in enumerate(lines):
    a += 1
    if i%2 == 0:
        g.append(lines[i])
        print(i),
    elif i%2 == 1:
        u.append(lines[i])
        print(i),


问:
SSIS (DT_Decimal) to (DT_Str) removes trailing zeros for decimals
When converting from DT_Decimal to DT_Str, the derived column stips off decimals from my result.

ex.:
-0.1250 returns -0.125
-2.0000 returns -2

Is there a way to keep the zeros to have a final string with always four decimals ?

Here is my derived column for the decimal value calculation:

```<code>(DT_DECIMAL,4)ROUND((DT_Decimal,4)[Column 1] / (DT_DECIMAL,4)@[User::rate],2)
</code>```

Here is my string expression to bring it to right aligned string with 11 characters:

```<code>RIGHT(REPLICATE(" ",11) + TRIM((DT_STR,11,1252)
(DT_DECIMAL,4)ROUND((DT_Decimal,4)[Column 1] / (DT_DECIMAL,4)@[User::rate],2)
),11)
</code>```

I'm using SSIS 2008.

Thanks in advance.
Francis

答:
What about testing for posision of "."
If greather than  append "0000" and take the left part of the string. The length argument for the Left function should be the position of "." plus 4

If zero then append ".0000"

Please be carefull when using division. If you divide by zero you get an error.
I normally divide by NULLIF(Rate, 0), and get NULL if I try to divide by zero.

ContentLicense: CC BY-SA 2.5

Body:
When converting from DT_Decimal to DT_Str, the derived column stips off decimals from my result.

ex.:
-0.1250 returns -0.125
-2.0000 returns -2

Is there a way to keep the zeros to have a final string with always four decimals ?

Here is my derived column for the decimal value calculation:

(DT_DECIMAL,4)ROUND((DT_Decimal,4)[Column 1] / (DT_DECIMAL,4)@[User::rate],2)

Here is my string expression to bring it to right aligned string with 11 characters:

RIGHT(REPLICATE(" ",11) + TRIM((DT_STR,11,1252)
(DT_DECIMAL,4)ROUND((DT_Decimal,4)[Column 1] / (DT_DECIMAL,4)@[User::rate],2)
),11)

I'm using SSIS 2008.

Thanks in advance.
Francis


答:
open(filename) gives you an iterator over the lines of a file. This iterator will be exhausted after reading all the lines once, any subsequent calls to readlines after the first one will therefore give you an empty list.

Demo:

```<code>>>> with open('testfile.txt') as f:
...     a = f.readlines()
...     b = f.readlines()
...     a
...     b
...
['hello\n', 'stack\n', 'overflow\n']
[]
</code>```

Title: Why does this code (Python) only return one line?

Body:
open(filename) gives you an iterator over the lines of a file. This iterator will be exhausted after reading all the lines once, any subsequent calls to readlines after the first one will therefore give you an empty list.

Demo:

>>> with open('testfile.txt') as f:
...     a = f.readlines()
...     b = f.readlines()
...     a
...     b
...
['hello\n', 'stack\n', 'overflow\n']
[]


问:
Need help to understand locking behaviour observed during DELETE in DB2 on z/OS
Examining the behaviour of two transactions launched from two DbVisualizer instances pointing at an instance of DB2 database on z/OS, I have noticed the following behaviour during deletion of records from tables.

Suppose I have a table MYTABLE with primary key MYID, and suppose that executing

select MYID from MYTABLE

gives something like (numbers are arbitrary and are written down just make things concrete)

```<code>112
119
...
...
789
...
</code>```

In trial A I execute, from the first transaction (using the first DBVisualizer instance) and without committing,

```<code>DELETE FROM MYTABLE WHERE MYID=112
</code>```

Then I execute from the second transaction (using the second DBVisualizer instance)

```<code>DELETE FROM MYTABLE WHERE MYID=119
</code>```

This however blocks the second transaction, and after some time produces the error

```<code>UNSUCCESSFUL EXECUTION CAUSED BY DEADLOCK OR TIMEOUT.
REASON CODE 00C9008E, TYPE OF RESOURCE 00000302, AND...
</code>```

In a similar trial, trial B, when I use MYIDs 112 and 789 instead (789 is "not  near" 112), the second transaction does not block. Looking up the meaning of TYPE OF RESOURCE 00000302 one finds, on https://www.ibm.com/support/knowledgecenter/en/SSEPEK_10.0.0/codes/src/tpc/db2z_resourcetypes.html, "Table space page" (the link is for DB2 on z/OS).

So it looks like in trial A, the first DELETE "locked" some "page" to which both records with MYID 112 and 119 "belonged", and that this lock blocked then the second transaction. While in trial B the two records belong to different "pages" and the first DELETE does not block the second.

Taking a well known book on DB2 I read "Depending on the operations requested, the database manager can acquire locks on table rows, table blocks, tables, table spaces, buffer pools, and databases". It is then explained that there are various "locking modes".

My question is: does "locks on table blocks" in the citation above refers to the observed in trial A "lock on table space pages", or it is some other lock type not mentioned in the citation?
And why at all the lock used is the "table space page lock" and not the row level lock which presumably would not cause the second transaction to block during trial A?
(I read about lock escalation in DB2, but as far as I know there were no transactions going on at that time which involved MYTABLE)

The DB2 version involved is 10 in "compatibility mode" which downgrades it to something like DB2 version 8. I think that the configuration should otherwise be "default" or "standard".

(This question is a result of my effort to understand a problem described in an earlier question Can one delete statement which deletes multiple rows cause deadlock?)

EDIT

Just tried that on DB2 Express on my Windows notebook, and the behaviour I see is different; the locks are row locks just as I would expect (so the second DELETE blocks only if I try to delete the same row). So is this indeed about DB2 on z/OS? Or is it the DB2 old version? Or perhaps the observation hints at some special configuration of DB2?

答:
I believe the default setting for a DB2 z/OS tablespace is LOCKSIZE ANY, which effectively means LOCKSIZE PAGE, that is, the entire tablespace page is locked if any row on that page is updated. Documentation reference. This would explain the behaviour you're seeing.

Issue (or ask your DBA to issue) an ALTER TABLESPACE ... LOCKSIZE ROW statement for the tablespace holding the table in question. For DB2 on z/OS it is common practice to have one table per tablespace, so this change should not have much effect on other workloads (unless you manage to use up all lock memory in the database).

In DB2 for LUW only row- and table-level locks are possible, so that also explains the difference you're seeing with DB2 Express on Windows.

Body:
Examining the behaviour of two transactions launched from two DbVisualizer instances pointing at an instance of DB2 database on z/OS, I have noticed the following behaviour during deletion of records from tables.

Suppose I have a table MYTABLE with primary key MYID, and suppose that executing

select MYID from MYTABLE

gives something like (numbers are arbitrary and are written down just make things concrete)

112
119
...
...
789
...

In trial A I execute, from the first transaction (using the first DBVisualizer instance) and without committing,

DELETE FROM MYTABLE WHERE MYID=112

Then I execute from the second transaction (using the second DBVisualizer instance)

DELETE FROM MYTABLE WHERE MYID=119

This however blocks the second transaction, and after some time produces the error

UNSUCCESSFUL EXECUTION CAUSED BY DEADLOCK OR TIMEOUT.
REASON CODE 00C9008E, TYPE OF RESOURCE 00000302, AND...

In a similar trial, trial B, when I use MYIDs 112 and 789 instead (789 is "not  near" 112), the second transaction does not block. Looking up the meaning of TYPE OF RESOURCE 00000302 one finds, on https://www.ibm.com/support/knowledgecenter/en/SSEPEK_10.0.0/codes/src/tpc/db2z_resourcetypes.html, "Table space page" (the link is for DB2 on z/OS).

So it looks like in trial A, the first DELETE "locked" some "page" to which both records with MYID 112 and 119 "belonged", and that this lock blocked then the second transaction. While in trial B the two records belong to different "pages" and the first DELETE does not block the second.

Taking a well known book on DB2 I read "Depending on the operations requested, the database manager can acquire locks on table rows, table blocks, tables, table spaces, buffer pools, and databases". It is then explained that there are various "locking modes".

My question is: does "locks on table blocks" in the citation above refers to the observed in trial A "lock on table space pages", or it is some other lock type not mentioned in the citation?
And why at all the lock used is the "table space page lock" and not the row level lock which presumably would not cause the second transaction to block during trial A?
(I read about lock escalation in DB2, but as far as I know there were no transactions going on at that time which involved MYTABLE)

The DB2 version involved is 10 in "compatibility mode" which downgrades it to something like DB2 version 8. I think that the configuration should otherwise be "default" or "standard".

(This question is a result of my effort to understand a problem described in an earlier question Can one delete statement which deletes multiple rows cause deadlock?)

EDIT

Just tried that on DB2 Express on my Windows notebook, and the behaviour I see is different; the locks are row locks just as I would expect (so the second DELETE blocks only if I try to delete the same row). So is this indeed about DB2 on z/OS? Or is it the DB2 old version? Or perhaps the observation hints at some special configuration of DB2?


问:
How to perform a multivariate linear regression when y is an indicator matrix in r?
this is the first time I am posting a question, hope it looks not confusing. And thanks very much for your time.

I am working on a zipcode dataset, which can be downloaded here:http://statweb.stanford.edu/~tibs/ElemStatLearn/datasets/zip.train.gz
http://statweb.stanford.edu/~tibs/ElemStatLearn/datasets/zip.test.gz

In general, my goal is to fit principle component regression model with the top 3 PCs on the train dataset for those response variable are the handwriting digits of 2, 3, 5, and 8, and then predict by using the test data. My main problem is that after performing PCA on the X matrix, I am not sure if I did the regression part correctly. I have turned the response variables into an 2487*4 indicator matrix, and want to fit a multivariate linear regression model. But the prediction results are not binomial indicators, so I am confused that how should I interpret the predictions back to the original response variables, i.e., which are predicted as 2, 3, 5, or 8. Or did I do the regression part totally wrong? Here are my code as follows:

First of all, I built the subset with those response variables are equal to 2, 3, 5, and 8:

```<code>zip_train <- read.table(gzfile("zip.train.gz"))
zip_test <- read.table(gzfile("zip.test.gz"))
train <- data.frame(zip_train)
train_sub <- train[which(train$V1 == 2 | train$V1 == 3 | train$V1 == 5 | train$V1 == 8),]
test <- data.frame(zip_test)
test_sub <- test[which(test$V1 == 2 | test$V1 == 3 | test$V1 == 5 | test$V1 == 8),]
xtrain <- train_sub[,-1]
xtest <- test_sub[,-1]
ytrain <- train_sub$V1
ytest <- test_sub$V1
</code>```

Second, I centered the X matrix, and calculated the top 3 principal components by using svd:

```<code>cxtrain <- scale(xtrain)
svd.xtrain <- svd(cxtrain)
cxtest <- scale(xtest)
svd.xtest <- svd(cxtest)

utrain.r3 <- svd.xtrain$u[,c(1:3)] # this is the u_r
vtrain.r3 <- svd.xtrain$v[,c(1:3)] # this is the v_r
dtrain.r3 <- svd.xtrain$d[c(1:3)]
Dtrain.r3 <- diag(x=dtrain.r3,ncol=3,nrow=3) # creat the diagonal matrix D with r=3
ztrain.r3 <- cxtrain %*% vtrain.r3 # this is the scores, the new components

utest.r3 <- svd.xtest$u[,c(1:3)]
vtest.r3 <- svd.xtest$v[,c(1:3)]
dtest.r3 <- svd.xtest$d[c(1:3)]
Dtest.r3 <- diag(x=dtest.r3,ncol=3,nrow=3)
ztest.r3 <- cxtest %*% vtest.r3
</code>```

Third, which is the part I was not sure if I did in the correct way, I turned the response variables into an indicator matrix, and performed a multivariate linear regression like this:

```<code>ytrain.ind <-cbind(I(ytrain==2)*1,I(ytrain==3)*1,I(ytrain==5)*1,I(ytrain==8)*1)
ytest.ind <- cbind(I(ytest==2)*1,I(ytest==3)*1,I(ytest==5)*1,I(ytest==8)*1)

mydata <- data.frame(cbind(ztrain.r3,ytrain.ind))
model_train <- lm(cbind(X4,X5,X6,X7)~X1+X2+X3,data=mydata)
new <- data.frame(ztest.r3)
pred <- predict(model_train,newdata=new)
</code>```

However, the pred was not an indicator matrix, so I am getting lost that how to interpret them back to the digits and compare them with the real test data to further calculate the prediction error.

答:
I finally figured out how to perform multivariate linear regression with categorical y. First we need to turn the y into an indicator matrix, so then we could interpret the 0 and 1 in this matrix as probabilities. And then regress y on x to build a linear model, and finally use this linear model to predict with the test set of x. The result is a matrix with same dimensions as our indicator matrix. And all the entries should be interpreted as probabilities too, although they could be larger than 1 or smaller than 0 (that's why it confused me before). So we need to find the maximum number per row, to see which predicted y has the highest probability, and this y would be our final prediction. In this way, we could convert the continuous numbers back into categories, and then make a table to compare with the test set of y. So I updated my previous code as below.

First of all, I built the subset with those response variables are equal to 2, 3, 5, and 8 (the code remains the same as the one I posted in my question):

```<code>zip_train <- read.table(gzfile("zip.train.gz"))
zip_test <- read.table(gzfile("zip.test.gz"))
train <- data.frame(zip_train)
train_sub <- train[which(train$V1 == 2 | train$V1 == 3 | train$V1 == 5 | train$V1 == 8),]
test <- data.frame(zip_test)
test_sub <- test[which(test$V1 == 2 | test$V1 == 3 | test$V1 == 5 | test$V1 == 8),]
xtrain <- train_sub[,-1]
xtest <- test_sub[,-1]
ytrain <- train_sub$V1
ytest <- test_sub$V1
</code>```

Second, I centered the X matrix, and calculated the top 3 principal components by using eigen(). I updated this part of code, because I standardized x instead of centering it in my previous code, leading to a wrong computation of the covariance matrix of x and eigenvectors of cov(x).

```<code>cxtrain <- scale(xtrain, center = TRUE, scale = FALSE)
eigenxtrain <- eigen(t(cxtrain) %*% cxtrain / (nrow(cxtrain) -1)) # same as get eigen(cov(xtrain)), because I have already centered x before
cxtest <- scale(xtest, center = TRUE, scale = FALSE)
eigenxtest <- eigen(t(cxtest) %*% cxtest/ (nrow(cxtest) -1))
r=3 # set r=3 to get top 3 principles
vtrain <- eigenxtrain$vectors[,c(1:r)]
ztrain <- scale(xtrain) %*% vtrain # this is the scores, the new componenets
vtest <- eigenxtrain$vectors[,c(1:r)]
ztest <- scale(xtest) %*% vtest
</code>```

Third, I turned the response variables into an indicator matrix, and performed a multivariate linear regression on the training set. And then use this linear model to predict.

```<code>ytrain.ind <- cbind(I(ytrain==2)*1,I(ytrain==3)*1,I(ytrain==5)*1,I(ytrain==8)*1)
ytest.ind <- cbind(I(ytest==2)*1,I(ytest==3)*1,I(ytest==5)*1,I(ytest==8)*1)

mydata <- data.frame(cbind(ztrain,ytrain.ind))
model_train <- lm(cbind(X4,X5,X6,X7)~X1+X2+X3,data=mydata)
new <- data.frame(ztest)
pred<- predict(model_train,newdata=new)
</code>```

The pred is a matrix with all the entries of probabilities, so we need to convert it back into a list of categorical y.

```<code>pred.ind <- matrix(rep(0,690*4),nrow=690,ncol=4) # build a matrix with the same dimensions as pred, and all the entries are 0.
for (i in 1:690){
  j=which.max(pred[i,]) # j is the column number of the highest probability per row
  pred.ind[i,j]=1 # we set 1 to the columns with highest probability per row, in this way, we could turn our pred matrix back into an indicator matrix
}

pred.col1=as.matrix(pred.ind[,1]*2) # first column are those predicted as digit 2
pred.col2=as.matrix(pred.ind[,2]*3)
pred.col3=as.matrix(pred.ind[,3]*5)
pred.col4=as.matrix(pred.ind[,4]*8)
pred.col5 <- cbind(pred.col1,pred.col2,pred.col3,pred.col4)

pred.list <- NULL
for (i in 1:690){
  pred.list[i]=max(pred.col5[i,])
} # In this way, we could finally get a list with categorical y

tt=table(pred.list,ytest)
err=(sum(tt)-sum(diag(tt)))/sum(tt) # error rate was 0.3289855
</code>```

For the third part, we could also perform a multinomial logistic regression instead. But in this way, we don't need to convert y into an indicator matrix, we just factor it. So the code looks as below:

```<code>library(nnet)
trainmodel <- data.frame(cbind(ztrain, ytrain))
mul <- multinom(factor(ytrain) ~., data=trainmodel)
new <- as.matrix(ztest)
colnames(new) <- colnames(trainmodel)[1:r]
predict<- predict(mul,new)
tt=table(predict,ytest)
err=(sum(tt)-sum(diag(tt)))/sum(tt) # error rate was 0.2627907
</code>```

So it showed that the logistic model do perform better than the linear model.

Body:
this is the first time I am posting a question, hope it looks not confusing. And thanks very much for your time.

I am working on a zipcode dataset, which can be downloaded here:http://statweb.stanford.edu/~tibs/ElemStatLearn/datasets/zip.train.gz
http://statweb.stanford.edu/~tibs/ElemStatLearn/datasets/zip.test.gz

In general, my goal is to fit principle component regression model with the top 3 PCs on the train dataset for those response variable are the handwriting digits of 2, 3, 5, and 8, and then predict by using the test data. My main problem is that after performing PCA on the X matrix, I am not sure if I did the regression part correctly. I have turned the response variables into an 2487*4 indicator matrix, and want to fit a multivariate linear regression model. But the prediction results are not binomial indicators, so I am confused that how should I interpret the predictions back to the original response variables, i.e., which are predicted as 2, 3, 5, or 8. Or did I do the regression part totally wrong? Here are my code as follows:

First of all, I built the subset with those response variables are equal to 2, 3, 5, and 8:

zip_train <- read.table(gzfile("zip.train.gz"))
zip_test <- read.table(gzfile("zip.test.gz"))
train <- data.frame(zip_train)
train_sub <- train[which(train$V1 == 2 | train$V1 == 3 | train$V1 == 5 | train$V1 == 8),]
test <- data.frame(zip_test)
test_sub <- test[which(test$V1 == 2 | test$V1 == 3 | test$V1 == 5 | test$V1 == 8),]
xtrain <- train_sub[,-1]
xtest <- test_sub[,-1]
ytrain <- train_sub$V1
ytest <- test_sub$V1

Second, I centered the X matrix, and calculated the top 3 principal components by using svd:

cxtrain <- scale(xtrain)
svd.xtrain <- svd(cxtrain)
cxtest <- scale(xtest)
svd.xtest <- svd(cxtest)

utrain.r3 <- svd.xtrain$u[,c(1:3)] # this is the u_r
vtrain.r3 <- svd.xtrain$v[,c(1:3)] # this is the v_r
dtrain.r3 <- svd.xtrain$d[c(1:3)]
Dtrain.r3 <- diag(x=dtrain.r3,ncol=3,nrow=3) # creat the diagonal matrix D with r=3
ztrain.r3 <- cxtrain %*% vtrain.r3 # this is the scores, the new components

utest.r3 <- svd.xtest$u[,c(1:3)]
vtest.r3 <- svd.xtest$v[,c(1:3)]
dtest.r3 <- svd.xtest$d[c(1:3)]
Dtest.r3 <- diag(x=dtest.r3,ncol=3,nrow=3)
ztest.r3 <- cxtest %*% vtest.r3

Third, which is the part I was not sure if I did in the correct way, I turned the response variables into an indicator matrix, and performed a multivariate linear regression like this:

ytrain.ind <-cbind(I(ytrain==2)*1,I(ytrain==3)*1,I(ytrain==5)*1,I(ytrain==8)*1)
ytest.ind <- cbind(I(ytest==2)*1,I(ytest==3)*1,I(ytest==5)*1,I(ytest==8)*1)

mydata <- data.frame(cbind(ztrain.r3,ytrain.ind))
model_train <- lm(cbind(X4,X5,X6,X7)~X1+X2+X3,data=mydata)
new <- data.frame(ztest.r3)
pred <- predict(model_train,newdata=new)

However, the pred was not an indicator matrix, so I am getting lost that how to interpret them back to the digits and compare them with the real test data to further calculate the prediction error.

Body:
I finally figured out how to perform multivariate linear regression with categorical y. First we need to turn the y into an indicator matrix, so then we could interpret the 0 and 1 in this matrix as probabilities. And then regress y on x to build a linear model, and finally use this linear model to predict with the test set of x. The result is a matrix with same dimensions as our indicator matrix. And all the entries should be interpreted as probabilities too, although they could be larger than 1 or smaller than 0 (that's why it confused me before). So we need to find the maximum number per row, to see which predicted y has the highest probability, and this y would be our final prediction. In this way, we could convert the continuous numbers back into categories, and then make a table to compare with the test set of y. So I updated my previous code as below.

First of all, I built the subset with those response variables are equal to 2, 3, 5, and 8 (the code remains the same as the one I posted in my question):

zip_train <- read.table(gzfile("zip.train.gz"))
zip_test <- read.table(gzfile("zip.test.gz"))
train <- data.frame(zip_train)
train_sub <- train[which(train$V1 == 2 | train$V1 == 3 | train$V1 == 5 | train$V1 == 8),]
test <- data.frame(zip_test)
test_sub <- test[which(test$V1 == 2 | test$V1 == 3 | test$V1 == 5 | test$V1 == 8),]
xtrain <- train_sub[,-1]
xtest <- test_sub[,-1]
ytrain <- train_sub$V1
ytest <- test_sub$V1

Second, I centered the X matrix, and calculated the top 3 principal components by using eigen(). I updated this part of code, because I standardized x instead of centering it in my previous code, leading to a wrong computation of the covariance matrix of x and eigenvectors of cov(x).

cxtrain <- scale(xtrain, center = TRUE, scale = FALSE)
eigenxtrain <- eigen(t(cxtrain) %*% cxtrain / (nrow(cxtrain) -1)) # same as get eigen(cov(xtrain)), because I have already centered x before
cxtest <- scale(xtest, center = TRUE, scale = FALSE)
eigenxtest <- eigen(t(cxtest) %*% cxtest/ (nrow(cxtest) -1))
r=3 # set r=3 to get top 3 principles
vtrain <- eigenxtrain$vectors[,c(1:r)]
ztrain <- scale(xtrain) %*% vtrain # this is the scores, the new componenets
vtest <- eigenxtrain$vectors[,c(1:r)]
ztest <- scale(xtest) %*% vtest

Third, I turned the response variables into an indicator matrix, and performed a multivariate linear regression on the training set. And then use this linear model to predict.

ytrain.ind <- cbind(I(ytrain==2)*1,I(ytrain==3)*1,I(ytrain==5)*1,I(ytrain==8)*1)
ytest.ind <- cbind(I(ytest==2)*1,I(ytest==3)*1,I(ytest==5)*1,I(ytest==8)*1)

mydata <- data.frame(cbind(ztrain,ytrain.ind))
model_train <- lm(cbind(X4,X5,X6,X7)~X1+X2+X3,data=mydata)
new <- data.frame(ztest)
pred<- predict(model_train,newdata=new)

The pred is a matrix with all the entries of probabilities, so we need to convert it back into a list of categorical y.

pred.ind <- matrix(rep(0,690*4),nrow=690,ncol=4) # build a matrix with the same dimensions as pred, and all the entries are 0.
for (i in 1:690){
  j=which.max(pred[i,]) # j is the column number of the highest probability per row
  pred.ind[i,j]=1 # we set 1 to the columns with highest probability per row, in this way, we could turn our pred matrix back into an indicator matrix
}

pred.col1=as.matrix(pred.ind[,1]*2) # first column are those predicted as digit 2
pred.col2=as.matrix(pred.ind[,2]*3)
pred.col3=as.matrix(pred.ind[,3]*5)
pred.col4=as.matrix(pred.ind[,4]*8)
pred.col5 <- cbind(pred.col1,pred.col2,pred.col3,pred.col4)

pred.list <- NULL
for (i in 1:690){
  pred.list[i]=max(pred.col5[i,])
} # In this way, we could finally get a list with categorical y

tt=table(pred.list,ytest)
err=(sum(tt)-sum(diag(tt)))/sum(tt) # error rate was 0.3289855

For the third part, we could also perform a multinomial logistic regression instead. But in this way, we don't need to convert y into an indicator matrix, we just factor it. So the code looks as below:

library(nnet)
trainmodel <- data.frame(cbind(ztrain, ytrain))
mul <- multinom(factor(ytrain) ~., data=trainmodel)
new <- as.matrix(ztest)
colnames(new) <- colnames(trainmodel)[1:r]
predict<- predict(mul,new)
tt=table(predict,ytest)
err=(sum(tt)-sum(diag(tt)))/sum(tt) # error rate was 0.2627907

So it showed that the logistic model do perform better than the linear model.


问:
Rails HABTM nested array in joins query?
I'm creating a REST api with Rails 5 that involves authors and media with a has_and_belongs_to_many relationship between them.

Here are the models:

```<code>class Author < ApplicationRecord
  has_and_belongs_to_many :media
end

class Medium < ApplicationRecord
  has_and_belongs_to_many :authors
end
</code>```

and here are the migrations:

```<code>class CreateMedia < ActiveRecord::Migration[5.0]
  def change
    create_table :media do |t|
      t.string :title
      t.text :description
      t.datetime :published_date
      t.string :type
      t.integer :pages
      t.time :length
      t.string :site
      t.timestamps
    end
  end
end

class CreateAuthors < ActiveRecord::Migration[5.0]
  def change
    create_table :authors do |t|
      t.string :first_name
      t.string :last_name
      t.text :bio
      t.string :site
      t.timestamps
    end
  end
end

class CreateJoinTableMediumAuthor < ActiveRecord::Migration[5.0]
  def change
    create_join_table :media, :authors do |t|
      t.index [:medium_id, :author_id]
      t.index [:author_id, :medium_id]
    end
  end
end
</code>```

The issue I'm having is I want to nest the authors in the media when making a general query and vice-versa, similar to what you can do in Laravel with Collections. I've looked everywhere and can't seem to find a solution.

To make it clearer here's a current example JSON response for a query for all media (Medium.all.includes(:authors)):

```<code>[
  {
    "id": 1,
    "title": "The Personal MBA",
    "description": "Master the art of business",
    "published_date": "2017-03-31T14:51:46.675Z",
    "pages": 400,
    "length": null,
    "site": null,
    "created_at": "2017-03-31T14:51:46.687Z",
    "updated_at": "2017-03-31T14:51:46.687Z"
  },
  {
    "id": 2,
    "title": "The Circle",
    "description": "A chlling and prophetic tale",
    "published_date": "2017-03-31T14:51:46.690Z",
    "pages": 333,
    "length": null,
    "site": null,
    "created_at": "2017-03-31T14:51:46.691Z",
    "updated_at": "2017-03-31T14:51:46.691Z"
  },
]
</code>```

where as I would like a response like this:

```<code>[
  {
    "id": 1,
    "title": "The Personal MBA",
    "description": "Master the art of business",
    "published_date": "2017-03-31T14:51:46.675Z",
    "pages": 400,
    "length": null,
    "site": null,
    "authors": [
      {
        "id": 1,
        "first_name": "Josh",
        "last_name": "Kaufman",
        "bio": "A business writer",
      },
      {
        "id": 2,
        "first_name": "Dave",
        "last_name": "Eggers",
        "bio": "fiction",
      }
    ]
    "created_at": "2017-03-31T14:51:46.687Z",
    "updated_at": "2017-03-31T14:51:46.687Z"
  },
  {
    "id": 2,
    "title": "The Circle",
    "description": "A chlling and prophetic tale",
    "published_date": "2017-03-31T14:51:46.690Z",
    "pages": 333,
    "length": null,
    "site": null,
    "authors": [
      {
        "id": 2,
        "first_name": "Dave",
        "last_name": "Eggers",
        "bio": "fiction",
      }
    ],
    "created_at": "2017-03-31T14:51:46.691Z",
    "updated_at": "2017-03-31T14:51:46.691Z"
  },
]
</code>```

The difference beings the authors array included in the response.

答:
```<code>class Medium < ApplicationRecord
  has_and_belongs_to_many :authors

  def details
    as_json(
     include: {authors: except: [:created_at, :updated_at]}
    )
  end
end
</code>```

Now call this details method. Example Medium.first.details, you will have your authors included in that object.

Body:
I'm creating a REST api with Rails 5 that involves authors and media with a has_and_belongs_to_many relationship between them.

Here are the models:

class Author < ApplicationRecord
  has_and_belongs_to_many :media
end

class Medium < ApplicationRecord
  has_and_belongs_to_many :authors
end

and here are the migrations:

class CreateMedia < ActiveRecord::Migration[5.0]
  def change
    create_table :media do |t|
      t.string :title
      t.text :description
      t.datetime :published_date
      t.string :type
      t.integer :pages
      t.time :length
      t.string :site
      t.timestamps
    end
  end
end

class CreateAuthors < ActiveRecord::Migration[5.0]
  def change
    create_table :authors do |t|
      t.string :first_name
      t.string :last_name
      t.text :bio
      t.string :site
      t.timestamps
    end
  end
end

class CreateJoinTableMediumAuthor < ActiveRecord::Migration[5.0]
  def change
    create_join_table :media, :authors do |t|
      t.index [:medium_id, :author_id]
      t.index [:author_id, :medium_id]
    end
  end
end

The issue I'm having is I want to nest the authors in the media when making a general query and vice-versa, similar to what you can do in Laravel with Collections. I've looked everywhere and can't seem to find a solution.

To make it clearer here's a current example JSON response for a query for all media (Medium.all.includes(:authors)):

[
  {
    "id": 1,
    "title": "The Personal MBA",
    "description": "Master the art of business",
    "published_date": "2017-03-31T14:51:46.675Z",
    "pages": 400,
    "length": null,
    "site": null,
    "created_at": "2017-03-31T14:51:46.687Z",
    "updated_at": "2017-03-31T14:51:46.687Z"
  },
  {
    "id": 2,
    "title": "The Circle",
    "description": "A chlling and prophetic tale",
    "published_date": "2017-03-31T14:51:46.690Z",
    "pages": 333,
    "length": null,
    "site": null,
    "created_at": "2017-03-31T14:51:46.691Z",
    "updated_at": "2017-03-31T14:51:46.691Z"
  },
]

where as I would like a response like this:

[
  {
    "id": 1,
    "title": "The Personal MBA",
    "description": "Master the art of business",
    "published_date": "2017-03-31T14:51:46.675Z",
    "pages": 400,
    "length": null,
    "site": null,
    "authors": [
      {
        "id": 1,
        "first_name": "Josh",
        "last_name": "Kaufman",
        "bio": "A business writer",
      },
      {
        "id": 2,
        "first_name": "Dave",
        "last_name": "Eggers",
        "bio": "fiction",
      }
    ]
    "created_at": "2017-03-31T14:51:46.687Z",
    "updated_at": "2017-03-31T14:51:46.687Z"
  },
  {
    "id": 2,
    "title": "The Circle",
    "description": "A chlling and prophetic tale",
    "published_date": "2017-03-31T14:51:46.690Z",
    "pages": 333,
    "length": null,
    "site": null,
    "authors": [
      {
        "id": 2,
        "first_name": "Dave",
        "last_name": "Eggers",
        "bio": "fiction",
      }
    ],
    "created_at": "2017-03-31T14:51:46.691Z",
    "updated_at": "2017-03-31T14:51:46.691Z"
  },
]

The difference beings the authors array included in the response.

Body:
class Medium < ApplicationRecord
  has_and_belongs_to_many :authors

  def details
    as_json(
     include: {authors: except: [:created_at, :updated_at]}
    )
  end
end

Now call this details method. Example Medium.first.details, you will have your authors included in that object.


问:
Saving data using where clause
I would like to be able to save data while providing a where clause.

I have the following code:

```<code>$game = $this->Games->newEntity();
if ($this->request->is('post')) {
    $game = $this->Games->patchEntity($game, $this->request->data);
    if ($this->Games->save($game)) {
        $this->Flash->success(__('The game has been saved.'));

        return $this->redirect(['action' => 'index']);
    } else {
        $this->Flash->error(__('The game could not be saved. Please, try again.'));
    }
}
</code>```

I tried this, but it didn't work:

```<code>$this->Games->save($game)->innerJoinWith('Leagues', function ($q) use($s) {
                    return $q->where(['Leagues.user_id' => $s]);
                }
            )
</code>```

I suspect having to do a find with a where clause and patch the request data to it?

```<code>$game = $this->Games->find()->innerJoinWith('Leagues', function ($q) {
    return $q->where(['Leagues.user_id' => $this->Auth->user('id')]);
})
->where(['Games.id' => $id])
->first();

if(! count($game)){
    $this->Flash->error(__('The game could not be found.'));
    return $this->redirect(['action' => 'index']);
}

if ($this->request->is('post')) {
    $game = $this->Games->patchEntity($game, $this->request->data);
    if ($this->Games->save($game)) {
        $this->Flash->success(__('The game has been saved.'));

        return $this->redirect(['action' => 'index']);
    } else {
        $this->Flash->error(__('The game could not be saved. Please, try again.'));
    }
}
</code>```

Anything simpler?

答:
There is no such saving syntax, retrieving the proper entity in beforehand is the correct way to go, and there isn't really a "simpler" way - however there surely is room for optimization.

Personally I'd use finders to DRY things up, ie create a finder on the GamesTable that restricts things to specific league users:

```<code>public function findForLeagueUser(\Cake\ORM\Query $query, array $options)
{
    if (!isset($options['id'])) {
        throw new \InvalidArgumentException('The `id` option is invalid or missing.');
    }

    return $query
        ->innerJoinWith('Leagues', function (\Cake\ORM\Query $query) use ($options) {
            return $query->where([
                $this->Leagues->aliasField('user_id') => $options['id']
            ]);
        });
}
</code>```

and combine things in the controller action:

```<code>$game = $this->Games
    ->find('forLeagueUser', ['id' => $this->Auth->user('id')])
    ->where(['Games.id' => $id])
    ->first();
</code>```

You could also use firstOrFail() instead, which throws an exception if the record cannot be found, this is what Table::get() does internally too.

And you could reduce things even further by using a dynamic finder for the games id:

```<code>$game = $this->Games
    ->findById($id)
    ->find('forLeagueUser', ['id' => $this->Auth->user('id')])
    ->first();
</code>```

See also

Cookbook > Database Access & ORM > Retrieving Data & ... > Using Finders to Load Data

Cookbook > Database Access & ORM > Retrieving Data & ... > Custom Finder Methods

Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Dynamic Finders

API > \Cake\Datasource\QueryTrait::firstOrFail()

Title: Saving data using where clause

Body:
I would like to be able to save data while providing a where clause.

I have the following code:

$game = $this->Games->newEntity();
if ($this->request->is('post')) {
    $game = $this->Games->patchEntity($game, $this->request->data);
    if ($this->Games->save($game)) {
        $this->Flash->success(__('The game has been saved.'));

        return $this->redirect(['action' => 'index']);
    } else {
        $this->Flash->error(__('The game could not be saved. Please, try again.'));
    }
}

I tried this, but it didn't work:

$this->Games->save($game)->innerJoinWith('Leagues', function ($q) use($s) {
                    return $q->where(['Leagues.user_id' => $s]);
                }
            )

I suspect having to do a find with a where clause and patch the request data to it?

$game = $this->Games->find()->innerJoinWith('Leagues', function ($q) {
    return $q->where(['Leagues.user_id' => $this->Auth->user('id')]);
})
->where(['Games.id' => $id])
->first();

if(! count($game)){
    $this->Flash->error(__('The game could not be found.'));
    return $this->redirect(['action' => 'index']);
}

if ($this->request->is('post')) {
    $game = $this->Games->patchEntity($game, $this->request->data);
    if ($this->Games->save($game)) {
        $this->Flash->success(__('The game has been saved.'));

        return $this->redirect(['action' => 'index']);
    } else {
        $this->Flash->error(__('The game could not be saved. Please, try again.'));
    }
}

Anything simpler?

Body:
There is no such saving syntax, retrieving the proper entity in beforehand is the correct way to go, and there isn't really a "simpler" way - however there surely is room for optimization.

Personally I'd use finders to DRY things up, ie create a finder on the GamesTable that restricts things to specific league users:

public function findForLeagueUser(\Cake\ORM\Query $query, array $options)
{
    if (!isset($options['id'])) {
        throw new \InvalidArgumentException('The `id` option is invalid or missing.');
    }

    return $query
        ->innerJoinWith('Leagues', function (\Cake\ORM\Query $query) use ($options) {
            return $query->where([
                $this->Leagues->aliasField('user_id') => $options['id']
            ]);
        });
}

and combine things in the controller action:

$game = $this->Games
    ->find('forLeagueUser', ['id' => $this->Auth->user('id')])
    ->where(['Games.id' => $id])
    ->first();

You could also use firstOrFail() instead, which throws an exception if the record cannot be found, this is what Table::get() does internally too.

And you could reduce things even further by using a dynamic finder for the games id:

$game = $this->Games
    ->findById($id)
    ->find('forLeagueUser', ['id' => $this->Auth->user('id')])
    ->first();

See also

Cookbook > Database Access & ORM > Retrieving Data & ... > Using Finders to Load Data

Cookbook > Database Access & ORM > Retrieving Data & ... > Custom Finder Methods

Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Dynamic Finders

API > \Cake\Datasource\QueryTrait::firstOrFail()


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
Inspired the word

BASIC Beginners All Purpose Symbolic Instruction Code

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych


问:
Use report components several times during report generation?
I'm maintaining a project which uses a pretty hefty Crystal Report and, during moving from VS2008 to VS2010, the report just stopped working at runtime (but it still Previews just fine. Go figure.), so I'm having to reconstruct it from the ground up.

During report creation, several parts of the report are used more than once. The following section shows the basic layout of the main report page (each bullet point represents a different section of the Main Report form), along with the behaviour of each section.

On Page 1

The first section of the main report form is empty, but the empty space in it appears not to print

The second section of the main report is printed

The third section of the main report is not printed

The fourth section of the main report is printed

Subreport A may be printed, depending on a data element

Subreport B is printed

SubReport C is not printed

Main report footer is printed

On Page 2

The first section of the main report form is empty, but the empty space in it appears not to print

The second section of the main report is printed

The third section of the main report is printed

The fourth section of the main report is not printed

Subreport A is not printed

Subreport B is not printed

SubReport C is printed several times, according to the number of rows returned by a query, one printing for each query

Main report footer is printed

If SubReport C is printed enough times, another copy of Page 2 will be printed, with the two main report sections (2 and 3) reprinted on each page.

What I want to know is where I can program these things to happen. I can't seem to see any code that's actually giving these instructions. The only code that's used to generate the report at runtime is, reportObject.ExportToDisk(), so it's not being done there.

答:
Go to Report->Section Expert and you'll see all the options you're talking about.  For each section & subsection, this is where you can suppress sections, move content to new pages , etc. (Once you're in there, you can F11 for help.)

To activate an option only on certain conditions (like the value of a field), use the X-2 button to enter the Formula Editor.  In most cases, you'll have to make a formula that results in a boolean value.


问:
SQL Create XML from a query without the Repeating of the tags
Im trying to write an sql query which generates xml and im nearly there but i need to be able to stop it from repeating the tags.

This is the query i am currently using

```<code>select DISTINCT
  objecttype.Type
, object.text
, objectelement.Value
, objectlanguage.CultureInfo
, isnull(objectelementtext.ElementText, objectelement.Value)
from [object] object
    inner join [objecttype] objecttype
        on object.ObjectTypeID = objecttype.ObjectTypeID
    inner join [ObjectElement] objectelement
        on object.ObjectID = objectelement.ObjectID
    outer APPLY
        (
            select objectlanguage.ObjectLanguageID,    objectlanguage.CultureInfo
                from [ObjectLanguage] objectlanguage
                where active = 1
        ) objectlanguage
    left join [ObjectElementText] objectelementtext
        on objectelementtext.ObjectElementID = objectelement.ObjectElementID
            and objectlanguage.ObjectLanguageID = objectelementtext.ObjectLanguageID
FOR XML AUTO, ELEMENTS, ROOT('Translations')
</code>```

So this generates the XML but it looks like the following.

```<code>    <Translations>
      <objecttype>
        <Type>Report</Type>
        <object>
  <text>TrayList</text>
  <objectelement>
    <Value>***** For Information Only *****</Value>
    <objectlanguage>
      <CultureInfo>en-gb</CultureInfo>***** For Information Only *****</objectlanguage>
    <objectlanguage>
      <CultureInfo>en-tt</CultureInfo>******** For Information Only *****</objectlanguage>
    <objectlanguage>
      <CultureInfo>en-us</CultureInfo>***** For Information Only *****</objectlanguage>
    <objectlanguage>
      <CultureInfo>it-it</CultureInfo>***** Solo Per Informazione *****</objectlanguage>
    <objectlanguage>
      <CultureInfo>zh-cn</CultureInfo>***** For Information Only *****</objectlanguage>
  </objectelement>
</code>```

What im trying to do is stop it from repeating the opening tags, so for example

```<code>    <objectlanguage>
        <CultureInfo ci="en-gb" text ="***** For Information Only*****"/>
        <CultureInfo ci="en-it" text ="***** For Information Only*****"/>
        <CultureInfo ci="en-us" text ="***** For Information Only*****"/>
        <CultureInfo ci="zn-cn" text ="***** For Information Only*****"/>
        <CultureInfo ci="it-tt" text ="***** For Information Only*****"/>
    </objectlanguage>
</code>```

Any help with this would be very much appreciated please, i think i am on the right lines but i need to tweak my query some how to tell it to not repeat them but i am unsure how.

答:
Your expected output is not valid XML. There is no <SomeElement="content"/> ...

Look at this example:

```<code>DECLARE @dummy TABLE(CultureInfo VARCHAR(100),SomeText VARCHAR(100));
INSERT INTO @dummy VALUES ('en-gb','Today is Friday')
                         ,('de-de','Heute ist Freitag');
SELECT CultureInfo AS [@ci]
      ,SomeText AS [@text]
FROM @dummy
FOR XML PATH('CultureInfo'),ROOT('objectlanguage');
</code>```

The result

```<code><objectlanguage>
  <CultureInfo ci="en-gb" text="Today is Friday" />
  <CultureInfo ci="de-de" text="Heute ist Freitag" />
</objectlanguage>
</code>```

You should prefer FOR XML PATH as it allows the most influence on the final structure. With FOR XML AUTO you let other people decide for you... And with ELEMENTS you force the engine to put your content in elements and not in attributes...

UPDATE

This is a blind flight, but you might try something like this

```<code>  select DISTINCT
  objecttype.Type
, object.text
, (
    SELECT CultureInfo AS [@ci]
          ,SomeText AS [@text]
    FROM ObjectLanguage
    WHERE active=1 AND ObjectLanguage.ObjectLanguageID=ObjectElement.ObjectLanguageID
    FOR XML PATH('CultureInfo'),ROOT('objectlanguage'),TYPE
  )
  --, more columns
  FROM ... the rest without objectLanguage
</code>```

Body:
Im trying to write an sql query which generates xml and im nearly there but i need to be able to stop it from repeating the tags.

This is the query i am currently using

select DISTINCT
  objecttype.Type
, object.text
, objectelement.Value
, objectlanguage.CultureInfo
, isnull(objectelementtext.ElementText, objectelement.Value)
from [object] object
    inner join [objecttype] objecttype
        on object.ObjectTypeID = objecttype.ObjectTypeID
    inner join [ObjectElement] objectelement
        on object.ObjectID = objectelement.ObjectID
    outer APPLY
        (
            select objectlanguage.ObjectLanguageID,    objectlanguage.CultureInfo
                from [ObjectLanguage] objectlanguage
                where active = 1
        ) objectlanguage
    left join [ObjectElementText] objectelementtext
        on objectelementtext.ObjectElementID = objectelement.ObjectElementID
            and objectlanguage.ObjectLanguageID = objectelementtext.ObjectLanguageID
FOR XML AUTO, ELEMENTS, ROOT('Translations')

So this generates the XML but it looks like the following.

    <Translations>
      <objecttype>
        <Type>Report</Type>
        <object>
  <text>TrayList</text>
  <objectelement>
    <Value>***** For Information Only *****</Value>
    <objectlanguage>
      <CultureInfo>en-gb</CultureInfo>***** For Information Only *****</objectlanguage>
    <objectlanguage>
      <CultureInfo>en-tt</CultureInfo>******** For Information Only *****</objectlanguage>
    <objectlanguage>
      <CultureInfo>en-us</CultureInfo>***** For Information Only *****</objectlanguage>
    <objectlanguage>
      <CultureInfo>it-it</CultureInfo>***** Solo Per Informazione *****</objectlanguage>
    <objectlanguage>
      <CultureInfo>zh-cn</CultureInfo>***** For Information Only *****</objectlanguage>
  </objectelement>

What im trying to do is stop it from repeating the opening tags, so for example

    <objectlanguage>
        <CultureInfo ci="en-gb" text ="***** For Information Only*****"/>
        <CultureInfo ci="en-it" text ="***** For Information Only*****"/>
        <CultureInfo ci="en-us" text ="***** For Information Only*****"/>
        <CultureInfo ci="zn-cn" text ="***** For Information Only*****"/>
        <CultureInfo ci="it-tt" text ="***** For Information Only*****"/>
    </objectlanguage>

Any help with this would be very much appreciated please, i think i am on the right lines but i need to tweak my query some how to tell it to not repeat them but i am unsure how.

Body:
Your expected output is not valid XML. There is no <SomeElement="content"/> ...

Look at this example:

DECLARE @dummy TABLE(CultureInfo VARCHAR(100),SomeText VARCHAR(100));
INSERT INTO @dummy VALUES ('en-gb','Today is Friday')
                         ,('de-de','Heute ist Freitag');
SELECT CultureInfo AS [@ci]
      ,SomeText AS [@text]
FROM @dummy
FOR XML PATH('CultureInfo'),ROOT('objectlanguage');

The result

<objectlanguage>
  <CultureInfo ci="en-gb" text="Today is Friday" />
  <CultureInfo ci="de-de" text="Heute ist Freitag" />
</objectlanguage>

You should prefer FOR XML PATH as it allows the most influence on the final structure. With FOR XML AUTO you let other people decide for you... And with ELEMENTS you force the engine to put your content in elements and not in attributes...

UPDATE

This is a blind flight, but you might try something like this

  select DISTINCT
  objecttype.Type
, object.text
, (
    SELECT CultureInfo AS [@ci]
          ,SomeText AS [@text]
    FROM ObjectLanguage
    WHERE active=1 AND ObjectLanguage.ObjectLanguageID=ObjectElement.ObjectLanguageID
    FOR XML PATH('CultureInfo'),ROOT('objectlanguage'),TYPE
  )
  --, more columns
  FROM ... the rest without objectLanguage


问:
Python Selenium, get elementtext xPath
I am stacked at the code where I need to print full text of
 element

```<code><h2>Product details</h2>
  <div class="content">

<ul>

    <li> <b>Paperback:</b> 288 pages</li>
    <li> <b>Publisher:</b> Pocket Books (October 1, 1998)</li>
    <li> <b>Language:</b> English</li>
    <li> <b>ISBN-10:</b> 0671027034</li>
    <li> <b>ISBN-13:</b> 978-0671027032</li>
    <li>  <b>Product Dimensions: </b>5.3 x 0.8 x 8.2 inches</li>

</ul>
</code>```

It's actually amazon product details.I am using xpath to find class that contains text "ISBN-10":

```<code>print driver.find_element_by_xpath("//*[contains(text(), 'ISBN-10')]").text
</code>```

It finds element great, but my output will be:

```<code>ISBN-10
</code>```

What should I use to get text that comes with ISBN-10 so my output should be:

```<code>ISBN-10: 0671027034
</code>```

I don't want to search for all
 elements and print [3] from list.

答:
Your XPath is pretty close. The issue is that you are looking for * as the element which in XPath terms means any element. If you look at the HTML, the match you are getting is the B tag,

```<code><b>ISBN-10:</b>
</code>```

because that's what matches. If you just change your XPath to look for the containing LI tag instead of *, you will get what you are looking for.

```<code>print driver.find_element_by_xpath("//li[contains(text(), 'ISBN-10')]").text
</code>```

Title: Python Selenium, get elementtext xPath

Body:
I am stacked at the code where I need to print full text of
 element

Product details

 Paperback: 288 pages

 Publisher: Pocket Books (October 1, 1998)

 Language: English

 ISBN-10: 0671027034

 ISBN-13: 978-0671027032

  Product Dimensions: 5.3 x 0.8 x 8.2 inches

It's actually amazon product details.I am using xpath to find class that contains text "ISBN-10":

print driver.find_element_by_xpath("//*[contains(text(), 'ISBN-10')]").text

It finds element great, but my output will be:

ISBN-10

What should I use to get text that comes with ISBN-10 so my output should be:

ISBN-10: 0671027034

I don't want to search for all
 elements and print [3] from list.

Body:
Your XPath is pretty close. The issue is that you are looking for * as the element which in XPath terms means any element. If you look at the HTML, the match you are getting is the B tag,

<b>ISBN-10:</b>

because that's what matches. If you just change your XPath to look for the containing LI tag instead of *, you will get what you are looking for.

print driver.find_element_by_xpath("//li[contains(text(), 'ISBN-10')]").text


问:
webview inside fragment android opening outside of the app in a browser
I got a webview in my app and it opens outside of it, while I want it to open inside... I've read all examples on stackoverflow and still don't know why it's like this

NewsFragment.java

```<code>import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

public class NewsFragment extends Fragment {

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

        View rootView = inflater.inflate(R.layout.news, container, false);

        WebView webView = (WebView)rootView.findViewById(R.id.webView);

        webView.setInitialScale(1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setScrollbarFadingEnabled(false);

        webView.loadUrl("https://www.google.com");

        return rootView;
    }
}
</code>```

XML file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
</code>```

答:
try this ...as when u click on web view in the fragment it won't ask you to open in a new browser application!! </p>

```<code>    String url = "https://www.google.co.in/";
    WebView view = (WebView) rootView.findViewById(R.id.webView1);

    view.getSettings().setJavaScriptEnabled(true);
    view.getSettings().setLoadWithOverviewMode(true);
    view.getSettings().setUseWideViewPort(true);
    view.getSettings().setBuiltInZoomControls(true);
    view.getSettings().setPluginState(WebSettings.PluginState.ON);
    view.setWebViewClient(new WebViewClient());

    view.loadUrl(url);

    return rootView ;
}
</code>```

Body:
I got a webview in my app and it opens outside of it, while I want it to open inside... I've read all examples on stackoverflow and still don't know why it's like this

NewsFragment.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

public class NewsFragment extends Fragment {

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

        View rootView = inflater.inflate(R.layout.news, container, false);

        WebView webView = (WebView)rootView.findViewById(R.id.webView);

        webView.setInitialScale(1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setScrollbarFadingEnabled(false);

        webView.loadUrl("https://www.google.com");

        return rootView;
    }
}

XML file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Body:
try this ...as when u click on web view in the fragment it won't ask you to open in a new browser application!!

    String url = "https://www.google.co.in/";
    WebView view = (WebView) rootView.findViewById(R.id.webView1);

    view.getSettings().setJavaScriptEnabled(true);
    view.getSettings().setLoadWithOverviewMode(true);
    view.getSettings().setUseWideViewPort(true);
    view.getSettings().setBuiltInZoomControls(true);
    view.getSettings().setPluginState(WebSettings.PluginState.ON);
    view.setWebViewClient(new WebViewClient());

    view.loadUrl(url);

    return rootView ;
}


问:
Trouble returning a vector array c++
I am fairly new to C++ so sorry if this is a simple question!

I am currently making a Sudoku solver. Each cell has a candidate list which is a set of values that it could possibly be. The candidate decreases by deleting values that are on the same row, column and block, till eventually there is only one single value in the candidate list, and that will be the cell's new solved value.

I have that part working, however another way the cell may be solved is by 'hidden values'. Hidden values are found by comparing the cell's candidate list, with the candidate lists from the cell's row, column or block. If the current cell has a value in it's candidate list which can not be found in any of the others, then that must be the cell's  solved value.

What I am having trouble with is returning the cell's candidate list so I can return it with others.

I have a cell class, and a cell group class. The cell group is basically a row, column or block. Each group contains 9 cells.

In the cell group class I have the following method:

```<code> int CellGroup::checkHiddenSinglesRow(Cell * cell) const
{
int candidateList[] = { cell->getCandidateList() }; //not returning correctly

 int hiddenSingle = 0;
for (int i = 0; i < 9; ++i)
{
    Cell *cells = m_cells[i];
    bool found = cells->SearchCandidateList(value);
    if (found == true) {

        hiddenSingle = hiddenSingle + 1;
    }
}
return hiddenSingle;
</code>```

}

The search candidate method basically goes through a cells candidate list and returns true if it has found the value, in the cell class:

```<code> bool Cell::SearchCandidateList(int value) {
bool found;
auto it = find(m_candidateList.begin(), m_candidateList.end(), value);
if (it != m_candidateList.end()) {
    found = true;
}
else {
    found = false;
}
return found;
</code>```

}

And this is the method I used to return the current cells candidate list, in the cell class:

```<code>   int Cell::getCandidateList(void) const
 {
for (auto i = m_candidateList.begin(); i != m_candidateList.end(); ++i) {
    int j;
    j = *i;
    return j;
}

}
</code>```

The getCandidateList is returning 1 which may be the first value in the candidate list.
It may be useful to return the list as an array so i can compare the values inside it, however I am unsure how to implement this.

Any help would be massively appreciated!

Thanks Lucy

答:
You can return vector like that:</p>

```<code>std::vector<int> Cell::getCandidateList() const
{
    return m_candidateList;
}
</code>```

Title: Trouble returning a vector array c++

Body:
I am fairly new to C++ so sorry if this is a simple question!

I am currently making a Sudoku solver. Each cell has a candidate list which is a set of values that it could possibly be. The candidate decreases by deleting values that are on the same row, column and block, till eventually there is only one single value in the candidate list, and that will be the cell's new solved value.

I have that part working, however another way the cell may be solved is by 'hidden values'. Hidden values are found by comparing the cell's candidate list, with the candidate lists from the cell's row, column or block. If the current cell has a value in it's candidate list which can not be found in any of the others, then that must be the cell's  solved value.

What I am having trouble with is returning the cell's candidate list so I can return it with others.

I have a cell class, and a cell group class. The cell group is basically a row, column or block. Each group contains 9 cells.

In the cell group class I have the following method:

 int CellGroup::checkHiddenSinglesRow(Cell * cell) const
{
int candidateList[] = { cell->getCandidateList() }; //not returning correctly

 int hiddenSingle = 0;
for (int i = 0; i < 9; ++i)
{
    Cell *cells = m_cells[i];
    bool found = cells->SearchCandidateList(value);
    if (found == true) {

        hiddenSingle = hiddenSingle + 1;
    }
}
return hiddenSingle;

}

The search candidate method basically goes through a cells candidate list and returns true if it has found the value, in the cell class:

 bool Cell::SearchCandidateList(int value) {
bool found;
auto it = find(m_candidateList.begin(), m_candidateList.end(), value);
if (it != m_candidateList.end()) {
    found = true;
}
else {
    found = false;
}
return found;

}

And this is the method I used to return the current cells candidate list, in the cell class:

   int Cell::getCandidateList(void) const
 {
for (auto i = m_candidateList.begin(); i != m_candidateList.end(); ++i) {
    int j;
    j = *i;
    return j;
}

}

The getCandidateList is returning 1 which may be the first value in the candidate list.
It may be useful to return the list as an array so i can compare the values inside it, however I am unsure how to implement this.

Any help would be massively appreciated!

Thanks Lucy

Body:
You can return vector like that:

std::vector<int> Cell::getCandidateList() const
{
    return m_candidateList;
}


问:
Tomcat 8 Oracle 11 JNDI Cannot create JDBC driver of class '' for connect URL 'null'
I'm trying to set up a Spring 4 MVC application in STS using a Tomcat 8 server and an Oracle 11g database, and I'm having problems setting up the datasource.

I know there's nothing wrong with the Spring setup because, without the datasource, it works fine.

Here's the datasource bean:

```<code><bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/myDB" />
    <property name="resourceRef" value="false" />
</bean>
</code>```

My web.xml resource ref:

```<code><resource-ref>
   <res-ref-name>jdbc/myDB</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth>
</resource-ref>
</code>```

My Tomcat's server.xml resources:

-->

```<code><Resource name="jdbc/myDB"
          global="jdbc/myDB"
          auth="Container"
          type="javax.sql.DataSource"
          username="xxxxx"
          password="yyyyyy"
          url="jdbc:oracle:thin:@xxx.yyy"
          driverClassName="oracle.jdbc.OracleDriver"
          initialSize="20"
          maxWaitMillis="15000"
          maxTotal="75"
          maxIdle="20"
          maxAge="7200000"
          testOnBorrow="true"
          validationQuery="select 1 from dual"
          />
</code>```

And my context.xml

```<code>  <ResourceLink name="jdbc/myDB"
    global="jdbc/myDB"
    type="javax.sql.DataSource"/>
</code>```

The error I'm getting is this:

ERROR: Unable obtain JDBC Connection java.sql.SQLException: Cannot
  create JDBC driver of class '' for connect URL 'null'     at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2167)
    at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2037)
    at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
    at
  org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
    at
  org.hibernate.internal.SessionFactoryImpl$1.obtainConnection(SessionFactoryImpl.java:419)
    at
  org.hibernate.hql.spi.id.IdTableHelper.executeIdTableCreationStatements(IdTableHelper.java:67)
    at
  org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:125)
    at
  org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:42)
    at
  org.hibernate.hql.spi.id.AbstractMultiTableBulkIdStrategyImpl.prepare(AbstractMultiTableBulkIdStrategyImpl.java:88)
    at
  org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:302)
    at
  org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
    at
  org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
    at
  org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
    at
  org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:511)
    at
  org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:495)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
    at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at
  org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at
  org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    at
  org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    at
  org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    at
  org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at
  org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4940)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5250)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at java.util.concurrent.FutureTask.run(Unknown Source)  at
  java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)     at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)    at
  java.lang.Thread.run(Unknown Source) Caused by: java.sql.SQLException:
  No suitable driver    at java.sql.DriverManager.getDriver(Unknown
  Source)   at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2151)
    ... 44 more

My Tomcat lib directory has the ojdbc jar that I need,  and I've even included it on my build script. What could be causing this?

答: The solution was as simple as it was embarrassingly stupid. Since I was working in Eclipse, Eclipse generates and uses its own server.xml and context.xml documents in a Servers directory. Once I put my datasource into those files, everything worked fine</p>

Body:
I'm trying to set up a Spring 4 MVC application in STS using a Tomcat 8 server and an Oracle 11g database, and I'm having problems setting up the datasource.

I know there's nothing wrong with the Spring setup because, without the datasource, it works fine.

Here's the datasource bean:

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/myDB" />
    <property name="resourceRef" value="false" />
</bean>

My web.xml resource ref:

<resource-ref>
   <res-ref-name>jdbc/myDB</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth>
</resource-ref>

My Tomcat's server.xml resources:

-->

<Resource name="jdbc/myDB"
          global="jdbc/myDB"
          auth="Container"
          type="javax.sql.DataSource"
          username="xxxxx"
          password="yyyyyy"
          url="jdbc:oracle:thin:@xxx.yyy"
          driverClassName="oracle.jdbc.OracleDriver"
          initialSize="20"
          maxWaitMillis="15000"
          maxTotal="75"
          maxIdle="20"
          maxAge="7200000"
          testOnBorrow="true"
          validationQuery="select 1 from dual"
          />

And my context.xml

  <ResourceLink name="jdbc/myDB"
    global="jdbc/myDB"
    type="javax.sql.DataSource"/>

The error I'm getting is this:

ERROR: Unable obtain JDBC Connection java.sql.SQLException: Cannot
  create JDBC driver of class '' for connect URL 'null'     at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2167)
    at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2037)
    at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
    at
  org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
    at
  org.hibernate.internal.SessionFactoryImpl$1.obtainConnection(SessionFactoryImpl.java:419)
    at
  org.hibernate.hql.spi.id.IdTableHelper.executeIdTableCreationStatements(IdTableHelper.java:67)
    at
  org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:125)
    at
  org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:42)
    at
  org.hibernate.hql.spi.id.AbstractMultiTableBulkIdStrategyImpl.prepare(AbstractMultiTableBulkIdStrategyImpl.java:88)
    at
  org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:302)
    at
  org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
    at
  org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
    at
  org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
    at
  org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:511)
    at
  org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:495)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
    at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at
  org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
    at
  org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
    at
  org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
    at
  org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
    at
  org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
    at
  org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)   at
  org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4940)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5250)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at java.util.concurrent.FutureTask.run(Unknown Source)  at
  java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)     at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)    at
  java.lang.Thread.run(Unknown Source) Caused by: java.sql.SQLException:
  No suitable driver    at java.sql.DriverManager.getDriver(Unknown
  Source)   at
  org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2151)
    ... 44 more

My Tomcat lib directory has the ojdbc jar that I need,  and I've even included it on my build script. What could be causing this?


答: Your for loop starts reading the file line by line. But then its contents go and read the rest of the file in a single readlines call; after that, there's nothing more to be read! So you end up with the first line in line and the second line in g, since you only kept one of the lines that readlines() read.

Body:
I recently started programming and I wanted to sort a file, but in the end, this code only returns one line, even though the text file has 65 lines...

f = open(".\\test.txt")
g, u = [], []
a = 0

for i, line in enumerate(f):
    a += 1
    if i%2 == 0:
        g.append(f.readlines()[i])
        print(i),
    elif i%2 == 1:
        u.append(f.readlines()[i])
        print(i),

print(u),
print(g)


问:
about synchronization with two threads
Say one singleton instance accessed by two threads. Two threads are accessing the same function called doTask().

```<code>public class MySingleton {
    Object lock = new Object();
    // I omit the constructor here.

    public void doTask() {
         //first non-synchronized code

         synchronize(lock) {
             //some heavy task
         }

         //final non-synchronized code
    }
}
</code>```

If thread B is doing the heavy task, when thread A access doTask(), I know Thread A will run the //first non-synchronized code, then thread A noticed the lock is acquired by Thread B, so it can't run synchronized //some heavy task. But would thread A skip the synchronized heavy task continue run //final non-synchronized code or will thread A wait for the lock without even executing the //final non-synchronized code?

(I know I can try it out, but currently I don't have a proper development environment...)

答:
The synchronized block in java forces threads to wait until they can acquire the object's lock.

It will wait until B is done, and then snag the lock for lock, and run the code inside the block, and continue out the other end.

It is important to note that when B finishes executing the contents of some heavy task it will release the lock on lock and run the final non-synchronized code at the "same time" that A runs the synchronized block.

Title: about synchronization with two threads

Body:
Say one singleton instance accessed by two threads. Two threads are accessing the same function called doTask().

public class MySingleton {
    Object lock = new Object();
    // I omit the constructor here.

    public void doTask() {
         //first non-synchronized code

         synchronize(lock) {
             //some heavy task
         }

         //final non-synchronized code
    }
}

If thread B is doing the heavy task, when thread A access doTask(), I know Thread A will run the //first non-synchronized code, then thread A noticed the lock is acquired by Thread B, so it can't run synchronized //some heavy task. But would thread A skip the synchronized heavy task continue run //final non-synchronized code or will thread A wait for the lock without even executing the //final non-synchronized code?

(I know I can try it out, but currently I don't have a proper development environment...)