问:
Inflating WebView is slow since Lollipop
In fact I am surprised that I found no similar question in Stackoverflow, but I really can't figure it out.

First of all, please be reminded that this is not related to the performance of browsing webpage inside a WebView. It is only about inflating even an empty WebView, without loading any URL.

To eliminate all other factors, I have created a brand new project which contains things only necessary to reproduce the problem.

In this almost empty project, I have a layout which contains only a WebView:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.testing.WebViewOnlyActivity">

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

</FrameLayout>
</code>```

And I have a MainActivity which contains only a Button which starts this WebViewOnlyActivity:

```<code>public class MainActivity extends AppCompatActivity {

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

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, WebViewOnlyActivity.class);
                startActivity(intent);
            }
        });
    }
}
</code>```

Simple enough, right?

Now, when I build the project, click the button, the WebViewOnlyActivity takes more than 1 second to popup. But then if I press back button, and press the button again, the WebViewOnlyActivity appears immediately. Apparently Android cached something of WebView.

Here are my testing devices:

1. Android 7.1.1: Slow

2. Android 7.0.0: Slow

3. Android 5.0.2 Slow

4. Android 4.4.1 Fast

So it appears to me this only happens since Lollipop.

However, such 1.x second delay is still unacceptable to me. Does anyone knows how to solve it? (Well, I think it is hard because I did nothing to this WebView... May be I should use some 3rd party WebView?)

P.S. I have also used traceview to see what are the differences between a 7.1.1 device and 4.4.1 Device. It is clear that WebView's init() method is taking up a lot of time.

7.1.1:

And further deeper:

4.4.1:

And further deeper:

Big Difference!

Although it is really empty, but requested by Axel, I will post the code for WebViewOnlyActivity as well:

```<code>public class WebViewOnlyActivity extends AppCompatActivity {

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

    }
}
</code>```

答:
EDIT 2017-12-21

I even created a library to tackle this problem easily.

You may download it here.

Give it a star if you find it useful :P

Thanks to @XavierRubioJansana 's hint, I tried ViewStub to delay the inflation.

However, even if I delay the inflation to onResume(), it will still slows the activity creation.

But then if I use a Handler to postDelay the inflation, activity creates immediately!

```<code>    Handler webViewInflateHandler = new Handler();
    webViewInflateHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!webViewInflated) {
                webView = (WebView) webViewStub.inflate();
                webViewInflated = true;
            }
        }
    }, 50);
</code>```

Then, you need to delay all kinds of setup and loading of WebView until it is inflated. I will suggest using RxJava here to observe an BehaviorSubject<Boolean>.

Body:
In fact I am surprised that I found no similar question in Stackoverflow, but I really can't figure it out.

First of all, please be reminded that this is not related to the performance of browsing webpage inside a WebView. It is only about inflating even an empty WebView, without loading any URL.

To eliminate all other factors, I have created a brand new project which contains things only necessary to reproduce the problem.

In this almost empty project, I have a layout which contains only a WebView:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.testing.WebViewOnlyActivity">

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

</FrameLayout>

And I have a MainActivity which contains only a Button which starts this WebViewOnlyActivity:

public class MainActivity extends AppCompatActivity {

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

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, WebViewOnlyActivity.class);
                startActivity(intent);
            }
        });
    }
}

Simple enough, right?

Now, when I build the project, click the button, the WebViewOnlyActivity takes more than 1 second to popup. But then if I press back button, and press the button again, the WebViewOnlyActivity appears immediately. Apparently Android cached something of WebView.

Here are my testing devices:

1. Android 7.1.1: Slow

2. Android 7.0.0: Slow

3. Android 5.0.2 Slow

4. Android 4.4.1 Fast

So it appears to me this only happens since Lollipop.

However, such 1.x second delay is still unacceptable to me. Does anyone knows how to solve it? (Well, I think it is hard because I did nothing to this WebView... May be I should use some 3rd party WebView?)

P.S. I have also used traceview to see what are the differences between a 7.1.1 device and 4.4.1 Device. It is clear that WebView's init() method is taking up a lot of time.

7.1.1:

And further deeper:

4.4.1:

And further deeper:

Big Difference!

Although it is really empty, but requested by Axel, I will post the code for WebViewOnlyActivity as well:

public class WebViewOnlyActivity extends AppCompatActivity {

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

    }
}

Body:
EDIT 2017-12-21

I even created a library to tackle this problem easily.

You may download it here.

Give it a star if you find it useful :P

Thanks to @XavierRubioJansana 's hint, I tried ViewStub to delay the inflation.

However, even if I delay the inflation to onResume(), it will still slows the activity creation.

But then if I use a Handler to postDelay the inflation, activity creates immediately!

    Handler webViewInflateHandler = new Handler();
    webViewInflateHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!webViewInflated) {
                webView = (WebView) webViewStub.inflate();
                webViewInflated = true;
            }
        }
    }, 50);

Then, you need to delay all kinds of setup and loading of WebView until it is inflated. I will suggest using RxJava here to observe an BehaviorSubject<Boolean>.


来源: stackexchange

问:
Why got Object when use map to get length of each string element
I am learning Java 8. So I write code like this:

```<code>@Test
public void getLengthOfEachString() throws Exception {
    String[] strings = {"I", "am", "IronMan"};
    Object[] lengthOfStrings = Arrays.stream(strings).map(String::length).toArray();
    assertThat(lengths, is(new int[]{1, 2, 7}));
}
</code>```

I found lengthOfStrings can't be int[]

Why?

答:
Because the types do not match, you can fix by mapping to int instead of Object (and then int[] instead of Object[]). Change

```<code>Object[] lengthOfStrings = Arrays.stream(strings).map(String::length).toArray();
assertThat(lengths, is(new int[]{1, 2, 7}));
</code>```

to (and don't forget the variable names need to match) something like

```<code>int[] lengthOfStrings = Arrays.stream(strings).mapToInt(String::length).toArray();
assertThat(lengthOfStrings, is(new int[]{1, 2, 7}));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am learning Java 8. So I write code like this:

@Test
public void getLengthOfEachString() throws Exception {
    String[] strings = {"I", "am", "IronMan"};
    Object[] lengthOfStrings = Arrays.stream(strings).map(String::length).toArray();
    assertThat(lengths, is(new int[]{1, 2, 7}));
}

I found lengthOfStrings can't be int[]

Why?

Body:
Because the types do not match, you can fix by mapping to int instead of Object (and then int[] instead of Object[]). Change

Object[] lengthOfStrings = Arrays.stream(strings).map(String::length).toArray();
assertThat(lengths, is(new int[]{1, 2, 7}));

to (and don't forget the variable names need to match) something like

int[] lengthOfStrings = Arrays.stream(strings).mapToInt(String::length).toArray();
assertThat(lengthOfStrings, is(new int[]{1, 2, 7}));


问:
ReactNative: how to center text?
How to center Text in ReactNative both in horizontal and vertical?

I have an example application in rnplay.org where justifyContent="center" and alignItems="center" is not working:
https://rnplay.org/apps/AoxNKQ

The text should being centered.
And why is there a margin at the top between the text (yellow) and parent container?

Code:

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  Image,
  View,
} = React;

var SampleApp = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <View style={styles.topBox}>
          <Text style={styles.headline}>
            lorem ipsum{'\n'}
            ipsum lorem lorem
          </Text>
        </View>
        <View style={styles.otherContainer}>
        </View>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: 'red',
    justifyContent: 'center',
    alignItems: 'center',
  },
  topBox: {
    flex: 1,
    flexDirection: 'row',
    backgroundColor: 'lightgray',
    justifyContent: 'center',
    alignItems: 'center',
  },
  headline: {
    fontWeight: 'bold',
    fontSize: 18,
  marginTop: 0,
    width: 200,
    height: 80,
  backgroundColor: 'yellow',
    justifyContent: 'center',
    alignItems: 'center',
  },
  otherContainer: {
    flex: 4,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'green',
  },
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);

module.exports = SampleApp;
```

答:
const styles = StyleSheet.create({
        navigationView: {
        height: 44,
        width: '100%',
        backgroundColor:'darkgray',
        justifyContent: 'center',
        alignItems: 'center'
    },
    titleText: {
        fontSize: 20,
        fontWeight: 'bold',
        color: 'white',
        textAlign: 'center',
    },
})

render() {
    return (
        <View style = { styles.navigationView }>
            <Text style = { styles.titleText } > Title name here </Text>
        </View>
    )

}
```

ContentLicense: CC BY-SA 4.0

Title: ReactNative: how to center text?


问:
Allow non-admin users to created CouchDB databases
I'm using CouchDB 2.1.0 and for my use case I would like non-admin users to be able to create their own databases that they will then have write/read access to, and the ability to add other users with write/read access.

Note that this is not one database per user, which seems to be the common use case, but many user-created databases per user.

Users are being created right now by POSTing to the _users database. Authentication is being handled by CouchDB's built-in authentication.

I could create a backend service that has admin credentials that would create these databases, but I would like to avoid doing so. Reading through docs it seems like by default CouchDB only allows admins to create databases; is there a way to change this?

答:
Honestly, I think the only real answer here is that you'll have to make a backend service that has admin credentials that can create new databases. Kind of a bummer since one of my goals for this project was "no backend other than CouchDB".

My backend service ended up just taking a list of users that should have access to the created database, creating the database with a unique ID, and returning that ID. I then have a document in each user's DB that lists all of the DBs they have created.


问:
phpDocumentor on legacy code
Can phpDocumentor be used to generate HTML docs for some legacy code that does not necessarily conform to its standard?

I'd like to generate some preliminary documentation for an old code tree and later on start improving my comments and add the appropriate @ tags as I get fluent with phpDocumentor. I've never used this piece of software before and the examples I've found focus on how to write new code that conforms to its syntax and generate HTML file by file with the -f parameter.

I've installed latest phpDocumentor through the PEAR command line installer and tried this little *.bat file on Windows XP:

```<code>@echo off
phpdoc ^
    --directory "\\server\project\trunk" ^
    --target "C:\tests\project-doc"
</code>```

... but this is all I get:

```<code>PHP Version 5.3.5
phpDocumentor version 1.4.3

Parsing configuration file phpDocumentor.ini...
   (found in C:\Archivos de programa\PHP\pear\data/PhpDocumentor/)...

done
Maximum memory usage set at 256M after considering php.ini...
using tokenizer Parser
directory: ''  not found
</code>```

I've also tried mapping the UNC path to a drive letter:

```<code>@echo off
phpdoc ^
    --directory "I:\" ^
    --target "C:\tests\project-doc"
</code>```

... but:

```<code>PHP Version 5.3.5
phpDocumentor version 1.4.3

Parsing configuration file phpDocumentor.ini...
   (found in C:\Archivos de programa\PHP\pear\data/PhpDocumentor/)...

done
Maximum memory usage set at 256M after considering php.ini...
using tokenizer Parser
a target directory must be specified
 try phpdoc -h
</code>```

This error message is the same if I create "C:\tests\project-doc" before.

What's exactly wrong in my syntax?

答:
phpDocumentor can indeed run against "undocumented" code.  It builds its docs based on the code itself, and uses the docblocks as additional info (and additional organization, in the case of @package and @subpackage tags).

I'd suggest starting with phpDocumentor against your existing code, and work towards clearing out the warnings you see in the errors.html file that results -- this file is generated in the top level of your output docs, but there isn't any link to it from the output docs.

Once you have those cleared, you can start running phpDocumentor with the -ue argument (--undocumentedelements), which will add new warnings to errors.html, highlighting (in much greater detail) things that still need to be documented in docblocks.

Now, as for the issue you're having trying to run the program against code on a shared drive, I'm not sure what's wrong there.  The script is clearly able to execute PHP and find the phpDocumentor code itself.  You might try putting the arguments in the same line, rather than using the ^ as a line-feed escape character, and perhaps remove the quotes around the paths (since no spaces exist in the paths).

ContentLicense: CC BY-SA 2.5

Title: phpDocumentor on legacy code

Body:
Can phpDocumentor be used to generate HTML docs for some legacy code that does not necessarily conform to its standard?

I'd like to generate some preliminary documentation for an old code tree and later on start improving my comments and add the appropriate @ tags as I get fluent with phpDocumentor. I've never used this piece of software before and the examples I've found focus on how to write new code that conforms to its syntax and generate HTML file by file with the -f parameter.

I've installed latest phpDocumentor through the PEAR command line installer and tried this little *.bat file on Windows XP:

@echo off
phpdoc ^
    --directory "\\server\project\trunk" ^
    --target "C:\tests\project-doc"

... but this is all I get:

PHP Version 5.3.5
phpDocumentor version 1.4.3

Parsing configuration file phpDocumentor.ini...
   (found in C:\Archivos de programa\PHP\pear\data/PhpDocumentor/)...

done
Maximum memory usage set at 256M after considering php.ini...
using tokenizer Parser
directory: ''  not found

I've also tried mapping the UNC path to a drive letter:

@echo off
phpdoc ^
    --directory "I:\" ^
    --target "C:\tests\project-doc"

... but:

PHP Version 5.3.5
phpDocumentor version 1.4.3

Parsing configuration file phpDocumentor.ini...
   (found in C:\Archivos de programa\PHP\pear\data/PhpDocumentor/)...

done
Maximum memory usage set at 256M after considering php.ini...
using tokenizer Parser
a target directory must be specified
 try phpdoc -h

This error message is the same if I create "C:\tests\project-doc" before.

What's exactly wrong in my syntax?


问:
mysql database value as select id
I am trying to assign an ID to values to be posted with the submit tag

```<code>$query = "SELECT * FROM `events`";
$result2 = mysqli_query($connect, $query);

$options = "";
while($row2 = mysqli_fetch_array($result2))
{
    $options = $options."<option>$row2[1] $row2[2]</option>";
}
</code>```

```<code><select>
    <?php echo $options;?>
</select>
</code>```

Doing this outputs the event name and the date it will take place ( 2nd and 3rd item in my mysql database. This later gets used in a form and lists these as options for someone to pick. I was wondering if there was a way to add a proper value= to them. The first thing in my mysql database is a random generated ID for each "event" but I can't figure out how to echo the id of each event in the option tag without it breaking.

答:
First, when using positional results (ie $row2[0], $row2[1], etc), you should be explicit in your SELECT query to guarantee order, ie

```<code>SELECT `ID`, `name`, `date` FROM `events`
</code>```

Really all you need is to interpolate whatever dynamic values you need into the HTML string.

It's best to use something like htmlspecialchars() in these cases to avoid issues with markup. For example

```<code>while($row2 = mysqli_fetch_array($result2)) {
    $options .= vsprintf('<option value="%s">%s %s</option>',
        array_map('htmlspecialchars', $row2));
}
</code>```

Title: mysql database value as select id

Body:
I am trying to assign an ID to values to be posted with the submit tag

$query = "SELECT * FROM `events`";
$result2 = mysqli_query($connect, $query);

$options = "";
while($row2 = mysqli_fetch_array($result2))
{
    $options = $options."<option>$row2[1] $row2[2]</option>";
}

<select>
    <?php echo $options;?>
</select>

Doing this outputs the event name and the date it will take place ( 2nd and 3rd item in my mysql database. This later gets used in a form and lists these as options for someone to pick. I was wondering if there was a way to add a proper value= to them. The first thing in my mysql database is a random generated ID for each "event" but I can't figure out how to echo the id of each event in the option tag without it breaking.

Body:
First, when using positional results (ie $row2[0], $row2[1], etc), you should be explicit in your SELECT query to guarantee order, ie

SELECT `ID`, `name`, `date` FROM `events`

Really all you need is to interpolate whatever dynamic values you need into the HTML string.

It's best to use something like htmlspecialchars() in these cases to avoid issues with markup. For example

while($row2 = mysqli_fetch_array($result2)) {
    $options .= vsprintf('<option value="%s">%s %s</option>',
        array_map('htmlspecialchars', $row2));
}


问:
Error 504 while trying to download CSV through Microsoft Gateway
I have problem with below request:
https://graph.microsoft.com/beta/reports/OneDriveActivity(view='Detail',period='D7')/content

It is very slow and unreliable... Sometimes it works but takes ~30 seconds to provide the result (CSV ~225 KB), and very often it does time out with Error 504 Gateway Timeout

My problem looks similar to this one but I opened a different question as I am not authorized to comment on this question:
504 TimeOut Errors Accessing Microsoft Graph Reports

@dan-kershaw-msft, as you offered in the other question, would you please have a look to my query. Here are details:

Date → Mon, 16 Oct 2017 08:58:13 GMT

Duration → 15011.5868

client-request-id → 58541992-8df4-4685-b768-10e154fa9d82

request-id → 58541992-8df4-4685-b768-10e154fa9d82

答: It should be improved since 10/19. Can you please give it a try and let us know?</p>


问:
How to bind rows of svymean output?
In order to apply weights etc. on survey data I am working with the survey package. There included is a wonderful function svymean() which gives me neat pairs of mean and standard errors. I now have several of these pairs and want them combine with rbind() into a data.frame.

```<code>library(survey)
data(fpc)

fpc.w1 <- with(fpc, svydesign(ids = ~0, weights = weight, data = fpc))
fpc.w2 <- with(fpc, svydesign(ids = stratid, weights = weight, data = fpc))

(msd.1 <- svymean(fpc$x, fpc.w1))
#        mean     SE
# [1,] 5.4481 0.7237

(msd.2 <- svymean(fpc$x, fpc.w2))
#        mean     SE
# [1,] 5.4481 0.5465

rbind(msd.1, msd.2)
#           [,1]
# msd.1 5.448148
# msd.2 5.448148
</code>```

As one can see, the SE is missing. Examining the object yields following:

```<code>class(msd.1)
# [1] "svystat"

str(msd.1)
# Class 'svystat'  atomic [1:1] 5.45
#   ..- attr(*, "var")= num [1, 1] 0.524
#   .. ..- attr(*, "dimnames")=List of 2
#   .. .. ..$ : NULL
#   .. .. ..$ : NULL
#   ..- attr(*, "statistic")= chr "mean"
</code>```

So I made some guesswork.

```<code>msd.1$mean
# Error in msd.1$mean : $ operator is invalid for atomic vectors

msd.1$SE
# Error in msd.1$SE : $ operator is invalid for atomic vectors

msd.1[2]
# [1] NA

msd.1[1, 2]
# Error in msd.1[1, 2] : incorrect number of dimensions
</code>```

Included in the package is a function called SE() which yields:

```<code>SE(msd.1)
#          [,1]
# [1,] 0.723725
</code>```

Ok. By this I finally could accomplish a solution to bind these rows:

```<code>t(data.frame(msd.1=c(msd.1, SE(msd.1)),
             msd.2=c(msd.2, SE(msd.2)),
             row.names = c("mean", "SD")))
#           mean        SD
# msd.1 5.448148 0.7237250
# msd.2 5.448148 0.5465021
</code>```

Do I actually have to take this pain with the package to bind rows, or am I missing something?

答:
Or a tidyverse option would be

```<code>library(tidyverse)
list(msd.1, msd.2) %>%
            map_df(as.tibble)
# A tibble: 2 x 2
#     mean        SE
#     <dbl>     <dbl>
#1 5.448148 0.7237250
#2 5.448148 0.5465021
</code>```

Title: How to bind rows of svymean output?

Body:
In order to apply weights etc. on survey data I am working with the survey package. There included is a wonderful function svymean() which gives me neat pairs of mean and standard errors. I now have several of these pairs and want them combine with rbind() into a data.frame.

library(survey)
data(fpc)

fpc.w1 <- with(fpc, svydesign(ids = ~0, weights = weight, data = fpc))
fpc.w2 <- with(fpc, svydesign(ids = stratid, weights = weight, data = fpc))

(msd.1 <- svymean(fpc$x, fpc.w1))
#        mean     SE
# [1,] 5.4481 0.7237

(msd.2 <- svymean(fpc$x, fpc.w2))
#        mean     SE
# [1,] 5.4481 0.5465

rbind(msd.1, msd.2)
#           [,1]
# msd.1 5.448148
# msd.2 5.448148

As one can see, the SE is missing. Examining the object yields following:

class(msd.1)
# [1] "svystat"

str(msd.1)
# Class 'svystat'  atomic [1:1] 5.45
#   ..- attr(*, "var")= num [1, 1] 0.524
#   .. ..- attr(*, "dimnames")=List of 2
#   .. .. ..$ : NULL
#   .. .. ..$ : NULL
#   ..- attr(*, "statistic")= chr "mean"

So I made some guesswork.

msd.1$mean
# Error in msd.1$mean : $ operator is invalid for atomic vectors

msd.1$SE
# Error in msd.1$SE : $ operator is invalid for atomic vectors

msd.1[2]
# [1] NA

msd.1[1, 2]
# Error in msd.1[1, 2] : incorrect number of dimensions

Included in the package is a function called SE() which yields:

SE(msd.1)
#          [,1]
# [1,] 0.723725

Ok. By this I finally could accomplish a solution to bind these rows:

t(data.frame(msd.1=c(msd.1, SE(msd.1)),
             msd.2=c(msd.2, SE(msd.2)),
             row.names = c("mean", "SD")))
#           mean        SD
# msd.1 5.448148 0.7237250
# msd.2 5.448148 0.5465021

Do I actually have to take this pain with the package to bind rows, or am I missing something?

Body:
Or a tidyverse option would be

library(tidyverse)
list(msd.1, msd.2) %>%
            map_df(as.tibble)
# A tibble: 2 x 2
#     mean        SE
#     <dbl>     <dbl>
#1 5.448148 0.7237250
#2 5.448148 0.5465021


问:
Binary search Python Why do we use mid + 1 or mid - 1
I am learning binary search and the sample code uses" low = mid +1 and high = mid -1" but I don't understand why we do not use "low = mid and high = mid " instead?

```<code>def binarysearch(sequence, value):
    lo, hi = 0, len(sequence) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if sequence[mid] < value:
            lo = mid + 1
        elif value < sequence[mid]:
            hi = mid - 1
        else:
            return mid
    return None

my_list = [1, 3, 5, 7, 9]
binarysearch(my_list, 3)
</code>```

答:
The reason is to avoid overlapping searches; it places the boundary of the search ranges on the items that have not been checked yet.

For instance: if mid is at index 10, the next search left will look at values up to index 9, and the right search from values at index 11.

```<code>                    mid
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|                 |    |                           |
<-from 0 to mid-1->    <-- from mid+1 to the end -->

note that in this example, the boundary values are included
</code>```

Body:
I am learning binary search and the sample code uses" low = mid +1 and high = mid -1" but I don't understand why we do not use "low = mid and high = mid " instead?

def binarysearch(sequence, value):
    lo, hi = 0, len(sequence) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if sequence[mid] < value:
            lo = mid + 1
        elif value < sequence[mid]:
            hi = mid - 1
        else:
            return mid
    return None

my_list = [1, 3, 5, 7, 9]
binarysearch(my_list, 3)

Body:
The reason is to avoid overlapping searches; it places the boundary of the search ranges on the items that have not been checked yet.

For instance: if mid is at index 10, the next search left will look at values up to index 9, and the right search from values at index 11.

                    mid
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|                 |    |                           |
<-from 0 to mid-1->    <-- from mid+1 to the end -->

note that in this example, the boundary values are included


问:
How to force a specific dependency version in a gradle buildscript
There's an issue for the gradle-docker-plugin and SpringBootVersion 2.0.0.M4

M4 uses a newer jersey client and using the docker-plugin ends in an Exception:

```<code>ERROR com.github.dockerjava.core.async.ResultCallbackTemplate - Error during callback
java.lang.IllegalStateException: InjectionManagerFactory not found.
    at org.glassfish.jersey.internal.inject.Injections.lambda$lookupInjectionManagerFactory$0(Injections.java:98)
    at java.util.Optional.orElseThrow(Optional.java:290)
    at org.glassfish.jersey.internal.inject.Injections.lookupInjectionManagerFactory(Injections.java:98)
    at org.glassfish.jersey.internal.inject.Injections.createInjectionManager(Injections.java:68)
    at org.glassfish.jersey.client.ClientConfig$State.initRuntime(ClientConfig.java:432)
    at org.glassfish.jersey.internal.util.collection.Values$LazyValueImpl.get(Values.java:341)
    at org.glassfish.jersey.client.ClientConfig.getRuntime(ClientConfig.java:826)
    at org.glassfish.jersey.client.ClientRequest.getConfiguration(ClientRequest.java:285)
    at org.glassfish.jersey.client.JerseyInvocation.validateHttpMethodAndEntity(JerseyInvocation.java:143)
    at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:112)
    at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:108)
    at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:99)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:456)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:357)
    at com.github.dockerjava.jaxrs.async.POSTCallbackNotifier.response(POSTCallbackNotifier.java:29)
    at com.github.dockerjava.jaxrs.async.AbstractCallbackNotifier.call(AbstractCallbackNotifier.java:50)
    at com.github.dockerjava.jaxrs.async.AbstractCallbackNotifier.call(AbstractCallbackNotifier.java:24)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

My BuildScript in my main project:

```<code>buildscript {
    ext {
        springBootVersion = "2.0.0.M4"
    }

    repositories {
        maven { url "https://repo.spring.io/plugins-snapshot" }
        maven { url "https://plugins.gradle.org/m2/" }
    }

    dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
    }
}
....
</code>```

As you can see, we load the spring-boot-gradle-plugin version=2.0.0.M4 and all its dependencies.

My subproject build.gradle:

```<code>apply plugin: "org.springframework.boot"
apply from: "docker.gradle"
....
</code>```

Most important the docker.gradle file in the same directory as the build.gradle of the subproject:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.bmuschko:gradle-docker-plugin:3.0.11'
    }
}

apply plugin: com.bmuschko.gradle.docker.DockerRemoteApiPlugin

import com.bmuschko.gradle.docker.tasks.image.*
...
task buildImage(type: DockerBuildImage, dependsOn: copyDockerFiles) {
    version.release = true
    dockerFile = file("${projectDir}/build/docker/Dockerfile")
    inputDir = file("${projectDir}/build/docker")
    tags = ['...']
}
</code>```

My Questions:
How do I know which Version of the jersey client loads SpringBoot 2.0.0.M4?
How do I force gradle in docker.gradle to use a specific version of the jersey client?
Adding to the classpath didn't work. I think gradle will just use the newest version, which will be loaded by SpringBoot 2.0.0.M4

答:
You have to add the following in your build.gradle dependencies as pointed in: This Link

```<code>dockerJava 'com.nirima:docker-java-shaded:0.16.2'
dockerJava 'org.slf4j:slf4j-simple:1.7.5'
dockerJava 'cglib:cglib:3.2.0'
</code>```

After that you have to separate "buildImage" and "tagImage" tasks as suggested in This link

I have tested this with: spring boot 2.0.0.M6

Body:
There's an issue for the gradle-docker-plugin and SpringBootVersion 2.0.0.M4

M4 uses a newer jersey client and using the docker-plugin ends in an Exception:

ERROR com.github.dockerjava.core.async.ResultCallbackTemplate - Error during callback
java.lang.IllegalStateException: InjectionManagerFactory not found.
    at org.glassfish.jersey.internal.inject.Injections.lambda$lookupInjectionManagerFactory$0(Injections.java:98)
    at java.util.Optional.orElseThrow(Optional.java:290)
    at org.glassfish.jersey.internal.inject.Injections.lookupInjectionManagerFactory(Injections.java:98)
    at org.glassfish.jersey.internal.inject.Injections.createInjectionManager(Injections.java:68)
    at org.glassfish.jersey.client.ClientConfig$State.initRuntime(ClientConfig.java:432)
    at org.glassfish.jersey.internal.util.collection.Values$LazyValueImpl.get(Values.java:341)
    at org.glassfish.jersey.client.ClientConfig.getRuntime(ClientConfig.java:826)
    at org.glassfish.jersey.client.ClientRequest.getConfiguration(ClientRequest.java:285)
    at org.glassfish.jersey.client.JerseyInvocation.validateHttpMethodAndEntity(JerseyInvocation.java:143)
    at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:112)
    at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:108)
    at org.glassfish.jersey.client.JerseyInvocation.<init>(JerseyInvocation.java:99)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:456)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:357)
    at com.github.dockerjava.jaxrs.async.POSTCallbackNotifier.response(POSTCallbackNotifier.java:29)
    at com.github.dockerjava.jaxrs.async.AbstractCallbackNotifier.call(AbstractCallbackNotifier.java:50)
    at com.github.dockerjava.jaxrs.async.AbstractCallbackNotifier.call(AbstractCallbackNotifier.java:24)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

My BuildScript in my main project:

buildscript {
    ext {
        springBootVersion = "2.0.0.M4"
    }

    repositories {
        maven { url "https://repo.spring.io/plugins-snapshot" }
        maven { url "https://plugins.gradle.org/m2/" }
    }

    dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
    }
}
....

As you can see, we load the spring-boot-gradle-plugin version=2.0.0.M4 and all its dependencies.

My subproject build.gradle:

apply plugin: "org.springframework.boot"
apply from: "docker.gradle"
....

Most important the docker.gradle file in the same directory as the build.gradle of the subproject:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.bmuschko:gradle-docker-plugin:3.0.11'
    }
}

apply plugin: com.bmuschko.gradle.docker.DockerRemoteApiPlugin

import com.bmuschko.gradle.docker.tasks.image.*
...
task buildImage(type: DockerBuildImage, dependsOn: copyDockerFiles) {
    version.release = true
    dockerFile = file("${projectDir}/build/docker/Dockerfile")
    inputDir = file("${projectDir}/build/docker")
    tags = ['...']
}

My Questions:
How do I know which Version of the jersey client loads SpringBoot 2.0.0.M4?
How do I force gradle in docker.gradle to use a specific version of the jersey client?
Adding to the classpath didn't work. I think gradle will just use the newest version, which will be loaded by SpringBoot 2.0.0.M4

Body:
You have to add the following in your build.gradle dependencies as pointed in: This Link

dockerJava 'com.nirima:docker-java-shaded:0.16.2'
dockerJava 'org.slf4j:slf4j-simple:1.7.5'
dockerJava 'cglib:cglib:3.2.0'

After that you have to separate "buildImage" and "tagImage" tasks as suggested in This link

I have tested this with: spring boot 2.0.0.M6


问:
What's the deal with Jaxer?
Remember Aptana Jaxer? It plugs into Apache and allows using JavaScript on the server-side as an alternative to languages such as PHP. It comes with a consistens and slick API for filesystem access, database connectivity, socket communication and whatever else you need.

I wonder why hasn't this been more widely adopted, why aren't more people using this? Javascript is a modern and clean programming language as opposed to PHP and the Jaxer API is just so much more consistent and neat. No offense, but the PHP API is just such a big mess with all its inconsistencies and its inconsequent function naming convention.

Jaxer also makes client/server communication really convenient with its runat="server-proxy" where you can directly call server-side function from within your client-side script and Jaxer takes care of all the XML HTTP request stuff.

So I would just really like to here what people think about it or why there's hardly anyone using it. Not wanting to start a flamewar here, I'm just curious.

Thanks

答:
I remember taking a look at Jaxer, back when it came out. I don't remember any sample applications at the time though. I wanted to get a feel for what it was good at. Just because a language is "cleaner", may not be enough to get people switch. What is its "unique benefit"? For example, Node.js is good at real-time applications and they make that relatively clear in the sample code on their front page.

I think there was also been more uptake of Javascript, since Jaxer was initially released. There seem to be more back-end developers who now also know Javascript. I would say that's more true now than when Jaxer was released. In other words, maybe it was ahead of its time.

Title: What's the deal with Jaxer?


答:
```<code>$options .= $options.'<option value="'.htmlspecialchars($id).'">'.htmlspecialchars($event).'</option>';
</code>```

I think your answer is this.

Title: mysql database value as select id

Body:
$options .= $options.'<option value="'.htmlspecialchars($id).'">'.htmlspecialchars($event).'</option>';

I think your answer is this.


问:
Undefined Name "Y", as well as weird outputting issue
my code compiles, but when I try to run it, it gives me an error of "undefined name" when I'm running a Y/N loop control variable.  I've input the coding of the whole program below.

Also, it displays the closing dialog while it's asking the loop question.. what did I do wrong here?

```<code>//declarations
String itemName;  //name of item
String itemPriceInput;  //user input of price
double itemPrice;  //parsed name of price
String itemQuantityInput;  //user input of quantity
double itemQuantity; //parsed input of quantity
String inputMore; //loop control

//Create file instance
java.io.File itemAttributes = new java.io.File("Items_In_Stock.txt");

//Create a scanner for the file
Scanner input = new Scanner(itemAttributes);

System.out.println("Welcome to the inventory list program");  //welcome dialog for user
System.out.println("This program will show items on hand, as well as their info"); //more dialog

System.out.println("Enter 'Y' to proceed, or 'Q' to quit"); //asking to start program

inputMore=input.next(); //taking input for loop control

while (inputMore.equalsIgnoreCase("y")) //beginning outer loop

{
  while (input.hasNext()) //beginning inner loop
  {
    itemName=input.next(); // input item name
    System.out.print (" ");

    itemPriceInput=input.next(); //input item price
    itemPrice=Double.parseDouble(itemPriceInput); //parse to double
    System.out.print (" ");

    itemQuantityInput=input.next(); //input quantity
    itemQuantity=Double.parseDouble(itemQuantityInput); //parse to double

    System.out.println("Name: " + itemName + " " + "Price: " + itemPrice + " " + "Quantity: " + itemQuantity); //display input items
  } //close inner loop

  System.out.print("Enter 'Y' to input more, or 'Q' to quit"); //asking user to input more, or quit

} //close outer loop
  input.close(); //close program

  System.out.println("Thank you for using the program.  Goodbye");//goodbye statement
</code>```

答:
The only mistake I see is

```<code>while (inputMore.equalsIgnoreCase("y"))
</code>```

You forgot to update inputMore at the end of the loop, in other words inputMoreinputMore.equalsIgnoreCase("y") will always return true because you never change it's value.

you can either change to

```<code>if (inputMore.equalsIgnoreCase("y"))
</code>```

or add at the end of the loop an other

```<code>inputMore = input.hext();
</code>```

Body:
my code compiles, but when I try to run it, it gives me an error of "undefined name" when I'm running a Y/N loop control variable.  I've input the coding of the whole program below.

Also, it displays the closing dialog while it's asking the loop question.. what did I do wrong here?

//declarations
String itemName;  //name of item
String itemPriceInput;  //user input of price
double itemPrice;  //parsed name of price
String itemQuantityInput;  //user input of quantity
double itemQuantity; //parsed input of quantity
String inputMore; //loop control

//Create file instance
java.io.File itemAttributes = new java.io.File("Items_In_Stock.txt");

//Create a scanner for the file
Scanner input = new Scanner(itemAttributes);

System.out.println("Welcome to the inventory list program");  //welcome dialog for user
System.out.println("This program will show items on hand, as well as their info"); //more dialog

System.out.println("Enter 'Y' to proceed, or 'Q' to quit"); //asking to start program

inputMore=input.next(); //taking input for loop control

while (inputMore.equalsIgnoreCase("y")) //beginning outer loop

{
  while (input.hasNext()) //beginning inner loop
  {
    itemName=input.next(); // input item name
    System.out.print (" ");

    itemPriceInput=input.next(); //input item price
    itemPrice=Double.parseDouble(itemPriceInput); //parse to double
    System.out.print (" ");

    itemQuantityInput=input.next(); //input quantity
    itemQuantity=Double.parseDouble(itemQuantityInput); //parse to double

    System.out.println("Name: " + itemName + " " + "Price: " + itemPrice + " " + "Quantity: " + itemQuantity); //display input items
  } //close inner loop

  System.out.print("Enter 'Y' to input more, or 'Q' to quit"); //asking user to input more, or quit

} //close outer loop
  input.close(); //close program

  System.out.println("Thank you for using the program.  Goodbye");//goodbye statement

Body:
The only mistake I see is

while (inputMore.equalsIgnoreCase("y"))

You forgot to update inputMore at the end of the loop, in other words inputMoreinputMore.equalsIgnoreCase("y") will always return true because you never change it's value.

you can either change to

if (inputMore.equalsIgnoreCase("y"))

or add at the end of the loop an other

inputMore = input.hext();


问:
How can I trigger an segue action on button in a UITableViewCell created from a nib?
Right now I am creating a table view cell from a nib file. I have a button in this nib file. I want this button to trigger a segue to a specific view controller on the storyboard.

Seems pretty straight forward, except this nib file is being used in many different tables on different view controllers throughout my app, and I want the button to link to the same destination view controller in every single instance. Furthermore, the destination view controller also contains a table with this nib file as a cell, meaning it will also need to link to itself.

For these reasons, I would love if there was a solution that contained this code to the UITableViewCell subclass for said nib file. (however I doubt this is possible.)

A good example of the functionality I want is Instagram. Think about how several different tabs on Instagram have tables with cells that look like this:

and no matter what tab you are in, clicking the username on the top left of this cell transitions you to the user view controller, even if you are already in the user view controller:

答:
Use addTarget to your button.

put this code in cellForRowAt method of tableView.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "YOUR_ID", for: indexPath) as? InstagramCell else { return }
    cell.nasaBtn.addTarget(self, action: #selector(firstViewController.nasaBtnPressed(_:)), for: .touchUpInside)
    return cell

}

@objc func nasaBtnPressed(_ sender: UIButton) {
    performSegue(withIdentifier: "NASA_PROFILEID", sender: nil)
}
</code>```

Body:
Use addTarget to your button.

put this code in cellForRowAt method of tableView.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "YOUR_ID", for: indexPath) as? InstagramCell else { return }
    cell.nasaBtn.addTarget(self, action: #selector(firstViewController.nasaBtnPressed(_:)), for: .touchUpInside)
    return cell

}

@objc func nasaBtnPressed(_ sender: UIButton) {
    performSegue(withIdentifier: "NASA_PROFILEID", sender: nil)
}


问:
Segmentation fault in "end program" statement in Fortran
I have some Fortran code consisting of a subroutine and a call to it. It's supposed to calculate the mean of the elements in a matrix using a defined window size. For example, calling the subroutine on a (10,10) array using winsize=2 would return a (5,5) array.

The code is as shown:

```<code>SUBROUTINE avgwin(ts, sizelat,sizelon,winsize,size2,size3,ts_new)
implicit none
double precision, dimension(10,sizelat,sizelon) :: ts
double precision, dimension(winsize,winsize) :: store
double precision, dimension(10,size2,size3) :: ts_new
double precision :: par,ave
integer :: sizelat, sizelon,i,j,k,winsize,size2,size3
integer :: A, B,p,m,numb
A=0
B=0
par = 11 !Hypothetical value to be excluded
do i=1,10 !Looping through time
    do j=1,sizelat !Looping through latitude
        if ((j+winsize) > sizelat) then !Checks if it will exceed bounds
            exit !If it'll exceed, discard remaining cells
        end if
        do k=1,sizelon !Looping through longitude
            if ((k+winsize)>sizelon) then
               exit
            end if
            store = ts(i,j:j+winsize,k:k+winsize) !Gets the values for that window
            where (store == par) store = -99 !Replaces masked with -99
            ave = 0
            numb = 0 !Variable to count
            do p=1,winsize
                do m=1,winsize
                    if (store(p,m)==-99) then !Evaluates if it's masked, i.e., =-99
                        ave = ave
                    else
                        ave = ave + store(p,m) !Sum of existent values
                        numb = numb +1 !Updates counting variable
                    end if
                end do
            end do
            ave = ave/numb !Calculates the mean
            ts_new(i,A,B) = ave
            B=B+1
        end do
        B=0
        A=A+1
    end do
A=0
B=0
end do
END SUBROUTINE

program testefor
implicit none
double precision, dimension(10,10,10) :: teste
double precision, dimension(10,5,5) :: oi
integer :: i,j,k

do i=1,10
   do j=1,10
      do k=1,10
         teste(i,j,k)=i
      end do
   end do
 end do

CALL avgwin(teste,10,10,2,5,5,oi)
print*, oi(1,5,5)

end program testefor
</code>```

When I'm running it, however, I get a Segmentation Fault. I tried debugging it with GDB and, to my surprise, it returns a correct result but segfaults when exiting the program. What I get from gdb can be found below:

```<code>Breakpoint 1, testefor () at testefor.f90:56
56      do i=1,10
(gdb) cont
Continuing.
   1.0000000000000000

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400f73 in testefor () at testefor.f90:67
67  end program testefor
</code>```

So the program is returning the correct (1,5,5) element = 1.0 but faulting somewhere else.

Can someone help me identify the problem? Thanks

答:
This is not meant as the answer to your question (I've already answered that), but a few hints that should help you.

If you loop over a multi-dimensional array, you should always have the inner-most loop over the first index, and so forth, so

```<code>! Inefficient way to do it:
do i = 1, 10
    do j = 1, 10
        do k = 1, 10
            a(i, j, k) = i*j+k
        end do
    end do
end do

!Efficient way to do it:
do k = 1, 10                   !  <-+
    do j = 1, 10               !    | swapped
        do i = 1, 10           !  <-+
            a(i, j, k) = i*j+k
        end do
    end do
end do
</code>```

The way Fortran stores multi-dimensional arrays is with the first index changing fastest. The efficient method therefore reads successive elements, whereas the inefficient method needs to jump around in memory quite a bit.

Instead of this convoluted loop, you could just as easily use SUM and COUNT:

COUNT counts the instances of .TRUE. in an array, so your value of numb could just as easily be calculated as numb=COUNT(store/=-99)

SUM has the optional argument MASK that you can use to omit certain values. To sum up all the values that are not -99, you can use: s = SUM(store, MASK=(store /= -99))

So you could replace about 15 lines of your code with just:

```<code>ave = sum(store, MASK=(store/=par)) / count(store/=par)
</code>```

Both store and par are double precision, and comparing floating point variables for absolute equality is tricky

Body:
I have some Fortran code consisting of a subroutine and a call to it. It's supposed to calculate the mean of the elements in a matrix using a defined window size. For example, calling the subroutine on a (10,10) array using winsize=2 would return a (5,5) array.

The code is as shown:

SUBROUTINE avgwin(ts, sizelat,sizelon,winsize,size2,size3,ts_new)
implicit none
double precision, dimension(10,sizelat,sizelon) :: ts
double precision, dimension(winsize,winsize) :: store
double precision, dimension(10,size2,size3) :: ts_new
double precision :: par,ave
integer :: sizelat, sizelon,i,j,k,winsize,size2,size3
integer :: A, B,p,m,numb
A=0
B=0
par = 11 !Hypothetical value to be excluded
do i=1,10 !Looping through time
    do j=1,sizelat !Looping through latitude
        if ((j+winsize) > sizelat) then !Checks if it will exceed bounds
            exit !If it'll exceed, discard remaining cells
        end if
        do k=1,sizelon !Looping through longitude
            if ((k+winsize)>sizelon) then
               exit
            end if
            store = ts(i,j:j+winsize,k:k+winsize) !Gets the values for that window
            where (store == par) store = -99 !Replaces masked with -99
            ave = 0
            numb = 0 !Variable to count
            do p=1,winsize
                do m=1,winsize
                    if (store(p,m)==-99) then !Evaluates if it's masked, i.e., =-99
                        ave = ave
                    else
                        ave = ave + store(p,m) !Sum of existent values
                        numb = numb +1 !Updates counting variable
                    end if
                end do
            end do
            ave = ave/numb !Calculates the mean
            ts_new(i,A,B) = ave
            B=B+1
        end do
        B=0
        A=A+1
    end do
A=0
B=0
end do
END SUBROUTINE

program testefor
implicit none
double precision, dimension(10,10,10) :: teste
double precision, dimension(10,5,5) :: oi
integer :: i,j,k

do i=1,10
   do j=1,10
      do k=1,10
         teste(i,j,k)=i
      end do
   end do
 end do

CALL avgwin(teste,10,10,2,5,5,oi)
print*, oi(1,5,5)

end program testefor

When I'm running it, however, I get a Segmentation Fault. I tried debugging it with GDB and, to my surprise, it returns a correct result but segfaults when exiting the program. What I get from gdb can be found below:

Breakpoint 1, testefor () at testefor.f90:56
56      do i=1,10
(gdb) cont
Continuing.
   1.0000000000000000

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400f73 in testefor () at testefor.f90:67
67  end program testefor

So the program is returning the correct (1,5,5) element = 1.0 but faulting somewhere else.

Can someone help me identify the problem? Thanks

Body:
This is not meant as the answer to your question (I've already answered that), but a few hints that should help you.

If you loop over a multi-dimensional array, you should always have the inner-most loop over the first index, and so forth, so

! Inefficient way to do it:
do i = 1, 10
    do j = 1, 10
        do k = 1, 10
            a(i, j, k) = i*j+k
        end do
    end do
end do

!Efficient way to do it:
do k = 1, 10                   !  <-+
    do j = 1, 10               !    | swapped
        do i = 1, 10           !  <-+
            a(i, j, k) = i*j+k
        end do
    end do
end do

The way Fortran stores multi-dimensional arrays is with the first index changing fastest. The efficient method therefore reads successive elements, whereas the inefficient method needs to jump around in memory quite a bit.

Instead of this convoluted loop, you could just as easily use SUM and COUNT:

COUNT counts the instances of .TRUE. in an array, so your value of numb could just as easily be calculated as numb=COUNT(store/=-99)

SUM has the optional argument MASK that you can use to omit certain values. To sum up all the values that are not -99, you can use: s = SUM(store, MASK=(store /= -99))

So you could replace about 15 lines of your code with just:

ave = sum(store, MASK=(store/=par)) / count(store/=par)

Both store and par are double precision, and comparing floating point variables for absolute equality is tricky


问:
django - cannot save password correctly in form
I am trying to have a form that allows the user to change password.

Everytime I change the password, it cannot login.
for example if password is "jake", I change to "jake1", I cant login with the password "jake1" or even "jake"

Here is how the form looks like:
https://imgur.com/a/MdPs0

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py

```<code>@login_required(login_url='/employee/sign-in/')

def employee_account(request):

    employee_form = EmployeeFormEdit(instance = request.user)

    if request.method == "POST":
        employee_form = EmployeeFormEdit(request.POST, instance = request.user)

        if employee_form.is_valid():
            employee_form.save()

    return render(request, 'employee/account.html', {
        "employee_form":employee_form
        })
</code>```

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/forms.py

```<code>class EmployeeFormEdit(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ("password",)
</code>```

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/templates/employee/account.html

```<code> <form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {% bootstrap_form employee_form %}
    <button type="submit" class="btn btn-pink">Update</button>
  </form>
</code>```

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py
Its just using the standard User model

```<code>class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
</code>```

答:
```<code>class EmployeeFormEdit(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ("password",)

    def save(self, commit=True):
        user = super(EmployeeFormEdit, self).save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user
</code>```

you must use user.set_password() to set your password.

Body:
I am trying to have a form that allows the user to change password.

Everytime I change the password, it cannot login.
for example if password is "jake", I change to "jake1", I cant login with the password "jake1" or even "jake"

Here is how the form looks like:
https://imgur.com/a/MdPs0

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py

@login_required(login_url='/employee/sign-in/')

def employee_account(request):

    employee_form = EmployeeFormEdit(instance = request.user)

    if request.method == "POST":
        employee_form = EmployeeFormEdit(request.POST, instance = request.user)

        if employee_form.is_valid():
            employee_form.save()

    return render(request, 'employee/account.html', {
        "employee_form":employee_form
        })

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/forms.py

class EmployeeFormEdit(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ("password",)

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/templates/employee/account.html

 <form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {% bootstrap_form employee_form %}
    <button type="submit" class="btn btn-pink">Update</button>
  </form>

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py
Its just using the standard User model

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

Body:
class EmployeeFormEdit(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ("password",)

    def save(self, commit=True):
        user = super(EmployeeFormEdit, self).save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user

you must use user.set_password() to set your password.


问:
mvn command line java compiler version is mistaken
I have jdk8 and 9 installed. And in the effective pom.xml I can see the compiler plugin is assigned to 1.8, however mvn clean install prints error a sun class is missing, making me believe it still uses jdk9.

```<code>$ mvn -version
Maven home: D:\Java\apache-maven-3.2.5
Java version: 9, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk-9
</code>```

pom.xml:

```<code><plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.1</version>
        <executions>
          <execution>
            <id>default-compile</id>
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
              <encoding>UTF-8</encoding>
            </configuration>
          </execution>
          <execution>
            <id>default-testCompile</id>
            <phase>test-compile</phase>
            <goals>
              <goal>testCompile</goal>
            </goals>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
              <encoding>UTF-8</encoding>
            </configuration>
          </execution>
        </executions>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
</code>```

答:
You have an edge case.

You (presumably) have some code that was originally developed for Java 8 (or earlier) that depends on an internal JRE class.  Code is not supposed to do that.

What has apparently happened is that the internal class has been removed or replaced.

The only way you are going to be able to compile this code is by downloading and installing a genuine Java 8 JDK and setting your $PATH to refer to it before running Maven.

But that is only a stop-gap.  The real solution is to convert your code so that id doesn't depend on internal classes.  You are going to have to do that eventually anyway.  So may as well do it now ... and avoid the hassle of a special Java 8 setup to build your code.

There is nothing you can do with your POM file to fix this.  Those classes are (probably) no longer present in the "rt.jar" file where the java compiler and runtime are looking for them.

I finally got this work again! After rebooting os.

What probably happened is that you changed a PATH setting in a ".rc" file but did not restart your shell or re-source the file.  Or something like that.  The reboot probably wasn't necessary.  Logging out and logging in again would probably have been sufficient.

Body:
I have jdk8 and 9 installed. And in the effective pom.xml I can see the compiler plugin is assigned to 1.8, however mvn clean install prints error a sun class is missing, making me believe it still uses jdk9.

$ mvn -version
Maven home: D:\Java\apache-maven-3.2.5
Java version: 9, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk-9

pom.xml:

<plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.1</version>
        <executions>
          <execution>
            <id>default-compile</id>
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
              <encoding>UTF-8</encoding>
            </configuration>
          </execution>
          <execution>
            <id>default-testCompile</id>
            <phase>test-compile</phase>
            <goals>
              <goal>testCompile</goal>
            </goals>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
              <encoding>UTF-8</encoding>
            </configuration>
          </execution>
        </executions>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>


答:
Although Phil's way is probably proper. I don't know how I didn't try

```<code>"<option value=$row2[0]>$row2[1] $row2[2]</option>"
</code>```

removing the extra " that I had around $row2[0] made it work.

Title: mysql database value as select id

Body:
I am trying to assign an ID to values to be posted with the submit tag

$query = "SELECT * FROM `events`";
$result2 = mysqli_query($connect, $query);

$options = "";
while($row2 = mysqli_fetch_array($result2))
{
    $options = $options."<option>$row2[1] $row2[2]</option>";
}

<select>
    <?php echo $options;?>
</select>

Doing this outputs the event name and the date it will take place ( 2nd and 3rd item in my mysql database. This later gets used in a form and lists these as options for someone to pick. I was wondering if there was a way to add a proper value= to them. The first thing in my mysql database is a random generated ID for each "event" but I can't figure out how to echo the id of each event in the option tag without it breaking.

Body:
Although Phil's way is probably proper. I don't know how I didn't try

"<option value=$row2[0]>$row2[1] $row2[2]</option>"

removing the extra " that I had around $row2[0] made it work.


问:
Firebase JavaScript value Change Events
I am wondering how i can solve the following issue. I have a Record in the Firebase DB which i am monitoring. The App is a Sports Score So far so good.
When user loads the initial page i check if Game is Running or Stopped and so a few things.
below is a snipped of what i do

```<code>if(Clock.Status=='Running'){
            ......
        }
        else if(Clock.Status == 'Stopped'){
            .......
        }
</code>```

So far so good when user hits the page for first time. But now i want to monitor if the ClockStatus changes

```<code>clockStatusRef = firebase.database().ref("games/"+gameId+"/Score/");
clockStatusRef.on("child_changed", function(snapshot) {
    var Clock = snapshot.val();
    var status = Clock.Status;

    // clock stopped - second scenario
    if(status=='Stopped'){
        stopTimer();
    }
    else if(status == 'Running'){
        // clock status running- third scenario
        firebase.database().ref('/.info/serverTimeOffset')
              .once('value')
              .then(function stv(data) {
                console.log('hi');
                serverTime = (data.val() + Date.now())/1000;
                var timeElapsed = serverTime - Clock.ClockStart;
                var totalCounts    = document.getElementById("total_counts");
                if(Clock.Timer > timeElapsed){
                    initTimer(Math.floor(Clock.Timer- timeElapsed),60);
                }
                else{
                    var Current_Clock = document.getElementById("count");
                    Current_Clock.innerHTML = '00:00';
                }
              }, function (err) {
                return err;
              });
    }
    console.log("Clock status changed: "+status);

});
</code>```

for some strange reason on a change of status it starts with the main if

```<code>if(Clock.Status=='Running')
</code>```

So i am wondering what am i missing and what is the best way to fix this so the first if is only run on the initial load and all subsequent will use the if's which handle status change of clock.

Here is the Json for games/B8120ACD-DF51-A64A-A83E-556007522E80/Score/Clock

```<code>{
  "ClockStart" : 1510535632,
  "Period" : 1,
  "Status" : "Stopped",
  "Timer" : 900
}
</code>```

答: As there seem to be some limitation as far as what is triggered when multiple listeners looking for changes and data overlaps i changed my code. As my App does not have any heavy traffic so changes are not that often, i use one listener for changes and to address my issue i just went ahead and added the run once for the initial setup then run different code on updates. Would have been nice to control what listener gets the notification of change, also the child_changed seems to have its limitations as i got it to fire but was not able to tell which child actually changed.</p>

Title: Firebase JavaScript value Change Events

Body:
I am wondering how i can solve the following issue. I have a Record in the Firebase DB which i am monitoring. The App is a Sports Score So far so good.
When user loads the initial page i check if Game is Running or Stopped and so a few things.
below is a snipped of what i do

if(Clock.Status=='Running'){
            ......
        }
        else if(Clock.Status == 'Stopped'){
            .......
        }

So far so good when user hits the page for first time. But now i want to monitor if the ClockStatus changes

clockStatusRef = firebase.database().ref("games/"+gameId+"/Score/");
clockStatusRef.on("child_changed", function(snapshot) {
    var Clock = snapshot.val();
    var status = Clock.Status;

    // clock stopped - second scenario
    if(status=='Stopped'){
        stopTimer();
    }
    else if(status == 'Running'){
        // clock status running- third scenario
        firebase.database().ref('/.info/serverTimeOffset')
              .once('value')
              .then(function stv(data) {
                console.log('hi');
                serverTime = (data.val() + Date.now())/1000;
                var timeElapsed = serverTime - Clock.ClockStart;
                var totalCounts    = document.getElementById("total_counts");
                if(Clock.Timer > timeElapsed){
                    initTimer(Math.floor(Clock.Timer- timeElapsed),60);
                }
                else{
                    var Current_Clock = document.getElementById("count");
                    Current_Clock.innerHTML = '00:00';
                }
              }, function (err) {
                return err;
              });
    }
    console.log("Clock status changed: "+status);

});

for some strange reason on a change of status it starts with the main if

if(Clock.Status=='Running')

So i am wondering what am i missing and what is the best way to fix this so the first if is only run on the initial load and all subsequent will use the if's which handle status change of clock.

Here is the Json for games/B8120ACD-DF51-A64A-A83E-556007522E80/Score/Clock

{
  "ClockStart" : 1510535632,
  "Period" : 1,
  "Status" : "Stopped",
  "Timer" : 900
}


问:
C#. How to excecute a query on recordset?
HI,

I am trying to convert the following vba code to c# and i am facing some errors.Hope someone can help me

vba code

```<code>    Open "C:\testfile.txt" For Input As #1
        varii = ""
        Do While Not EOF(1)
        Line Input #1, strField
        varii = varii & "," & strField
        Loop
        Close #1
        astrFields = Split(varii, ",")

    For intIx = 1 To UBound(astrFields)
    counter = 0
    i = i + 1

    Dim cn As New ADODB.Connection, cn2 As New ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim connString As String
    Dim SelectFieldName
    Set cn = CurrentProject.Connection
    SelectFieldName = astrFields(intIx)
    Set rs = cn.OpenSchema(adSchemaColumns, _
    Array(Empty, Empty, Empty, SelectFieldName))

        If Left(rs!Table_Name, 4) <> "MSys" And Left(rs!Table_Name, 4) <> "Abfr
    " Then

strSql = "SELECT t.[" & astrFields(intIx) & "], t.fall from [" & rs!Tab
    le_Name & "] t Inner Join 01UMWELT on t.fall = [01UMWELT].fall "
            End If
    Set rs3 = CurrentDb.OpenRecordset(strSql)
    Do While Not rs3.EOF
    With rs3
    feedbackmsg = "Processing " & rs!Table_Name & " Record no : "
    & .Fields(1)
    SysCmd acSysCmdSetStatus, feedbackmsg
    varii = Nz(.Fields(astrFields(intIx)), "NullValue")
    If varii = "NullValue" Then
    Call .Edit
    .Fields(astrFields(intIx)) = 888
    Call .Update
</code>```

THis is the c# code so far i have coded

```<code>FileInfo theSourceFile = new FileInfo("C:\\csharp\\testfile.txt");
            StreamReader reader = theSourceFile.OpenText();
            varii = "";

            do
            {
                text = reader.ReadLine();
                varii = varii + "," + reader.ReadLine();
                //Console.WriteLine(text);

            } while (text != null);

            string[] split = varii.Split(new Char[] {' '});

            foreach (string s in split)
            {

                if (s.Trim() != "")
                    Console.WriteLine(s);
            }

                    int temp = split.GetUpperBound(1);
                    for (intix = 1; intix <= temp; intix++)
                    {
                        counter = 0;

                        i++;
                        ADODB.Connection cn = new ADODB.Connection();
                        ADODB.Connection cn2 = new ADODB.Connection();
                        ADODB.Recordset rs;
                        object selectfieldname;

                        //ConnectionClass conDatabase = new ADODB.Connection();

                        cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                                              "Data Source='C:\\csharp\\accident_database.mdb';";

                        rs = cn.OpenSchema(ADODB.SchemaEnum.adSchemaTables, Missing.Value, Missing.Value);

                        if (Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "MSys" && +
                            Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "Abfr")
                        {
                            strsql = "SELECT t.[" + split(intix) + "],t.fall from [" + rs.Fields("Table_Name").Value + "]" +
                                    "t Inner join 01umwelt on t.fall = [01umwelt].fall";

                        }
                        rs3 = CurrentDB.OpenRecordset(strsql);

                        while (!rs3.EOF)
                        {

                            feedbackmsg = "Processing" + rs.Fields("Table_Name").Value + "Record no:" + rs3.Fields(1).Value;
                            SysCmd acSysCmdSetStatus, feecbackmsg;
                            varii = Nz(rs3.Fields(astrfields(intix)).Value, "NullValue");

                            if (varii == "NullValue")
                            {
                                rs3.Edit();
                                rs3.Fields[astrfields(intix)].Value = 888;
                                rs3.Update();
</code>```

I am recieving errors in the if statement

```<code>if (Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "MSys" && +
            Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "Abfr")
</code>```

here Vbe.left is not getting accepted

and secondly in the sql statement following this i get an error split is an variablebut used like method.

Thanks

答: If you add using VB = Microsoft.VisualBasic; namespace on top you can use VB.Left() instead of Microsoft.Vbe.Left()

OwnerDisplayName: tksy

Body:
HI,

I am trying to convert the following vba code to c# and i am facing some errors.Hope someone can help me

vba code

    Open "C:\testfile.txt" For Input As #1
        varii = ""
        Do While Not EOF(1)
        Line Input #1, strField
        varii = varii & "," & strField
        Loop
        Close #1
        astrFields = Split(varii, ",")

    For intIx = 1 To UBound(astrFields)
    counter = 0
    i = i + 1

    Dim cn As New ADODB.Connection, cn2 As New ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim connString As String
    Dim SelectFieldName
    Set cn = CurrentProject.Connection
    SelectFieldName = astrFields(intIx)
    Set rs = cn.OpenSchema(adSchemaColumns, _
    Array(Empty, Empty, Empty, SelectFieldName))

        If Left(rs!Table_Name, 4) <> "MSys" And Left(rs!Table_Name, 4) <> "Abfr
    " Then

strSql = "SELECT t.[" & astrFields(intIx) & "], t.fall from [" & rs!Tab
    le_Name & "] t Inner Join 01UMWELT on t.fall = [01UMWELT].fall "
            End If
    Set rs3 = CurrentDb.OpenRecordset(strSql)
    Do While Not rs3.EOF
    With rs3
    feedbackmsg = "Processing " & rs!Table_Name & " Record no : "
    & .Fields(1)
    SysCmd acSysCmdSetStatus, feedbackmsg
    varii = Nz(.Fields(astrFields(intIx)), "NullValue")
    If varii = "NullValue" Then
    Call .Edit
    .Fields(astrFields(intIx)) = 888
    Call .Update

THis is the c# code so far i have coded

FileInfo theSourceFile = new FileInfo("C:\\csharp\\testfile.txt");
            StreamReader reader = theSourceFile.OpenText();
            varii = "";

            do
            {
                text = reader.ReadLine();
                varii = varii + "," + reader.ReadLine();
                //Console.WriteLine(text);

            } while (text != null);

            string[] split = varii.Split(new Char[] {' '});

            foreach (string s in split)
            {

                if (s.Trim() != "")
                    Console.WriteLine(s);
            }

                    int temp = split.GetUpperBound(1);
                    for (intix = 1; intix <= temp; intix++)
                    {
                        counter = 0;

                        i++;
                        ADODB.Connection cn = new ADODB.Connection();
                        ADODB.Connection cn2 = new ADODB.Connection();
                        ADODB.Recordset rs;
                        object selectfieldname;

                        //ConnectionClass conDatabase = new ADODB.Connection();

                        cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                                              "Data Source='C:\\csharp\\accident_database.mdb';";

                        rs = cn.OpenSchema(ADODB.SchemaEnum.adSchemaTables, Missing.Value, Missing.Value);

                        if (Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "MSys" && +
                            Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "Abfr")
                        {
                            strsql = "SELECT t.[" + split(intix) + "],t.fall from [" + rs.Fields("Table_Name").Value + "]" +
                                    "t Inner join 01umwelt on t.fall = [01umwelt].fall";

                        }
                        rs3 = CurrentDB.OpenRecordset(strsql);

                        while (!rs3.EOF)
                        {

                            feedbackmsg = "Processing" + rs.Fields("Table_Name").Value + "Record no:" + rs3.Fields(1).Value;
                            SysCmd acSysCmdSetStatus, feecbackmsg;
                            varii = Nz(rs3.Fields(astrfields(intix)).Value, "NullValue");

                            if (varii == "NullValue")
                            {
                                rs3.Edit();
                                rs3.Fields[astrfields(intix)].Value = 888;
                                rs3.Update();

I am recieving errors in the if statement

if (Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "MSys" && +
            Microsoft.Vbe.Left(rs.Fields("Table_Name").Value, 4) != "Abfr")

here Vbe.left is not getting accepted

and secondly in the sql statement following this i get an error split is an variablebut used like method.

Thanks

LastEditorDisplayName: tksy

OwnerDisplayName: Eduardo Campañó


问:
Mysql Group_Concat function
Not understanding how to use the GROUP_CONCAT function as my queries seem to repeat values that I don't actually want.

I have three tables:

```<code>------------------
Content
------------------
cid | title
2334 | Lorem Ipsum

------------------
Organizers
------------------
cid | name | sort
2334 | John Doe | 0

------------------
Participants
------------------
cid | name | sort
2334 | Jane Doe | 0
2334 | Bob Hope | 1
2334 | Bart Simpson | 2
</code>```

I'm trying to write a query that will produce:

```<code>cid | title | organizers | participants
2334 | Lorem Ipsum | John Doe | Jane Doe, Bob Hope, Bart Simpson
</code>```

So, I'm trying to use GROUP_CONCAT.  But, values are being repeated, so I'm not sure how to output the results I'm looking for?

```<code>SELECT GROUP_CONCAT(co.name) as organizers,
GROUP_CONCAT(cp.name) FROM content n
LEFT JOIN organizers co ON n.cid = co.cid
LEFT JOIN participants cp ON n.cid = cp.cid
WHERE n.cid = 2334
</code>```

The above yields:

```<code>cid | title | organizers | participants
2334 | Lorem Ipsum | John Doe, John Doe, John Doe | Jane Doe, Bob Hope, Bart Simpson
</code>```

答:
```<code>select group_concat(distinct co.name)
</code>```

details : http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

syntax

```GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])```

Title: Mysql Group_Concat function

Body:
Not understanding how to use the GROUP_CONCAT function as my queries seem to repeat values that I don't actually want.

I have three tables:

------------------
Content
------------------
cid | title
2334 | Lorem Ipsum

------------------
Organizers
------------------
cid | name | sort
2334 | John Doe | 0

------------------
Participants
------------------
cid | name | sort
2334 | Jane Doe | 0
2334 | Bob Hope | 1
2334 | Bart Simpson | 2

I'm trying to write a query that will produce:

cid | title | organizers | participants
2334 | Lorem Ipsum | John Doe | Jane Doe, Bob Hope, Bart Simpson

So, I'm trying to use GROUP_CONCAT.  But, values are being repeated, so I'm not sure how to output the results I'm looking for?

SELECT GROUP_CONCAT(co.name) as organizers,
GROUP_CONCAT(cp.name) FROM content n
LEFT JOIN organizers co ON n.cid = co.cid
LEFT JOIN participants cp ON n.cid = cp.cid
WHERE n.cid = 2334

The above yields:

cid | title | organizers | participants
2334 | Lorem Ipsum | John Doe, John Doe, John Doe | Jane Doe, Bob Hope, Bart Simpson

Body:
select group_concat(distinct co.name)

details : http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

syntax

GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])


问:
Matlab: "Matrix Exceeds Dimensions Error" in While Loop?
My tutor and I were solving problem simulating the war card game. The only variation in the rules is that two cards with same value are both discarded.

My tutor and I came up with a solution

```<code>deck1 = randi(13,1,26);
    deck2 = randi(13,1,26);

    winner1 = 0;
    winner2 = 0;
    n = 1;

    while (length(deck1) ~= 0 || length(deck1) ~= 0)
        n = length(deck1);
        m = length(deck2);
        if deck1(1) == deck2(1)
            deck1(1) = [];
            deck2(1) = [];
        elseif deck1(1) < deck2(1)
            winner2 = winner2 + 1;
            deck2(m+1) = deck2(1);
            deck1(1) = [];
            deck2(1) = [];
        else
            deck1(27) = deck1(1);
            deck1(n+1) = deck2(1);
            deck1(1) = [];
            deck2(1) = [];
            winner1 = winner1 + 1;
        end
    end

    if winner1 > winner2
        k = 1;
    elseif winner1 == winner2
        k = 0;
    else k = 2;
    end
    disp(k)
</code>```

The loop works for k=2 and k=0 but not for k=1. It return the following

```<code> Index exceeds matrix dimensions.

Error in TutorVersionWarCardGame (line 16)
    if deck1(1) == deck2(1)
</code>```

How should I edit the loop?

答:
You compare deck1 2 times in the while loop as below

```<code>while (length(deck1) ~= 0 || length(deck1) ~= 0)
</code>```

I think it should be

```<code>while (length(deck1) ~= 0 || length(deck2) ~= 0)
</code>```

Edit:

I added try catch to check the if conditions inside the while loop. I found matrix keep decrease until its size reaches to 0, therefore, I replace the || with && while (length(deck1) ~= 0 && length(deck2) ~= 0) but the result now always k=2.

Body:
My tutor and I were solving problem simulating the war card game. The only variation in the rules is that two cards with same value are both discarded.

My tutor and I came up with a solution

deck1 = randi(13,1,26);
    deck2 = randi(13,1,26);

    winner1 = 0;
    winner2 = 0;
    n = 1;

    while (length(deck1) ~= 0 || length(deck1) ~= 0)
        n = length(deck1);
        m = length(deck2);
        if deck1(1) == deck2(1)
            deck1(1) = [];
            deck2(1) = [];
        elseif deck1(1) < deck2(1)
            winner2 = winner2 + 1;
            deck2(m+1) = deck2(1);
            deck1(1) = [];
            deck2(1) = [];
        else
            deck1(27) = deck1(1);
            deck1(n+1) = deck2(1);
            deck1(1) = [];
            deck2(1) = [];
            winner1 = winner1 + 1;
        end
    end

    if winner1 > winner2
        k = 1;
    elseif winner1 == winner2
        k = 0;
    else k = 2;
    end
    disp(k)

The loop works for k=2 and k=0 but not for k=1. It return the following

 Index exceeds matrix dimensions.

Error in TutorVersionWarCardGame (line 16)
    if deck1(1) == deck2(1)

How should I edit the loop?

Body:
You compare deck1 2 times in the while loop as below

while (length(deck1) ~= 0 || length(deck1) ~= 0)

I think it should be

while (length(deck1) ~= 0 || length(deck2) ~= 0)

Edit:

I added try catch to check the if conditions inside the while loop. I found matrix keep decrease until its size reaches to 0, therefore, I replace the || with && while (length(deck1) ~= 0 && length(deck2) ~= 0) but the result now always k=2.


问:
Microsoft Graph - Skype for Business reporting
I created a thread which can be found here -- Error 400 Bad Request when attempting to pull Skype for Business activity via Graph API

The Microsoft Graph support site points you here for questions such as these.

Can someone at Microsoft please provide some kind of input on when Microsoft Graph or PowerShell will have access to retrieve Skype for Business PSTN call \ activity details?

The Graph Beta API is functioning now but it still doesn't return PSTN call data.

Using the reports GUI in the SfB console of Office 365 doesn't have the functionality we need.

Please let me know if I'm missing some documentation about how to obtain these statistics in an automated fashion?

答: We don't support PSTN report in the Graph API. In UX we provide the link to PSTN report managed by Sfb team. The link is something like: https://admin1a.online.lync.com/lscp/?language=en-US&tenantID=&p=ReportsPSTNUsageDetails</p>


问:
Django allauth facebook login failed to redirect back when in an in-app-browser
Problem

When in an in-app-browser, like Google Hangout, Telegram or LINE messenger, the user won't be redirected back to my website after a success login through facebook login dialog. It just shows a blank page.

Everything works fine when using iPhone Safari app or Android Chrome app.

Environment

I am using Django==1.11.3 and django-allauth==0.34.0 (which utilizes Facebook Graph API v2.5), and here are my settings.py

```<code>SOCIALACCOUNT_PROVIDERS = {
    'facebook': {
        'SCOPE': ['email', 'public_profile', 'user_friends'],
        'METHOD': 'js_sdk',
        'LOCALE_FUNC': lambda request: 'zh_TW',
        'VERIFIED_EMAIL': True
    }
}
</code>```

Anyone experienced the same issue?

答:
As of 2013, Facebook: Native iOS and Android apps must not use their own web views for Facebook Login.

Technically, the root cause of the problem is that FB opens a new page to get correct login credentials, then close the new page and post the credential back to the parent page. However, there is no parent page in webview (only a single page), so it stays there as a blank page. see Making facebook login work with an Android Webview

Body:
Problem

When in an in-app-browser, like Google Hangout, Telegram or LINE messenger, the user won't be redirected back to my website after a success login through facebook login dialog. It just shows a blank page.

Everything works fine when using iPhone Safari app or Android Chrome app.

Environment

I am using Django==1.11.3 and django-allauth==0.34.0 (which utilizes Facebook Graph API v2.5), and here are my settings.py

SOCIALACCOUNT_PROVIDERS = {
    'facebook': {
        'SCOPE': ['email', 'public_profile', 'user_friends'],
        'METHOD': 'js_sdk',
        'LOCALE_FUNC': lambda request: 'zh_TW',
        'VERIFIED_EMAIL': True
    }
}

Anyone experienced the same issue?


问:
Hibernate error in Spring boot initialized JPA application
I use spring boot 1.5.8 to initialize a web application with JPA, however, it doesn't allow me to start the application. It shows the hibernate error. It is supposed the spring-boot-starter-data-jpa will install related dependencies but it seems not:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
...
...
...
Caused by: java.lang.ClassNotFoundException: org.hibernate.HibernateException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
    ... 60 common frames omitted
</code>```

Following is my dependencies in pom.xml:

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</code>```

答:
The reason is the Version 1.5.8 has problem. Using the other versions of Spring boot initializer. I do not need to add or delete any dependency, and it works now:

change to

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.BUILD-SNAPSHOT</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
</code>```

Body:
I use spring boot 1.5.8 to initialize a web application with JPA, however, it doesn't allow me to start the application. It shows the hibernate error. It is supposed the spring-boot-starter-data-jpa will install related dependencies but it seems not:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
...
...
...
Caused by: java.lang.ClassNotFoundException: org.hibernate.HibernateException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
    ... 60 common frames omitted

Following is my dependencies in pom.xml:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

Body:
The reason is the Version 1.5.8 has problem. Using the other versions of Spring boot initializer. I do not need to add or delete any dependency, and it works now:

change to

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.BUILD-SNAPSHOT</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>


问:
Bootstrap not working with ruby
I have tried everything and I just cant get my navbar in bootstrap to work.
I am using a up to date version of ruby and rails version

I have the gems the github tells me to put in my code

Gems

and its says that they are being used

used

I changed my application file from application.css to a scss file and got rid of all the require statements.

scss file change

I updated my application.js file the way they told me to.

js file

but when I try and put this boostrap header in my file

header

I end up with this

rendered

instead of this

from the website

If anyone could help it would be appreciated. I have done everything I could think of.

答:
I recently done a project in ruby on rails with Bootstrap 4 beta 2, here are my setup:

Gemfile

```<code>gem 'jquery-ui-rails', '~> 5.0', '>= 5.0.5'
gem 'bootstrap', '~> 4.0.0.beta2'
gem 'jquery-rails', '~> 4.3', '>= 4.3.1'
gem 'font-awesome-rails'
</code>```

app/assets/javascripts/application.js (The sequence are important)

```<code>//= require jquery3
//= require popper
//= require rails-ujs
//= require jquery-ui
//= require_tree .
//= require bootstrap-sprockets
</code>```

assets/stylesheets/application.scss

```<code>@import "bootstrap";
@import "font-awesome";
</code>```

For more details, go visit bootstrap-sass gem

HERE IS THE UPDATE (refer to bootstrap-sass)

Generate new rails app rails new bootstrap4test

bundle install

Scaffold a simple blog with text rails g scaffold Blog content:text

Database Migrate rails db:seed && rails db:migrate

Add gem into Gemfile

gem 'bootstrap-sass', '~> 3.3.7'
gem 'sass-rails', '>= 3.2'

rename app/assests/stylesheets/application.css to .scss

remove everything in the application.scss and add these

// "bootstrap-sprockets" must be imported before "bootstrap" and "bootstrap/variables"
@import "bootstrap-sprockets";
@import "bootstrap";

Now, add another gem gem 'jquery-rails' into your Gemfile

bundle install

in app/assets/javascripts/application.js add 2 lines

//= require jquery
//= require bootstrap-sprockets

Your application.js should look like this

```<code>//= require jquery
//= require bootstrap-sprockets
//= require rails-ujs
//= require turbolinks
//= require_tree .
</code>```

Then start server rails s and go to http://localhost:3000/blogs

Tested on Mac, ruby: 2.4.2, rails: 5.1.4

Title: Bootstrap not working with ruby

Body:
I recently done a project in ruby on rails with Bootstrap 4 beta 2, here are my setup:

Gemfile

gem 'jquery-ui-rails', '~> 5.0', '>= 5.0.5'
gem 'bootstrap', '~> 4.0.0.beta2'
gem 'jquery-rails', '~> 4.3', '>= 4.3.1'
gem 'font-awesome-rails'

app/assets/javascripts/application.js (The sequence are important)

//= require jquery3
//= require popper
//= require rails-ujs
//= require jquery-ui
//= require_tree .
//= require bootstrap-sprockets

assets/stylesheets/application.scss

@import "bootstrap";
@import "font-awesome";

For more details, go visit bootstrap-sass gem

HERE IS THE UPDATE (refer to bootstrap-sass)

Generate new rails app rails new bootstrap4test

bundle install

Scaffold a simple blog with text rails g scaffold Blog content:text

Database Migrate rails db:seed && rails db:migrate

Add gem into Gemfile

gem 'bootstrap-sass', '~> 3.3.7'
gem 'sass-rails', '>= 3.2'

rename app/assests/stylesheets/application.css to .scss

remove everything in the application.scss and add these

// "bootstrap-sprockets" must be imported before "bootstrap" and "bootstrap/variables"
@import "bootstrap-sprockets";
@import "bootstrap";

Now, add another gem gem 'jquery-rails' into your Gemfile

bundle install

in app/assets/javascripts/application.js add 2 lines

//= require jquery
//= require bootstrap-sprockets

Your application.js should look like this

//= require jquery
//= require bootstrap-sprockets
//= require rails-ujs
//= require turbolinks
//= require_tree .

Then start server rails s and go to http://localhost:3000/blogs

Tested on Mac, ruby: 2.4.2, rails: 5.1.4