问:
IllegalStateException: Content has been consumed
I got struck because of IllegalStateException in the following code. Can anybody please help me? Code:

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        Button bt = (Button) findViewById(R.id.logbt);
        final EditText user = (EditText) findViewById(R.id.loguser);
        final EditText pw = (EditText) findViewById(R.id.logpw);
        bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (user.getText().toString() != "" && pw.getText().toString() != "") {
                    Thread t = new Thread() {
                        public void run() {
                            try {
                                HttpClient client = new DefaultHttpClient();
                                String postURL = "http://surfkid.redio.de/login";
                                HttpPost post = new HttpPost(postURL);
                                ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
                                params.add(new BasicNameValuePair("username", user.getText().toString()));
                                params.add(new BasicNameValuePair("password", md5(pw.getText().toString())));
                                UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
                                post.setEntity(ent);
                                HttpResponse responsePOST = client.execute(post);
                                HttpEntity resEntity = responsePOST.getEntity();
                                final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
                                Log.e("XXX", EntityUtils.toString(resEntity));
                            } catch (Exception e) {
                                Log.e("XXX", e.toString());
                            }
                        }
                    };
                    t.start();
                    // Log.e("XXX",s);
                }
            }
        });
    }

    private String md5(String in) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
            digest.reset();
            digest.update(in.getBytes());
            byte[] a = digest.digest();
            int len = a.length;
            StringBuilder sb = new StringBuilder(len << 1);
            for (int i = 0; i < len; i++) {
                sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
                sb.append(Character.forDigit(a[i] & 0x0f, 16));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
</code>```

Logcat message:

01-18 18:39:53.383: ERROR/XXX(7113):
  java.lang.IllegalStateException:
  Content has been consumed

答:
First, this has to be a mistake that every single new android programmer makes and it's asked here every single day. You have

```<code>user.getText().toString()!= ""&& pw.getText().toString()!= ""
</code>```

This doesn't do what you want it to. You need

```<code> !user.getText().toString().equals("")&& !pw.getText().toString().equals("")
</code>```

Also, you need to print the stacktrace. In your exception, you need

```<code>e.printStackTrace()
</code>```

instead of logging

```<code>e.toString()
</code>```

Body:
I got struck because of IllegalStateException in the following code. Can anybody please help me? Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        Button bt = (Button) findViewById(R.id.logbt);
        final EditText user = (EditText) findViewById(R.id.loguser);
        final EditText pw = (EditText) findViewById(R.id.logpw);
        bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (user.getText().toString() != "" && pw.getText().toString() != "") {
                    Thread t = new Thread() {
                        public void run() {
                            try {
                                HttpClient client = new DefaultHttpClient();
                                String postURL = "http://surfkid.redio.de/login";
                                HttpPost post = new HttpPost(postURL);
                                ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
                                params.add(new BasicNameValuePair("username", user.getText().toString()));
                                params.add(new BasicNameValuePair("password", md5(pw.getText().toString())));
                                UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);
                                post.setEntity(ent);
                                HttpResponse responsePOST = client.execute(post);
                                HttpEntity resEntity = responsePOST.getEntity();
                                final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
                                Log.e("XXX", EntityUtils.toString(resEntity));
                            } catch (Exception e) {
                                Log.e("XXX", e.toString());
                            }
                        }
                    };
                    t.start();
                    // Log.e("XXX",s);
                }
            }
        });
    }

    private String md5(String in) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
            digest.reset();
            digest.update(in.getBytes());
            byte[] a = digest.digest();
            int len = a.length;
            StringBuilder sb = new StringBuilder(len << 1);
            for (int i = 0; i < len; i++) {
                sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
                sb.append(Character.forDigit(a[i] & 0x0f, 16));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Logcat message:

01-18 18:39:53.383: ERROR/XXX(7113):
  java.lang.IllegalStateException:
  Content has been consumed

Body:
First, this has to be a mistake that every single new android programmer makes and it's asked here every single day. You have

user.getText().toString()!= ""&& pw.getText().toString()!= ""

This doesn't do what you want it to. You need

 !user.getText().toString().equals("")&& !pw.getText().toString().equals("")

Also, you need to print the stacktrace. In your exception, you need

e.printStackTrace()

instead of logging

e.toString()


来源: stackexchange

问:
Close NSWindow but do not nil it
I have a window-less app with the "Application is agent" set to YES. In that app I have a "let mainWindow: NSWindow" and with the click on a menu item I do the following:

```<code>func createNewWindow(){
    mainWindow.center()
    mainWindow.hidesOnDeactivate = true
    mainWindow.isMovableByWindowBackground = true
    mainWindow.backgroundColor = NSColor(calibratedHue: 0, saturation: 0, brightness: 1, alpha: 0.4)
    mainWindow.contentViewController = searchView
    mainWindow.makeKeyAndOrderFront(nil)
    NSApp.activate(ignoringOtherApps: true)
}</code>```

If I click outside my window or in any way shift focus to another app, my window closes and I have to click my menu item to open it again. Now this is what I want, so this is great. But if I in the view controller call "self.view.window?.close()" and there after click my menu item to open my window again, I get a bad access when accessing mainWindow, so I am guessing something has set it to nil when I close it.

How do I close my window in the same way as when I click outside the window? Or how do I otherwise prevent the bad access error?

Thank you

Søren

答:
Not something, you set it to nil when you close the window.

From the documentation of close()

If the window is set to be released when closed, a release message is
  sent to the object after the current event is completed. For an
  NSWindow object, the default is to be released on closing, while for
  an NSPanel object, the default is not to be released. You can use the
  isReleasedWhenClosed property to change the default behavior.

Either change the behavior or call orderOut(_:) which doesn't release the window.

ContentLicense: CC BY-SA 3.0

Title: Close NSWindow but do not nil it

Body:
I have a window-less app with the "Application is agent" set to YES. In that app I have a "let mainWindow: NSWindow" and with the click on a menu item I do the following:

func createNewWindow(){
    mainWindow.center()
    mainWindow.hidesOnDeactivate = true
    mainWindow.isMovableByWindowBackground = true
    mainWindow.backgroundColor = NSColor(calibratedHue: 0, saturation: 0, brightness: 1, alpha: 0.4)
    mainWindow.contentViewController = searchView
    mainWindow.makeKeyAndOrderFront(nil)
    NSApp.activate(ignoringOtherApps: true)
}

If I click outside my window or in any way shift focus to another app, my window closes and I have to click my menu item to open it again. Now this is what I want, so this is great. But if I in the view controller call "self.view.window?.close()" and there after click my menu item to open my window again, I get a bad access when accessing mainWindow, so I am guessing something has set it to nil when I close it.

How do I close my window in the same way as when I click outside the window? Or how do I otherwise prevent the bad access error?

Thank you

Søren


问:
SQL Server Analysis Services still needed if using Power BI?
I have a project that requires using SQL Server Analysis Services, but we've also started looking at PowerBI.

I'm not entirely clear on how PowerBI functions, and where the computations/data storage takes place. If we use PowerBI for generating the analytics, is there still a benefit to having an Analysis Services layer?

答:
To Use Analysis Services or Not?

It depends. If you already have an Analysis Services (SSAS) model, as Caio mentions, then I wouldn't get rid of it. Power BI works very well with Analysis Services and Analysis Services is going to offer a lot of enterprise-grade options that Power BI isn't going to improve upon (such as the ability to handle millions of new rows each day).

However, if you don't have an Analysis Services model already, SSAS isn't a prerequisite for using Power BI. As Mike mentions, Power BI is fully featured by itself and can easily handle most needs (importing data, modeling the data, and then visualizing the data).

To answer your question about computation and storage, Power BI has a number of layers:

An ETL layer (M). This is how data is brought into your model.

A modeling layer (DAX). This is where the data is stored, and where calculations run.

A visualization layer.

When you use Power BI with Analysis Services in Direct Query mode, then the ETL & data modeling side of things are handled by SSAS. All computation & data storage happens in Analysis Services and Power BI becomes a visualization layer only, sending queries to Analysis Services as needed for your reports.

When you don't have Analysis Services (and are using Data Import mode), then the data is stored in Power BI and all the computations run inside Power BI too.

Pros & Cons of Each Option

The advantage of using Power BI without SSAS is speed of delivery. Everything is handled in one file by one person. If you need to change your data model to make a report work, you can do that within Power BI. When you have a SSAS model, making changes to your data model can be cumbersome (partly because you have to use another tool and partly because any changes will affect all users).

The advantage of using Power BI with SSAS is scalability. Configured correctly, a single Analysis Services model can grow to handle hundreds of gigabytes, hundreds of reports, and hundreds of users with no issue. Analysis Services offers a level of enterprise robustness that goes beyond what you'd want a Power BI file to handle.

That said, introducing Analysis Services brings a number of disadvantages: most importantly, licensing & maintaining a SQL Server & keeping that server up-to-date. Power BI Desktop is updated monthly and is a quick download to get the latest & greatest DAX features. Using SSAS means you have to wait for new releases of SQL Server that include the same DAX features, then test & install them.

Conclusion

If you're not dealing with vast amounts of data (e.g. millions of new rows each month), one way to know if you need the enterprise-grade features of Analysis Services would be to think about the reports needed at the end of the project. If there's a dozen or less reports and you plan to build them all yourself, then Power BI alone offers a lot of advantages. If, on the other hand, there's a whole department of report writers waiting for you to build a data model, then Analysis Services is the way to go.

Sidenote

What's more important than Analysis Services vs. Power BI for ETL/modeling is getting your data model right. A poor data model will be slow using either tool. A well-designed data model will be fast using either option. Make sure to spend plenty of time understanding best practices when it comes to modeling your data. "Analyzing Data with Power BI and Power Pivot for Excel" by Alberto Ferrari & Marco Russo is well worth picking up if you're new to data modeling & BI in general. (Not saying you are.)


问:
How to show a user-defined data type in Haskell
So I'm trying to define my own data type which expresses natural numbers recursively, as such:

```<code> data Nat = Zero | Succ Nat
</code>```

This function works correctly:

```<code> showNat :: Nat -> String
 showNat Zero = "Zero"
 showNat (Succ k) = "Succ " ++ (showNat k)
</code>```

However, I don't want to have to call it every time I want to output a Nat to the screen. I attempted this:

```<code>  instance Show Nat where
  show Zero = "Zero"
  show (Succ k) = "Succ " ++ Main.show k
</code>```

But it returns an error:

```<code>• No explicit implementation for
    either ‘showsPrec’ or ‘Prelude.show’
• In the instance declaration for ‘Show Nat’
|
| > instance Show Nat where   |            ^^^^^^^^
</code>```

How can I correctly write instances of 'Show'?

答:
Just to clarify, without the indentation, you are doing two separate things:

Defining instance Show Nat without implementing any functions in it and

Defining an unrelated function called show. This is why

Using just "show" (which I did originally) gave an "Ambiguous occurrence" error

there are two show functions in scope and Haskell rules don't give priority to one of them.

Body:
So I'm trying to define my own data type which expresses natural numbers recursively, as such:

 data Nat = Zero | Succ Nat

This function works correctly:

 showNat :: Nat -> String
 showNat Zero = "Zero"
 showNat (Succ k) = "Succ " ++ (showNat k)

However, I don't want to have to call it every time I want to output a Nat to the screen. I attempted this:

  instance Show Nat where
  show Zero = "Zero"
  show (Succ k) = "Succ " ++ Main.show k

But it returns an error:

• No explicit implementation for
    either ‘showsPrec’ or ‘Prelude.show’
• In the instance declaration for ‘Show Nat’
|
| > instance Show Nat where   |            ^^^^^^^^

How can I correctly write instances of 'Show'?


问:
Goroutine does not run
I'm trying to use a goroutine to write item to database. The goroutine however doesn't seem to do anything for some reason.

I've got following functions:

```<code>func addEvent(w http.ResponseWriter, r *http.Request) {
    body, err := ioutil.ReadAll(r.Body)
    fmt.Println(string(body[:]))

    if err != nil {
        panic(err)
    }

    eventCh := make(chan []byte)
    eventCh <- body
    go models.WriteEventToDb(eventCh)

}
</code>```

and

```<code>func WriteEventToDb(eventCh chan []byte) {
    fmt.Println("event")
    event := <-eventCh
    newEvent := createNewEvent(event)
    err := db.Insert(&newEvent)

    if err != nil {
        panic(err)
    }

}
</code>```

Any idea why WriteEventToDb does not run?

答:
Your function blocks before it gets to start the goroutine:

```<code>eventCh := make(chan []byte)
eventCh <- body
</code>```

This makes a new channel, and before it can be passed off to any other routine, it tries to send a message to that channel. Since the channel is unbuffered and nothing is reading from it, the send blocks indefinitely.

Title: Goroutine does not run

Body:
I'm trying to use a goroutine to write item to database. The goroutine however doesn't seem to do anything for some reason.

I've got following functions:

func addEvent(w http.ResponseWriter, r *http.Request) {
    body, err := ioutil.ReadAll(r.Body)
    fmt.Println(string(body[:]))

    if err != nil {
        panic(err)
    }

    eventCh := make(chan []byte)
    eventCh <- body
    go models.WriteEventToDb(eventCh)

}

and

func WriteEventToDb(eventCh chan []byte) {
    fmt.Println("event")
    event := <-eventCh
    newEvent := createNewEvent(event)
    err := db.Insert(&newEvent)

    if err != nil {
        panic(err)
    }

}

Any idea why WriteEventToDb does not run?

Body:
Your function blocks before it gets to start the goroutine:

eventCh := make(chan []byte)
eventCh <- body

This makes a new channel, and before it can be passed off to any other routine, it tries to send a message to that channel. Since the channel is unbuffered and nothing is reading from it, the send blocks indefinitely.


问:
Delete row from php array
How can I remove an element from an array?

For example:

```<code>$data = Array('first' , 'second' , 'third');
array_delete($data[2]);

#$data would now read Array('first', 'second')
</code>```

Does such a built-in function exist?
Thanks.

答:
```<code>unset($data[2]);
</code>```

yes it does. unset().

ContentLicense: CC BY-SA 2.5

Title: Delete row from php array

Body:
How can I remove an element from an array?

For example:

$data = Array('first' , 'second' , 'third');
array_delete($data[2]);

#$data would now read Array('first', 'second')

Does such a built-in function exist?
Thanks.

Body:
unset($data[2]);

yes it does. unset().


问:
NodeJS Mongoose not working properly
I have a problem with NodeJS and Mongoose. The connection to the DB stands but I can't get any data from there. I can connect to /api/buckets as well with no problems. Here is my code:

app.js

```<code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

Bucket = require('./models/bucket');

// Connect to Mongoose
mongoose.connect('mongodb://localhost/worldbucket', function (err) {
    if (err) throw err;
    console.log('Successfully connected');
});

app.get('/', function (req, res) {
    res.send('Please use sth other');
});

app.get('/api/buckets', function (req, res) {
    Bucket.getBuckets(function (err, buckets) {
        console.log("funkt");
        if (err) {
            throw err;
        }
        res.json(buckets);
    });
});

app.listen(3000);
console.log('Running on port 3000');
</code>```

and bucket.js:

```<code>var mongoose = require('mongoose');

// Bucket Schema
var bucketSchema = mongoose.Schema({
    id: mongoose.Schema.Types.ObjectId,
    creator: String,
    text: String,
    fulfilment: String,
    latitude: Number,
    longtitude: Number
});

var  Bucket = mongoose.model('bucket', bucketSchema);

module.exports = Bucket;

// get Buckets
module.exports.getBuckets = (callback, limit) => {
    Bucket.find(callback).limit(limit);
}
</code>```

I hope you can help me.

Thanks in advance

答:
Im not sure what version of mongoose you using, but from their docs

http://mongoosejs.com/docs/queries.html

```<code>// With a JSON doc
  Person
      .find({
        occupation: /host/
      })
      .limit(10)
      .sort({ occupation: -1 })
      .select({ name: 1, occupation: 1 })
      .exec(callback);
</code>```

So in your case should be

```<code>Bucket.find({}).limit(limit).exec(callback);
</code>```

Hope this helps.

Title: NodeJS Mongoose not working properly

Body:
I have a problem with NodeJS and Mongoose. The connection to the DB stands but I can't get any data from there. I can connect to /api/buckets as well with no problems. Here is my code:

app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

Bucket = require('./models/bucket');

// Connect to Mongoose
mongoose.connect('mongodb://localhost/worldbucket', function (err) {
    if (err) throw err;
    console.log('Successfully connected');
});

app.get('/', function (req, res) {
    res.send('Please use sth other');
});

app.get('/api/buckets', function (req, res) {
    Bucket.getBuckets(function (err, buckets) {
        console.log("funkt");
        if (err) {
            throw err;
        }
        res.json(buckets);
    });
});

app.listen(3000);
console.log('Running on port 3000');

and bucket.js:

var mongoose = require('mongoose');

// Bucket Schema
var bucketSchema = mongoose.Schema({
    id: mongoose.Schema.Types.ObjectId,
    creator: String,
    text: String,
    fulfilment: String,
    latitude: Number,
    longtitude: Number
});

var  Bucket = mongoose.model('bucket', bucketSchema);

module.exports = Bucket;

// get Buckets
module.exports.getBuckets = (callback, limit) => {
    Bucket.find(callback).limit(limit);
}

I hope you can help me.

Thanks in advance

Body:
Im not sure what version of mongoose you using, but from their docs

http://mongoosejs.com/docs/queries.html

// With a JSON doc
  Person
      .find({
        occupation: /host/
      })
      .limit(10)
      .sort({ occupation: -1 })
      .select({ name: 1, occupation: 1 })
      .exec(callback);

So in your case should be

Bucket.find({}).limit(limit).exec(callback);

Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
Open all dataset files of a given directory in R
I m looking for a better way to open all xlsx and csv files of a repository at a time and then merge them. Here is what I have done, but as you will see there are some manual actions that I m trying to automate. Can you please help me?

Define the Working directory

```<code>setwd("~/Desktop/repo/")
list.files()

[1] "dataset1.csv"
[2] "dataset2.csv"
[3] "dataset3.csv"
[4] "dataset4.csv"
[5] "export.xlsx"
[6] "export1.xlsx"
[7] "export2.xlsx"
</code>```

Open all CSV files (this part seems OK to me, as each dataset opens automatically)

```<code>file.list <- list.files(pattern='*.csv')
csv_df <- lapply(file.list, read.csv, header=TRUE)
csv_df <- do.call("rbind", csv_df) #open all csv in a single dataframe
</code>```

Open all XLSX files (here comes the most ugly manually part)

```<code>df1 <- lapply(excel_sheets("export.xlsx"), read_excel, path = "export.xlsx")
df2 <- lapply(excel_sheets("export1.xlsx"), read_excel, path = "export(1).xlsx")
df3 <- lapply(excel_sheets("export2.xlsx"), read_excel, path = "export(2).xlsx")
df1 <- do.call("rbind", df1)
df2 <- do.call("rbind", df2)
df3 <- do.call("rbind", df3)
xlsx_df <- rbind(df1, df2, df3) #merge all xlsx
</code>```

Merge everything in a big dataset

```<code>big_df <- rbind(csv_df, xlsx_df)
</code>```

Any suggestions ? How can I improve this script (specially the 3. part)?

答:
For reading in Excel files other than .csv files, I recommend package XLConnect, which can read in all kinds of Excel files (.xlsx, .xls,.xlsm).
I made some minor edits to your 2nd part and this should work (assuming all your column names are the same in each .xlsx file):

```<code>library(XLConnect)

list.files()
file.list <- list.files(pattern='*.xlsx')
xlsx_df <- lapply(file.list, readWorksheetFromFile, header = T)
xlsx_df <- do.call("rbind", xlsx_df)
</code>```

If you cannot install the XLConnect package, try to install package openxlsx which does not require java. The code would be like this:

```<code>library(openxlsx)

list.files()
file.list <- list.files(pattern='*.xlsx')
xlsx_df <- lapply(file.list, read.xlsx, header = T)
xlsx_df <- do.call("rbind", xlsx_df)
</code>```

Edits:
To read in all sheets from a Excel file: I borrowed a function created in this post  and make it a openxlsx version:

```<code>library(openxlsx)
read_excel_allsheets <- function(filename) {
  sheets <- names(loadWorkbook(filename))
  x <- lapply(sheets, function(X) readWorkbook(filename, sheet = X))
  names(x) <- sheets
  x
}

data <- read_excel_allsheets("file.xlsx")
</code>```

Body:
I m looking for a better way to open all xlsx and csv files of a repository at a time and then merge them. Here is what I have done, but as you will see there are some manual actions that I m trying to automate. Can you please help me?

Define the Working directory

setwd("~/Desktop/repo/")
list.files()

[1] "dataset1.csv"
[2] "dataset2.csv"
[3] "dataset3.csv"
[4] "dataset4.csv"
[5] "export.xlsx"
[6] "export1.xlsx"
[7] "export2.xlsx"

Open all CSV files (this part seems OK to me, as each dataset opens automatically)

file.list <- list.files(pattern='*.csv')
csv_df <- lapply(file.list, read.csv, header=TRUE)
csv_df <- do.call("rbind", csv_df) #open all csv in a single dataframe

Open all XLSX files (here comes the most ugly manually part)

df1 <- lapply(excel_sheets("export.xlsx"), read_excel, path = "export.xlsx")
df2 <- lapply(excel_sheets("export1.xlsx"), read_excel, path = "export(1).xlsx")
df3 <- lapply(excel_sheets("export2.xlsx"), read_excel, path = "export(2).xlsx")
df1 <- do.call("rbind", df1)
df2 <- do.call("rbind", df2)
df3 <- do.call("rbind", df3)
xlsx_df <- rbind(df1, df2, df3) #merge all xlsx

Merge everything in a big dataset

big_df <- rbind(csv_df, xlsx_df)

Any suggestions ? How can I improve this script (specially the 3. part)?

Body:
For reading in Excel files other than .csv files, I recommend package XLConnect, which can read in all kinds of Excel files (.xlsx, .xls,.xlsm).
I made some minor edits to your 2nd part and this should work (assuming all your column names are the same in each .xlsx file):

library(XLConnect)

list.files()
file.list <- list.files(pattern='*.xlsx')
xlsx_df <- lapply(file.list, readWorksheetFromFile, header = T)
xlsx_df <- do.call("rbind", xlsx_df)

If you cannot install the XLConnect package, try to install package openxlsx which does not require java. The code would be like this:

library(openxlsx)

list.files()
file.list <- list.files(pattern='*.xlsx')
xlsx_df <- lapply(file.list, read.xlsx, header = T)
xlsx_df <- do.call("rbind", xlsx_df)

Edits:
To read in all sheets from a Excel file: I borrowed a function created in this post  and make it a openxlsx version:

library(openxlsx)
read_excel_allsheets <- function(filename) {
  sheets <- names(loadWorkbook(filename))
  x <- lapply(sheets, function(X) readWorkbook(filename, sheet = X))
  names(x) <- sheets
  x
}

data <- read_excel_allsheets("file.xlsx")


问:
Node js, starting Discord.js bot using exec, doesn’t properly run
So let’s say I have 2 files, a.js and b.js, where a.js is a simple node.js script which calls b.js which is a Discord.js bot.

a.js

```<code>const { exec } = require(‘child_process’);
exec(‘node b.js’, (err,stdout,stderr) => {
console.log(‘err: ‘ + err + ‘\n stdout: ‘ + stdout + ‘\n stderr:‘ + stderr);
});
</code>```

b.js

```<code>const Discord = require(‘discord.js’);
const fs = require(‘fs’);
var bot = new Discord.Client();
var token;
fs.readFile(‘token.txt’,(err,data) => {
    if(err){console.log(err); process.exit(0);}
    token = data;
});
bot.on(‘ready’,()=>{console.log(‘ready’);});
bot.on(‘message’, message => {
    if(message.content == ‘ping’){
        message.channel.send(‘pong’);
    }
});
bot.login(token);
</code>```

When I run a.js, the only output is

```<code>err:
stdout:
stderr:
</code>```

a.js then terminates and it appears as if b.js never ran.
I was wondering why this happens and why.
Additionally if anyone is wondering why I am doing this, I have this as apart of a bigger script and I boiled down the problem to this. And the main part is that b.js MUST be run from exec. I am running this in Windows 10 using the most recent version of node, and Discord.js. Thank you

答:
I had a go at running a.js with b.js, except I changed b.js to simply console.log

a.js

```<code>const { exec } = require('child_process');
exec('node b.js', (err,stdout,stderr) => {
console.log('err: ' + err + '\n stdout: ' + stdout + '\n stderr:' + stderr);
});
</code>```

b.js

```<code>console.log("B was called");
</code>```

Then when i run node a.js i get;

```<code>node .\a.js
err: null
 stdout: B was called

 stderr:
</code>```

I'm guessing there's a path issue where A can't find B relative to where it's being called from?

Body:
So let’s say I have 2 files, a.js and b.js, where a.js is a simple node.js script which calls b.js which is a Discord.js bot.

a.js

const { exec } = require(‘child_process’);
exec(‘node b.js’, (err,stdout,stderr) => {
console.log(‘err: ‘ + err + ‘\n stdout: ‘ + stdout + ‘\n stderr:‘ + stderr);
});

b.js

const Discord = require(‘discord.js’);
const fs = require(‘fs’);
var bot = new Discord.Client();
var token;
fs.readFile(‘token.txt’,(err,data) => {
    if(err){console.log(err); process.exit(0);}
    token = data;
});
bot.on(‘ready’,()=>{console.log(‘ready’);});
bot.on(‘message’, message => {
    if(message.content == ‘ping’){
        message.channel.send(‘pong’);
    }
});
bot.login(token);

When I run a.js, the only output is

err:
stdout:
stderr:

a.js then terminates and it appears as if b.js never ran.
I was wondering why this happens and why.
Additionally if anyone is wondering why I am doing this, I have this as apart of a bigger script and I boiled down the problem to this. And the main part is that b.js MUST be run from exec. I am running this in Windows 10 using the most recent version of node, and Discord.js. Thank you

Body:
I had a go at running a.js with b.js, except I changed b.js to simply console.log

a.js

const { exec } = require('child_process');
exec('node b.js', (err,stdout,stderr) => {
console.log('err: ' + err + '\n stdout: ' + stdout + '\n stderr:' + stderr);
});

b.js

console.log("B was called");

Then when i run node a.js i get;

node .\a.js
err: null
 stdout: B was called

 stderr:

I'm guessing there's a path issue where A can't find B relative to where it's being called from?


问:
Scale limit for matrix transform for a Microsoft Surface application
I've developed a surface application in which users are able to pull from a menu a movie and drag it on the main canvas. I've created a user control to host the movie and I implemented Affine2dManipulation in order to allow the users to rotate, scale and move the control on the main canvas.
The problem is that i want to set a scale limit for control. The RenderTransform is handled by a MatrixTransform.

If anyone has any ideeas on how to limit the scaletransform for the matrix please let me know

答: Is there any particular reason why you aren't using ScatterView/ScatterViewItem? Because those controls are meant to give you the exact behavior you explained here. </p>


问:
How can I deserialize an array of objects in Symfony Serializer?
Is is possible in Symfony Serializer to deserialize an array of objects in a property? I have a Boss class with the $Npc = [] property that needs to hold a array of Npc objects. I did see some examples in the documentation, but they do not state this feature.  I have a json string with an array of NPC's For example:

```<code>class Boss {

    private $Npc = [];

    /**
    * @return Npc[]
    */
    public function getNpcs(): array
    {
        return $this->npcs;
    }
}
</code>```

I am using php7.1 and symfony/serializer version ^3.3.

Edit:
I already tried PhpDocExtractor, but it would not let me install it. :(

Edit:
This is a possible JSON value:

```<code>{
    "bossname": "Epic boss!",
    "npcs": [{
        "id": 24723,
        "name": "Selin Fireheart",
        "urlSlug": "selin-fireheart",
        "creatureDisplayId": 22642
    }]
}
</code>```

答:
Yes, you can deserialize the array but you need to provide on the second parameter the object as well as the information that it is in fact an array. You can do this like this:

```<code>use Symfony\Component\Serializer\Serializer;

class Boss {

    private $Npc = [];

    /**
    * @return Npc[]
    */
    public function getNpcs(): array
    {
        return $serializer->deserialize($this->npcs, 'Acme\Npc[]', 'json');

    }
}
</code>```

You can find more information about this in the documentation on handling arrays

Body:
Is is possible in Symfony Serializer to deserialize an array of objects in a property? I have a Boss class with the $Npc = [] property that needs to hold a array of Npc objects. I did see some examples in the documentation, but they do not state this feature.  I have a json string with an array of NPC's For example:

class Boss {

    private $Npc = [];

    /**
    * @return Npc[]
    */
    public function getNpcs(): array
    {
        return $this->npcs;
    }
}

I am using php7.1 and symfony/serializer version ^3.3.

Edit:
I already tried PhpDocExtractor, but it would not let me install it. :(

Edit:
This is a possible JSON value:

{
    "bossname": "Epic boss!",
    "npcs": [{
        "id": 24723,
        "name": "Selin Fireheart",
        "urlSlug": "selin-fireheart",
        "creatureDisplayId": 22642
    }]
}

Body:
Yes, you can deserialize the array but you need to provide on the second parameter the object as well as the information that it is in fact an array. You can do this like this:

use Symfony\Component\Serializer\Serializer;

class Boss {

    private $Npc = [];

    /**
    * @return Npc[]
    */
    public function getNpcs(): array
    {
        return $serializer->deserialize($this->npcs, 'Acme\Npc[]', 'json');

    }
}

You can find more information about this in the documentation on handling arrays


问:
Attached ShadowRoot using Polyfill is not query-able
In the following sample, I am trying to create a menu component to experiment component hierarchy.

index.html

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="robots" content="index, follow">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Sample Menu App</title>
    <script src="js/webcomponents-lite.js"></script>
    <!-- Components -->
    <link rel="import" href="components/global/site-navigation.html">
</head>

<body>
    <site-navigation></site-navigation>
</body>

</html>
</code>```

/components/global/site-navigation.html

```<code><link rel="import" href="nav-item.html">
<template>
    <div class="nav">Header Goes here</div>
    <ul class="nav">
        <nav-item>Item 1</nav-item> <!-- This is a child component-->
    </ul>
</template>
<script>
    (function (currentDocument) {
        customElements.define('site-navigation', class SiteNavigation extends HTMLElement {
        constructor() {
            super();
            const shadowTemplate = currentDocument.querySelector('template').content.cloneNode(true);
            this.DOM = this.attachShadow({ mode: 'open' });
            this.DOM.appendChild(shadowTemplate);
            console.log(this.DOM);
        }

        connectedCallback(){
            this.Initialize();
        }

        Initialize(){
            this.DOM.querySelector("div.nav").innerHTML = "Title"
        }
    });
    })((document.currentScript || document._currentScript).ownerDocument);
</script>
</code>```

/components/global/nav-item.html

```<code><template>
    <li class="nitem">
        <a href="#">Elements</a>
    </li>
</template>
<script>
    (function(currentDocument) {
        customElements.define('nav-item', class SiteNavigationItem extends HTMLElement {
            constructor() {
                super();
                const shadowTemplate = currentDocument.querySelector('template').content.cloneNode(true);
                this.DOM = this.attachShadow({ mode: 'open' });
                this.DOM.appendChild(shadowTemplate);
            }

            connectedCallback(){
                this.Initialize();
            }

            Initialize(){
                let aTag = this.DOM.querySelector('a');
                aTag.innerHTML = "Link 1"
            }
        });
    })((document._currentScript||document.currentScript).ownerDocument);
</script>
</code>```

It works fine in Chrome. I have applied Polyfill to make it work in other browsers. However, the Initialize method fails in FireFox with message TypeError: this.DOM.querySelector(...) is null. On debugging it is found that the this.DOM = this.attachShadow({ mode: 'open' }); returns different type of objects in FF and Chrome and in the FF result, there is no querySelector! How can I tackle this?

FF Result

Chrome Result

UPDATE:
The parent component (site-navigation) is working fine if link/reference to the child component (nav-item) is removed.

答:
As you stated, it seems that component hierarchy is not supported in the HTML Imports polyfill.

document.currentScript doesn't work either. The polyfill will copy the <template> in the main document for the 2 imported documents.

That's why when you query querySelector( 'template' ) in the mail document, it's nav-item's template which is returned, with no div.nav inside.

As a workaroud, you should be more specific when you query the <template>.

In site-navigtion.html:

```<code><template id="site-navigation">
...
</template>
...
const shadowTemplate = currentDocument.querySelector('template#site-navigation').content.cloneNode(true);
</code>```

Thus you'll get the right template, even in Firefox.

Note: document._currentScript doesn't seem to work any more with Polyfill v1.

Body:
In the following sample, I am trying to create a menu component to experiment component hierarchy.

index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="robots" content="index, follow">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Sample Menu App</title>

    <link rel="import" href="components/global/site-navigation.html">

    <site-navigation></site-navigation>

/components/global/site-navigation.html

<link rel="import" href="nav-item.html">
<template>

Header Goes here

        Item 1

</template>

/components/global/nav-item.html

<template>

        Elements

</template>

It works fine in Chrome. I have applied Polyfill to make it work in other browsers. However, the Initialize method fails in FireFox with message TypeError: this.DOM.querySelector(...) is null. On debugging it is found that the this.DOM = this.attachShadow({ mode: 'open' }); returns different type of objects in FF and Chrome and in the FF result, there is no querySelector! How can I tackle this?

FF Result

Chrome Result

UPDATE:
The parent component (site-navigation) is working fine if link/reference to the child component (nav-item) is removed.

Body:
As you stated, it seems that component hierarchy is not supported in the HTML Imports polyfill.

document.currentScript doesn't work either. The polyfill will copy the <template> in the main document for the 2 imported documents.

That's why when you query querySelector( 'template' ) in the mail document, it's nav-item's template which is returned, with no div.nav inside.

As a workaroud, you should be more specific when you query the <template>.

In site-navigtion.html:

<template id="site-navigation">
...
</template>
...
const shadowTemplate = currentDocument.querySelector('template#site-navigation').content.cloneNode(true);

Thus you'll get the right template, even in Firefox.

Note: document._currentScript doesn't seem to work any more with Polyfill v1.


问:
How to set id to a Grid generated by GridMvc
Hi guys I have an issue with grid mvc (GridMvc 3.0), the problem is who I can put and id like "grid1" or something like that, because I want to freeze the header and the only form I have found is with .freezeHeader() but I need to put an Id/Name to the grid/table.</p>

```<code><div>
@Html.Grid(Model).Columns(col =>
{
    col.Add(m => m.NumeroEmpleado).Titled("Usuario").Filterable(true);
    col.Add(m => m.Nombre).Titled("Nombre Completo").Sortable(true).Filterable(true);
})
</div>
</code>```

答:
Based on this page, you can add html attributes in "Attributed" element:

http://mvc6-grid.azurewebsites.net/Grid/HtmlAttributes

```<code>@model IEnumerable<PersonModel>

@(Html
    .Grid(Model)
    .Build(columns =>
    {
        columns.Add(model => model.Name).Titled("Name");
        columns.Add(model => model.Surname).Titled("Surname");
    })
    .Attributed(new { id = "your_id" })
)
</code>```

Body:
Hi guys I have an issue with grid mvc (GridMvc 3.0), the problem is who I can put and id like "grid1" or something like that, because I want to freeze the header and the only form I have found is with .freezeHeader() but I need to put an Id/Name to the grid/table.

@Html.Grid(Model).Columns(col =>
{
    col.Add(m => m.NumeroEmpleado).Titled("Usuario").Filterable(true);
    col.Add(m => m.Nombre).Titled("Nombre Completo").Sortable(true).Filterable(true);
})

Body:
Based on this page, you can add html attributes in "Attributed" element:

http://mvc6-grid.azurewebsites.net/Grid/HtmlAttributes

@model IEnumerable<PersonModel>

@(Html
    .Grid(Model)
    .Build(columns =>
    {
        columns.Add(model => model.Name).Titled("Name");
        columns.Add(model => model.Surname).Titled("Surname");
    })
    .Attributed(new { id = "your_id" })
)


问:
What am I doing wrong? Trying to receive exa1 - exa4 input but on the output the calculations are giving me 0
```<code>public class Student extends Person{
    public double exa1, exa2, exa3, exa4, midexa1, midexa2, midexa3, finexa, finGrade;
    public char finCourseGrd;

    public Student(String f2, String l2, String a2,
            String n2, int edad2, int e1, int e2, int e3, int e4) {
        super(f2, l2, a2, n2, edad2);
        exa1 = e1;
        exa2 = e2;
        exa3 = e3;
        exa4 = e4;
    }

    public void midGrades() {
        midexa1 = (20/100)*(exa1/50);
        midexa2 = (20/100)*(exa2/50);
        midexa3 = (20/100)*(exa3/50);
    }

    public void exafinGrade() {
        finexa = (40/100)*(exa4/100);
    }

    public void finalGrade() {
        finGrade = ( midexa1 + midexa2 + midexa3 + finexa ) * 100;
    }

    public void finalCourseGrade() {
        if (finGrade >= 85 && finGrade <= 100) {
            finCourseGrd = 'A';
        }
        else if (finGrade >= 78 && finGrade <= 84) {
            finCourseGrd = 'B';
        }
        else if (finGrade >= 65 && finGrade <= 77) {
            finCourseGrd = 'C';
        }
        else if (finGrade >= 40 && finGrade <= 64) {
            finCourseGrd = 'D';
        }
        else if (finGrade >= 0 && finGrade <= 39) {
            finCourseGrd = 'F';
        }
    }

    public String toString() {
        return super.toString() + "First midterm Grade: " + midexa1 + "\n" + "Second midterm Grade: " + midexa2 + "\n"
        + "Third midterm Grade: " + midexa3 + "\n" + "Final term Grade: " + finexa + "\n" + "The students final course grade: " + finGrade + finCourseGrd;
    }

}
</code>```

I have a test class everything runs ok, but im having issues displaying the end result of the grades

答:
You have some casting problem while calculating the grades.
As they are declared integers so the output would be zero.
e.g.
20/100 o/p = 0
but if cast them explicitly then
(float)20/(float)100 o/p=0.200000

so try this:

```<code>public void midGrades() {
        midexa1 = ((double)20/(double)100)*(exa1/50);
        midexa2 = ((double)20/(double)100)*(exa2/50);
        midexa3 = ((double)20/(double)100)*(exa3/50);
    }

    public void exafinGrade() {
        finexa = ((double)40/(double)100)*(exa4/100);
    }
</code>```

Body:
public class Student extends Person{
    public double exa1, exa2, exa3, exa4, midexa1, midexa2, midexa3, finexa, finGrade;
    public char finCourseGrd;

    public Student(String f2, String l2, String a2,
            String n2, int edad2, int e1, int e2, int e3, int e4) {
        super(f2, l2, a2, n2, edad2);
        exa1 = e1;
        exa2 = e2;
        exa3 = e3;
        exa4 = e4;
    }

    public void midGrades() {
        midexa1 = (20/100)*(exa1/50);
        midexa2 = (20/100)*(exa2/50);
        midexa3 = (20/100)*(exa3/50);
    }

    public void exafinGrade() {
        finexa = (40/100)*(exa4/100);
    }

    public void finalGrade() {
        finGrade = ( midexa1 + midexa2 + midexa3 + finexa ) * 100;
    }

    public void finalCourseGrade() {
        if (finGrade >= 85 && finGrade <= 100) {
            finCourseGrd = 'A';
        }
        else if (finGrade >= 78 && finGrade <= 84) {
            finCourseGrd = 'B';
        }
        else if (finGrade >= 65 && finGrade <= 77) {
            finCourseGrd = 'C';
        }
        else if (finGrade >= 40 && finGrade <= 64) {
            finCourseGrd = 'D';
        }
        else if (finGrade >= 0 && finGrade <= 39) {
            finCourseGrd = 'F';
        }
    }

    public String toString() {
        return super.toString() + "First midterm Grade: " + midexa1 + "\n" + "Second midterm Grade: " + midexa2 + "\n"
        + "Third midterm Grade: " + midexa3 + "\n" + "Final term Grade: " + finexa + "\n" + "The students final course grade: " + finGrade + finCourseGrd;
    }

}

I have a test class everything runs ok, but im having issues displaying the end result of the grades

Body:
You have some casting problem while calculating the grades.
As they are declared integers so the output would be zero.
e.g.
20/100 o/p = 0
but if cast them explicitly then
(float)20/(float)100 o/p=0.200000

so try this:

public void midGrades() {
        midexa1 = ((double)20/(double)100)*(exa1/50);
        midexa2 = ((double)20/(double)100)*(exa2/50);
        midexa3 = ((double)20/(double)100)*(exa3/50);
    }

    public void exafinGrade() {
        finexa = ((double)40/(double)100)*(exa4/100);
    }


问:
Copying files from AWS s3 (SSE) bucket to google cloud
We were trying to copy some data from a S3 bucket to google cloud storage. However, the gsutil copy command results in the following error:

```<code>gsutil cp s3://my_s3_bucket/datadir1 gs://my_google_bucket
</code>```

Error:

```<code>Requests specifying Server Side Encryption with AWS KMS managed keys require AWS Signature Version 4
</code>```

Is there a way to get around this?

答:
The latest version of gsutil supports AWS Signature Version 4 for calls to S3, but you'll need to explicitly enable it.

First, update to the latest version of gsutil (you'll need 4.28 or higher). In the [S3] section of your ".boto" configuration file, set these parameters:

```<code>[s3]
use-sigv4 = True
host = s3.<some AWS region>.amazonaws.com
</code>```

Body:
We were trying to copy some data from a S3 bucket to google cloud storage. However, the gsutil copy command results in the following error:

gsutil cp s3://my_s3_bucket/datadir1 gs://my_google_bucket

Error:

Requests specifying Server Side Encryption with AWS KMS managed keys require AWS Signature Version 4

Is there a way to get around this?

Body:
The latest version of gsutil supports AWS Signature Version 4 for calls to S3, but you'll need to explicitly enable it.

First, update to the latest version of gsutil (you'll need 4.28 or higher). In the [S3] section of your ".boto" configuration file, set these parameters:

[s3]
use-sigv4 = True
host = s3.<some AWS region>.amazonaws.com


问:
Disable/Toggle visualization of tracked planes in ARCore unity
I have been looking on the code for ARCore Unity for a while and I want to do one simple task that is, to have a toggle button so user can place an object in the scene while knowing where to place it while the tracked planes are visible and once the user places the object, he is given the option of just visually disabling the tracked planes so it looks more realistic. I was able to do this in Android Studio by doing something like this in the main HelloArActivity.java:

```<code>if (planeToggle) {
                mPlaneRenderer.drawPlanes(mSession.getAllPlanes(), frame.getPose(), projmtx);
            }
</code>```

this was really simple. I made a bool named planeToggle and just placed the mPlaneRenderer.drawPlanes function in an if condition. When the bool is true it displays the planes and when its false, it does not...

However, with Unity I am confused. I did something like this in the HelloARController.cs :

I made a button to togglePlanes.
Set an event listener to it to toggle a boolean variable and did something like this :

```<code>for (int i = 0; i < m_newPlanes.Count; i++)
                {
                // Instantiate a plane visualization prefab and set it to track the new plane. The transform is set to
                // the origin with an identity rotation since the mesh for our prefab is updated in Unity World
                // coordinates.

                GameObject planeObject = Instantiate(m_trackedPlanePrefab, Vector3.zero, Quaternion.identity,
                        transform);
                    planeObject.GetComponent<TrackedPlaneVisualizer>().SetTrackedPlane(m_newPlanes[i]);

                    m_planeColors[0].a = 0;

                    // Apply a random color and grid rotation.
                    planeObject.GetComponent<Renderer>().material.SetColor("_GridColor", m_planeColors[0]);
                    planeObject.GetComponent<Renderer>().material.SetFloat("_UvRotation", Random.Range(0.0f, 360.0f));

        if (togglePlanes == false){    // my code

          planeObject.SetActive(false); // my code

          } //
  }
</code>```

Nothing happens when I press the toggle button.

The other option I had was to make changes in the TrackedPlaneVisualizer.cs where I did something like this :

```<code>for (int i = 0; i < planePolygonCount; ++i)
            {
                Vector3 v = m_meshVertices[i];

                // Vector from plane center to current point
                Vector3 d = v - planeCenter;

                float scale = 1.0f - Mathf.Min((FEATHER_LENGTH / d.magnitude), FEATHER_SCALE);
                m_meshVertices.Add(scale * d + planeCenter);

                if (togglePlanesbool == true) // my code
                {
                    m_meshColors.Add(new Color(0.0f, 0.0f, 0.0f, 1.0f)); // my code
                }

                else
                {
                    m_meshColors.Add(new Color(0.0f, 0.0f, 0.0f, 0.0f)); // my code
                }
     }
</code>```

This did work. But I am experiencing delays in toggling and sometimes if two different planes have been rendered they start toggling between themselves(if one is enabled, other gets disabled). So I guess this is also not the option to go for....Anyone who can help?

Note that I am a beginner in Unity.

答:
The sample isn't really designed to hide and show the planes, so you have to add a couple things.

First, there is no collection of the GameObjects that represent the ARCore planes. The easiest way to do this is to add a tag to the game objects:

In the Unity editor, find the TrackedPlaneVisualizer prefab and select it. Then in the property inspector, drop down the Tag dropdown and add a tag named plane.

Next, in the Toggle handler method, you need to find all the game objects with the "plane" tag.  Then get both the Renderer and TrackedPlaneVisualizer components and enable or disable them based on the toggle.  You need to do both components; the Renderer draws the plane, and the TrackedPlaneVisualizer re-enables the Renderer (ideally it would honor the Renderer's state).

```<code>    public void OnTogglePlanes(bool flag) {
        showPlanes = flag;
        foreach (GameObject plane in GameObject.FindGameObjectsWithTag ("plane")) {
            Renderer r = plane.GetComponent<Renderer> ();
            TrackedPlaneVisualizer t = plane.GetComponent<TrackedPlaneVisualizer>();
            r.enabled = flag;
            t.enabled = flag;
        }
    }
</code>```

You can also do a similar thing where the GameObject is instantiated, so new planes honor the toggle.

Body:
I have been looking on the code for ARCore Unity for a while and I want to do one simple task that is, to have a toggle button so user can place an object in the scene while knowing where to place it while the tracked planes are visible and once the user places the object, he is given the option of just visually disabling the tracked planes so it looks more realistic. I was able to do this in Android Studio by doing something like this in the main HelloArActivity.java:

if (planeToggle) {
                mPlaneRenderer.drawPlanes(mSession.getAllPlanes(), frame.getPose(), projmtx);
            }

this was really simple. I made a bool named planeToggle and just placed the mPlaneRenderer.drawPlanes function in an if condition. When the bool is true it displays the planes and when its false, it does not...

However, with Unity I am confused. I did something like this in the HelloARController.cs :

I made a button to togglePlanes.
Set an event listener to it to toggle a boolean variable and did something like this :

for (int i = 0; i < m_newPlanes.Count; i++)
                {
                // Instantiate a plane visualization prefab and set it to track the new plane. The transform is set to
                // the origin with an identity rotation since the mesh for our prefab is updated in Unity World
                // coordinates.

                GameObject planeObject = Instantiate(m_trackedPlanePrefab, Vector3.zero, Quaternion.identity,
                        transform);
                    planeObject.GetComponent<TrackedPlaneVisualizer>().SetTrackedPlane(m_newPlanes[i]);

                    m_planeColors[0].a = 0;

                    // Apply a random color and grid rotation.
                    planeObject.GetComponent<Renderer>().material.SetColor("_GridColor", m_planeColors[0]);
                    planeObject.GetComponent<Renderer>().material.SetFloat("_UvRotation", Random.Range(0.0f, 360.0f));

        if (togglePlanes == false){    // my code

          planeObject.SetActive(false); // my code

          } //
  }

Nothing happens when I press the toggle button.

The other option I had was to make changes in the TrackedPlaneVisualizer.cs where I did something like this :

for (int i = 0; i < planePolygonCount; ++i)
            {
                Vector3 v = m_meshVertices[i];

                // Vector from plane center to current point
                Vector3 d = v - planeCenter;

                float scale = 1.0f - Mathf.Min((FEATHER_LENGTH / d.magnitude), FEATHER_SCALE);
                m_meshVertices.Add(scale * d + planeCenter);

                if (togglePlanesbool == true) // my code
                {
                    m_meshColors.Add(new Color(0.0f, 0.0f, 0.0f, 1.0f)); // my code
                }

                else
                {
                    m_meshColors.Add(new Color(0.0f, 0.0f, 0.0f, 0.0f)); // my code
                }
     }

This did work. But I am experiencing delays in toggling and sometimes if two different planes have been rendered they start toggling between themselves(if one is enabled, other gets disabled). So I guess this is also not the option to go for....Anyone who can help?

Note that I am a beginner in Unity.

Body:
The sample isn't really designed to hide and show the planes, so you have to add a couple things.

First, there is no collection of the GameObjects that represent the ARCore planes. The easiest way to do this is to add a tag to the game objects:

In the Unity editor, find the TrackedPlaneVisualizer prefab and select it. Then in the property inspector, drop down the Tag dropdown and add a tag named plane.

Next, in the Toggle handler method, you need to find all the game objects with the "plane" tag.  Then get both the Renderer and TrackedPlaneVisualizer components and enable or disable them based on the toggle.  You need to do both components; the Renderer draws the plane, and the TrackedPlaneVisualizer re-enables the Renderer (ideally it would honor the Renderer's state).

    public void OnTogglePlanes(bool flag) {
        showPlanes = flag;
        foreach (GameObject plane in GameObject.FindGameObjectsWithTag ("plane")) {
            Renderer r = plane.GetComponent<Renderer> ();
            TrackedPlaneVisualizer t = plane.GetComponent<TrackedPlaneVisualizer>();
            r.enabled = flag;
            t.enabled = flag;
        }
    }

You can also do a similar thing where the GameObject is instantiated, so new planes honor the toggle.


问:
Firebase Database: why do the key/ref in my queried datasnapshot refer to its parent?
I would like to delete an entry from the realtime database that i looked up through a query but i am getting unexpected results for both the ref and key properties.

```<code>ref('photos/users/USERID')
    .orderByChild('photoname')
    .equalTo('photoname i want to look up')
    .limitToFirst(1)
    .query('once')
    .then(snapshot => {
        // correct data at 'photos/users/USERID/PHOTOID'
        const entry = snapshot.val();

        // seems to be the ref to photos/users/USERID'
        const ref = snapshot.ref;

        // seems to be USERID
        const key = snapshot.key
    })
</code>```

Why aren't these the ref/key to the entry i just found? And what is the best approach to remove this entry?

答:
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

Your code needs to take this list into account, and iterate over snapshot.forEach() to get the actual matching item:

```<code>ref('photos/users/USERID')
    .orderByChild('photoname')
    .equalTo('photoname i want to look up')
    .limitToFirst(1)
    .query('once')
    .then(snapshot => {
      snapshot.forEach(child => {
        const entry = child.val();
        const ref = child.ref;
        const key = child.key
      });
    })
</code>```

Body:
I would like to delete an entry from the realtime database that i looked up through a query but i am getting unexpected results for both the ref and key properties.

ref('photos/users/USERID')
    .orderByChild('photoname')
    .equalTo('photoname i want to look up')
    .limitToFirst(1)
    .query('once')
    .then(snapshot => {
        // correct data at 'photos/users/USERID/PHOTOID'
        const entry = snapshot.val();

        // seems to be the ref to photos/users/USERID'
        const ref = snapshot.ref;

        // seems to be USERID
        const key = snapshot.key
    })

Why aren't these the ref/key to the entry i just found? And what is the best approach to remove this entry?

Body:
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

Your code needs to take this list into account, and iterate over snapshot.forEach() to get the actual matching item:

ref('photos/users/USERID')
    .orderByChild('photoname')
    .equalTo('photoname i want to look up')
    .limitToFirst(1)
    .query('once')
    .then(snapshot => {
      snapshot.forEach(child => {
        const entry = child.val();
        const ref = child.ref;
        const key = child.key
      });
    })


问:
Connecting to Mysql using Jhipster
I have generated an spring boot + angular application . imported entities with jdl. working properly with h2 . I am newbie and want to use mysql.I have configured datasource in application-dev.yml with following code.

```<code>datasource:
    type: com.zaxxer.hikari.HikariDataSource
    url: jdbc:mysql://localhost:3306/blogdb?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: name
    password:pass
h2:
    console:
        enabled: false
     hikari:
            data-source-properties:
                cachePrepStmts: true
                prepStmtCacheSize: 250
                prepStmtCacheSqlLimit: 2048
                useServerPrepStmts: true
    jpa:
        database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    database: mysql
    show-sql: true
</code>```

2) I have updated my pom configuration from h2 to mysql with following code.

```<code><plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>${liquibase.version}</version>
            <configuration>
                <changeLogFile>src/main/resources/config/liquibase/master.xml</changeLogFile>
                <diffChangeLogFile>src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml</diffChangeLogFile>
                <driver>com.mysql.jdbc.Driver</driver>
                <url>jdbc:mysql://localhost:3306/blogdb</url>
                <defaultSchemaName>blogdb</defaultSchemaName>
                <username>name</username>
                <password>**</password>
                <referenceUrl>hibernate:spring:pt.farol.destfinder.domain?dialect=org.hibernate.dialect.MySQLInnoDBDialect&hibernate.ejb.naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringNamingStrategy</referenceUrl>
                <verbose>true</verbose>
                <logging>debug</logging>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.javassist</groupId>
                    <artifactId>javassist</artifactId>
                    <version>${javassist.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.liquibase.ext</groupId>
                    <artifactId>liquibase-hibernate5</artifactId>
                    <version>${liquibase-hibernate5.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-data-jpa</artifactId>
                    <version>${project.parent.version}</version>
                </dependency>
                <dependency>
                    <groupId>javax.validation</groupId>
                    <artifactId>validation-api</artifactId>
                    <version>${validation-api.version}</version>
                </dependency>
            </dependencies>
        </plugin>
</code>```

PROBLEM when i run my project i am getting following error .

```<code>    The Class-Path manifest attribute in C:\..\..\.m2\repository\org\liquibase\liquibase-core\3.5.3\liquibase-core-3.5.3.jar referenced one or more files that do not exist: C:\..\.\.m2\repository\org\liquibase\liquibase-core\3.5.3\lib\snakeyaml-1.13.jar
22:58:49.740 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
22:58:49.751 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
22:58:49.751 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/G:/Java%20Projects/target/classes/]
22:58:52.636 [restartedMain] DEBUG org.springframework.boot.logging.ClasspathLoggingApplicationListener - Application failed to start with classpath: [file:/G:/Java%20Projects/target/classes/]
</code>```

Edit
git repository link

yo-rc.json file

```<code>{
  "generator-jhipster": {
    "promptValues": {
      "packageName": "com.beam"
    },
    "jhipsterVersion": "4.10.2",
    "baseName": "beam",
    "packageName": "com.beam",
    "packageFolder": "com/beam",
    "serverPort": "8080",
    "authenticationType": "session",
    "hibernateCache": "ehcache",
    "clusteredHttpSession": false,
    "websocket": false,
    "databaseType": "sql",
    "devDatabaseType": "mysql",
    "prodDatabaseType": "mysql",
    "searchEngine": false,
    "messageBroker": false,
    "serviceDiscoveryType": false,
    "buildTool": "maven",
    "enableSocialSignIn": false,
    "enableSwaggerCodegen": false,
    "rememberMeKey": "801a22f60c33f866035c634e04c3b5b096fdedc6",
    "clientFramework": "angularX",
    "useSass": true,
    "clientPackageManager": "yarn",
    "applicationType": "monolith",
    "testFrameworks": [],
    "jhiPrefix": "jhi",
    "enableTranslation": false
  }
}
</code>```

答:
This is not an answer but I needed more space than in comments.

I have generated an app using your .yo-rc.json file and jhipster 4.10.2, it works fine. I also have the Class-Path manifest warning but it's harmless and the application works.

```<code>[INFO] --- spring-boot-maven-plugin:1.5.7.RELEASE:run (default-cli) @ beam ---
[INFO] Attaching agents: []
The Class-Path manifest attribute in C:\Users\Gaël\.m2\repository\org\liquibase\liquibase-core\3.5.3\liquibase-core-3.5.3.jar referenced one or more files tha
t do not exist: C:\Users\Gaël\.m2\repository\org\liquibase\liquibase-core\3.5.3\lib\snakeyaml-1.13.jar
22:15:34.613 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
22:15:34.617 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/,

2017-11-13 22:15:57.237  INFO 20472 --- [  restartedMain] com.beam.BeamApp                         :
----------------------------------------------------------
        Application 'beam' is running! Access URLs:
        Local:          http://localhost:8180
        External:       http://172.27.112.1:8180
        Profile(s):     [swagger, dev]
----------------------------------------------------------
</code>```

So, I guess you're not pasting the real error.
What exactly is the symptom?

Title: Connecting to Mysql using Jhipster

Body:
I have generated an spring boot + angular application . imported entities with jdl. working properly with h2 . I am newbie and want to use mysql.I have configured datasource in application-dev.yml with following code.

datasource:
    type: com.zaxxer.hikari.HikariDataSource
    url: jdbc:mysql://localhost:3306/blogdb?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: name
    password:pass
h2:
    console:
        enabled: false
     hikari:
            data-source-properties:
                cachePrepStmts: true
                prepStmtCacheSize: 250
                prepStmtCacheSqlLimit: 2048
                useServerPrepStmts: true
    jpa:
        database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    database: mysql
    show-sql: true

2) I have updated my pom configuration from h2 to mysql with following code.

<plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>${liquibase.version}</version>
            <configuration>
                <changeLogFile>src/main/resources/config/liquibase/master.xml</changeLogFile>
                <diffChangeLogFile>src/main/resources/config/liquibase/changelog/${maven.build.timestamp}_changelog.xml</diffChangeLogFile>
                <driver>com.mysql.jdbc.Driver</driver>
                <url>jdbc:mysql://localhost:3306/blogdb</url>
                <defaultSchemaName>blogdb</defaultSchemaName>
                <username>name</username>
                <password>**</password>
                <referenceUrl>hibernate:spring:pt.farol.destfinder.domain?dialect=org.hibernate.dialect.MySQLInnoDBDialect&hibernate.ejb.naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringNamingStrategy</referenceUrl>
                <verbose>true</verbose>
                <logging>debug</logging>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.javassist</groupId>
                    <artifactId>javassist</artifactId>
                    <version>${javassist.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.liquibase.ext</groupId>
                    <artifactId>liquibase-hibernate5</artifactId>
                    <version>${liquibase-hibernate5.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-data-jpa</artifactId>
                    <version>${project.parent.version}</version>
                </dependency>
                <dependency>
                    <groupId>javax.validation</groupId>
                    <artifactId>validation-api</artifactId>
                    <version>${validation-api.version}</version>
                </dependency>
            </dependencies>
        </plugin>

PROBLEM when i run my project i am getting following error .

    The Class-Path manifest attribute in C:\..\..\.m2\repository\org\liquibase\liquibase-core\3.5.3\liquibase-core-3.5.3.jar referenced one or more files that do not exist: C:\..\.\.m2\repository\org\liquibase\liquibase-core\3.5.3\lib\snakeyaml-1.13.jar
22:58:49.740 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
22:58:49.751 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
22:58:49.751 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/G:/Java%20Projects/target/classes/]
22:58:52.636 [restartedMain] DEBUG org.springframework.boot.logging.ClasspathLoggingApplicationListener - Application failed to start with classpath: [file:/G:/Java%20Projects/target/classes/]

Edit
git repository link

yo-rc.json file

{
  "generator-jhipster": {
    "promptValues": {
      "packageName": "com.beam"
    },
    "jhipsterVersion": "4.10.2",
    "baseName": "beam",
    "packageName": "com.beam",
    "packageFolder": "com/beam",
    "serverPort": "8080",
    "authenticationType": "session",
    "hibernateCache": "ehcache",
    "clusteredHttpSession": false,
    "websocket": false,
    "databaseType": "sql",
    "devDatabaseType": "mysql",
    "prodDatabaseType": "mysql",
    "searchEngine": false,
    "messageBroker": false,
    "serviceDiscoveryType": false,
    "buildTool": "maven",
    "enableSocialSignIn": false,
    "enableSwaggerCodegen": false,
    "rememberMeKey": "801a22f60c33f866035c634e04c3b5b096fdedc6",
    "clientFramework": "angularX",
    "useSass": true,
    "clientPackageManager": "yarn",
    "applicationType": "monolith",
    "testFrameworks": [],
    "jhiPrefix": "jhi",
    "enableTranslation": false
  }
}

Body:
This is not an answer but I needed more space than in comments.

I have generated an app using your .yo-rc.json file and jhipster 4.10.2, it works fine. I also have the Class-Path manifest warning but it's harmless and the application works.

[INFO] --- spring-boot-maven-plugin:1.5.7.RELEASE:run (default-cli) @ beam ---
[INFO] Attaching agents: []
The Class-Path manifest attribute in C:\Users\Gaël\.m2\repository\org\liquibase\liquibase-core\3.5.3\liquibase-core-3.5.3.jar referenced one or more files tha
t do not exist: C:\Users\Gaël\.m2\repository\org\liquibase\liquibase-core\3.5.3\lib\snakeyaml-1.13.jar
22:15:34.613 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
22:15:34.617 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/,

2017-11-13 22:15:57.237  INFO 20472 --- [  restartedMain] com.beam.BeamApp                         :
----------------------------------------------------------
        Application 'beam' is running! Access URLs:
        Local:          http://localhost:8180
        External:       http://172.27.112.1:8180
        Profile(s):     [swagger, dev]
----------------------------------------------------------

So, I guess you're not pasting the real error.
What exactly is the symptom?


问:
Why does the Constant Buffer update partially in Direct11
Working my way through the "Introduction to 3D Game Programming with Directx 11". I am reworking the samples so as to not use the Effects Framework, so far all good.

However, I have come up with a problem that one of the constant buffers only partially updates.

CPU side CB struct:

```<code>struct CBPerFrame
{
    DirectionalLight  DirLight[3];
    DirectX::XMFLOAT3 EyePositionW;

    DirectX::XMFLOAT4 FogColour;

    float             FogStart;
    float             FogRange;

    int               LightNumber;
    double            Padding;
};
</code>```

Where I update the CB prior to any drawing.

```<code>CBPerFrame cbPerFrame { };

    cbPerFrame.DirLight[ 0 ] = mDirectionalLights[ 0 ];
    cbPerFrame.DirLight[ 1 ] = mDirectionalLights[ 1 ];
    cbPerFrame.DirLight[ 2 ] = mDirectionalLights[ 2 ];

    cbPerFrame.EyePositionW  = mEyePosW;

    cbPerFrame.FogColour     = XMFLOAT4( Colors::Black );
    cbPerFrame.FogRange      = 1.0F;
    cbPerFrame.FogStart      = 0.0F;

    cbPerFrame.LightNumber   = mLightCount;

    cbPerFrame.Padding       = 0.0;

mD3DImmediateContext->UpdateSubresource( mCBPerFrame.Get( ), 0, nullptr, &cbPerFrame, 0, 0 );
</code>```

Pixel Shader:

```<code>cbuffer CBPerFrame : register( b0 )
{
    DirectionalLight gDirectionalLights[ 3 ];
    float3           gEyePosW;

    float4           gFogColor;
    float            gFogStart;
    float            gFogRange;

    int              gLightCount;
    double           gPadding;
}

cbuffer CBPerObject : register( b1 )
{
    matrix   gWorld;
    matrix   gWorldInverseTranspose;
    matrix   gWorldViewProjection;
    float4x4 gTextureTransform;
    Material gMaterial;
}

float4 main( VertexOut input ) : SV_TARGET
{
    // Interpolating normal can unnormalize it, so normalize it.
    input.NormalW = normalize( input.NormalW );

    // The toEye vector is used in lighting.
    float3 toEye = normalize( gEyePosW - input.PositionW );

    // Cache the distance to the eye from this surface point.
    float distToEye = length( toEye );

    // Normalize.
    toEye /= distToEye;

    //
    // Lighting.
    //

    // Start with a sum of zero.
    float4 ambient = float4( 0.0F, 0.0F, 0.0F, 0.0F );
    float4 diffuse = float4( 0.0F, 0.0F, 0.0F, 0.0F );
    float4 spec    = float4( 0.0F, 0.0F, 0.0F, 0.0F );

    // Sum the light contribution from each light source.
   /* [unroll]*/
    for ( int i = 0; i < gLightCount; i++ )
    {
        float4 A, D, S;

        ComputeDirectionalLight( gMaterial, gDirectionalLights[ i ], input.NormalW, toEye, A, D, S );

        ambient += A;
        diffuse += D;
        spec    += S;
    }

    float4 litColour = ambient + diffuse + spec;

    // Common to take alpha from diffuse material.
    litColour.a = gMaterial.Diffuse.a;

    return litColour;
}
</code>```

gLightCount is always set to 0, even though it should be set to 2 at the start of the application. If I change the condition of the loop to a hardcoded 1/2/3 the shader works as it should.

I realise that there are extra variables in the CB, but the sample code has this and I believe it is used in further examples.

I think the issue is to do with how the CBPerFrame struct is padded, so it isn't been copied over to the GPU correctly. Any thoughts?

Thanks for any help.

答:
It seems to be an issue with packing. According to Packing Rules for Constant Variables data should be packed at 4-byte boundaries but also so data blocks won't cross 16-byte boundary. In this case there will be definitely a padding after EyePositionW:

```<code>struct CBPerFrame
{
    DirectionalLight  DirLight[3];
    DirectX::XMFLOAT3 EyePositionW;
    float             padding1;
    DirectX::XMFLOAT4 FogColour;
</code>```

Also i'm not sure why is there double gPadding; at the end. It should probably be another int.

Body:
Working my way through the "Introduction to 3D Game Programming with Directx 11". I am reworking the samples so as to not use the Effects Framework, so far all good.

However, I have come up with a problem that one of the constant buffers only partially updates.

CPU side CB struct:

struct CBPerFrame
{
    DirectionalLight  DirLight[3];
    DirectX::XMFLOAT3 EyePositionW;

    DirectX::XMFLOAT4 FogColour;

    float             FogStart;
    float             FogRange;

    int               LightNumber;
    double            Padding;
};

Where I update the CB prior to any drawing.

CBPerFrame cbPerFrame { };

    cbPerFrame.DirLight[ 0 ] = mDirectionalLights[ 0 ];
    cbPerFrame.DirLight[ 1 ] = mDirectionalLights[ 1 ];
    cbPerFrame.DirLight[ 2 ] = mDirectionalLights[ 2 ];

    cbPerFrame.EyePositionW  = mEyePosW;

    cbPerFrame.FogColour     = XMFLOAT4( Colors::Black );
    cbPerFrame.FogRange      = 1.0F;
    cbPerFrame.FogStart      = 0.0F;

    cbPerFrame.LightNumber   = mLightCount;

    cbPerFrame.Padding       = 0.0;

mD3DImmediateContext->UpdateSubresource( mCBPerFrame.Get( ), 0, nullptr, &cbPerFrame, 0, 0 );

Pixel Shader:

cbuffer CBPerFrame : register( b0 )
{
    DirectionalLight gDirectionalLights[ 3 ];
    float3           gEyePosW;

    float4           gFogColor;
    float            gFogStart;
    float            gFogRange;

    int              gLightCount;
    double           gPadding;
}

cbuffer CBPerObject : register( b1 )
{
    matrix   gWorld;
    matrix   gWorldInverseTranspose;
    matrix   gWorldViewProjection;
    float4x4 gTextureTransform;
    Material gMaterial;
}

float4 main( VertexOut input ) : SV_TARGET
{
    // Interpolating normal can unnormalize it, so normalize it.
    input.NormalW = normalize( input.NormalW );

    // The toEye vector is used in lighting.
    float3 toEye = normalize( gEyePosW - input.PositionW );

    // Cache the distance to the eye from this surface point.
    float distToEye = length( toEye );

    // Normalize.
    toEye /= distToEye;

    //
    // Lighting.
    //

    // Start with a sum of zero.
    float4 ambient = float4( 0.0F, 0.0F, 0.0F, 0.0F );
    float4 diffuse = float4( 0.0F, 0.0F, 0.0F, 0.0F );
    float4 spec    = float4( 0.0F, 0.0F, 0.0F, 0.0F );

    // Sum the light contribution from each light source.
   /* [unroll]*/
    for ( int i = 0; i < gLightCount; i++ )
    {
        float4 A, D, S;

        ComputeDirectionalLight( gMaterial, gDirectionalLights[ i ], input.NormalW, toEye, A, D, S );

        ambient += A;
        diffuse += D;
        spec    += S;
    }

    float4 litColour = ambient + diffuse + spec;

    // Common to take alpha from diffuse material.
    litColour.a = gMaterial.Diffuse.a;

    return litColour;
}

gLightCount is always set to 0, even though it should be set to 2 at the start of the application. If I change the condition of the loop to a hardcoded 1/2/3 the shader works as it should.

I realise that there are extra variables in the CB, but the sample code has this and I believe it is used in further examples.

I think the issue is to do with how the CBPerFrame struct is padded, so it isn't been copied over to the GPU correctly. Any thoughts?

Thanks for any help.

Body:
It seems to be an issue with packing. According to Packing Rules for Constant Variables data should be packed at 4-byte boundaries but also so data blocks won't cross 16-byte boundary. In this case there will be definitely a padding after EyePositionW:

struct CBPerFrame
{
    DirectionalLight  DirLight[3];
    DirectX::XMFLOAT3 EyePositionW;
    float             padding1;
    DirectX::XMFLOAT4 FogColour;

Also i'm not sure why is there double gPadding; at the end. It should probably be another int.


答:
Yes, I would have made it shorter, but it needs at least 30 characters.
so here you go:

unset($data[2]);
```

Title: Delete row from php array

Body:
How can I remove an element from an array?

For example:

$data = Array('first' , 'second' , 'third');
array_delete($data[2]);

#$data would now read Array('first', 'second')

Does such a built-in function exist?
Thanks.


问:
PHP on Windows with XAMPP running 100 times too slow
PHP runs so slowly on my Windows desktop that phpMyAdmin takes minutes to open a database. Here’s a comparison of the time to run a simple PHP test program:

Windows 8.1 machine running XAMPP: 3597 ms

iPage shared hosting: 65 ms

A2Hosting shared hosting: 26 ms

Here’s the test program…

```<code><?php
$rStartTime = microtime(true);
$countTo = 100000;
$a = 0;
//$countTo = $countTo * 100;
for ($x = 0; $x <= $countTo; $x++) {
    $a = sqrt(pow($x, 2));
}
$rMs = floor((microtime(true) - $rStartTime) * 1000);
echo 'timer done, countTo=' . $a . ' ms=' . $rMs;
</code>```

The test program is run without debugging, by entering "http://localhost/timer.php" into Firefox.

The local machine is normally blazing fast. It’s running…

Windows 8.1

XAMPP 1.8.3 (control panel v3.2.1)

Apache 2.4.4 (latest is 2.4.20)

PHP 5.5.3

Antimalware = Windows Defender

IDE = PHPStorm 10.0.2

What's making PHP run so slowly?

答: I Had the same problem with xampp, and the problem was WINDOWS DEFENDER, if you disable the windows defender protection, xampp is faster (normal speed), Also you can search the xampp folder as exlusion in windows defender. these is the solution.</p>

Body:
PHP runs so slowly on my Windows desktop that phpMyAdmin takes minutes to open a database. Here’s a comparison of the time to run a simple PHP test program:

Windows 8.1 machine running XAMPP: 3597 ms

iPage shared hosting: 65 ms

A2Hosting shared hosting: 26 ms

Here’s the test program…

<?php
$rStartTime = microtime(true);
$countTo = 100000;
$a = 0;
//$countTo = $countTo * 100;
for ($x = 0; $x <= $countTo; $x++) {
    $a = sqrt(pow($x, 2));
}
$rMs = floor((microtime(true) - $rStartTime) * 1000);
echo 'timer done, countTo=' . $a . ' ms=' . $rMs;

The test program is run without debugging, by entering "http://localhost/timer.php" into Firefox.

The local machine is normally blazing fast. It’s running…

Windows 8.1

XAMPP 1.8.3 (control panel v3.2.1)

Apache 2.4.4 (latest is 2.4.20)

PHP 5.5.3

Antimalware = Windows Defender

IDE = PHPStorm 10.0.2

What's making PHP run so slowly?


问:
How do I test `image.onload` using jest in the context of redux actions (or other callbacks assigned in the action)
My problem was that I am trying to make a unit test for a function but can't figure out how to test a part of it.

This is a react / redux action that does the following:

1) retrieves json data with an image url

2) loads the image into an Image instance and dispatches its size to the reducer (asynchronously when image is loaded using Image.onload)

3) dispatches that the fetch was completed to the reducer

The image onload happens asynchronously, so when I try to unit test it it wouldn't be called. Moreover, I can't just mock things out because the image instance is created within the function...

Here's the code I wanted to test (removing some checks, branching logic, and stuff):

```<code>export function fetchInsuranceCardPhoto() {
    return dispatch => {
        dispatch(requestingInsuranceCardPhoto());
        return fetch(`${api}`,
            {
                headers: {},
                credentials: 'same-origin',
                method: 'GET',
            })
            .then(response => {
                switch (response.status) {
                    case 200:
                        return response.json()
                            .then(json => {
                                dispatch(receivedInsuranceCardPhoto(json));
                            })
                }
            });
    };
}

function receivedInsuranceCardPhoto(json) {
    return dispatch => {
        const insuranceCardFrontImg = json.insuranceCardData.url_front;
        const insuranceCardBackImg = json.insuranceCardData.url_back;

        if (insuranceCardFrontImg) {
            dispatch(storeImageSize(insuranceCardFrontImg, 'insuranceCardFront'));
        }

        return dispatch(receivedInsuranceCardPhotoSuccess(json));
    };
}

function receivedInsuranceCardPhotoSuccess(json) {
    const insuranceCardFrontImg = json.insuranceCardData.url_front;
    const insuranceCardBackImg = json.insuranceCardData.url_back;
    const insuranceCardId = json.insuranceCardData.id;

    return {
        type: RECEIVED_INSURANCE_CARD_PHOTO,
        insuranceCardFrontImg,
        insuranceCardBackImg,
        insuranceCardId,
    };
}

function storeImageSize(imgSrc, side) {
    return dispatch => {
        const img = new Image();
        img.src = imgSrc;
        img.onload = () => {
            return dispatch({
                type: STORE_CARD_IMAGE_SIZE,
                side,
                width: img.naturalWidth,
                height: img.naturalHeight,
            });
        };
    };
}
</code>```

Notice in that last storeImageSize private function how there's an instance of Image created and an image.onload that is assigned to a function.

Now here's my test:

```<code>it('triggers RECEIVED_INSURANCE_CARD_PHOTO when 200 returned without data', async () => {
        givenAPICallSucceedsWithData();

        await store.dispatch(fetchInsuranceCardPhoto());

        expectActionsToHaveBeenTriggered(
            REQUESTING_INSURANCE_CARD_PHOTO,
            RECEIVED_INSURANCE_CARD_PHOTO,
            STORE_CARD_IMAGE_SIZE,
        );
    });
</code>```

This test though will fail because the test finishes before the image.onload callback is called.

How can I force the image.onload callback to be called so that I can test that the `STORE_CARD_IMAGE_SIZE action gets broadcasted?

答:
After some investigation, I found a very interesting javascript function that would solve my issue.

It is this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Here's how I used Object.defineProperty(...) to solve my issue:

```<code>describe('fetchInsuranceCardPhoto', () => {
    let imageOnload = null;

    /** Override Image global to save onload setting here so that I can trigger it manually in my test */
    function trackImageOnload() {
        Object.defineProperty(Image.prototype, 'onload', {
            get: function () {
                return this._onload;
            },
            set: function (fn) {
                imageOnload = fn;
                this._onload = fn;
            },
        });
    }

    it('triggers RECEIVED_INSURANCE_CARD_PHOTO when 200 returned with data', async () => {
        trackImageOnload();
        givenAPICallSucceedsWithData();

        await store.dispatch(fetchInsuranceCardPhoto());
        imageOnload();

        expectActionsToHaveBeenTriggered(
            REQUESTING_INSURANCE_CARD_PHOTO,
            RECEIVED_INSURANCE_CARD_PHOTO,
            STORE_CARD_IMAGE_SIZE,
        );
    });
</code>```

What I did here was use define property to override the setter of any instance of Image. the setter would continue to get or set like normal but would also save the value (in this case a function) that was set to a variable in the scope of the unit test. After which, you can just run that function you captured before the verification step of your the test.

Gotchas
- configurable needs to be set
- note that defineProperty is a different function than defineProperties
- This is bad practice in real code.
- remember to use the prototype

Hope this post can help a dev in need!

Body:
My problem was that I am trying to make a unit test for a function but can't figure out how to test a part of it.

This is a react / redux action that does the following:

1) retrieves json data with an image url

2) loads the image into an Image instance and dispatches its size to the reducer (asynchronously when image is loaded using Image.onload)

3) dispatches that the fetch was completed to the reducer

The image onload happens asynchronously, so when I try to unit test it it wouldn't be called. Moreover, I can't just mock things out because the image instance is created within the function...

Here's the code I wanted to test (removing some checks, branching logic, and stuff):

export function fetchInsuranceCardPhoto() {
    return dispatch => {
        dispatch(requestingInsuranceCardPhoto());
        return fetch(`${api}`,
            {
                headers: {},
                credentials: 'same-origin',
                method: 'GET',
            })
            .then(response => {
                switch (response.status) {
                    case 200:
                        return response.json()
                            .then(json => {
                                dispatch(receivedInsuranceCardPhoto(json));
                            })
                }
            });
    };
}

function receivedInsuranceCardPhoto(json) {
    return dispatch => {
        const insuranceCardFrontImg = json.insuranceCardData.url_front;
        const insuranceCardBackImg = json.insuranceCardData.url_back;

        if (insuranceCardFrontImg) {
            dispatch(storeImageSize(insuranceCardFrontImg, 'insuranceCardFront'));
        }

        return dispatch(receivedInsuranceCardPhotoSuccess(json));
    };
}

function receivedInsuranceCardPhotoSuccess(json) {
    const insuranceCardFrontImg = json.insuranceCardData.url_front;
    const insuranceCardBackImg = json.insuranceCardData.url_back;
    const insuranceCardId = json.insuranceCardData.id;

    return {
        type: RECEIVED_INSURANCE_CARD_PHOTO,
        insuranceCardFrontImg,
        insuranceCardBackImg,
        insuranceCardId,
    };
}

function storeImageSize(imgSrc, side) {
    return dispatch => {
        const img = new Image();
        img.src = imgSrc;
        img.onload = () => {
            return dispatch({
                type: STORE_CARD_IMAGE_SIZE,
                side,
                width: img.naturalWidth,
                height: img.naturalHeight,
            });
        };
    };
}

Notice in that last storeImageSize private function how there's an instance of Image created and an image.onload that is assigned to a function.

Now here's my test:

it('triggers RECEIVED_INSURANCE_CARD_PHOTO when 200 returned without data', async () => {
        givenAPICallSucceedsWithData();

        await store.dispatch(fetchInsuranceCardPhoto());

        expectActionsToHaveBeenTriggered(
            REQUESTING_INSURANCE_CARD_PHOTO,
            RECEIVED_INSURANCE_CARD_PHOTO,
            STORE_CARD_IMAGE_SIZE,
        );
    });

This test though will fail because the test finishes before the image.onload callback is called.

How can I force the image.onload callback to be called so that I can test that the `STORE_CARD_IMAGE_SIZE action gets broadcasted?

Body:
After some investigation, I found a very interesting javascript function that would solve my issue.

It is this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Here's how I used Object.defineProperty(...) to solve my issue:

describe('fetchInsuranceCardPhoto', () => {
    let imageOnload = null;

    /** Override Image global to save onload setting here so that I can trigger it manually in my test */
    function trackImageOnload() {
        Object.defineProperty(Image.prototype, 'onload', {
            get: function () {
                return this._onload;
            },
            set: function (fn) {
                imageOnload = fn;
                this._onload = fn;
            },
        });
    }

    it('triggers RECEIVED_INSURANCE_CARD_PHOTO when 200 returned with data', async () => {
        trackImageOnload();
        givenAPICallSucceedsWithData();

        await store.dispatch(fetchInsuranceCardPhoto());
        imageOnload();

        expectActionsToHaveBeenTriggered(
            REQUESTING_INSURANCE_CARD_PHOTO,
            RECEIVED_INSURANCE_CARD_PHOTO,
            STORE_CARD_IMAGE_SIZE,
        );
    });

What I did here was use define property to override the setter of any instance of Image. the setter would continue to get or set like normal but would also save the value (in this case a function) that was set to a variable in the scope of the unit test. After which, you can just run that function you captured before the verification step of your the test.

Gotchas
- configurable needs to be set
- note that defineProperty is a different function than defineProperties
- This is bad practice in real code.
- remember to use the prototype

Hope this post can help a dev in need!


问:
minikube can't access remote Harbor registry
Even start minikube using minikube start --insecure-registry "<HARBOR_HOST_IP>", when tried to run a deployment yaml file which include image path like <HARBOR_HOST_IP>/app/server, got error:

Failed to pull image "[HARBOR_IP]/app/server": rpc error: code = 2 desc = Error response from daemon: {"message":"Get https://[HARBOR_IP]/v1/_ping: dial tcp [HARBOR_IP]:443: getsockopt: connection refused"}
  Error syncing pod

How to set insecure-registry correctly in minikube?

Edit

Tag current docker image with 80 port:

```<code>docker tag server <HARBOR_HOST_IP>:80/app/server
</code>```

Push it to Harbor registry server:

```<code>docker push <HARBOR_HOST_IP>:80/app/server
</code>```

Unfortunately remote Harbor host denied:

```<code>The push refers to a repository [<HARBOR_HOST_IP>:80/app/server]
00491a929c2e: Preparing
ec4cc3fab4be: Preparing
e7d3ac95d998: Preparing
8bb050c3d78d: Preparing
4aa9e88e4148: Preparing
978b58726b5e: Waiting
2b0fb280b60d: Waiting
denied: requested access to the resource is denied
</code>```

Even added <HARBOR_HOST_IP>:80 to local insecure-registries list.

答:
It is working if you always define port 80 when you communicate with your docker registry which works on port 80.

Build an image:

```<code>docker build -t <REGISTRY_IP>:80/<name> <path>
</code>```

Push it to registry:

```<code>docker push <REGISTRY_IP>:80/<name>
</code>```

Start minikube with this insecure registry:

```<code>minikube start --insecure-registry <REGISTRY_IP>:80
</code>```

Create deployment:

```<code>kubectl create -f test.yaml
</code>```

where test.yaml is:

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: test
spec:
  template:
    metadata:
      labels:
        app: test
    spec:
      containers:
      - image: 192.168.1.11:80/<name>
        name: test
        imagePullPolicy: Always
</code>```

Body:
Even start minikube using minikube start --insecure-registry "<HARBOR_HOST_IP>", when tried to run a deployment yaml file which include image path like <HARBOR_HOST_IP>/app/server, got error:

Failed to pull image "[HARBOR_IP]/app/server": rpc error: code = 2 desc = Error response from daemon: {"message":"Get https://[HARBOR_IP]/v1/_ping: dial tcp [HARBOR_IP]:443: getsockopt: connection refused"}
  Error syncing pod

How to set insecure-registry correctly in minikube?

Edit

Tag current docker image with 80 port:

docker tag server <HARBOR_HOST_IP>:80/app/server

Push it to Harbor registry server:

docker push <HARBOR_HOST_IP>:80/app/server

Unfortunately remote Harbor host denied:

The push refers to a repository [<HARBOR_HOST_IP>:80/app/server]
00491a929c2e: Preparing
ec4cc3fab4be: Preparing
e7d3ac95d998: Preparing
8bb050c3d78d: Preparing
4aa9e88e4148: Preparing
978b58726b5e: Waiting
2b0fb280b60d: Waiting
denied: requested access to the resource is denied

Even added <HARBOR_HOST_IP>:80 to local insecure-registries list.

Body:
It is working if you always define port 80 when you communicate with your docker registry which works on port 80.

Build an image:

docker build -t <REGISTRY_IP>:80/<name> <path>

Push it to registry:

docker push <REGISTRY_IP>:80/<name>

Start minikube with this insecure registry:

minikube start --insecure-registry <REGISTRY_IP>:80

Create deployment:

kubectl create -f test.yaml

where test.yaml is:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: test
spec:
  template:
    metadata:
      labels:
        app: test
    spec:
      containers:
      - image: 192.168.1.11:80/<name>
        name: test
        imagePullPolicy: Always