问:
Having trouble putting 4 images in a 2 by 2 square to fit on half of the page in HTML/CSS
I've tried everything. Need Help PLEASE! Wanting to get the wire frame images in a 2 by 2 on the right side of the page. Being able to be responsive at the sametime.

any help will be appreciated soo much!

.flex-container {
    display: -webkit-flex;
 display: flex;
 -webkit-flex-direction: row;
 column-count:2;
 width: 100%;
 height: 25%;

}

.flex-item1 {

    font-family: sans-serif;
    width: 400px;
    height:auto;
    padding:50px;
    margin: 0,0,40px,0;
    text-align: justify;

}

.flex-item2 {

    font-family: sans-serif;
    width: 100px;
    height: 100px;
    align-items:center;
    display:flex;
    flex-wrap: wrap;

}

h1{

    text-align: center;
}

h2 {
    text-align: center;
    font-family: sans-serif;
    margin: 0;
    padding-left:200%;
    padding-top: 20px;
    width: 100%;
    height: auto;

}
.wireframe-container{

    position:fixed;
    width:100%;
    max-width: 100%;
    height: auto;
    margin: 0 auto;
    padding: 0px;
    text-align:center;

}

.wire{

    position:relative;
    display:inline-block;
    width:30%; max-width:180px;
    vertical-align: middle;
    margin:0 10px;
    padding-left:10px;

}

.desc {

    margin: 10px;
    padding-bottom:100px;

}

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="Assignment 1.css"/>

<title>Page Title</title>

</head>

<body>

  <img src="ass 1 background.png" class="responsive-image">

<div class="flex-container">

    <div class="flex-item1">
    Creating an app designed for mobile devices (smart phones and tablets). Able to use the smart phones camera or tablet to view the picture in real-time. Jager is centred around the old-style game of I Spy/Scavenger hunt played usually by kids. This focus would be part of the Mahuki Gamelab team. Creating games used for education in fun ways to help get children involved in the seasonal museum exhibitions.
        <br><br>
       <h1>Abstract</h1>
        <br><br>
    To create a game for mobile devices, tablets and smart phones. An app that uses augmented reality technology to involve users in the environment around them. The game is a scavenger hunt / I SPY type of game played using your smart phone or tablet’s built-in camera to view the world through. The app will generate an object to make the user search for from a list of pre-programmed items and paths. The app will give users a hint or a clue to the general area or direction of the object. A timer and a score will be used to create competition between children.  Students should be able to compare scores and time, from a type of leader board system. Animations and buttons will be projected onto user’s screens in real time off the objects. Users can gain achievements and badges for doing certain task also.
    </div>

<div class="flex-item2">

    <h2>Wireframes</h2>

     <div class="wireframes-container">

         <div class="wire">

           <img src="wire1.png"style="width:10em; height:15em;" />

           <div class="desc">phone</div>

            <img src="wire2.png"style="width:15em; height:15em;" />

            <div class="desc">tablet</div>

         <img src="wire4.png"style="width:10em; height:15em;" />

        <div class="desc">AR mode</div>

         <img src="wire3.png"style="width:15em; height:15em;" />
        <div class="desc">AR mode</div>

        </div>

        </div>

    </div>

    </div>

</body>

</html></code>```

答:
I believe this is what you're trying to achieve; it's very simple with the use of display:table and display:table-cell. Using these properties gives great browser support as well (IE 8+). Check out this bin:
http://jsbin.com/wedapulixa/edit?html,output

You'll likely need to change how the images are sized based on your needs, but I'll leave that up to you. You could utilize divs with the background-image and background-size properties instead of imgs depending on your needs.

Body:
I've tried everything. Need Help PLEASE! Wanting to get the wire frame images in a 2 by 2 on the right side of the page. Being able to be responsive at the sametime.

any help will be appreciated soo much!

.flex-container {
    display: -webkit-flex;
 display: flex;
 -webkit-flex-direction: row;
 column-count:2;
 width: 100%;
 height: 25%;

}

.flex-item1 {

    font-family: sans-serif;
    width: 400px;
    height:auto;
    padding:50px;
    margin: 0,0,40px,0;
    text-align: justify;

}

.flex-item2 {

    font-family: sans-serif;
    width: 100px;
    height: 100px;
    align-items:center;
    display:flex;
    flex-wrap: wrap;

}

h1{

    text-align: center;
}

h2 {
    text-align: center;
    font-family: sans-serif;
    margin: 0;
    padding-left:200%;
    padding-top: 20px;
    width: 100%;
    height: auto;

}
.wireframe-container{

    position:fixed;
    width:100%;
    max-width: 100%;
    height: auto;
    margin: 0 auto;
    padding: 0px;
    text-align:center;

}

.wire{

    position:relative;
    display:inline-block;
    width:30%; max-width:180px;
    vertical-align: middle;
    margin:0 10px;
    padding-left:10px;

}

.desc {

    margin: 10px;
    padding-bottom:100px;

}

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="Assignment 1.css"/>

<title>Page Title</title>

    Creating an app designed for mobile devices (smart phones and tablets). Able to use the smart phones camera or tablet to view the picture in real-time. Jager is centred around the old-style game of I Spy/Scavenger hunt played usually by kids. This focus would be part of the Mahuki Gamelab team. Creating games used for education in fun ways to help get children involved in the seasonal museum exhibitions.

Abstract

    To create a game for mobile devices, tablets and smart phones. An app that uses augmented reality technology to involve users in the environment around them. The game is a scavenger hunt / I SPY type of game played using your smart phone or tablet’s built-in camera to view the world through. The app will generate an object to make the user search for from a list of pre-programmed items and paths. The app will give users a hint or a clue to the general area or direction of the object. A timer and a score will be used to create competition between children.  Students should be able to compare scores and time, from a type of leader board system. Animations and buttons will be projected onto user’s screens in real time off the objects. Users can gain achievements and badges for doing certain task also.

Wireframes

phone

tablet

AR mode

AR mode


来源: stackexchange

问:
SSRS Charts: solution for better assignment of colors to the legend
If you have a line chart in SSRS with many lines, it is nearly impossible to identify which line belongs to which item in the legend, as the colors are nearly the same. Is there a better solution?

bad example of line chart legend

答:
All good ideas by R Richards. I often end up with charts looking like yours. The first thing I do is ask. Is this of any use to the end user, if not I'll try to rationalise the chart. Some of the ideas in the earlier answer are things I try but also you can try the following without reducing the amount of data in the chart.

Simply make the lines thicker, it's much easier to identify the colours with thicker lines.

Add tooltips to the data points so that the user can hover over the
lines and get info about the line and/or point.

Use a custom pallet, the default palette does not have many colours in (7 I think), so colours are repeated. Creating a custom palette with more colours will make it easier to identify each line. It also means, if you can ensure the order of series in your data that you can you produce consistent charts were a colour always represents a specific business object.

If you have breaks in the data, change the chart to use an average
to give you a continuous line. I think your x axis has to be set as
a time type for this to work, I can't remember off the top of my
head.

Here's a before and after the first two ideas were applied to a sample chart I built.

If you think you need to reduce the data, group line with smaller values together and then add a drill down chart to show these lines.

ContentLicense: CC BY-SA 3.0


问:
Else if statement ending program
I've attempted to write a function yes that confirms if the user wants to exit the program. If the user enters 'Y' or 'y' it exits successfully and if the user enters an invalid input it also exits successfully however, if the user enters 'N' or 'n' it will return them to the menu, but any further input will simply end the program. I've tried a do while loop as well, but was met with similar issues. Here's my code:

```<code>void GroceryInventorySystem(void) {
    int menuSelection;
    int exitSelection;

    welcome();
    printf("\n");

    while (menuSelection != 0)
    {
        menuSelection = menu();
        switch (menuSelection)
    {
        case 1:
        printf("List Items under construction!\n");
        pause();
        break;

        case 2:
        printf("Search Items under construction!\n");
        pause();
        break;

        case 3:
        printf("Checkout Item under construction!\n");
        pause();
        break;

        case 4:
        printf("Stock Item under construction!\n");
        pause();
        break;

        case 5:
        printf("Add/Update Item under construction!\n");
        pause();
        break;

        case 6:
        printf("Delete Item under construction!\n");
        pause();
        break;

        case 7:
        printf("Search by name under construction!\n");
        pause();
        break;

        default:
        printf("Exit the program? (Y)es/(N)o: ");
        exitSelection = yes();
        break;
        }
    }
}

int yes(void) {
        char YN;
        begin:;

        scanf("%c", &YN);
        flushKeyboard();

        if (YN == 'Y' || YN == 'y') {
        }

        else if (YN == 'N' || YN == 'n') {
        menu();
        }

        else {
            printf("Only (Y)es or (N)o are acceptable: ");
            goto begin;
        }
}

int menu(void) {
    int option;
    int firstSelection = 0;
    int lastSelection = 7;
    printf("\n1- List all items\n");
    printf("2- Search by SKU\n");
    printf("3- Checkout an item\n");
    printf("4- Stock an item\n");
    printf("5- Add new item or update item\n");
    printf("6- Delete item\n");
    printf("7- Search by name\n");
    printf("0- Exit program\n");
    printf("> ");
    option = getIntLimited(firstSelection, lastSelection);
    return option;
}
</code>```

I can provide the rest of the code if necessary.

答:
```<code>int yes(void)
{
            char YN;
            begin:;

            scanf("%c", &YN);
            flushKeyboard();

            if (YN == 'N' || YN == 'n') {
                    return 0;
            }

            else if (YN == 'Y' || YN == 'y') {
                    printf("Goodbye!\n");
            }

            else {
                    printf("Only (Y)es or (N)o are acceptable: ");
                    goto begin;
            }
}
</code>```

Title: Else if statement ending program

Body:
I've attempted to write a function yes that confirms if the user wants to exit the program. If the user enters 'Y' or 'y' it exits successfully and if the user enters an invalid input it also exits successfully however, if the user enters 'N' or 'n' it will return them to the menu, but any further input will simply end the program. I've tried a do while loop as well, but was met with similar issues. Here's my code:

void GroceryInventorySystem(void) {
    int menuSelection;
    int exitSelection;

    welcome();
    printf("\n");

    while (menuSelection != 0)
    {
        menuSelection = menu();
        switch (menuSelection)
    {
        case 1:
        printf("List Items under construction!\n");
        pause();
        break;

        case 2:
        printf("Search Items under construction!\n");
        pause();
        break;

        case 3:
        printf("Checkout Item under construction!\n");
        pause();
        break;

        case 4:
        printf("Stock Item under construction!\n");
        pause();
        break;

        case 5:
        printf("Add/Update Item under construction!\n");
        pause();
        break;

        case 6:
        printf("Delete Item under construction!\n");
        pause();
        break;

        case 7:
        printf("Search by name under construction!\n");
        pause();
        break;

        default:
        printf("Exit the program? (Y)es/(N)o: ");
        exitSelection = yes();
        break;
        }
    }
}

int yes(void) {
        char YN;
        begin:;

        scanf("%c", &YN);
        flushKeyboard();

        if (YN == 'Y' || YN == 'y') {
        }

        else if (YN == 'N' || YN == 'n') {
        menu();
        }

        else {
            printf("Only (Y)es or (N)o are acceptable: ");
            goto begin;
        }
}

int menu(void) {
    int option;
    int firstSelection = 0;
    int lastSelection = 7;
    printf("\n1- List all items\n");
    printf("2- Search by SKU\n");
    printf("3- Checkout an item\n");
    printf("4- Stock an item\n");
    printf("5- Add new item or update item\n");
    printf("6- Delete item\n");
    printf("7- Search by name\n");
    printf("0- Exit program\n");
    printf("> ");
    option = getIntLimited(firstSelection, lastSelection);
    return option;
}

I can provide the rest of the code if necessary.


问:
Correct usage of Clojure for macro
There are 100 buffaloes on the field.
There are 100 whisks on the field.
Each standing buffalo eats 5 whisks.
Each lying buffalo eats 3 whisks.
Each 3 old buffaloes eat 1 whisks.
How many buffaloes of each type are there on the filed?

This is my Clojure code to solve this problem:

```<code>;; s: number of Standing buffaloes
;; l: number of Lying buffaloes
;; o: number of Old buffaloes
(for [s (range 101) l (range 101) o (range 101)
      :while (and
              (= 100 (+ s l o)
               (= 100 (+ (* s 5) (* l 3) (* o 1/3)))))]
     [s l o])
</code>```

My code doesn't work. It should return how many buffaloes of each type but my code only returns an empty sequence. It seems to be logically incorrect. What's wrong with it?

答:
2 main issues:

By using :while, you're telling it to stop searching as soon as the condition returns false. I believe your intent was to skip cases where the condition is false. For that, you use :when.

Your condition has a misplaced brace, causing you to compare booleans and numbers, which is always false. Add a brace at the end of (= 100 (+ s l o). If you're using Cursive to write this, make sure you vertically align forms so Parinfer can manage braces for you.

Title: Correct usage of Clojure for macro

Body:
There are 100 buffaloes on the field.
There are 100 whisks on the field.
Each standing buffalo eats 5 whisks.
Each lying buffalo eats 3 whisks.
Each 3 old buffaloes eat 1 whisks.
How many buffaloes of each type are there on the filed?

This is my Clojure code to solve this problem:

;; s: number of Standing buffaloes
;; l: number of Lying buffaloes
;; o: number of Old buffaloes
(for [s (range 101) l (range 101) o (range 101)
      :while (and
              (= 100 (+ s l o)
               (= 100 (+ (* s 5) (* l 3) (* o 1/3)))))]
     [s l o])

My code doesn't work. It should return how many buffaloes of each type but my code only returns an empty sequence. It seems to be logically incorrect. What's wrong with it?


问:
Path to the project current dir in qt
I want to get a path to the project directory in Qt and reference the other files of my project relative to it. I know this issue have been already discussed here
Get current working directory in a Qt application
and here
How to get current working directory path of a Qt application?
but the answer is still unknown. In case it's impossible to get such a path then what is the approach of navigation among files of the Qt project.</p>

答:
Based on your comment, you are trying to:

Access some images which are being used in my program. I could of course put them into build target directory, but it becomes uncomfortable to pass my code to others.

The approach to store resource files in the project source directory and rely on such structure at runtime is not a greatest idea. I can't imagine the situation when mixing the concepts of initially decoupled source and build directories could be useful, correct me if I'm wrong.

So, according to your needs:

The most simple and plain way is to use the Qt resource system. The resource files are simply embedded into the executable, so there will be no need to access the file system.

Another way is the automatic deployment of the needed files. This answer describes the way to copy your files to the target directory using qmake.

Title: Path to the project current dir in qt


问:
Java Subversion libraries
I've been researching Java APIs for Subversion (SVN). It seems there are 3 available:

JavaHL - part of the SVN project. Provides a relatively low-level API

svnClientAdapter - part of the Subclipse project. Provides a relatively high-level API

SVNKit - unlike the other 2, this provides a 100% Java implementation of the SVN protocol, i.e. no native libaries must be installed. It provides a high-level API, a low-level API, an implementation of JavaHL, and a command-line client that uses SVNKit for it's implementation.

I have no practical experience with any of these APIs, but assuming the above is true, SVNKit looks like a clear winner. I know from experience that appearances can be deceiving, so am looking for feedback from someone who has actually used one or more of these libraries. Is SVNKit the runaway winner, as suggested above, or is there a better choice.

I guess the answer will depend on what I'll be doing with the API, and (perhaps surprisingly), the answer is mostly writing, e.g. adding, updating and deleting files, creating projects and repositories, branching, etc.

Thanks!
Don

答:
I've used SVNKit, it worked for me...they have some example's in their downloads... I was not so much comfortable learning it by those examples, but this link worked for me...

I could implement following functionality easily: CheckIn(Local Copy(LC) to Repository(R)), CheckOut(R to LC), Commit(Update changes from LC to Rep) , importing Dir/File to R, deleting Dir/File from R...

P.S. - This forum is also very helpful.

ContentLicense: CC BY-SA 2.5

Title: Java Subversion libraries


问:
firebase createUserWithEmailAndPassword is not working in android
I'm trying to use the createUserWithEmailAndPassword method to create users but not able to do so.
The OnAuthenticate method is being called but user object is null and no user is being created inside firebase console.
Here is my code, which is the one available online as well.

MAinActivity.java

```<code>private static FirebaseAuth mAuth;
private static FirebaseAuth.AuthStateListener mAuthListener;
private static String TAG = "RegisterDEbug";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);
    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            waitForDebugger();
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // ...
        }
    };
    mAuth.addAuthStateListener(mAuthListener);
    mAuth.createUserWithEmailAndPassword("9199999989@pintech.com", "corrfecthorsebatterystaple")
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    waitForDebugger();
                    Log.d(TAG, "Authentication successful");
                    if (!task.isSuccessful()) {
                        //Toast.makeText(this, "Authentication failed.",  Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
</code>```

app.properties

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'

        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

app.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.pt.reg"
        minSdkVersion 10
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.android.gms:play-services:9.0.2'
    //compile 'com.google.android.gms:play-services-auth:9.0.2'

    compile 'com.google.firebase:firebase-core:9.0.2'
    compile 'com.google.firebase:firebase-auth:9.0.2'
}

apply plugin: 'com.google.gms.google-services'
</code>```

Note -
 I have tried web solution from firebase for creating a user which works fine.

答:
I have the same problem.

change:

```<code>mAuth.createUserWithEmailAndPassword("9199999989@pintech.com", "corrfecthorsebatterystaple")
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
</code>```

to:

```<code>mAuth.createUserWithEmailAndPassword("9199999989@pintech.com", "corrfecthorsebatterystaple")
            .addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use the createUserWithEmailAndPassword method to create users but not able to do so.
The OnAuthenticate method is being called but user object is null and no user is being created inside firebase console.
Here is my code, which is the one available online as well.

MAinActivity.java

private static FirebaseAuth mAuth;
private static FirebaseAuth.AuthStateListener mAuthListener;
private static String TAG = "RegisterDEbug";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_main);
    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            waitForDebugger();
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // ...
        }
    };
    mAuth.addAuthStateListener(mAuthListener);
    mAuth.createUserWithEmailAndPassword("9199999989@pintech.com", "corrfecthorsebatterystaple")
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    waitForDebugger();
                    Log.d(TAG, "Authentication successful");
                    if (!task.isSuccessful()) {
                        //Toast.makeText(this, "Authentication failed.",  Toast.LENGTH_SHORT).show();
                    }
                }
            });
}

app.properties

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'

        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.pt.reg"
        minSdkVersion 10
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.google.android.gms:play-services:9.0.2'
    //compile 'com.google.android.gms:play-services-auth:9.0.2'

    compile 'com.google.firebase:firebase-core:9.0.2'
    compile 'com.google.firebase:firebase-auth:9.0.2'
}

apply plugin: 'com.google.gms.google-services'

Note -
 I have tried web solution from firebase for creating a user which works fine.

Body:
I have the same problem.

change:

mAuth.createUserWithEmailAndPassword("9199999989@pintech.com", "corrfecthorsebatterystaple")
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>()

to:

mAuth.createUserWithEmailAndPassword("9199999989@pintech.com", "corrfecthorsebatterystaple")
            .addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>()


问:
How can I optimize if-else statement to be more simple?
Im working with the code below in developing simple ios app using objective-C.Is that have another way to optimize this code:

```<code> if ([segue.identifier isEqualToString:@"showCommitDetail"]) {
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    CommitDetailsTableViewController *destViewController = segue.destinationViewController;

      RepoObject *repoObj = [self.RepoListArray objectAtIndex:indexPath.row];
    NSString *repoCommit_url = [repoObj.Commit_url stringByReplacingOccurrencesOfString:@"{/sha}" withString:@""];

if (indexPath.row == 0) {
    NSString *SpringBootURL = repoCommit_url;
    self.commit_url = SpringBootURL;
    destViewController.CommitRepoURL = self.commit_url;
    destViewController.navigationItem.title = @"Spring-Integration-in-Action";
}else if (indexPath.row == 1){
    NSString *SpringFrameworkURL = repoCommit_url;
    self.commit_url = SpringFrameworkURL;
    destViewController.CommitRepoURL = self.commit_url;
    destViewController.navigationItem.title = @"spring-data-jdbc-ext";
}else if (indexPath.row == 2){
    NSString *SpringAmqpURL = repoCommit_url;
    self.commit_url = SpringAmqpURL;
    destViewController.CommitRepoURL = self.commit_url;
    destViewController.navigationItem.title = @"spring-data-commons";
}else if (indexPath.row == 3){
    NSString *SpringIdeURL = repoCommit_url;
    self.commit_url = SpringIdeURL;
    destViewController.CommitRepoURL = self.commit_url;
    destViewController.navigationItem.title = @"spring-data-graph";
}else{
    NSString *SpringIntegratURL = repoCommit_url;
    self.commit_url = SpringIntegratURL;
    destViewController.CommitRepoURL = self.commit_url;
    destViewController.navigationItem.title = @"spring-data-document-examples";
}

}
</code>```

Beside that, how can i assign title directly without hard-coding it like i did above.?

答:
You can try change the second if elses to the following, it will optimize lines of code and legibility.

```<code>NSString *url = repoCommit_url;
self.commit_url = url;
destViewController.CommitRepoURL = self.commit_url;

if (indexPath.row == 0) {
    destViewController.navigationItem.title = @"Spring-Integration-in-Action";
}else if (indexPath.row == 1){
    destViewController.navigationItem.title = @"spring-data-jdbc-ext";
}else if (indexPath.row == 2){
    destViewController.navigationItem.title = @"spring-data-commons";
}else if (indexPath.row == 3){
    destViewController.navigationItem.title = @"spring-data-graph";
}else{
    destViewController.navigationItem.title = @"spring-data-document-examples";
}
</code>```

Body:
Im working with the code below in developing simple ios app using objective-C.Is that have another way to optimize this code:

 if ([segue.identifier isEqualToString:@"showCommitDetail"]) {
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    CommitDetailsTableViewController *destViewController = segue.destinationViewController;

      RepoObject *repoObj = [self.RepoListArray objectAtIndex:indexPath.row];
    NSString *repoCommit_url = [repoObj.Commit_url stringByReplacingOccurrencesOfString:@"{/sha}" withString:@""];

if (indexPath.row == 0) {
    NSString *SpringBootURL = repoCommit_url;
    self.commit_url = SpringBootURL;
    destViewController.CommitRepoURL = self.commit_url;
    destViewController.navigationItem.title = @"Spring-Integration-in-Action";
}else if (indexPath.row == 1){
    NSString *SpringFrameworkURL = repoCommit_url;
    self.commit_url = SpringFrameworkURL;
    destViewController.CommitRepoURL = self.commit_url;
    destViewController.navigationItem.title = @"spring-data-jdbc-ext";
}else if (indexPath.row == 2){
    NSString *SpringAmqpURL = repoCommit_url;
    self.commit_url = SpringAmqpURL;
    destViewController.CommitRepoURL = self.commit_url;
    destViewController.navigationItem.title = @"spring-data-commons";
}else if (indexPath.row == 3){
    NSString *SpringIdeURL = repoCommit_url;
    self.commit_url = SpringIdeURL;
    destViewController.CommitRepoURL = self.commit_url;
    destViewController.navigationItem.title = @"spring-data-graph";
}else{
    NSString *SpringIntegratURL = repoCommit_url;
    self.commit_url = SpringIntegratURL;
    destViewController.CommitRepoURL = self.commit_url;
    destViewController.navigationItem.title = @"spring-data-document-examples";
}

}

Beside that, how can i assign title directly without hard-coding it like i did above.?

Body:
You can try change the second if elses to the following, it will optimize lines of code and legibility.

NSString *url = repoCommit_url;
self.commit_url = url;
destViewController.CommitRepoURL = self.commit_url;

if (indexPath.row == 0) {
    destViewController.navigationItem.title = @"Spring-Integration-in-Action";
}else if (indexPath.row == 1){
    destViewController.navigationItem.title = @"spring-data-jdbc-ext";
}else if (indexPath.row == 2){
    destViewController.navigationItem.title = @"spring-data-commons";
}else if (indexPath.row == 3){
    destViewController.navigationItem.title = @"spring-data-graph";
}else{
    destViewController.navigationItem.title = @"spring-data-document-examples";
}


问:
SAS: Merging two tables with identical columns while dropping null values
I'm not sure if the title does this question justice, but here it goes:

I have three datasets Forecasts1, Forecasts2 and Forecasts3. They are all time series data composed of a date variable and variables r1 through r241.

For a given r variable (lets just use r1-r3, and only Forecasts 1 and 2 for now) each dataset has only one row where the value isn't null, and it is a different row in each dataset.

Forecast 1 looks like this:

Forecast 2 looks like this:

I need to be able to combine them such that r1-r3 contain all the non-null values, without creating duplicate date rows to hold the null values.

So ideally the finished produce would look like this:

I've tried various types of merges and sets, but I keep getting duplicate date rows. How would I go about doing this properly for all 241 (or more) variables? (specifically in SAS or Proc SQL?)

LINKS TO GOOGLE DOCS CONTAINING DATA:

Forecasts1: https://docs.google.com/spreadsheets/d/1iUEwPltU6V6ijgnkALFiIdrwrolDFt8xaITZaFC4WN8/edit?usp=sharing

Forecasts2:
https://docs.google.com/spreadsheets/d/1lQGKYJlz6AAR-DWtoWnl8SwzCNAmSpj7yxRqRgnybr8/edit?usp=sharing

答:
I tend to approach these types of problems using proc sql.  Assuming one row per date in the data sets, you can use full outer join:

```<code>proc sql;
    select coalesce(f1.date, f2.date) as date,
           coalesce(f1.r1, f2.r1) as r1,
           coalesce(f1.r2, f2.r2) as r2,
           coalesce(f1.r3, f2.r3) as r3
    from forecast1 f1 full outer join
         forecast2 f2
         on f1.date = f2.date
</code>```

Body:
I tend to approach these types of problems using proc sql.  Assuming one row per date in the data sets, you can use full outer join:

proc sql;
    select coalesce(f1.date, f2.date) as date,
           coalesce(f1.r1, f2.r1) as r1,
           coalesce(f1.r2, f2.r2) as r2,
           coalesce(f1.r3, f2.r3) as r3
    from forecast1 f1 full outer join
         forecast2 f2
         on f1.date = f2.date


问:
Raise async event in EF's DbContext.SaveChangesAsync()
I'm using EF Core, in an ASP.NET Core environment. My context is registered in my DI container as per-request.

I need to perform extra work before the context's SaveChanges() or SaveChangesAsync(), such as validation, auditing, dispatching notifications, etc. Some of that work is sync, and some is async.

So I want to raise a sync or async event to allow listeners do extra work, block until they are done (!), and then call the DbContext base class to actually save.

```<code>public class MyContext : DbContext
{

  // sync: ------------------------------

  // define sync event handler
  public event EventHandler<EventArgs> SavingChanges;

  // sync save
  public override int SaveChanges(bool acceptAllChangesOnSuccess)
  {
    // raise event for sync handlers to do work BEFORE the save
    var handler = SavingChanges;
    if (handler != null)
      handler(this, EventArgs.Empty);
    // all work done, now save
    return base.SaveChanges(acceptAllChangesOnSuccess);
  }

  // async: ------------------------------

  // define async event handler
  //public event /* ??? */ SavingChangesAsync;

  // async save
  public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
  {
    // raise event for async handlers to do work BEFORE the save (block until they are done!)
    //await ???
    // all work done, now save
    return await base.SaveChangesAsync(acceptAllChangesOnSuccess,  cancellationToken);
  }

}
</code>```

As you can see, it's easy for SaveChanges(), but how do I do it for SaveChangesAsync()?

答:
There is a simpler way (based on this).

Declare a multicast delegate which returns a Task:

```<code>namespace MyProject
{
  public delegate Task AsyncEventHandler<TEventArgs>(object sender, TEventArgs e);
}
</code>```

Update the context (I'm only showing async stuff, because sync stuff is unchanged):

```<code>public class MyContext : DbContext
{

  public event AsyncEventHandler<EventArgs> SavingChangesAsync;

  public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
  {
    var delegates = SavingChangesAsync;
    if (delegates != null)
    {
      var tasks = delegates
        .GetInvocationList()
        .Select(d => ((AsyncEventHandler<EventArgs>)d)(this, EventArgs.Empty))
        .ToList();
      await Task.WhenAll(tasks);
    }
    return await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
  }

}
</code>```

The calling code looks like this:

```<code>context.SavingChanges += OnContextSavingChanges;
context.SavingChangesAsync += OnContextSavingChangesAsync;

public void OnContextSavingChanges(object sender, EventArgs e)
{
  someSyncMethod();
}

public async Task OnContextSavingChangesAsync(object sender, EventArgs e)
{
  await someAsyncMethod();
}
</code>```

I'm not sure if this is a 100% safe way to do this. Async events are tricky. I tested with multiple subscribers, and it worked. My environment is ASP.NET Core, so I don't know if it works elsewhere.

I don't know how it compares with the other solution, or which is better, but this one is simpler and makes more sense to me.

EDIT: this works well if your handler doesn't change shared state. If it does, see the much more robust approach by @stephencleary above

Body:
I'm using EF Core, in an ASP.NET Core environment. My context is registered in my DI container as per-request.

I need to perform extra work before the context's SaveChanges() or SaveChangesAsync(), such as validation, auditing, dispatching notifications, etc. Some of that work is sync, and some is async.

So I want to raise a sync or async event to allow listeners do extra work, block until they are done (!), and then call the DbContext base class to actually save.

public class MyContext : DbContext
{

  // sync: ------------------------------

  // define sync event handler
  public event EventHandler<EventArgs> SavingChanges;

  // sync save
  public override int SaveChanges(bool acceptAllChangesOnSuccess)
  {
    // raise event for sync handlers to do work BEFORE the save
    var handler = SavingChanges;
    if (handler != null)
      handler(this, EventArgs.Empty);
    // all work done, now save
    return base.SaveChanges(acceptAllChangesOnSuccess);
  }

  // async: ------------------------------

  // define async event handler
  //public event /* ??? */ SavingChangesAsync;

  // async save
  public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
  {
    // raise event for async handlers to do work BEFORE the save (block until they are done!)
    //await ???
    // all work done, now save
    return await base.SaveChangesAsync(acceptAllChangesOnSuccess,  cancellationToken);
  }

}

As you can see, it's easy for SaveChanges(), but how do I do it for SaveChangesAsync()?

Body:
There is a simpler way (based on this).

Declare a multicast delegate which returns a Task:

namespace MyProject
{
  public delegate Task AsyncEventHandler<TEventArgs>(object sender, TEventArgs e);
}

Update the context (I'm only showing async stuff, because sync stuff is unchanged):

public class MyContext : DbContext
{

  public event AsyncEventHandler<EventArgs> SavingChangesAsync;

  public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
  {
    var delegates = SavingChangesAsync;
    if (delegates != null)
    {
      var tasks = delegates
        .GetInvocationList()
        .Select(d => ((AsyncEventHandler<EventArgs>)d)(this, EventArgs.Empty))
        .ToList();
      await Task.WhenAll(tasks);
    }
    return await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
  }

}

The calling code looks like this:

context.SavingChanges += OnContextSavingChanges;
context.SavingChangesAsync += OnContextSavingChangesAsync;

public void OnContextSavingChanges(object sender, EventArgs e)
{
  someSyncMethod();
}

public async Task OnContextSavingChangesAsync(object sender, EventArgs e)
{
  await someAsyncMethod();
}

I'm not sure if this is a 100% safe way to do this. Async events are tricky. I tested with multiple subscribers, and it worked. My environment is ASP.NET Core, so I don't know if it works elsewhere.

I don't know how it compares with the other solution, or which is better, but this one is simpler and makes more sense to me.

EDIT: this works well if your handler doesn't change shared state. If it does, see the much more robust approach by @stephencleary above


问:
Very strange iPhone app crash problem with tabbar based app
I know the title sounds a bit awkward but let me explain my problem.

I have a tab bar based iPhone app which works perfectly so far. I can switch through the tabs and every tab loads a view controller.

But here is how it crashes. After I used the app and working with a bunch of other apps I switch back to my app (for example after one hour). The app shows the screen where I left it. Now when I try to change the tab, it crashes immediately.

The problem is that I can't reproduce this crash in the simulator or in the debug mode. I tried to open it, then close it, then reopen it but then everything works. Only after a certain amount of time the crash can be reproduced. But I don't have any logs.

Maybe anyone had the same the problem and knows what to do here?

答: Connect your device with system using iPhone utility and found the reason for crash.  It may be memory problem only.</p>


问:
problems between database and website. I can't access my website
I uploaded online all my prestashop website files and database but when I try to open the website I get this error  "Link to database cannot be established: SQLSTATE[28000] [1045] Access denied for user 'lt27mhfc_dkddb'@'localhost' (using password: YES)".

I read somewhere on-line that when you upload the website files and the database the connection between those gets lost so I modified the setting.inc.php file changing db_name, db_user, db_password to match my new credentials.

I made a second new user and I choose a second new password and I even tried with those, the strange thing is that the message stays the same instead of saying “…for user newuser@’localhost’…”; like I never changed the user and password the second time.

I am working online with cpanel.

Can anyone help?

答:
I also get this a lot of time when I upload a new website. One method I tried and worked is that you add a port after the host. like

```<code>define('_DB_SERVER_', 'localhost:3306');
</code>```

Try it and tell if it works

Body:
I also get this a lot of time when I upload a new website. One method I tried and worked is that you add a port after the host. like

define('_DB_SERVER_', 'localhost:3306');

Try it and tell if it works


问:
Array insert and shift
I have the below array:

```<code>a = [0, 1, 2, 3, 4, nil, nil]
</code>```

And I'd like to insert an element num into index 2 such that the resulting array is:

```<code>a = [0, 1, num, 2, 3, 4, nil] # note the size hasn't changed
</code>```

I realize an Array might not be the most suitable data structure for this exercise, but assume that's a requirement.

How can I do this?

Why?

I'm trying to solve this problem:

You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order

Here's my code so far:

```<code>def merge(a, b) # merge b -> a
  pointer = 0 # on a
  while !b.empty? do
    case b.first <=> a[pointer]
    when 0, 1 next
    when -1
      # insert element, shift array to the right
    end
  end
end
</code>```

答:
Is this what you are looking for?

```<code>a.insert(2, num)
</code>```

Not sure if you looking to manually shift the elements, but this should do all of the work for you.

Title: Array insert and shift

Body:
I have the below array:

a = [0, 1, 2, 3, 4, nil, nil]

And I'd like to insert an element num into index 2 such that the resulting array is:

a = [0, 1, num, 2, 3, 4, nil] # note the size hasn't changed

I realize an Array might not be the most suitable data structure for this exercise, but assume that's a requirement.

How can I do this?

Why?

I'm trying to solve this problem:

You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order

Here's my code so far:

def merge(a, b) # merge b -> a
  pointer = 0 # on a
  while !b.empty? do
    case b.first <=> a[pointer]
    when 0, 1 next
    when -1
      # insert element, shift array to the right
    end
  end
end

Body:
Is this what you are looking for?

a.insert(2, num)

Not sure if you looking to manually shift the elements, but this should do all of the work for you.


问:
UIBezierPath appending overlapping isn't filled
I'm trying to merge two overlapping UIBezierPaths using UIBezierPath.append, and I want the overlapping space to be filled. I tried setting the usesEvenOddFillRule property to false, but it still doesn't fill. Here is minimal example of the problem:

```<code>override func draw(_ rect: CGRect) {
    let firstShape = UIBezierPath()

    firstShape.move(to: CGPoint(x: 100, y: 100))
    firstShape.addLine(to: CGPoint(x: 100, y: 150))
    firstShape.addLine(to: CGPoint(x: 150, y: 170))
    firstShape.close()

    let secondShape = UIBezierPath(rect: CGRect(x: 125, y: 125, width: 75, height: 75))

    let combined = UIBezierPath()
    combined.append(firstShape)
    combined.append(secondShape)

    UIColor.black.setFill()
    combined.fill()
}
</code>```

This yields the following shape:

What I would like it to look like:

This problem also seems to occur when using move(to: CGPoint) on one UIBezierPath. If you would draw both these shapes on the same UIBezierPath, the same problem would occur.

Does anyone know how to make the overlapping region filled? Preferably the solution would also work when doing addClip()

答:
You were on the right track with setting the usesEvenOddFillRule to false.  In addition to that, you need to make sure your shapes are both drawn in the same direction (clockwise or counter-clockwise).

I reversed the order of your addLines when drawing the triangle to reverse it.

```<code>override func draw(_ rect: CGRect) {
    let firstShape = UIBezierPath()

    firstShape.move(to: CGPoint(x: 100, y: 100))
    firstShape.addLine(to: CGPoint(x: 150, y: 170))
    firstShape.addLine(to: CGPoint(x: 100, y: 150))
    firstShape.close()

    let secondShape = UIBezierPath(rect: CGRect(x: 125, y: 125, width: 75, height: 75))

    let combined = UIBezierPath()
    combined.append(firstShape)
    combined.append(secondShape)
    combined.usesEvenOddFillRule = false

    UIColor.black.setFill()
    combined.fill()
}
</code>```

Body:
I'm trying to merge two overlapping UIBezierPaths using UIBezierPath.append, and I want the overlapping space to be filled. I tried setting the usesEvenOddFillRule property to false, but it still doesn't fill. Here is minimal example of the problem:

override func draw(_ rect: CGRect) {
    let firstShape = UIBezierPath()

    firstShape.move(to: CGPoint(x: 100, y: 100))
    firstShape.addLine(to: CGPoint(x: 100, y: 150))
    firstShape.addLine(to: CGPoint(x: 150, y: 170))
    firstShape.close()

    let secondShape = UIBezierPath(rect: CGRect(x: 125, y: 125, width: 75, height: 75))

    let combined = UIBezierPath()
    combined.append(firstShape)
    combined.append(secondShape)

    UIColor.black.setFill()
    combined.fill()
}

This yields the following shape:

What I would like it to look like:

This problem also seems to occur when using move(to: CGPoint) on one UIBezierPath. If you would draw both these shapes on the same UIBezierPath, the same problem would occur.

Does anyone know how to make the overlapping region filled? Preferably the solution would also work when doing addClip()

Body:
You were on the right track with setting the usesEvenOddFillRule to false.  In addition to that, you need to make sure your shapes are both drawn in the same direction (clockwise or counter-clockwise).

I reversed the order of your addLines when drawing the triangle to reverse it.

override func draw(_ rect: CGRect) {
    let firstShape = UIBezierPath()

    firstShape.move(to: CGPoint(x: 100, y: 100))
    firstShape.addLine(to: CGPoint(x: 150, y: 170))
    firstShape.addLine(to: CGPoint(x: 100, y: 150))
    firstShape.close()

    let secondShape = UIBezierPath(rect: CGRect(x: 125, y: 125, width: 75, height: 75))

    let combined = UIBezierPath()
    combined.append(firstShape)
    combined.append(secondShape)
    combined.usesEvenOddFillRule = false

    UIColor.black.setFill()
    combined.fill()
}


问:
PHPExcel: is it necessary to getSheet once you have an object?
Ok so PHPExcel loads the file into its objectReader

```<code>// 1. Load file

    $inputFileType = PHPExcel_IOFactory::identify($this->inputFileName);
    $this->LogMsg("FileType identified as :".$inputFileType, "O", $opLog);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $this->LogMsg("Reader Created successfully", "O", $opLog);
    $objReader->setReadDataOnly(true);  // if set to read only, it will ignore styling and data validation
    $objReader->setLoadSheetsOnly($this->sheetname);
    $objReader= $objReader->setReadFilter($filterSubset);
    $objPHPExcel = $objReader->load($this->inputFileName);
    echo ("File Loaded <br>");
</code>```

Suppose the data is loaded into object. Now after that, in order to access data, (correct me if I'm wrong) you would normally load the worksheet. Either with or without filters. That's about the only thing documentation tells you how to do (and I've read the developer and user docs).

```<code>$worksheet = $objPHPExcel->getSheet(0);
</code>```

After that, you can transform $worksheet into an array, and you can pretty much work with data in it.  Thing is though that for big files, the getSheet method is the one that takes the most time (In my case, 5seconds for a 9Mb excel file).

I was wondering whether loading worksheet is even necessary. What does $objPHPExcel contain once the file is loaded? var_dumping it doesn't enlighten me much because it seems to have a bunch of protected properties which you can't even access from the outside. Is it anything like a $result dataset after a query? Can I work with it rather than load sheets? Are there any methods other than load() that can be used on it? Can you point me towards anything to read other than the documentation?

答:
Excel file consists of many sheets as it is a spreadsheet. Actually all data is stored in sheets even if there is only one sheet.

So to work with data stored in sheet you must load it in memory and make PHPExcel to analyze it. Before it there is no data available to work with.

Body:
Ok so PHPExcel loads the file into its objectReader

// 1. Load file

    $inputFileType = PHPExcel_IOFactory::identify($this->inputFileName);
    $this->LogMsg("FileType identified as :".$inputFileType, "O", $opLog);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $this->LogMsg("Reader Created successfully", "O", $opLog);
    $objReader->setReadDataOnly(true);  // if set to read only, it will ignore styling and data validation
    $objReader->setLoadSheetsOnly($this->sheetname);
    $objReader= $objReader->setReadFilter($filterSubset);
    $objPHPExcel = $objReader->load($this->inputFileName);
    echo ("File Loaded
");

Suppose the data is loaded into object. Now after that, in order to access data, (correct me if I'm wrong) you would normally load the worksheet. Either with or without filters. That's about the only thing documentation tells you how to do (and I've read the developer and user docs).

$worksheet = $objPHPExcel->getSheet(0);

After that, you can transform $worksheet into an array, and you can pretty much work with data in it.  Thing is though that for big files, the getSheet method is the one that takes the most time (In my case, 5seconds for a 9Mb excel file).

I was wondering whether loading worksheet is even necessary. What does $objPHPExcel contain once the file is loaded? var_dumping it doesn't enlighten me much because it seems to have a bunch of protected properties which you can't even access from the outside. Is it anything like a $result dataset after a query? Can I work with it rather than load sheets? Are there any methods other than load() that can be used on it? Can you point me towards anything to read other than the documentation?


问:
React rerender specific components
I have a controller, which renders a Table and action buttons.
The Table has Row childs, with checkboxes. This is my render func:

```<code>render() {
        <div>
            <Table items={this.props.items}></Table>
            <Actions selectedItems={_.filter(this.props.items, i => i.selected)}
        </div>
}
</code>```

By checking each row, I update the item in the list with a 'selected' property.
But now, If I want to change the selected indication, I have to rerender all the container, including the table.
How can I do that without rendering the whole table? (Only render the FloatingActions)

this is my redux mapping:

Thanks.

答:
You should use react key property and give each row a unique key.

In this case React calls the render method of Table but only re-renders the changed row in the DOM.

Take a look here.

Title: React rerender specific components

Body:
I have a controller, which renders a Table and action buttons.
The Table has Row childs, with checkboxes. This is my render func:

render() {

            <Actions selectedItems={_.filter(this.props.items, i => i.selected)}

}

By checking each row, I update the item in the list with a 'selected' property.
But now, If I want to change the selected indication, I have to rerender all the container, including the table.
How can I do that without rendering the whole table? (Only render the FloatingActions)

this is my redux mapping:

Thanks.


问:
Convert existing rails column from string to array
I've an existing rails application and one of column's has existing semi-colon separated string. I want to convert the same into an array with an empty array as default.

Also, for rows which already have data in the semi-colon separated string format we need it to get converted into a proper array.

Database: psql or PostgreSQL

Framework: Rails 4.2

答:
The above is a pretty common scenario in development of any application and a lot of people face problems while doing the same in Rails.

In my opinion the easiest way to get all this done is:

Generate a new migration : rails g migration changeSomethingToArray

In the new migration file, add the following code.

```<code>class ChangeQualificationToArray < ActiveRecord::Migration
def change
  rename_column :coaches, :qualifications, :qualifications_text
  add_column :coaches, :qualifications, :text, default: []

  coaches = Coach.all
  coaches.each do |c|
    c.qualifications = convert_to_array(c.qualifications_text)
    c.save
  end

  remove_column :coaches, :qualifications_text

end

private

def convert_to_array(string)
  string.split(';')
  # This can be changed to `,` or  whatever you're using to split your string.
end
end
</code>```

Body:
The above is a pretty common scenario in development of any application and a lot of people face problems while doing the same in Rails.

In my opinion the easiest way to get all this done is:

Generate a new migration : rails g migration changeSomethingToArray

In the new migration file, add the following code.

class ChangeQualificationToArray < ActiveRecord::Migration
def change
  rename_column :coaches, :qualifications, :qualifications_text
  add_column :coaches, :qualifications, :text, default: []

  coaches = Coach.all
  coaches.each do |c|
    c.qualifications = convert_to_array(c.qualifications_text)
    c.save
  end

  remove_column :coaches, :qualifications_text

end

private

def convert_to_array(string)
  string.split(';')
  # This can be changed to `,` or  whatever you're using to split your string.
end
end


问:
WPF: Cannot access inner Datagrid
i have a problem with an inner Element in WPF. Its the innerGrid DataGrid.
I have no access to it in the code behind only to the normal Datagrid. Have I forgotten to add something in the xaml-code?</p>

```<code>  <DataGrid x:Name="dataGrid" ItemsSource="{Binding Path = data, IsAsync=True}" HorizontalAlignment="Left" Height="198" Margin="35,38,0,0" VerticalAlignment="Top" Width="474" AutoGenerateColumns="False" IsReadOnly="True">
        <DataGrid.RowHeaderTemplate>
            <DataTemplate>
                <Expander Expanded="Expander_Expanded" Collapsed="Expander_Collapsed">
                </Expander>
            </DataTemplate>
        </DataGrid.RowHeaderTemplate>
        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
           <DataGrid x:Name="innerGrid" Height="200">
                    <DataGrid.Columns>
                        <DataGridTextColumn  Header="Patientennummer" />
                    </DataGrid.Columns>
                </DataGrid>
               </DataTemplate>
             </DataGrid.RowDetailsTemplate>
             </DataGrid>
</code>```

答:
You can access inner grid in LoadingRowDetails event of your main "dataGrid".

```<code>private void dataGrid_LoadingRowDetails(object sender, DataGridRowDetailsEventArgs e)
    {
        DataGrid innerGrid = e.DetailsElement as DataGrid;

        if (innerGrid != null)
        {
        }
    }
</code>```

Alternatively, you can add "Loaded" event for "inner grid" and inside this event handler, you can do whatever you want to with inner grid.

Hope this helps.

Title: WPF: Cannot access inner Datagrid

Body:
i have a problem with an inner Element in WPF. Its the innerGrid DataGrid.
I have no access to it in the code behind only to the normal Datagrid. Have I forgotten to add something in the xaml-code?

  <DataGrid x:Name="dataGrid" ItemsSource="{Binding Path = data, IsAsync=True}" HorizontalAlignment="Left" Height="198" Margin="35,38,0,0" VerticalAlignment="Top" Width="474" AutoGenerateColumns="False" IsReadOnly="True">
        <DataGrid.RowHeaderTemplate>
            <DataTemplate>
                <Expander Expanded="Expander_Expanded" Collapsed="Expander_Collapsed">
                </Expander>
            </DataTemplate>
        </DataGrid.RowHeaderTemplate>
        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
           <DataGrid x:Name="innerGrid" Height="200">
                    <DataGrid.Columns>
                        <DataGridTextColumn  Header="Patientennummer" />
                    </DataGrid.Columns>
                </DataGrid>
               </DataTemplate>
             </DataGrid.RowDetailsTemplate>
             </DataGrid>

Body:
You can access inner grid in LoadingRowDetails event of your main "dataGrid".

private void dataGrid_LoadingRowDetails(object sender, DataGridRowDetailsEventArgs e)
    {
        DataGrid innerGrid = e.DetailsElement as DataGrid;

        if (innerGrid != null)
        {
        }
    }

Alternatively, you can add "Loaded" event for "inner grid" and inside this event handler, you can do whatever you want to with inner grid.

Hope this helps.


问:
No property findAllEntries found for type Entry
I don't know why Spring doesn't like my code:

I have Entry.java:

```<code>@Entity
@Table(name = "entries")
public class Entry {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "text")
    private String text;
}
</code>```

EntryDao.java:

```<code>public interface EntryDao extends JpaRepository<Entry, Long> {
    List<Entry> findAllEntries();
}
</code>```

EntryService.java:

```<code>@Service
public interface EntryService {

    List<Entry> findAllEntries();

}
</code>```

EntryServiceImpl.java:

```<code>public class EntryServiceImpl implements EntryService {
    private EntryDao entryDao;
    private SessionFactory sessionFactory;

    @Override
    @SuppressWarnings("unchecked")
    public List<Entry> findAllEntries()  {
        Session session = this.sessionFactory.getCurrentSession();
        List<Entry> entries = session.createQuery("from entries").list();
        return entries;
    }
}
</code>```

This code gives me an error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entryDao': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findAllEntries found for type Entry!

I don't understand how to handle this error and why this error occurs.

答:
The root cause you got the exception is that you're against the convention/rules to declare/create queries in Spring Data JPA.

The official docs of Spring Data JPA mentioned that:

The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.

The central interface of abstraction is Repository, to manage your entity, you need to declare your own interface of Repository and JPA will help you to create proxy instances for those interfaces. There're already some base Repositories like CrudRepository or PagingAndSortingRepository to provide basic functionalities as you can tell from their names, so by extending those basic ones, you'll have many basic methods. To define more specific access methods, you need to follow the ways JPA provided to create queries:

Define method in your interface following the method name convention

Use @Query annotation to define it manually

For the first method, the docs of Query Create has detailed clarification, here's some key idea:

The mechanism strips the prefixes find…By, read…By, query…By, count…By, and get…By from the method and starts parsing the rest of it. The introducing clause can contain further expressions such as a Distinct to set a distinct flag on the query to be created. However, the first By acts as delimiter to indicate the start of the actual criteria. At a very basic level you can define conditions on entity properties and concatenate them with And and Or

Simply speaking, JPA will parse the method name and try to find the related property to create query criteria for you.

Now let's have a look at your code, if you just want to retrieve all of your entities, you don't need to define your own method, there's already findAll methods pre-defined, if you want to retrieve entities based on text content, it's supposed to look like:

```<code>Entity findByText(String text)
</code>```

but your method findAllEntites just don't match any rules, so JPA throws such an error message to you.

Body:
I don't know why Spring doesn't like my code:

I have Entry.java:

@Entity
@Table(name = "entries")
public class Entry {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "text")
    private String text;
}

EntryDao.java:

public interface EntryDao extends JpaRepository<Entry, Long> {
    List<Entry> findAllEntries();
}

EntryService.java:

@Service
public interface EntryService {

    List<Entry> findAllEntries();

}

EntryServiceImpl.java:

public class EntryServiceImpl implements EntryService {
    private EntryDao entryDao;
    private SessionFactory sessionFactory;

    @Override
    @SuppressWarnings("unchecked")
    public List<Entry> findAllEntries()  {
        Session session = this.sessionFactory.getCurrentSession();
        List<Entry> entries = session.createQuery("from entries").list();
        return entries;
    }
}

This code gives me an error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entryDao': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findAllEntries found for type Entry!

I don't understand how to handle this error and why this error occurs.

Body:
The root cause you got the exception is that you're against the convention/rules to declare/create queries in Spring Data JPA.

The official docs of Spring Data JPA mentioned that:

The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.

The central interface of abstraction is Repository, to manage your entity, you need to declare your own interface of Repository and JPA will help you to create proxy instances for those interfaces. There're already some base Repositories like CrudRepository or PagingAndSortingRepository to provide basic functionalities as you can tell from their names, so by extending those basic ones, you'll have many basic methods. To define more specific access methods, you need to follow the ways JPA provided to create queries:

Define method in your interface following the method name convention

Use @Query annotation to define it manually

For the first method, the docs of Query Create has detailed clarification, here's some key idea:

The mechanism strips the prefixes find…By, read…By, query…By, count…By, and get…By from the method and starts parsing the rest of it. The introducing clause can contain further expressions such as a Distinct to set a distinct flag on the query to be created. However, the first By acts as delimiter to indicate the start of the actual criteria. At a very basic level you can define conditions on entity properties and concatenate them with And and Or

Simply speaking, JPA will parse the method name and try to find the related property to create query criteria for you.

Now let's have a look at your code, if you just want to retrieve all of your entities, you don't need to define your own method, there's already findAll methods pre-defined, if you want to retrieve entities based on text content, it's supposed to look like:

Entity findByText(String text)

but your method findAllEntites just don't match any rules, so JPA throws such an error message to you.


问:
jQuery Ajax clicks doesn't work unless page is refreshed
I've been messing around with some JS and ajax in my PHP project and I am facing some problems. The ajax only seems to work when the page is refreshed after clicking or just refresh to click. I'm using jquery 3.2.1.

I was first using .live() but that is deprecated now and I read that .on() is an alternative so I am using that now.

This is my JS part:

```<code>  $(".up_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'upvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(".down_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'downvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $("#btnpost").click(function() {
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
  });
});
</code>```

Is there anything I am missing or done wrong?

答:
Hi I think you missing return false or e.preventDefault();

return false;  make browser cancel post form to server.

add return false or e.preventDefault() after ajax function;

example

```<code>$("#btnpost").click(function(e) { ///e here
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
    e.preventDefault(); //Here
    /// or
    return false; /// Here

  });
</code>```

Body:
I've been messing around with some JS and ajax in my PHP project and I am facing some problems. The ajax only seems to work when the page is refreshed after clicking or just refresh to click. I'm using jquery 3.2.1.

I was first using .live() but that is deprecated now and I read that .on() is an alternative so I am using that now.

This is my JS part:

  $(".up_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'upvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(".down_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'downvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $("#btnpost").click(function() {
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
  });
});

Is there anything I am missing or done wrong?

Body:
Hi I think you missing return false or e.preventDefault();

return false;  make browser cancel post form to server.

add return false or e.preventDefault() after ajax function;

example

$("#btnpost").click(function(e) { ///e here
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
    e.preventDefault(); //Here
    /// or
    return false; /// Here

  });


问:
Why am I getting these runtime errors? Cannot connect to database (Netbeans with sql db)
Ok,

The database is present. I have successfully run the sql query file.

I have included the bin.jar reference library to connect to the db.

When I run the program i get:

Cannot connect to database server

```<code>Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at DBControl.getAllIndredients(DBControl.java:29)
        at Main.initFromDB(Main.java:207)
        at Main.<init>(Main.java:184)
        at Main$4.run(Main.java:171)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
</code>```

Can someone construe from this or have any ideas why I can't connect to the db server?

答: A NULL Pointer exception means that a reference has not been initialized. Did you forget to call "New" on something? You probably need a db connection object instance of some sort.</p>

Body:
Ok,

The database is present. I have successfully run the sql query file.

I have included the bin.jar reference library to connect to the db.

When I run the program i get:

Cannot connect to database server

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at DBControl.getAllIndredients(DBControl.java:29)
        at Main.initFromDB(Main.java:207)
        at Main.<init>(Main.java:184)
        at Main$4.run(Main.java:171)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Can someone construe from this or have any ideas why I can't connect to the db server?


问:
Prevent multiple ajax post
For the below ajax request I see multiple request sent to server. How can I prevent it.

```<code>        $('#winnerEditModal').modal().promise().done(function () {
                $('#updateWinnerBtn').click(function () {
                    debugger
                    var currentModal = $(this).closest('.modal');
                    var postBody = {};
                    var inputIds=currentModal.find('input').map(function(){return $(this).attr('id')});
                    var inputVals=currentModal.find('input').map(function(){return $(this).val()});
                    var id = currentModal.attr('winnerId');
                    postBody.id = id;
                    _.each(inputIds, function (v, k) {
                        var key = inputIds[k];
                        var val = inputVals[k];
                        postBody[key] = val;
                    });

                    editWinner(postBody).done(function (response) {
                        console.log(response)
                        if(response){
                            $table.bootstrapTable('refresh');
                            toastr.success('Winner is updated successfully');
                        }else{
                            toastr.error('Winner is not updated successfully. Check info again!!');
                        }
                    })
                });
            });
</code>```

This is the function to call ajax post. What is causing this behaviour and how can I prevent it

```<code>var editWinner = function (postBody) {
    return $.post({
        url: getCookie('digrectargetDomain')  + 'api/winner/edit',
       // type: 'POST',
        contentType : 'application/json',
        data : JSON.stringify(postBody),
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', getCookie('digrectoken'));
        }
    });
}
</code>```

答:
The problem is that you bind a click handler every time the model promise resolves (cf. first 2 lines of your code).

Just get the click handler out of the done callback:

```<code>var isResolved = false;
$('#updateWinnerBtn').click(function () {
    if (!resolved) return; // <-- handle click only when resolved
    debugger
    // rest of the click handler ...
    // ...
});

$('#winnerEditModal').modal().promise().done(function () {
    isResolved = true; // allow clicks to be handled
});
</code>```

Title: Prevent multiple ajax post

Body:
For the below ajax request I see multiple request sent to server. How can I prevent it.

        $('#winnerEditModal').modal().promise().done(function () {
                $('#updateWinnerBtn').click(function () {
                    debugger
                    var currentModal = $(this).closest('.modal');
                    var postBody = {};
                    var inputIds=currentModal.find('input').map(function(){return $(this).attr('id')});
                    var inputVals=currentModal.find('input').map(function(){return $(this).val()});
                    var id = currentModal.attr('winnerId');
                    postBody.id = id;
                    _.each(inputIds, function (v, k) {
                        var key = inputIds[k];
                        var val = inputVals[k];
                        postBody[key] = val;
                    });

                    editWinner(postBody).done(function (response) {
                        console.log(response)
                        if(response){
                            $table.bootstrapTable('refresh');
                            toastr.success('Winner is updated successfully');
                        }else{
                            toastr.error('Winner is not updated successfully. Check info again!!');
                        }
                    })
                });
            });

This is the function to call ajax post. What is causing this behaviour and how can I prevent it

var editWinner = function (postBody) {
    return $.post({
        url: getCookie('digrectargetDomain')  + 'api/winner/edit',
       // type: 'POST',
        contentType : 'application/json',
        data : JSON.stringify(postBody),
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', getCookie('digrectoken'));
        }
    });
}

Body:
The problem is that you bind a click handler every time the model promise resolves (cf. first 2 lines of your code).

Just get the click handler out of the done callback:

var isResolved = false;
$('#updateWinnerBtn').click(function () {
    if (!resolved) return; // <-- handle click only when resolved
    debugger
    // rest of the click handler ...
    // ...
});

$('#winnerEditModal').modal().promise().done(function () {
    isResolved = true; // allow clicks to be handled
});


问:
Troubleshooting "The use statement with non-compound name ... has no effect"
Getting this error when I put use Blog; at the top.

Warning: The use statement with non-compound name 'Blog' has no effect
  in...

Blog is my namespace in which I have 3 classes: Article, List and Category and a few functions.

If I change my statememnt to use Blog\Article; then it works...

Can't I just specify the namespaces I want to use? Do I need to provide classes?

What if I have functions within that namespaces? When I call them outside of the namespace, I'm forced to prepend \Blog\ to each one's name...

答:
if you don't want to use 'as' syntax like   </p>

```<code>use \Blog as B;
</code>```

<p>define a namespace for the file </p>

```<code>namespace anyname;

use Blog
</code>```

Body:
if you don't want to use 'as' syntax like

use \Blog as B;

define a namespace for the file

namespace anyname;

use Blog


问:
"Frame not in module" when using glTexImage2D
I have never come across this error before and I use glTexImage2D elsewhere in the project without error. Below is a screenshot of what error Visual Studio shows, and a view of the disassembly:

Given the line has ptr in it I assume there's a pointer error but I don't know what I'm doing wrong.
Below is the function I use to convert from an SDL_surface to a texture.

```<code>void surfaceToTexture(SDL_Surface *&surface, GLuint &texture) {
    glEnable(GL_TEXTURE_2D);
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, surface->pixels);
    glDisable(GL_TEXTURE_2D);
}
</code>```

This function succeeds elsewhere in the program, for example when loading text:

```<code>SDL_Surface *surface;
surface = TTF_RenderText_Blended(tempFont, message.c_str(), color);
if (surface == NULL)
    printf("Unable to generate text surface using font: %s! SDL_ttf Error: %s\n", font.c_str(), TTF_GetError());
else {
    SDL_LockSurface(surface);
    width = surface->w;
    height = surface->h;
    if (style != TTF_STYLE_NORMAL)
        TTF_SetFontStyle(tempFont, TTF_STYLE_NORMAL);
    surfaceToTexture(surface, texture);
    SDL_UnlockSurface(surface);
}
SDL_FreeSurface(surface);
</code>```

But not when loading an image:

```<code>SDL_Surface* surface = IMG_Load(path.c_str());
if (surface == NULL)
    printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError());
else{
    SDL_LockSurface(surface);
    width = (w==0)?surface->w:w;
    height = (h==0)?surface->h/4:h;
    surfaceToTexture(surface, texture);
    SDL_UnlockSurface(surface);
}
SDL_FreeSurface(surface);
</code>```

Both examples are extracted from a class where texture is defined.
The path to the image is correct.
I know it's glTexImage2D that causes the problem as I added a breakpoint at the start of surfaceToTexture and stepped through the function.
Even when it doesn't work, texture and surface do have seemingly correct values/properties.

Any ideas?

答:
The error you're getting means, that the procress crashed within a section of code for which the debugger could not find any debugging information (association between assembly and source code) whatsoever. This is typically the case for anything that's part of a/your program's debug build.

Now in your case what happens is, that you called glTexImage2D with parameters that "lie" to it about the memory layout of the buffer you pointed it to with the data parameter. Pointers don't carry any meaningful meta information (as far as the assembly level is concerned, they're just another integer, with special meaning). So you must make sure, that all the parameters you pass to a function along with a pointer do match up. If not, somewhere deep in the bowles of that function, or whatever it calls (or that calls, etc.) the memory might be accessed in a way that violates constraints set up by the operating system, triggering that kind of crash.

Solution to your problem: Fix your code, i.e. make sure that what you pass to OpenGL is consistent. It crashes within the OpenGL driver, but only because you lied to it.

Body:
I have never come across this error before and I use glTexImage2D elsewhere in the project without error. Below is a screenshot of what error Visual Studio shows, and a view of the disassembly:

Given the line has ptr in it I assume there's a pointer error but I don't know what I'm doing wrong.
Below is the function I use to convert from an SDL_surface to a texture.

void surfaceToTexture(SDL_Surface *&surface, GLuint &texture) {
    glEnable(GL_TEXTURE_2D);
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, surface->pixels);
    glDisable(GL_TEXTURE_2D);
}

This function succeeds elsewhere in the program, for example when loading text:

SDL_Surface *surface;
surface = TTF_RenderText_Blended(tempFont, message.c_str(), color);
if (surface == NULL)
    printf("Unable to generate text surface using font: %s! SDL_ttf Error: %s\n", font.c_str(), TTF_GetError());
else {
    SDL_LockSurface(surface);
    width = surface->w;
    height = surface->h;
    if (style != TTF_STYLE_NORMAL)
        TTF_SetFontStyle(tempFont, TTF_STYLE_NORMAL);
    surfaceToTexture(surface, texture);
    SDL_UnlockSurface(surface);
}
SDL_FreeSurface(surface);

But not when loading an image:

SDL_Surface* surface = IMG_Load(path.c_str());
if (surface == NULL)
    printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError());
else{
    SDL_LockSurface(surface);
    width = (w==0)?surface->w:w;
    height = (h==0)?surface->h/4:h;
    surfaceToTexture(surface, texture);
    SDL_UnlockSurface(surface);
}
SDL_FreeSurface(surface);

Both examples are extracted from a class where texture is defined.
The path to the image is correct.
I know it's glTexImage2D that causes the problem as I added a breakpoint at the start of surfaceToTexture and stepped through the function.
Even when it doesn't work, texture and surface do have seemingly correct values/properties.

Any ideas?


问:
How to correctly syntax a chained promise function
I have a list that I would like it to go through a function and make some fixes on that list, so I can use it later.

Because its function is depended on the result of the previous, I decided to use the chained defer, to wait one another.

```<code>    var $q = Promise;
  $scope.list = function(scan_result) {

  return $q.resolve(scan_result)
    .then(function(scan_result) {
      // Creates an object list with bssid and signal
      const ap_list = scan_result.map(str => {
        return {
          bssid: str.match(/BSSID:\s(\S*)/)[1],
          signal: str.match(/Signal:\s(\S*)/)[1]
        }
      });
      console.log("1st Then:");
      console.log(ap_list);
      return ap_list;
    })

  .then(function(ap_list) {
  //Sort the elements Highest to Lowest Signal Level
  ap_list.sort(function(a, b) {
    return b.signal - a.signal;
  });
  console.log("2nd Then:");
  console.log(ap_list);
  return ap_list;
})

  .then(function(ap_list) {
    //Removes the elements that have signal bellow -50
    for (var i = 0; i < ap_list.length; i++) {
      if (ap_list[i].signal < -50) {
        ap_list.splice(i, 1);
      }
    }
    console.log("3rd Then:");
    console.log(ap_list);
    return ap_list;
  })

  .then(function(ap_list) {
    //From the list keep the highest 3
    //console.log(ap_list);
    console.log("4th Then:");
    console.log(ap_list.slice(0, 3));
    return ap_list.slice(0, 3);
  })
}

$scope.checkin = function() {
  var scan_result = $scope.getList();
  console.log(scan_result);
  $scope.list(scan_result)
    .then(function(result) {
      //console.log(result);
    })
}
</code>```

When I output the result of the $scope.list() function on the console, it says the promise is pending and the status equals to 0.

So, definitely something is wrong here. Im not a defer guru so I kindly ask for your help.

答:
it says the promise is pending and the status equals to 0.

Promise must need to either resolve or reject to complete its state.

You not doing it,So,it is in pending state.

To chain the promise,you must return the promise.

```<code>$scope.list = function(scan_result) {

  var defer = $q.defer();

  defer.promise
    .then(function() {
       //code
      defer.resolve(ap_list);
      return defer.promise;
    })

  .then(function(ap_list) {
    //code
    defer.resolve(ap_list);
    return defer.promise;

  })

  .then(function(ap_list) {
    //code

    defer.resolve(ap_list);
    return defer.promise;
  })

  .then(function(ap_list) {
    //From the list keep the highest 3
    defer.resolve(ap_list.slice(0, 2));
    return defer.promise;
  })

  defer.resolve() //EDIT CODE

  return defer.promise;
}
</code>```

Body:
I have a list that I would like it to go through a function and make some fixes on that list, so I can use it later.

Because its function is depended on the result of the previous, I decided to use the chained defer, to wait one another.

    var $q = Promise;
  $scope.list = function(scan_result) {

  return $q.resolve(scan_result)
    .then(function(scan_result) {
      // Creates an object list with bssid and signal
      const ap_list = scan_result.map(str => {
        return {
          bssid: str.match(/BSSID:\s(\S*)/)[1],
          signal: str.match(/Signal:\s(\S*)/)[1]
        }
      });
      console.log("1st Then:");
      console.log(ap_list);
      return ap_list;
    })

  .then(function(ap_list) {
  //Sort the elements Highest to Lowest Signal Level
  ap_list.sort(function(a, b) {
    return b.signal - a.signal;
  });
  console.log("2nd Then:");
  console.log(ap_list);
  return ap_list;
})

  .then(function(ap_list) {
    //Removes the elements that have signal bellow -50
    for (var i = 0; i < ap_list.length; i++) {
      if (ap_list[i].signal < -50) {
        ap_list.splice(i, 1);
      }
    }
    console.log("3rd Then:");
    console.log(ap_list);
    return ap_list;
  })

  .then(function(ap_list) {
    //From the list keep the highest 3
    //console.log(ap_list);
    console.log("4th Then:");
    console.log(ap_list.slice(0, 3));
    return ap_list.slice(0, 3);
  })
}

$scope.checkin = function() {
  var scan_result = $scope.getList();
  console.log(scan_result);
  $scope.list(scan_result)
    .then(function(result) {
      //console.log(result);
    })
}

When I output the result of the $scope.list() function on the console, it says the promise is pending and the status equals to 0.

So, definitely something is wrong here. Im not a defer guru so I kindly ask for your help.

Body:
it says the promise is pending and the status equals to 0.

Promise must need to either resolve or reject to complete its state.

You not doing it,So,it is in pending state.

To chain the promise,you must return the promise.

$scope.list = function(scan_result) {

  var defer = $q.defer();

  defer.promise
    .then(function() {
       //code
      defer.resolve(ap_list);
      return defer.promise;
    })

  .then(function(ap_list) {
    //code
    defer.resolve(ap_list);
    return defer.promise;

  })

  .then(function(ap_list) {
    //code

    defer.resolve(ap_list);
    return defer.promise;
  })

  .then(function(ap_list) {
    //From the list keep the highest 3
    defer.resolve(ap_list.slice(0, 2));
    return defer.promise;
  })

  defer.resolve() //EDIT CODE

  return defer.promise;
}


问:
PHP Largest Possible Integer Constant
Was reading the PHP manual on integer overflow in the manual and was wondering: is there a PHP pre-defined constant for the current largest integer value possible? Something equivalent to the JavaScript Number.MAX_VALUE constant.

答:
PHP_INT_MAX according to PHP.net. Please note that the actual max value depends on whether PHP is compiled for 32bit or 64bit.

Also, you can use PHP_INT_SIZE to get the size of the integer.

Title: PHP Largest Possible Integer Constant


问:
Rails & Postgresql: how to group queries by hour?
How do I group by hour in Postgres & Rails? I've read through quite a few SO answers but I'm getting errors.

This works when grouping by date:

```<code>Model.group("date(updated_at)").count
</code>```

Then I tried the following for hour but they didn't work:

```<code>Model.group("hour(updated_at)").count
Model.group("date_format(updated_at, '%H')").count
Model.group("extract(hour from updated_at)").count
</code>```

Once I've found certain hours I need to update, how would I then get the models with those hours? I.e:

```<code>Model.where("hour(updated_at) = ?", 5)
</code>```

答:
PostgreSQL presents two ways to extract a part of date/time:

EXTRACT is SQL standard function that exists in other SQL based databases.

```<code>Model.group("EXTRACT(hour FROM created_at)").count
Model.where("EXTRACT(hour FROM created_at) = ?", 5)
</code>```

date_part function

```<code>Model.group("date_part('hour', updated_at)").count
Model.where("date_part('hour', updated_at) = ?", 5)
</code>```

The official documentation.

Body:
How do I group by hour in Postgres & Rails? I've read through quite a few SO answers but I'm getting errors.

This works when grouping by date:

Model.group("date(updated_at)").count

Then I tried the following for hour but they didn't work:

Model.group("hour(updated_at)").count
Model.group("date_format(updated_at, '%H')").count
Model.group("extract(hour from updated_at)").count

Once I've found certain hours I need to update, how would I then get the models with those hours? I.e:

Model.where("hour(updated_at) = ?", 5)

Body:
PostgreSQL presents two ways to extract a part of date/time:

EXTRACT is SQL standard function that exists in other SQL based databases.

Model.group("EXTRACT(hour FROM created_at)").count
Model.where("EXTRACT(hour FROM created_at) = ?", 5)

date_part function

Model.group("date_part('hour', updated_at)").count
Model.where("date_part('hour', updated_at) = ?", 5)

The official documentation.


问:
How to get an array of records in php
I execute an SQL query with php, this is the code:

```<code>$get_inspection_dates_query = "SELECT `date`
                                            FROM `vehicles` INNER JOIN `inspection_dates` ON `plate` = `id_vehicle`
                                            WHERE `plate` = '$vehicle_plate'";
$result_set = $connection->query($get_inspection_dates_query);
$inspection_dates = $result_set->fetchAll(PDO::FETCH_NUM);
</code>```

inspection_dates is:

```<code>Array
(
[0] => Array
    (
        [0] => 2012-01-01
    )

[1] => Array
    (
        [0] => 2013-01-01
    )

)
</code>```

but I don't want this.
I simply want an array of records, without the columns (even because I select only one column, so I don't need to have an array inside the array), something like this:

```<code>Array
(
    [0] = 2012-01-01
    [1] = 2013-01-01
)
</code>```

I know that I could reach something like this with a while loop and fetch ($row = $result_set->fetch()), but I think it's a bit tricky.
Is there any other method to obtain that array quickly?

答:
Simply get each result one at a time and place the date in the array like this</p>

```<code>$get_inspection_dates_query = "SELECT `date`
                               FROM `vehicles` INNER JOIN `inspection_dates` ON `plate` = `id_vehicle`
                               WHERE `plate` = '$vehicle_plate'";
$result_set = $connection->query($get_inspection_dates_query);

$inspection_dates = array();  // init an empty array
while ( $row = $result_set->fetch(PDO::FETCH_NUM) ) {
    $inspection_dates[] = $row[0];
}
</code>```

Title: How to get an array of records in php

Body:
I execute an SQL query with php, this is the code:

$get_inspection_dates_query = "SELECT `date`
                                            FROM `vehicles` INNER JOIN `inspection_dates` ON `plate` = `id_vehicle`
                                            WHERE `plate` = '$vehicle_plate'";
$result_set = $connection->query($get_inspection_dates_query);
$inspection_dates = $result_set->fetchAll(PDO::FETCH_NUM);

inspection_dates is:

Array
(
[0] => Array
    (
        [0] => 2012-01-01
    )

[1] => Array
    (
        [0] => 2013-01-01
    )

)

but I don't want this.
I simply want an array of records, without the columns (even because I select only one column, so I don't need to have an array inside the array), something like this:

Array
(
    [0] = 2012-01-01
    [1] = 2013-01-01
)

I know that I could reach something like this with a while loop and fetch ($row = $result_set->fetch()), but I think it's a bit tricky.
Is there any other method to obtain that array quickly?

Body:
Simply get each result one at a time and place the date in the array like this

$get_inspection_dates_query = "SELECT `date`
                               FROM `vehicles` INNER JOIN `inspection_dates` ON `plate` = `id_vehicle`
                               WHERE `plate` = '$vehicle_plate'";
$result_set = $connection->query($get_inspection_dates_query);

$inspection_dates = array();  // init an empty array
while ( $row = $result_set->fetch(PDO::FETCH_NUM) ) {
    $inspection_dates[] = $row[0];
}


答:
Try using PDO::FETCH_COLUMN instead of PDO::FETCH_NUM.

```<code>$inspection_dates = $result_set->fetchAll(PDO::FETCH_COLUMN);
</code>```

Title: How to get an array of records in php

Body:
Try using PDO::FETCH_COLUMN instead of PDO::FETCH_NUM.

$inspection_dates = $result_set->fetchAll(PDO::FETCH_COLUMN);