问:
Join 2 arrays of objects based on grouping properties
With the following JSON API response:

```<code>{
   "default" : [
      {"val_a" : 5 , "val_b": 10, "key_a":"A", "key_b":"X"},
      {"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
      {"val_a" : 6 , "val_b": 12, "key_a":"B", "key_b":"Z"}
   ],
   "alt" : [
      {"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
      {"val_a" : 9 , "val_b": 10, "key_a":"A", "key_b":"X"}
   ]
}
</code>```

I'm trying to write a merging function that will give the following results:

```<code>[
 {"alt_val_a":9, "alt_val_b":10 ,"val_a" : 5 , "val_b": 10, "key_a":"A", "key_b":"X"},
 {"alt_val_a":15, "alt_val_b":11 ,"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
 {"val_a" : 6 , "val_b": 12, "key_a":"B", "key_b":"Z"}
]
</code>```

Explanation:

The results are merged based on 2 properties,"key_a" and "key_b" that produce a unique entry combination. The "alt" prefix is added to the other properties.

EDIT: The grouping keys (key_b , key_a) in the example above are dynamically changing based on the request to the api, so another API response could have another grouping key involved, for example key_c, therefore the function should be generic enough to accept the grouping keys as an array.

Edit 2 Just to make it clear, val_a and val_b are just an example of a specific response. On another response val_c could be present or val_a could be missing.

I'm thinking of a function that accepts the original JSON and an array of group by keys
like so:

```<code>function transformResults(results,groupings){
   //...
}
</code>```

Usage:

```<code>transformResults(originalJSON,["key_a","key_b"]);
</code>```

Any help is appreciated :)

答:
You could use a hash table for the same group.

This proposal mutates the original object.

function transformResults(object, keys) {
    var getValues = function (o) { return function (k) { return o[k]; }; },
        hash = Object.create(null),
        result = object.default.map(function (o) {
            var key = keys.map(getValues(o)).join('|');
            return hash[key] = o;
        });

    object.alt.forEach(function (o) {
        var key = keys.map(getValues(o)).join('|');
        if (!hash[key]) {
            result.push(hash[key] = {});
            keys.forEach(function (k) {
                hash[key][k] = o[k];
            });
        }
        Object.keys(o).forEach(function (k) {
            if (keys.indexOf(k) === -1) {
                return;
            }
            hash[key]['alt_' + k] = o[k];
        });
    });
    return result;
}

var object = { default: [{ val_a: 5, val_b: 10, key_a: "A", key_b: "X" }, { val_a: 15, val_b: 11, key_a: "A", key_b: "Y" }, { val_a: 6, val_b: 12, key_a: "B", key_b: "Z" }], alt: [{ val_a: 15, val_b: 11, key_a: "A", key_b: "Y" }, { val_a: 9, val_b: 10, key_a: "A", key_b: "X" }, { val_a: 9, val_b: 10, key_a: "C", key_b: "X" }] };

console.log(transformResults(object, ["key_a", "key_b"]));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
With the following JSON API response:

{
   "default" : [
      {"val_a" : 5 , "val_b": 10, "key_a":"A", "key_b":"X"},
      {"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
      {"val_a" : 6 , "val_b": 12, "key_a":"B", "key_b":"Z"}
   ],
   "alt" : [
      {"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
      {"val_a" : 9 , "val_b": 10, "key_a":"A", "key_b":"X"}
   ]
}

I'm trying to write a merging function that will give the following results:

[
 {"alt_val_a":9, "alt_val_b":10 ,"val_a" : 5 , "val_b": 10, "key_a":"A", "key_b":"X"},
 {"alt_val_a":15, "alt_val_b":11 ,"val_a" : 15 , "val_b": 11, "key_a":"A", "key_b":"Y"},
 {"val_a" : 6 , "val_b": 12, "key_a":"B", "key_b":"Z"}
]

Explanation:

The results are merged based on 2 properties,"key_a" and "key_b" that produce a unique entry combination. The "alt" prefix is added to the other properties.

EDIT: The grouping keys (key_b , key_a) in the example above are dynamically changing based on the request to the api, so another API response could have another grouping key involved, for example key_c, therefore the function should be generic enough to accept the grouping keys as an array.

Edit 2 Just to make it clear, val_a and val_b are just an example of a specific response. On another response val_c could be present or val_a could be missing.

I'm thinking of a function that accepts the original JSON and an array of group by keys
like so:

function transformResults(results,groupings){
   //...
}

Usage:

transformResults(originalJSON,["key_a","key_b"]);

Any help is appreciated :)

Body:
You could use a hash table for the same group.

This proposal mutates the original object.

function transformResults(object, keys) {
    var getValues = function (o) { return function (k) { return o[k]; }; },
        hash = Object.create(null),
        result = object.default.map(function (o) {
            var key = keys.map(getValues(o)).join('|');
            return hash[key] = o;
        });

    object.alt.forEach(function (o) {
        var key = keys.map(getValues(o)).join('|');
        if (!hash[key]) {
            result.push(hash[key] = {});
            keys.forEach(function (k) {
                hash[key][k] = o[k];
            });
        }
        Object.keys(o).forEach(function (k) {
            if (keys.indexOf(k) === -1) {
                return;
            }
            hash[key]['alt_' + k] = o[k];
        });
    });
    return result;
}

var object = { default: [{ val_a: 5, val_b: 10, key_a: "A", key_b: "X" }, { val_a: 15, val_b: 11, key_a: "A", key_b: "Y" }, { val_a: 6, val_b: 12, key_a: "B", key_b: "Z" }], alt: [{ val_a: 15, val_b: 11, key_a: "A", key_b: "Y" }, { val_a: 9, val_b: 10, key_a: "A", key_b: "X" }, { val_a: 9, val_b: 10, key_a: "C", key_b: "X" }] };

console.log(transformResults(object, ["key_a", "key_b"]));

.as-console-wrapper { max-height: 100% !important; top: 0; }


来源: stackexchange

问:
Click listener in ViewHolder only sometimes responds
I have the following piece of code. Below you can see my viewholder, adapter and my xml. The problem I'm encountering is that the click is sometimes not executed. Only when I'm also set clicklisteners in my viewholder on the textview and imageview than it works. Presumably the click gets eaten by the textview and imageview. Anybody have any idea why this behaviour occurs.

```<code>class GeneralListItemViewHolder(val view: View) : RecyclerView.ViewHolder(view) {

   var item: GeneralItemViewModel? = null

   init {
       view.setOnClickListener {
            item?.method?.invoke()
       }
   }

   fun bind(item: GeneralItemViewModel) {
      this.item = item
      //Do some nice UI things
   }
}
</code>```

My xml looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/ListItem">

<ImageView
    android:id="@+id/general_list_item_icon"
    style="@style/ListItem.Icon"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true" />

<TextView
    android:id="@+id/general_list_item_title"
    style="@style/ListItem.Labels.Title"
    android:layout_centerVertical="true"
    android:layout_marginStart="@dimen/margin"
    android:layout_toEndOf="@id/general_list_item_icon" />
</code>```

Furthermore my adapter code holds the following:

```<code>class GeneralItemAdapter(val items: List<GeneralItemViewModel>) : RecyclerView.Adapter<GeneralListItemViewHolder>() {

   override fun onBindViewHolder(holder: GeneralListItemViewHolder, position: Int) {
       return holder.bind(getItem(position))
   }

   override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GeneralListItemViewHolder {
       val view = parent.inflate(R.layout.general_list_item, false)
       return GeneralListItemViewHolder(view)
   }

   override fun getItemCount(): Int {
       return items.size
   }

   private fun getItem(position: Int): GeneralItemViewModel {
       return items[position]
   }
}
</code>```

答: You must set the ClickListener in the bind method.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have the following piece of code. Below you can see my viewholder, adapter and my xml. The problem I'm encountering is that the click is sometimes not executed. Only when I'm also set clicklisteners in my viewholder on the textview and imageview than it works. Presumably the click gets eaten by the textview and imageview. Anybody have any idea why this behaviour occurs.

class GeneralListItemViewHolder(val view: View) : RecyclerView.ViewHolder(view) {

   var item: GeneralItemViewModel? = null

   init {
       view.setOnClickListener {
            item?.method?.invoke()
       }
   }

   fun bind(item: GeneralItemViewModel) {
      this.item = item
      //Do some nice UI things
   }
}

My xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/ListItem">

<ImageView
    android:id="@+id/general_list_item_icon"
    style="@style/ListItem.Icon"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true" />

<TextView
    android:id="@+id/general_list_item_title"
    style="@style/ListItem.Labels.Title"
    android:layout_centerVertical="true"
    android:layout_marginStart="@dimen/margin"
    android:layout_toEndOf="@id/general_list_item_icon" />

Furthermore my adapter code holds the following:

class GeneralItemAdapter(val items: List<GeneralItemViewModel>) : RecyclerView.Adapter<GeneralListItemViewHolder>() {

   override fun onBindViewHolder(holder: GeneralListItemViewHolder, position: Int) {
       return holder.bind(getItem(position))
   }

   override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GeneralListItemViewHolder {
       val view = parent.inflate(R.layout.general_list_item, false)
       return GeneralListItemViewHolder(view)
   }

   override fun getItemCount(): Int {
       return items.size
   }

   private fun getItem(position: Int): GeneralItemViewModel {
       return items[position]
   }
}


问:
Is there a way to get rid of accents and convert a whole string to regular letters?
Is there a better way for getting rid of accents and making those letters regular apart from using String.replaceAll() method and replacing letters one by one?
Example:

Input:  orčpžsíáýd

Output: orcpzsiayd

It doesn't need to include all letters with accents like the Russian alphabet or the Chinese one.

答: I suggest Junidecode . It will handle not only 'Ł' and 'Ø', but it also works well for transcribing from other alphabets, such as Chinese, into Latin alphabet.</p>


问:
Call Interactive Mode of HSPICE in Python
I want to efficiently call HSPICE in Python. My final goal is speedup in my simulations (I have millions of it).

If I call HSPICE directly in shell:

```<code>hspice a1.sp                // method 1
hspice a2.sp
...
</code>```

or

```<code>hspice -I -L xxx.txt       // method 2
</code>```

Example of xxx.txt:

```<code>load a1.sp
run
load a2.sp
run
...
quit
</code>```

The difference is that method 1 checks HSPICE's license each time, but method 2 uses interactive mode (-I) and it checks the license one time, so it is more time efficient.

I want to call HSPICE in Python to automate my simulation process:

Method 1 works, but method 2 has problem. In other words:

```<code>os.system('hspice yyy.sp')           // it works
</code>```

However, when I use os.system, subprocess.call or subprocess.Popen, I cannot run it. For example,

```<code>args = ['hspice64', '-I', '-L', 'xxx.txt']
subprocess.Popen(args)
</code>```

or

```<code>os.system('hspice64 -I -L xxx.txt')
</code>```

It will stuck after Hspice license have checked out. The HSICE simulation is not done (thus, the whole simulation does not end)

Does any one have any idea what is happening and how can I solve it?

答: One workaround can be writing a shell script to automate the interactive HSPICE calls.</p>

Body:
I want to efficiently call HSPICE in Python. My final goal is speedup in my simulations (I have millions of it).

If I call HSPICE directly in shell:

hspice a1.sp                // method 1
hspice a2.sp
...

or

hspice -I -L xxx.txt       // method 2

Example of xxx.txt:

load a1.sp
run
load a2.sp
run
...
quit

The difference is that method 1 checks HSPICE's license each time, but method 2 uses interactive mode (-I) and it checks the license one time, so it is more time efficient.

I want to call HSPICE in Python to automate my simulation process:

Method 1 works, but method 2 has problem. In other words:

os.system('hspice yyy.sp')           // it works

However, when I use os.system, subprocess.call or subprocess.Popen, I cannot run it. For example,

args = ['hspice64', '-I', '-L', 'xxx.txt']
subprocess.Popen(args)

or

os.system('hspice64 -I -L xxx.txt')

It will stuck after Hspice license have checked out. The HSICE simulation is not done (thus, the whole simulation does not end)

Does any one have any idea what is happening and how can I solve it?


问:
Putting multiple varilables into single XPath for Selenium using Java
Suppose I have an XPath to identify an element like this:

```<code>//div[@id='%s1']//div[@class='%s2']
</code>```

The values for both s1 and s2 are to be passed at runtime. Is it possible to form an XPath (String) by passing these two variables from my code?

答:
```<code>public String varLocator(String locator, String holder1, String param1, String holder2, String param2) {

return locator.replace(holder1, param1).replace(holder2, param2);

}

public void sample() {

String eleLocator = "//div[@id='%s1']//div[@class='%s2']";

WebElement foo = driver.findElement(By.xpath(varLocator(eleLocator, "%s1", "foo", "%s2", "bar")));

}
</code>```

Body:
Suppose I have an XPath to identify an element like this:

//div[@id='%s1']//div[@class='%s2']

The values for both s1 and s2 are to be passed at runtime. Is it possible to form an XPath (String) by passing these two variables from my code?


问:
Confusion matrix from probabilities
I have the following scikit-learn machine learning pipeline:

```<code>cv = StratifiedKFold(n_splits=6)
classifier = svm.SVC(kernel='linear', probability=True,
                     random_state=random_state)

tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)

i = 0
for train, test in cv.split(X, y):
    probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test])
    # Compute ROC curve and area the curve
    fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])
    tprs.append(interp(mean_fpr, fpr, tpr))
    tprs[-1][0] = 0.0
    roc_auc = auc(fpr, tpr)
    aucs.append(roc_auc)
    i += 1
</code>```

Now I would like to also calculate (and plot) the confusion matrix. How can this be done with the above code? I'm only getting probabilities (which I need for caluclating AUC). I have 4 classes (1...4).

答:
You can use this example here to plot confusion matrix:

http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py

But for this, you need to have discrete class values (not probabilities). Which can be easily derived from your probas_ variable using:

```<code>y_pred = np.argmax(probas_, axis=1)
</code>```

Now you can use this y_pred in confusion matrix

Title: Confusion matrix from probabilities

Body:
I have the following scikit-learn machine learning pipeline:

cv = StratifiedKFold(n_splits=6)
classifier = svm.SVC(kernel='linear', probability=True,
                     random_state=random_state)

tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)

i = 0
for train, test in cv.split(X, y):
    probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test])
    # Compute ROC curve and area the curve
    fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])
    tprs.append(interp(mean_fpr, fpr, tpr))
    tprs[-1][0] = 0.0
    roc_auc = auc(fpr, tpr)
    aucs.append(roc_auc)
    i += 1

Now I would like to also calculate (and plot) the confusion matrix. How can this be done with the above code? I'm only getting probabilities (which I need for caluclating AUC). I have 4 classes (1...4).

Body:
You can use this example here to plot confusion matrix:

http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py

But for this, you need to have discrete class values (not probabilities). Which can be easily derived from your probas_ variable using:

y_pred = np.argmax(probas_, axis=1)

Now you can use this y_pred in confusion matrix


问:
How to correctly unquote url which is supposed to contain Japanese symbols
I have the following string for example (which was built as I realized from incorrectly encoded string)

https://ja-jp.facebook.com/%C3%A5%C2%90%C2%8D%C3%A5%C2%8F%C2%A4%C3%A5%C2%B1%E2%80%B9%C3%AF%C2%BD%C5%A0%C3%AF%C2%BD%E2%80%99%C3%A3%E2%80%9A%C2%B2%C3%A3%C6%92%C2%BC%C3%A3%C6%92%CB%86%C3%A3%E2%80%9A%C2%BF%C3%A3%C6%92%C2%AF%C3%A3%C6%92%C2%BC%C3%A3%C6%92%E2%80%BA%C3%A3%C6%92%E2%80%A0%C3%A3%C6%92%C2%AB-219123305237478

This url could be properly decoded by browser showing  the following:

https://ja-jp.facebook.com/名古屋ｊｒゲートタワーホテル-219123305237478/

Is there a way to unquote/decode the string so it's not presented like this:

https://ja-jp.facebook.com/åå¤å±‹ï½Šï½’ã‚²ãƒ¼ãƒˆã‚¿ãƒ¯ãƒ¼ãƒ›ãƒ†ãƒ«-219123305237478

Browser shows url with same rubbish initially for a short time, but then without redirect it adjustst the string so it looks fine.

I'm trying to fix encoding with this simple code:

```<code>def fix_encoding(s):
    for a in aliases:
        for b in aliases:
            try:
                fixed = s.encode(a).decode(b)
            except:
                pass
            else:
                print (a, b)
                print(fixed)

fix_encoding(u'åå¤å±‹ï½Šï½’ã‚²ãƒ¼ãƒˆã‚¿ãƒ¯ãƒ¼ãƒ›ãƒ†ãƒ«-219123305237478')
</code>```

The best results I've got are pretty close to what it should look like, but 2 first symbols are wrong for all same results. For ex.:

```<code>��屋ｊｒゲートタワーホテル-219123305237478
('1252', 'l8')
</code>```

答:
I was going to delete this question, because it seems it's not meaningful, but since it has received some points, I'm sharing some thoughts on this.

The url most probably was created in this way on Facebook due to non utf-8 encoded text that was copied from somewhere (or even with some bug on facebook in past). Some pages contain correctly encoded uri in scripts near updateURI property, that seems to be used by js to update url in browser address string.

This url was probably created automatically where possible or maybe added manually, so old url from search engines is still respected. So it's most probably pointlessly to find an universal way of fixing such bugs.

Body:
I have the following string for example (which was built as I realized from incorrectly encoded string)

https://ja-jp.facebook.com/%C3%A5%C2%90%C2%8D%C3%A5%C2%8F%C2%A4%C3%A5%C2%B1%E2%80%B9%C3%AF%C2%BD%C5%A0%C3%AF%C2%BD%E2%80%99%C3%A3%E2%80%9A%C2%B2%C3%A3%C6%92%C2%BC%C3%A3%C6%92%CB%86%C3%A3%E2%80%9A%C2%BF%C3%A3%C6%92%C2%AF%C3%A3%C6%92%C2%BC%C3%A3%C6%92%E2%80%BA%C3%A3%C6%92%E2%80%A0%C3%A3%C6%92%C2%AB-219123305237478

This url could be properly decoded by browser showing  the following:

https://ja-jp.facebook.com/名古屋ｊｒゲートタワーホテル-219123305237478/

Is there a way to unquote/decode the string so it's not presented like this:

https://ja-jp.facebook.com/åå¤å±‹ï½Šï½’ã‚²ãƒ¼ãƒˆã‚¿ãƒ¯ãƒ¼ãƒ›ãƒ†ãƒ«-219123305237478

Browser shows url with same rubbish initially for a short time, but then without redirect it adjustst the string so it looks fine.

I'm trying to fix encoding with this simple code:

def fix_encoding(s):
    for a in aliases:
        for b in aliases:
            try:
                fixed = s.encode(a).decode(b)
            except:
                pass
            else:
                print (a, b)
                print(fixed)

fix_encoding(u'åå¤å±‹ï½Šï½’ã‚²ãƒ¼ãƒˆã‚¿ãƒ¯ãƒ¼ãƒ›ãƒ†ãƒ«-219123305237478')

The best results I've got are pretty close to what it should look like, but 2 first symbols are wrong for all same results. For ex.:

��屋ｊｒゲートタワーホテル-219123305237478
('1252', 'l8')


问:
serial port communication accumulate big number of running threads
We have the follow C# code for our serial port communication:

```<code>               ProcCntrlSSPort = new SerialPort(portNumber, 115200, Parity.None, 8, StopBits.One);

                ProcCntrlSSPort.Handshake = Handshake.None;
                ProcCntrlSSPort.ReadTimeout = 10;
                ProcCntrlSSPort.ReadBufferSize = 32768;
                ProcCntrlSSPort.DataReceived += ProcCntrlSSPortDataReceived;
                //ProcCntrlSSPort.DataReceived += new SerialDataReceivedEventHandler(ProcCntrlSSPortDataReceived);
                ProcCntrlSSPort.ReceivedBytesThreshold = 1;
                try
                {
                    ProcCntrlSSPort.Open();
                    ProcCntrlSSPort.DiscardInBuffer();
                }
</code>```

Every 100 msec, there is a status message received by our application. I understand when the SerialPort received ReceivedBytesThreshold number of bytes, an event will be fired by the SerialPort. We have to use 1 for the ReceivedBytesThreshold because one of our important data is sent 1 byte each time whenever that byte is available.

When an event is fired by SerialPort and is processed by the receiver, that event should be disposed and the thread associated that event should be available for next use. so there should not be a big number of running thread accumulation.

But I found the running threads will continuously increase from 20 threads up to more than 400 threads after overnight. Just status message is sent to our application, no other activities then. I have disabled all process code so I am sure the accumulated threads are NOT from our code. That means we do nothing on the received data for the testing purpose.

I have increased the ReceivedBytesThreshold, saying 128, for testing purpose. It will slow down the accumulation but the thread count still goes up slowly. why .net framework cannot handle their threads properly? Or I didn't use it correctly?

答:
As SwDevMan81 said, DataReceived (like many other asynchronous events in .NET) is fired in a ThreadPool thread. There are a few things you shouldn't do in ThreadPool threads, most importantly: Don't wait for anything, i.e. don't use blocking file operations, don't use WaitForSingleObject, don't use ISynchronizeInvoke.Invoke unless you're sure it won't block (for long). Otherwise, the ThreadPool will simply start a new thread when a new work item is enqueued, until it hits the ThreadPool.MaxThreads limit (which is ridiculously high, IIRC).

The simplest way to find out if that's your problem is to look at ThreadPool.GetAvailableThreads - if it decreases over time, then you should maybe write your own thread to process the data and just put it into a thread-safe queue in ProcCntrlSSPortDataReceived.

ContentLicense: CC BY-SA 2.5

Body:
We have the follow C# code for our serial port communication:

               ProcCntrlSSPort = new SerialPort(portNumber, 115200, Parity.None, 8, StopBits.One);

                ProcCntrlSSPort.Handshake = Handshake.None;
                ProcCntrlSSPort.ReadTimeout = 10;
                ProcCntrlSSPort.ReadBufferSize = 32768;
                ProcCntrlSSPort.DataReceived += ProcCntrlSSPortDataReceived;
                //ProcCntrlSSPort.DataReceived += new SerialDataReceivedEventHandler(ProcCntrlSSPortDataReceived);
                ProcCntrlSSPort.ReceivedBytesThreshold = 1;
                try
                {
                    ProcCntrlSSPort.Open();
                    ProcCntrlSSPort.DiscardInBuffer();
                }

Every 100 msec, there is a status message received by our application. I understand when the SerialPort received ReceivedBytesThreshold number of bytes, an event will be fired by the SerialPort. We have to use 1 for the ReceivedBytesThreshold because one of our important data is sent 1 byte each time whenever that byte is available.

When an event is fired by SerialPort and is processed by the receiver, that event should be disposed and the thread associated that event should be available for next use. so there should not be a big number of running thread accumulation.

But I found the running threads will continuously increase from 20 threads up to more than 400 threads after overnight. Just status message is sent to our application, no other activities then. I have disabled all process code so I am sure the accumulated threads are NOT from our code. That means we do nothing on the received data for the testing purpose.

I have increased the ReceivedBytesThreshold, saying 128, for testing purpose. It will slow down the accumulation but the thread count still goes up slowly. why .net framework cannot handle their threads properly? Or I didn't use it correctly?


问:
Kotlin - extract list of parent objects of items in Collection
Is there a way in Kotlin to extract list of parent objects of items in Collection.
For instance if we have mutableMaps:

```<code>val AllPersons = mutableMapOf<Long,Person>()
val ClassAttendants = mutableMapOf<Long,Person>()
</code>```

where Person is:

```<code>data class Person( PID : Long
    Name: String
    Surname: String
    Father: Person?)
</code>```

Is there a way to select all (distinct) grandfathers from class attendants?

答:
As I'm not one for giving complete solutions, I'll give you a bunch of building blocks that should probably be helpful.

We can get the parent for a given element with somePerson.father.

We can apply a function over all value elements in a map like this:

```<code>myMap.values.map { value -> someFunction(value) }
</code>```

We can filter out null values like this:

```<code>myCollection.filterNotNull()
</code>```

A Set will automatically "discard" duplicate elements.  An alternative is something like this:

```<code>myCollection.distinct()
</code>```

I'd strongly recommend going through the Kotlin Koans.  In particular, the "Collections" section touches on applying quasi-functional techniques to manipulate collections.

Body:
Is there a way in Kotlin to extract list of parent objects of items in Collection.
For instance if we have mutableMaps:

val AllPersons = mutableMapOf<Long,Person>()
val ClassAttendants = mutableMapOf<Long,Person>()

where Person is:

data class Person( PID : Long
    Name: String
    Surname: String
    Father: Person?)

Is there a way to select all (distinct) grandfathers from class attendants?

Body:
As I'm not one for giving complete solutions, I'll give you a bunch of building blocks that should probably be helpful.

We can get the parent for a given element with somePerson.father.

We can apply a function over all value elements in a map like this:

myMap.values.map { value -> someFunction(value) }

We can filter out null values like this:

myCollection.filterNotNull()

A Set will automatically "discard" duplicate elements.  An alternative is something like this:

myCollection.distinct()

I'd strongly recommend going through the Kotlin Koans.  In particular, the "Collections" section touches on applying quasi-functional techniques to manipulate collections.


问:
"Package could not be registered" when deploying Windows Phone 8.1 solution
I am getting the error message quoted in the title when I try to deploy a Windows Phone Silverlight 8.1 solution to either the emulator on my PC or to a device. The error is not accompanied by any error codes, and I have no other hints as to exactly what the problem is, other than various tips that I have found online, both here and on other forums.

The background to this is that this is a corporate application which is already in use within my organisation. It was developed by an external supplier, and I have taken over the support internally. I have what I believe to be the current source code and Visual Studio solution for the project, and the company is registered as a developer on the Microsoft App portal. There are existing versions of the software on the portal, which is used to provide software updates to the devices which are in use.

I am using Visual Studio 2015 with this solution (VS2017 does not seem to like it).

I have tried various suggestions that I have found online, including:

Checking that the Publisher ID is correct

Ensuring that I am logged into the correct developer account when trying to deploy the solution

Ensuring that the Package.appxmanifest and WMAppManifest.xml files have consistent Product and Publisher IDs

Ensuring that all of the images referenced by those two manifests have the correct paths and filenames

Looking at the event logs suggested at https://msdn.microsoft.com/en-us/library/windows/desktop/hh973484(v=vs.85).aspx (none of them have anything in them, and I have no error code to match against the table given there).

I am now at a loss. This seems to be a fairly common issue with deploying Windows Phone software, judging by the number of people online who seem to have experienced a similar problem. However, some of the issues/suggestions that I have found online are a few years old, and I don't know which are still relevant.

I have not done Windows Phone development since the introduction of the App Store, so I have no previous experience of this way of deploying software.

I would welcome any suggestions of how to proceed. Is there any way to determine the exact cause of a "package could not be registered" error, in the absence of an error code or any event log entries?

答: The fix was to remove from Package.appxmanifest a line which I had added while investigating an earlier problem where the Windows.Devices.PointOfService namespace wasn't being recognised. I added a  line, following a recommendation that I saw among the suggestions I found while googling that problem. This turned out to be the source of the unhelpful "package could not be registered" message. Commenting out the line from Package.appxmanifest resulted in the software deploying to the emulator.</p>


问:
Is there a way to assign a value to a macro by reading a value from another file?
I am working on C++ project. I have a file named "version" where only 12343 like number is defined [In fact the version] in numeric form.
This "version" file is defined in Library A.
Somehow I need to assign this value to a macro in another library B file.

Is there any way to do it?

Since, the work is official, so I can't share the code here.

答:
Neither C nor C++ has a language feature that would allow you to set the expansion text of a macro to something read at compile time from an external file.  Such tasks are generally assigned to the build system, instead.

There are diverse mechanisms for the purpose, but they follow this general procedure:

An external program reads the file containing the wanted text

That program either

formats the text of a compilation option conveying the definition (e.g. -DVERSION=${what_I_read_from_the_file}), or

writes a header file containing the macro definition itself, e.g.

```<code>#define VERSION version-text-from-the-file
</code>```

Either way, the obtained information is provided to the build in the appropriate manner -- the compiler option alternative proceeds by ensuring that the chosen option is passed to the compiler at build time, whereas the header alternative depends on the files that need the macro #includeing the generated header.

Body:
Neither C nor C++ has a language feature that would allow you to set the expansion text of a macro to something read at compile time from an external file.  Such tasks are generally assigned to the build system, instead.

There are diverse mechanisms for the purpose, but they follow this general procedure:

An external program reads the file containing the wanted text

That program either

formats the text of a compilation option conveying the definition (e.g. -DVERSION=${what_I_read_from_the_file}), or

writes a header file containing the macro definition itself, e.g.

#define VERSION version-text-from-the-file

Either way, the obtained information is provided to the build in the appropriate manner -- the compiler option alternative proceeds by ensuring that the chosen option is passed to the compiler at build time, whereas the header alternative depends on the files that need the macro #includeing the generated header.


问:
Parsing alternate DNS servers from IP config
I am trying to extract the alternate DNS servers from this snippit from ipconfig /all. Basically, I want to write all the lines between the DNS Servers line and the NetBIOS over Tcpip line

```<code>Ethernet adapter Local Area Connection 2:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Realtek PCIe GBE Family Controller #2
   Physical Address. . . . . . . . . : 00-0B-AB-37-2D-28
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::edd5:2e2e:6979:5b59%3(Preferred)
   Autoconfiguration IPv4 Address. . : 169.254.91.89(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   Default Gateway . . . . . . . . . :
   DHCPv6 IAID . . . . . . . . . . . : 67111851
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-18-B0-7D-38-00-0B-AB-2E-90-1E
   DNS Servers . . . . . . . . . . . : fec0:0:0:ffff::1%1
                                       fec0:0:0:ffff::2%1
                                       fec0:0:0:ffff::3%1
   NetBIOS over Tcpip. . . . . . . . : Enabled
</code>```

Here's my code for getting the primary DNS server.

```<code>string[] lines = System.IO.File.ReadAllLines(@"C:\Temp\ipconfig.txt");
foreach (string line in lines)
    {
        if (line.Contains("DNS Servers")
        {
            txtPreferredDNS = line.Split(':').First();
        }
        // need help getting the alternate DNS servers
    }
</code>```

答:
I would do something like this:

1.- find the index where DNS Servers appear:

https://msdn.microsoft.com/en-us/library/system.array.indexof(v=vs.110).aspx

2.- knowing the index

```<code>   int index = lines.IndexOf('DNS Servers%')
 while (int i=index, i< lines.length, i++){
 if (!line.Contains("DNS Servers"))
       {
           txtPreferredDNS = line.Split(':').First(); // make it an array
 instead or a collection
        }
else {
  //change value of i to get out of the loop
 }

}
</code>```

your main problem is that you have assumed that the four DNS servers in your example are in the same line, when they are not.

You can also work out a regular expression to use it, which would be a better solution.

Body:
I am trying to extract the alternate DNS servers from this snippit from ipconfig /all. Basically, I want to write all the lines between the DNS Servers line and the NetBIOS over Tcpip line

Ethernet adapter Local Area Connection 2:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Realtek PCIe GBE Family Controller #2
   Physical Address. . . . . . . . . : 00-0B-AB-37-2D-28
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::edd5:2e2e:6979:5b59%3(Preferred)
   Autoconfiguration IPv4 Address. . : 169.254.91.89(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   Default Gateway . . . . . . . . . :
   DHCPv6 IAID . . . . . . . . . . . : 67111851
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-18-B0-7D-38-00-0B-AB-2E-90-1E
   DNS Servers . . . . . . . . . . . : fec0:0:0:ffff::1%1
                                       fec0:0:0:ffff::2%1
                                       fec0:0:0:ffff::3%1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Here's my code for getting the primary DNS server.

string[] lines = System.IO.File.ReadAllLines(@"C:\Temp\ipconfig.txt");
foreach (string line in lines)
    {
        if (line.Contains("DNS Servers")
        {
            txtPreferredDNS = line.Split(':').First();
        }
        // need help getting the alternate DNS servers
    }

Body:
I would do something like this:

1.- find the index where DNS Servers appear:

https://msdn.microsoft.com/en-us/library/system.array.indexof(v=vs.110).aspx

2.- knowing the index

   int index = lines.IndexOf('DNS Servers%')
 while (int i=index, i< lines.length, i++){
 if (!line.Contains("DNS Servers"))
       {
           txtPreferredDNS = line.Split(':').First(); // make it an array
 instead or a collection
        }
else {
  //change value of i to get out of the loop
 }

}

your main problem is that you have assumed that the four DNS servers in your example are in the same line, when they are not.

You can also work out a regular expression to use it, which would be a better solution.


问:
Google Cloud (GCE) doesn't have access to default service account while creating VM instance
Looks like there's a bug.
Following official documentation:
https://cloud.google.com/compute/docs/instances/create-start-instance

After

```<code>gcloud compute instances create test-2
</code>```

Recieved:

```<code>ERROR: (gcloud.compute.instances.create) Could not fetch resource:
 - The resource '1045904521672-compute@developer.gserviceaccount.com' of type 'serviceAccount' was not found.
</code>```

Being authorized correctly, role is set to Owner.

```<code>> gcloud auth list
</code>```

returns

```<code>      Credentialed Accounts
ACTIVE  ACCOUNT
*       **@gmail.com

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
</code>```

However, an instance can be created with custom service account.
Any ideas?

Thank you in advance.

答:
This seems similar to: Unable to create cluster on Dataproc after deleting default service account

Perhaps the answers there can help you out.

Body:
Looks like there's a bug.
Following official documentation:
https://cloud.google.com/compute/docs/instances/create-start-instance

After

gcloud compute instances create test-2

Recieved:

ERROR: (gcloud.compute.instances.create) Could not fetch resource:
 - The resource '1045904521672-compute@developer.gserviceaccount.com' of type 'serviceAccount' was not found.

Being authorized correctly, role is set to Owner.

> gcloud auth list

returns

      Credentialed Accounts
ACTIVE  ACCOUNT
*       **@gmail.com

To set the active account, run:
    $ gcloud config set account `ACCOUNT`

However, an instance can be created with custom service account.
Any ideas?

Thank you in advance.


问:
GLFW - many errors is this code
So my university lecturer gave us this code and it doesn't work.. it never has and no one has been able to get it to work so far.. are we being stupid or is our lecturer giving us broken material? I seriously can't figure this out and need help, i managed to get part way through in fixing many mistakes but after that the issues got harder and harder to solve despite this being '100% working' code.... side note: all the directories are formatted correctly and additional dependencies have all been set up correctly to the best of my knowledge.</p>

```<code>//First Shader Handling Program

#include "stdafx.h"

#include "gl_core_4_3.hpp"

#include <GLFW/glfw3.h>

int _tmain(int argc, _TCHAR* argv[])
{
    //Select the 4.3 core profile
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    //Start the OpenGL context and open a window using the //GLFW helper library

    if (!glfwInit()) {
        fprintf(stderr, "ERROR: could not start GLFW3\n");
        glfwTerminate();
        return 1;
    }

    GLFWwindow* window = glfwCreateWindow(640, 480, "First GLSL Triangle", NULL, NULL);

    if (!window) {
        fprintf(stderr, "ERROR: could not open window with GLFW3\n");
        glfwTerminate();
        return 1;
    }

    glfwMakeContextCurrent(window);

    //Load the OpenGL functions for C++ gl::exts::LoadTest didLoad = gl::sys::LoadFunctions(); if (!didLoad) {
    //Load failed
    fprintf(stderr, "ERROR: GLLoadGen failed to load functions\n");

    glfwTerminate();
    return 1;
}

printf("Number of functions that failed to load : %i.\n", didLoad.GetNumMissing());

//Tell OpenGL to only draw a pixel if its shape is closer to //the viewer

//i.e. Enable depth testing with smaller depth value //interpreted as being closer gl::Enable(gl::DEPTH_TEST); gl::DepthFunc(gl::LESS);

//Set up the vertices for a triangle
float points[] = {
    0.0f, 0.5f, 0.0f,
    0.5f, -0.5f, 0.0f,
    -0.5f, -0.5f, 0.0f
};

//Create a vertex buffer object to hold this data GLuint vbo=0;

gl::GenBuffers(1, &vbo);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::BufferData(gl::ARRAY_BUFFER, 9 * sizeof(float), points,
    gl::STATIC_DRAW);

//Create a vertex array object
GLuint vao = 0;
gl::GenVertexArrays(1, &vao);
gl::BindVertexArray(vao);
gl::EnableVertexAttribArray(0);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::VertexAttribPointer(0, 3, gl::FLOAT, FALSE, 0, NULL);

//The shader code strings which later we will put in //separate files

//The Vertex Shader
const char* vertex_shader =
"#version 400\n"
"in vec3 vp;"
"void main() {"
        " gl_Position = vec4(vp, 1.0);"
"}";

//The Fragment Shader
const char* fragment_shader =
"#version 400\n"
"out vec4 frag_colour;"

"void main() {"
        " frag_colour = vec4(1.0, 0.5, 0.0, 1.0);"
"}";

//Load the strings into shader objects and compile GLuint vs = gl::CreateShader(gl::VERTEX_SHADER); gl::ShaderSource(vs, 1, &vertex_shader, NULL); gl::CompileShader(vs);

GLuint fs = gl::CreateShader(gl::FRAGMENT_SHADER); gl::ShaderSource(fs, 1, &fragment_shader, NULL); gl::CompileShader(fs);

//Compiled shaders must be compiled into a single executable //GPU shader program

//Create empty program and attach shaders GLuint shader_program = gl::CreateProgram(); gl::AttachShader(shader_program, fs); gl::AttachShader(shader_program, vs); gl::LinkProgram(shader_program);

//Now draw
while (!glfwWindowShouldClose(window)) {
    //Clear the drawing surface
    gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
    gl::UseProgram(shader_program);
    gl::BindVertexArray(vao);

    //Draw point 0 to 3 from the currently bound VAO with
    //current in-use shader
    gl::DrawArrays(gl::TRIANGLES, 0, 3);

    //update GLFW event handling
    glfwPollEvents();

    //Put the stuff we have been drawing onto the display glfwSwapBuffers(window);

}

//Close GLFW and end
glfwTerminate();

return 0;

}
</code>```

答:
Your line endings seems to been mangled.

There are multiple lines in your code where actual code was not broken into two lines, so that code is now on the same line as a comment and therefor not being executed. This is your program with proper line endings:

```<code>//First Shader Handling Program

#include "stdafx.h"

#include "gl_core_4_3.hpp"

#include <GLFW/glfw3.h>

int _tmain(int argc, _TCHAR* argv[])
{
    //Select the 4.3 core profile
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    //Start the OpenGL context and open a window using the
    //GLFW helper library

    if (!glfwInit()) {
        fprintf(stderr, "ERROR: could not start GLFW3\n");
        glfwTerminate();
        return 1;
    }

    GLFWwindow* window = glfwCreateWindow(640, 480, "First GLSL Triangle", NULL, NULL);

    if (!window) {
        fprintf(stderr, "ERROR: could not open window with GLFW3\n");
        glfwTerminate();
        return 1;
    }

    glfwMakeContextCurrent(window);

    //Load the OpenGL functions for C++
    gl::exts::LoadTest didLoad = gl::sys::LoadFunctions();
    if (!didLoad) {
        //Load failed
        fprintf(stderr, "ERROR: GLLoadGen failed to load functions\n");

        glfwTerminate();
        return 1;
    }

printf("Number of functions that failed to load : %i.\n", didLoad.GetNumMissing());

//Tell OpenGL to only draw a pixel if its shape is closer to
//the viewer

//i.e. Enable depth testing with smaller depth value
//interpreted as being closer
gl::Enable(gl::DEPTH_TEST);
gl::DepthFunc(gl::LESS);

//Set up the vertices for a triangle
float points[] = {
    0.0f, 0.5f, 0.0f,
    0.5f, -0.5f, 0.0f,
    -0.5f, -0.5f, 0.0f
};

//Create a vertex buffer object to hold this data
GLuint vbo=0;

gl::GenBuffers(1, &vbo);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::BufferData(gl::ARRAY_BUFFER, 9 * sizeof(float), points, gl::STATIC_DRAW);

//Create a vertex array object
GLuint vao = 0;
gl::GenVertexArrays(1, &vao);
gl::BindVertexArray(vao);
gl::EnableVertexAttribArray(0);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::VertexAttribPointer(0, 3, gl::FLOAT, FALSE, 0, NULL);

//The shader code strings which later we will put in
//separate files

//The Vertex Shader
const char* vertex_shader =
"#version 400\n"
"in vec3 vp;"
"void main() {"
        " gl_Position = vec4(vp, 1.0);"
"}";

//The Fragment Shader
const char* fragment_shader =
"#version 400\n"
"out vec4 frag_colour;"

"void main() {"
        " frag_colour = vec4(1.0, 0.5, 0.0, 1.0);"
"}";

//Load the strings into shader objects and compile
GLuint vs = gl::CreateShader(gl::VERTEX_SHADER);
gl::ShaderSource(vs, 1, &vertex_shader, NULL);
gl::CompileShader(vs);

GLuint fs = gl::CreateShader(gl::FRAGMENT_SHADER);
gl::ShaderSource(fs, 1, &fragment_shader, NULL);
gl::CompileShader(fs);

//Compiled shaders must be compiled into a single executable
//GPU shader program

//Create empty program and attach shaders
GLuint shader_program = gl::CreateProgram();
gl::AttachShader(shader_program, fs);
gl::AttachShader(shader_program, vs);
gl::LinkProgram(shader_program);

//Now draw
while (!glfwWindowShouldClose(window)) {
    //Clear the drawing surface
    gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
    gl::UseProgram(shader_program);
    gl::BindVertexArray(vao);

    //Draw point 0 to 3 from the currently bound VAO with
    //current in-use shader
    gl::DrawArrays(gl::TRIANGLES, 0, 3);

    //update GLFW event handling
    glfwPollEvents();

    //Put the stuff we have been drawing onto the display
    glfwSwapBuffers(window);
}

//Close GLFW and end
glfwTerminate();

return 0;
}
</code>```

Title: GLFW - many errors is this code

Body:
So my university lecturer gave us this code and it doesn't work.. it never has and no one has been able to get it to work so far.. are we being stupid or is our lecturer giving us broken material? I seriously can't figure this out and need help, i managed to get part way through in fixing many mistakes but after that the issues got harder and harder to solve despite this being '100% working' code.... side note: all the directories are formatted correctly and additional dependencies have all been set up correctly to the best of my knowledge.

//First Shader Handling Program

#include "stdafx.h"

#include "gl_core_4_3.hpp"

#include <GLFW/glfw3.h>

int _tmain(int argc, _TCHAR* argv[])
{
    //Select the 4.3 core profile
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    //Start the OpenGL context and open a window using the //GLFW helper library

    if (!glfwInit()) {
        fprintf(stderr, "ERROR: could not start GLFW3\n");
        glfwTerminate();
        return 1;
    }

    GLFWwindow* window = glfwCreateWindow(640, 480, "First GLSL Triangle", NULL, NULL);

    if (!window) {
        fprintf(stderr, "ERROR: could not open window with GLFW3\n");
        glfwTerminate();
        return 1;
    }

    glfwMakeContextCurrent(window);

    //Load the OpenGL functions for C++ gl::exts::LoadTest didLoad = gl::sys::LoadFunctions(); if (!didLoad) {
    //Load failed
    fprintf(stderr, "ERROR: GLLoadGen failed to load functions\n");

    glfwTerminate();
    return 1;
}

printf("Number of functions that failed to load : %i.\n", didLoad.GetNumMissing());

//Tell OpenGL to only draw a pixel if its shape is closer to //the viewer

//i.e. Enable depth testing with smaller depth value //interpreted as being closer gl::Enable(gl::DEPTH_TEST); gl::DepthFunc(gl::LESS);

//Set up the vertices for a triangle
float points[] = {
    0.0f, 0.5f, 0.0f,
    0.5f, -0.5f, 0.0f,
    -0.5f, -0.5f, 0.0f
};

//Create a vertex buffer object to hold this data GLuint vbo=0;

gl::GenBuffers(1, &vbo);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::BufferData(gl::ARRAY_BUFFER, 9 * sizeof(float), points,
    gl::STATIC_DRAW);

//Create a vertex array object
GLuint vao = 0;
gl::GenVertexArrays(1, &vao);
gl::BindVertexArray(vao);
gl::EnableVertexAttribArray(0);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::VertexAttribPointer(0, 3, gl::FLOAT, FALSE, 0, NULL);

//The shader code strings which later we will put in //separate files

//The Vertex Shader
const char* vertex_shader =
"#version 400\n"
"in vec3 vp;"
"void main() {"
        " gl_Position = vec4(vp, 1.0);"
"}";

//The Fragment Shader
const char* fragment_shader =
"#version 400\n"
"out vec4 frag_colour;"

"void main() {"
        " frag_colour = vec4(1.0, 0.5, 0.0, 1.0);"
"}";

//Load the strings into shader objects and compile GLuint vs = gl::CreateShader(gl::VERTEX_SHADER); gl::ShaderSource(vs, 1, &vertex_shader, NULL); gl::CompileShader(vs);

GLuint fs = gl::CreateShader(gl::FRAGMENT_SHADER); gl::ShaderSource(fs, 1, &fragment_shader, NULL); gl::CompileShader(fs);

//Compiled shaders must be compiled into a single executable //GPU shader program

//Create empty program and attach shaders GLuint shader_program = gl::CreateProgram(); gl::AttachShader(shader_program, fs); gl::AttachShader(shader_program, vs); gl::LinkProgram(shader_program);

//Now draw
while (!glfwWindowShouldClose(window)) {
    //Clear the drawing surface
    gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
    gl::UseProgram(shader_program);
    gl::BindVertexArray(vao);

    //Draw point 0 to 3 from the currently bound VAO with
    //current in-use shader
    gl::DrawArrays(gl::TRIANGLES, 0, 3);

    //update GLFW event handling
    glfwPollEvents();

    //Put the stuff we have been drawing onto the display glfwSwapBuffers(window);

}

//Close GLFW and end
glfwTerminate();

return 0;

}

Body:
Your line endings seems to been mangled.

There are multiple lines in your code where actual code was not broken into two lines, so that code is now on the same line as a comment and therefor not being executed. This is your program with proper line endings:

//First Shader Handling Program

#include "stdafx.h"

#include "gl_core_4_3.hpp"

#include <GLFW/glfw3.h>

int _tmain(int argc, _TCHAR* argv[])
{
    //Select the 4.3 core profile
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    //Start the OpenGL context and open a window using the
    //GLFW helper library

    if (!glfwInit()) {
        fprintf(stderr, "ERROR: could not start GLFW3\n");
        glfwTerminate();
        return 1;
    }

    GLFWwindow* window = glfwCreateWindow(640, 480, "First GLSL Triangle", NULL, NULL);

    if (!window) {
        fprintf(stderr, "ERROR: could not open window with GLFW3\n");
        glfwTerminate();
        return 1;
    }

    glfwMakeContextCurrent(window);

    //Load the OpenGL functions for C++
    gl::exts::LoadTest didLoad = gl::sys::LoadFunctions();
    if (!didLoad) {
        //Load failed
        fprintf(stderr, "ERROR: GLLoadGen failed to load functions\n");

        glfwTerminate();
        return 1;
    }

printf("Number of functions that failed to load : %i.\n", didLoad.GetNumMissing());

//Tell OpenGL to only draw a pixel if its shape is closer to
//the viewer

//i.e. Enable depth testing with smaller depth value
//interpreted as being closer
gl::Enable(gl::DEPTH_TEST);
gl::DepthFunc(gl::LESS);

//Set up the vertices for a triangle
float points[] = {
    0.0f, 0.5f, 0.0f,
    0.5f, -0.5f, 0.0f,
    -0.5f, -0.5f, 0.0f
};

//Create a vertex buffer object to hold this data
GLuint vbo=0;

gl::GenBuffers(1, &vbo);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::BufferData(gl::ARRAY_BUFFER, 9 * sizeof(float), points, gl::STATIC_DRAW);

//Create a vertex array object
GLuint vao = 0;
gl::GenVertexArrays(1, &vao);
gl::BindVertexArray(vao);
gl::EnableVertexAttribArray(0);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::VertexAttribPointer(0, 3, gl::FLOAT, FALSE, 0, NULL);

//The shader code strings which later we will put in
//separate files

//The Vertex Shader
const char* vertex_shader =
"#version 400\n"
"in vec3 vp;"
"void main() {"
        " gl_Position = vec4(vp, 1.0);"
"}";

//The Fragment Shader
const char* fragment_shader =
"#version 400\n"
"out vec4 frag_colour;"

"void main() {"
        " frag_colour = vec4(1.0, 0.5, 0.0, 1.0);"
"}";

//Load the strings into shader objects and compile
GLuint vs = gl::CreateShader(gl::VERTEX_SHADER);
gl::ShaderSource(vs, 1, &vertex_shader, NULL);
gl::CompileShader(vs);

GLuint fs = gl::CreateShader(gl::FRAGMENT_SHADER);
gl::ShaderSource(fs, 1, &fragment_shader, NULL);
gl::CompileShader(fs);

//Compiled shaders must be compiled into a single executable
//GPU shader program

//Create empty program and attach shaders
GLuint shader_program = gl::CreateProgram();
gl::AttachShader(shader_program, fs);
gl::AttachShader(shader_program, vs);
gl::LinkProgram(shader_program);

//Now draw
while (!glfwWindowShouldClose(window)) {
    //Clear the drawing surface
    gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
    gl::UseProgram(shader_program);
    gl::BindVertexArray(vao);

    //Draw point 0 to 3 from the currently bound VAO with
    //current in-use shader
    gl::DrawArrays(gl::TRIANGLES, 0, 3);

    //update GLFW event handling
    glfwPollEvents();

    //Put the stuff we have been drawing onto the display
    glfwSwapBuffers(window);
}

//Close GLFW and end
glfwTerminate();

return 0;
}


问:
Free Silverlight mapping with Bing maps and OpenStreetMap?
I recently read this article. Which uses the Silverlight Bing maps control to display map data from OpenStreetMap.  In this article he extends MapCore and develops a true OpenStreetMap control which no longer requires you to use the Bing API key.

My question is simple.  Does this solution constitute free Silverlight mapping for commercial projects or does the use of the Bing map control itself require licensing?

Thanks in advance.

答:
the bing maps control will require a license, even if you are not using the bing tiles. Take a look at the completely open source deepearth silverlight map control, works well with OSM:

http://deepearth.codeplex.com/


问:
How to use onload event from Image in typescript?
I want to get some info from an image that i load using new image() with typescript. I try this code:

```<code>width;
heigth;
init(){
    let image = new Image();
    image.src = "url";

    image.onload((event) => {
    this.width = event.width;
    this.heigth = event.heigth;
    })
}
</code>```

But i get this error:

void' is not assignable to parameter of type 'Event'. Property
  'bubbles' is missing in type '() => void'

I search examples on how to use this event but i can't find anything.

答:
You are trying to call onload rather than assign an event handler. Here is a quick fix for you...

```<code>image.onload = (event) => {
  // ...
};
</code>```

You will also find that the general Event type doesn't have width and height, so you may need to specialise the type for that too.

```<code>interface SizedEvent {
  width: number;
  height: number;
}

function isSizedEvent(e: any): e is SizedEvent {
  return (e && e.width !== undefined && e.height !== undefined);
}

image.onload = (event) => {
  if (isSizedEvent(event)) {
    // event.width is now available
  }
};
</code>```

Body:
I want to get some info from an image that i load using new image() with typescript. I try this code:

width;
heigth;
init(){
    let image = new Image();
    image.src = "url";

    image.onload((event) => {
    this.width = event.width;
    this.heigth = event.heigth;
    })
}

But i get this error:

void' is not assignable to parameter of type 'Event'. Property
  'bubbles' is missing in type '() => void'

I search examples on how to use this event but i can't find anything.

Body:
You are trying to call onload rather than assign an event handler. Here is a quick fix for you...

image.onload = (event) => {
  // ...
};

You will also find that the general Event type doesn't have width and height, so you may need to specialise the type for that too.

interface SizedEvent {
  width: number;
  height: number;
}

function isSizedEvent(e: any): e is SizedEvent {
  return (e && e.width !== undefined && e.height !== undefined);
}

image.onload = (event) => {
  if (isSizedEvent(event)) {
    // event.width is now available
  }
};


问:
IndexOutOfBoundsException?
I'm trying to subtract two positions of different ArrayLists and save the result in another ArrayList but i'm getting the IndexOutOfBoundsException error. I understand how works this error and what it means.
The problem is that when I run my code with the debugger it works fine, but if I run it normally it gives me the error.

Here I declare the variables

Here is the for loop code.

Here is the error

Both Lists, "accels" and "gravs" have the same size 252. I don't understand why step by step it works and all continous no.

答: Try the loop without checking <= for your iteration. i.e (i < accels.size())

Title: IndexOutOfBoundsException?


问:
XAML editing options
I use Visual Studio 2010 for WPF development of desktop apps.  I edit my XAML with the visual editor, often tweaking it manually.  My code-behind is C#.   I haven't had any particular problems with this arrangement.

What are the advantages of Expression Blend over Visual Studio for editing XAML?    Why is Expression Blend so expensive (it's more expensive than I paid for Visual Studio!!)   Are there other full-featured XAML editors which are cheaper?   (I'm not talking about free ones like kaxaml - those are too limited)

Thanks in advance.

答: I find that the main advantage of Blend is that the UI makes it very, very easy to create complex animations and transitions - really gorgeous user experience things - but you need to spend some time 'learning' Blend to do it. To write the XAML in Visual Studio to create the same effects would be much more difficult - Blend does it much quicker, and you can preview the results instantly. It's not easy (if it's even possible - I've honestly not tried the more demanding stuff) with Visual Studio.</p>

Title: XAML editing options


问:
How to get the selected index of checkbox from tableview on javafx
I am very new to JavaFX, I need help in identifying the selected/checked checkbox from the table-view to . See the screenshot for the UI and code i used to the populate data on the table view. I am using scene builder for creating the UI

Code to initialize the table view

```<code>public void initialize(URL location, ResourceBundle resources) {

    ddUrls.setItems(urls);
    ddbrowserNames.setItems(browsers);
    ddFrames.setItems(frames);

    //testClassCl.setCellValueFactory(new PropertyValueFactory<TestSuite,String>("testClass"));
    testMethodCl.setCellValueFactory(new PropertyValueFactory<TestSuite,String>("testMethod"));
    testDescCl.setCellValueFactory(new PropertyValueFactory<TestSuite,String>("testDesc"));
    //runModeCl.setCellValueFactory(new PropertyValueFactory<TestSuite,Boolean>("runMode"));
    runModeCl.setCellFactory(column -> new CheckBoxTableCell());
    table.setItems(list);
    table.setEditable(true);
}
</code>```

Image of the UI

Here is the data model.

```<code>package com.automation.UI;
</code>```

import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;

public class TestSuite {

```<code>private SimpleStringProperty testClass;
private SimpleStringProperty testMethod;
private SimpleStringProperty testDesc;
private SimpleBooleanProperty runMode;

public TestSuite(String testClass, String testMethod, String testDesc, boolean runMode) {
    this.testClass = new SimpleStringProperty(testClass);
    this.testMethod = new SimpleStringProperty(testMethod);
    this.testDesc = new SimpleStringProperty(testDesc);
    this.runMode = new SimpleBooleanProperty(runMode);
}

public String getTestClass() {
    return testClass.get();
}

public String getTestMethod() {
    return testMethod.get();
}

public String getTestDesc() {
    return testDesc.get();
}

public boolean getRunMode() {
    return runMode.get();
}
</code>```

}

My aim is to get the Description( column next to check) of all the selected checkbox on clicking another button

答:
There is a couple of ways you can do this the first is to create a list of check boxes and iterate through them and check if(checkBox.isSelected()) otherwise you may have to iterate though all of your nodes to check if it is selected here is an example

```<code>List<Object> checkedList = new ArrayList<>();
for (Object node : vbox.getChildren())
    if (checkBox instanceof CheckBox)
        if (((CheckBox) checkBox).isSelected())
            checkedList.add(node);
</code>```

Then you will have a list of selected checkboxes

Body:
I am very new to JavaFX, I need help in identifying the selected/checked checkbox from the table-view to . See the screenshot for the UI and code i used to the populate data on the table view. I am using scene builder for creating the UI

Code to initialize the table view

public void initialize(URL location, ResourceBundle resources) {

    ddUrls.setItems(urls);
    ddbrowserNames.setItems(browsers);
    ddFrames.setItems(frames);

    //testClassCl.setCellValueFactory(new PropertyValueFactory<TestSuite,String>("testClass"));
    testMethodCl.setCellValueFactory(new PropertyValueFactory<TestSuite,String>("testMethod"));
    testDescCl.setCellValueFactory(new PropertyValueFactory<TestSuite,String>("testDesc"));
    //runModeCl.setCellValueFactory(new PropertyValueFactory<TestSuite,Boolean>("runMode"));
    runModeCl.setCellFactory(column -> new CheckBoxTableCell());
    table.setItems(list);
    table.setEditable(true);
}

Image of the UI

Here is the data model.

package com.automation.UI;

import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;

public class TestSuite {

private SimpleStringProperty testClass;
private SimpleStringProperty testMethod;
private SimpleStringProperty testDesc;
private SimpleBooleanProperty runMode;

public TestSuite(String testClass, String testMethod, String testDesc, boolean runMode) {
    this.testClass = new SimpleStringProperty(testClass);
    this.testMethod = new SimpleStringProperty(testMethod);
    this.testDesc = new SimpleStringProperty(testDesc);
    this.runMode = new SimpleBooleanProperty(runMode);
}

public String getTestClass() {
    return testClass.get();
}

public String getTestMethod() {
    return testMethod.get();
}

public String getTestDesc() {
    return testDesc.get();
}

public boolean getRunMode() {
    return runMode.get();
}

}

My aim is to get the Description( column next to check) of all the selected checkbox on clicking another button

Body:
There is a couple of ways you can do this the first is to create a list of check boxes and iterate through them and check if(checkBox.isSelected()) otherwise you may have to iterate though all of your nodes to check if it is selected here is an example

List<Object> checkedList = new ArrayList<>();
for (Object node : vbox.getChildren())
    if (checkBox instanceof CheckBox)
        if (((CheckBox) checkBox).isSelected())
            checkedList.add(node);

Then you will have a list of selected checkboxes


问:
App crashes after reinstall on emulator since FileProvider Class was not found
When I run the app on the emulator it always works on the first try. But when the app is already installed on the emulator it often results in a crash during the start of the app.
This behavior started to occur with Android Studio 2.0.
It does not occur on devices, therefore it is not so important but only annoying since I always need to delete the app from the emulator before installing a new version.

Since I have absolutely no idea what causes this issue and can't find similar issues during research, I hope that somebody can help me.

Error message:

```<code>08-25 09:55:35.023 4214-4214/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.mls.Search.Abbott, PID: 4214
    java.lang.RuntimeException: Unable to get provider android.support.v4.content.FileProvider: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.FileProvider" on path: DexPathList[[zip file "/data/app/com.mls.Search.Abbott-2/base.apk"],nativeLibraryDirectories=[/data/app/com.mls.Search.Abbott-2/lib/x86, /data/app/com.mls.Search.Abbott-2/base.apk!/lib/x86, /vendor/lib, /system/lib]]
        at android.app.ActivityThread.installProvider(ActivityThread.java:5156)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:4748)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4688)
        at android.app.ActivityThread.-wrap1(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.FileProvider" on path: DexPathList[[zip file "/data/app/com.mls.Search.Abbott-2/base.apk"],nativeLibraryDirectories=[/data/app/com.mls.Search.Abbott-2/lib/x86, /data/app/com.mls.Search.Abbott-2/base.apk!/lib/x86, /vendor/lib, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
        at android.app.ActivityThread.installProvider(ActivityThread.java:5141)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:4748)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4688)
        at android.app.ActivityThread.-wrap1(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Suppressed: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.FileProvider" on path: DexPathList[[dex file "/data/data/com.mls.Search.Abbott/files/instant-run/dex/slice-slice_3-classes.dex"],nativeLibraryDirectories=[/data/app/com.mls.Search.Abbott-2/lib/x86, /data/app/com.mls.Search.Abbott-2/base.apk!/lib/x86, /vendor/lib, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at com.android.tools.fd.runtime.IncrementalClassLoader$DelegateClassLoader.findClass(IncrementalClassLoader.java:90)
        at com.android.tools.fd.runtime.IncrementalClassLoader.findClass(IncrementalClassLoader.java:62)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
              ... 12 more
            Suppressed: java.lang.ClassNotFoundException: android.support.v4.content.FileProvider
        at java.lang.Class.classForName(Native Method)
        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
        at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                ... 13 more
    Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
</code>```

File Provider in Manifest:

```<code><provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/filepaths" />
</provider>
</code>```

答:
If you use Android 5.0 or lower in your emulator (api level 21),
then  add the multidex support library to your project:

If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file, as shown here:

```<code>android {
    defaultConfig {
        ...
        minSdkVersion 21
        targetSdkVersion 26
        multiDexEnabled true
    }
    ...
}
</code>```

if your minSdkVersion is set to 20 or lower, then you must use the multidex support library as follows:

Modify the module-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:

```<code>android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 26
        multiDexEnabled true
    }
    ...
}
</code>```

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

Look at
https://developer.android.com/studio/build/multidex.html#mdex-gradle

Body:
When I run the app on the emulator it always works on the first try. But when the app is already installed on the emulator it often results in a crash during the start of the app.
This behavior started to occur with Android Studio 2.0.
It does not occur on devices, therefore it is not so important but only annoying since I always need to delete the app from the emulator before installing a new version.

Since I have absolutely no idea what causes this issue and can't find similar issues during research, I hope that somebody can help me.

Error message:

08-25 09:55:35.023 4214-4214/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.mls.Search.Abbott, PID: 4214
    java.lang.RuntimeException: Unable to get provider android.support.v4.content.FileProvider: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.FileProvider" on path: DexPathList[[zip file "/data/app/com.mls.Search.Abbott-2/base.apk"],nativeLibraryDirectories=[/data/app/com.mls.Search.Abbott-2/lib/x86, /data/app/com.mls.Search.Abbott-2/base.apk!/lib/x86, /vendor/lib, /system/lib]]
        at android.app.ActivityThread.installProvider(ActivityThread.java:5156)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:4748)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4688)
        at android.app.ActivityThread.-wrap1(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.FileProvider" on path: DexPathList[[zip file "/data/app/com.mls.Search.Abbott-2/base.apk"],nativeLibraryDirectories=[/data/app/com.mls.Search.Abbott-2/lib/x86, /data/app/com.mls.Search.Abbott-2/base.apk!/lib/x86, /vendor/lib, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
        at android.app.ActivityThread.installProvider(ActivityThread.java:5141)
        at android.app.ActivityThread.installContentProviders(ActivityThread.java:4748)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4688)
        at android.app.ActivityThread.-wrap1(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Suppressed: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.FileProvider" on path: DexPathList[[dex file "/data/data/com.mls.Search.Abbott/files/instant-run/dex/slice-slice_3-classes.dex"],nativeLibraryDirectories=[/data/app/com.mls.Search.Abbott-2/lib/x86, /data/app/com.mls.Search.Abbott-2/base.apk!/lib/x86, /vendor/lib, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at com.android.tools.fd.runtime.IncrementalClassLoader$DelegateClassLoader.findClass(IncrementalClassLoader.java:90)
        at com.android.tools.fd.runtime.IncrementalClassLoader.findClass(IncrementalClassLoader.java:62)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
              ... 12 more
            Suppressed: java.lang.ClassNotFoundException: android.support.v4.content.FileProvider
        at java.lang.Class.classForName(Native Method)
        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
        at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                ... 13 more
    Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

File Provider in Manifest:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/filepaths" />
</provider>

Body:
If you use Android 5.0 or lower in your emulator (api level 21),
then  add the multidex support library to your project:

If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file, as shown here:

android {
    defaultConfig {
        ...
        minSdkVersion 21
        targetSdkVersion 26
        multiDexEnabled true
    }
    ...
}

if your minSdkVersion is set to 20 or lower, then you must use the multidex support library as follows:

Modify the module-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:

android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 26
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

Look at
https://developer.android.com/studio/build/multidex.html#mdex-gradle


问:
Strange behavior with cell construction with Simple TableView Swift
I have spent an insane time to fix this bug in our application. We are currently working in a chat and we have used a tableview for it.

Our tableview works fine until there is a certain amount of messages, after that, the table starts to flick. I coded without storyboards and for this reason I thought that constraints were the cause of trouble. So I decide to make a really simple tableview with some features of our chat tableview (actually our tableview is coredata linked and with a lot of graphic stuffs).

Because I suspected about constraints, I didn't use it in the code bellow just to see everything works fine, but it wasn't the case. In the gif image we can see two undesirable behaviors, the first one is that sometimes the table is re-generated completely, so cells disappear and appear in a very short time (this cause a very annoying flick). The second is no less annoying: cells are duplicated (I think this is for the cell reusability feature) but after a short period of time they are accommodated and everything goes fine.

https://github.com/hugounavez/pizzaWatch/blob/master/videoBug.gif

I tried adding the prepareForReuse() method and delete the views and creates them in the cell again but no results.

This is the example code, you can copy and run it with no problems in a Playground:

```<code>//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class Modelito{
    // This is the class tableview model
    var celda: String
    var valor: String
    init(celda: String, valor: String){
        self.celda = celda
        self.valor = valor
    }
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

    let tableview: UITableView = {
        let table = UITableView()
        table.translatesAutoresizingMaskIntoConstraints = false
        return table
    }()

    let button: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Click me to add new cell", for: .normal)
        button.setTitle("Click me to add new cell", for: .highlighted)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    var model: [Modelito] = []

    let tipoDeCelda = ["MyCustomCell", "MyCustomCell2"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupViews()

        self.tableview.register(MyCustomCell.self, forCellReuseIdentifier: "MyCustomCell")
        self.tableview.register(MyCustomCell2.self, forCellReuseIdentifier: "MyCustomCell2")

        self.tableview.dataSource = self
        self.tableview.delegate = self

        self.button.addTarget(self, action: #selector(self.addRow), for: .touchUpInside)

        // Here I generate semi random info
        self.dataGeneration()
    }

    func setupViews(){

        self.view.addSubview(self.tableview)
        self.tableview.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.tableview.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -50).isActive = true
        self.tableview.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 1).isActive = true
        self.tableview.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

        self.tableview.backgroundColor = .gray

        self.view.addSubview(self.button)
        self.button.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        self.button.topAnchor.constraint(equalTo: self.tableview.bottomAnchor).isActive = true
        self.button.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        self.button.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
        self.button.backgroundColor = .orange

    }

    func dataGeneration(){
        let number = 200
        // Based in the cell types availables and the senteces, we create random cell info
        for _ in 0...number{

            self.model.append(
                Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
            )
        }

        self.tableview.reloadData()
        // After we insert elements in the model we scroll table
        let indexPaths: [IndexPath] = [IndexPath(row: self.model.count - 1, section: 0)]
        self.tableview.scrollToRow(at: indexPaths[0], at: .bottom, animated: false)
    }

    @objc func addRow(){
        // This function insert a new random element
        self.tableview.beginUpdates()
        self.model.append(
            Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
        )

        // After inserting the element in the model, we insert it in the tableview
        let indexPaths: [IndexPath] = [IndexPath(row: self.model.count - 1, section: 0)]
        self.tableview.insertRows(at: indexPaths, with: .none)
        self.tableview.endUpdates()
        // Finally we scroll to last row
        self.tableview.scrollToRow(at: indexPaths[0], at: .bottom, animated: false)

    }

}

extension ViewController{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.model.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }

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

        let celldata = self.model[indexPath.row]

        switch celldata.celda {
        case "MyCustomCell":
            let cell = tableview.dequeueReusableCell(withIdentifier: "MyCustomCell", for: indexPath) as! MyCustomCell
            cell.myLabel.text = self.model[indexPath.row].valor
            return cell
        default:
            let cell = tableview.dequeueReusableCell(withIdentifier: "MyCustomCell2", for: indexPath) as! MyCustomCell2
            cell.myLabel.text = self.model[indexPath.row].valor
            return cell
        }

    }
}

class MyCustomCell: UITableViewCell {

    var myLabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        myLabel.backgroundColor = UIColor.green
        self.contentView.addSubview(myLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        myLabel.frame = CGRect(x: 25, y: 0, width: 370, height: 30)
    }
}

class MyCustomCell2: UITableViewCell {

    var myLabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        myLabel.backgroundColor = UIColor.yellow
        self.contentView.addSubview(myLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        myLabel.frame = CGRect(x: 0, y: 0, width: 370, height: 30)
    }

}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = ViewController()
</code>```

Thanks in advance.

Edit:

I changed the code base in the @Scriptable answer in order to be compatible with playground. At this point, I am starting to think that duplication cell bug is actually normal for tableview. In order to see the problem, the button should be pressed several times fastly.

答:
Using your current code in a playground produced a fatal error for me.

2017-11-13 15:10:46.739 MyPlayground[4005:234029] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[UITableView _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:]: row (200) beyond bounds (0) for section (0).'

I changed the dataGeneration function to the following code which just calls reloadData once the data has been generated and scrolls to the bottom.

I think the error was that without reloading, there wasn't that many rows to scroll to.

```<code>func dataGeneration(){
        let number = 200
        // Based in the cell types available and the sentences, we create random cell info
        for _ in 0...number{

            self.model.append(
                Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
            )
        }

        self.tableview.reloadData()
        // After we insert elements in the model we scroll table
        let indexPaths: [IndexPath] = [IndexPath(row: self.model.count - 1, section: 0)]
        self.tableview.scrollToRow(at: indexPaths[0], at: .bottom, animated: false)
    }
</code>```

Once I got around the crash, the tableView worked fine for me. No flickering or duplication.

Body:
I have spent an insane time to fix this bug in our application. We are currently working in a chat and we have used a tableview for it.

Our tableview works fine until there is a certain amount of messages, after that, the table starts to flick. I coded without storyboards and for this reason I thought that constraints were the cause of trouble. So I decide to make a really simple tableview with some features of our chat tableview (actually our tableview is coredata linked and with a lot of graphic stuffs).

Because I suspected about constraints, I didn't use it in the code bellow just to see everything works fine, but it wasn't the case. In the gif image we can see two undesirable behaviors, the first one is that sometimes the table is re-generated completely, so cells disappear and appear in a very short time (this cause a very annoying flick). The second is no less annoying: cells are duplicated (I think this is for the cell reusability feature) but after a short period of time they are accommodated and everything goes fine.

https://github.com/hugounavez/pizzaWatch/blob/master/videoBug.gif

I tried adding the prepareForReuse() method and delete the views and creates them in the cell again but no results.

This is the example code, you can copy and run it with no problems in a Playground:

//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class Modelito{
    // This is the class tableview model
    var celda: String
    var valor: String
    init(celda: String, valor: String){
        self.celda = celda
        self.valor = valor
    }
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

    let tableview: UITableView = {
        let table = UITableView()
        table.translatesAutoresizingMaskIntoConstraints = false
        return table
    }()

    let button: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Click me to add new cell", for: .normal)
        button.setTitle("Click me to add new cell", for: .highlighted)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    var model: [Modelito] = []

    let tipoDeCelda = ["MyCustomCell", "MyCustomCell2"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupViews()

        self.tableview.register(MyCustomCell.self, forCellReuseIdentifier: "MyCustomCell")
        self.tableview.register(MyCustomCell2.self, forCellReuseIdentifier: "MyCustomCell2")

        self.tableview.dataSource = self
        self.tableview.delegate = self

        self.button.addTarget(self, action: #selector(self.addRow), for: .touchUpInside)

        // Here I generate semi random info
        self.dataGeneration()
    }

    func setupViews(){

        self.view.addSubview(self.tableview)
        self.tableview.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        self.tableview.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -50).isActive = true
        self.tableview.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 1).isActive = true
        self.tableview.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

        self.tableview.backgroundColor = .gray

        self.view.addSubview(self.button)
        self.button.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        self.button.topAnchor.constraint(equalTo: self.tableview.bottomAnchor).isActive = true
        self.button.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        self.button.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
        self.button.backgroundColor = .orange

    }

    func dataGeneration(){
        let number = 200
        // Based in the cell types availables and the senteces, we create random cell info
        for _ in 0...number{

            self.model.append(
                Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
            )
        }

        self.tableview.reloadData()
        // After we insert elements in the model we scroll table
        let indexPaths: [IndexPath] = [IndexPath(row: self.model.count - 1, section: 0)]
        self.tableview.scrollToRow(at: indexPaths[0], at: .bottom, animated: false)
    }

    @objc func addRow(){
        // This function insert a new random element
        self.tableview.beginUpdates()
        self.model.append(
            Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
        )

        // After inserting the element in the model, we insert it in the tableview
        let indexPaths: [IndexPath] = [IndexPath(row: self.model.count - 1, section: 0)]
        self.tableview.insertRows(at: indexPaths, with: .none)
        self.tableview.endUpdates()
        // Finally we scroll to last row
        self.tableview.scrollToRow(at: indexPaths[0], at: .bottom, animated: false)

    }

}

extension ViewController{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.model.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 150
    }

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

        let celldata = self.model[indexPath.row]

        switch celldata.celda {
        case "MyCustomCell":
            let cell = tableview.dequeueReusableCell(withIdentifier: "MyCustomCell", for: indexPath) as! MyCustomCell
            cell.myLabel.text = self.model[indexPath.row].valor
            return cell
        default:
            let cell = tableview.dequeueReusableCell(withIdentifier: "MyCustomCell2", for: indexPath) as! MyCustomCell2
            cell.myLabel.text = self.model[indexPath.row].valor
            return cell
        }

    }
}

class MyCustomCell: UITableViewCell {

    var myLabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        myLabel.backgroundColor = UIColor.green
        self.contentView.addSubview(myLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        myLabel.frame = CGRect(x: 25, y: 0, width: 370, height: 30)
    }
}

class MyCustomCell2: UITableViewCell {

    var myLabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        myLabel.backgroundColor = UIColor.yellow
        self.contentView.addSubview(myLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        myLabel.frame = CGRect(x: 0, y: 0, width: 370, height: 30)
    }

}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = ViewController()

Thanks in advance.

Edit:

I changed the code base in the @Scriptable answer in order to be compatible with playground. At this point, I am starting to think that duplication cell bug is actually normal for tableview. In order to see the problem, the button should be pressed several times fastly.

Body:
Using your current code in a playground produced a fatal error for me.

2017-11-13 15:10:46.739 MyPlayground[4005:234029] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[UITableView _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:]: row (200) beyond bounds (0) for section (0).'

I changed the dataGeneration function to the following code which just calls reloadData once the data has been generated and scrolls to the bottom.

I think the error was that without reloading, there wasn't that many rows to scroll to.

func dataGeneration(){
        let number = 200
        // Based in the cell types available and the sentences, we create random cell info
        for _ in 0...number{

            self.model.append(
                Modelito(celda: tipoDeCelda[Int(arc4random_uniform(UInt32(self.tipoDeCelda.count)))], valor: "\(self.model.count)")
            )
        }

        self.tableview.reloadData()
        // After we insert elements in the model we scroll table
        let indexPaths: [IndexPath] = [IndexPath(row: self.model.count - 1, section: 0)]
        self.tableview.scrollToRow(at: indexPaths[0], at: .bottom, animated: false)
    }

Once I got around the crash, the tableView worked fine for me. No flickering or duplication.


问:
Angular 2: Retrieve objects from firebase
Below is my firebase database screenshot:

Below is the code in the "app.component":

```<code>import { AngularFireDatabase, FirebaseListObservable } from "angularfire2/database-deprecated";
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';

@Component ....

items: FirebaseListObservable<any[]>;

constructor(public af: AngularFireDatabase) {
   this.items = af.list('/projects', {
     query: {
       limitToLast: 10
     }
   });
   console.log(this.items);
}
</code>```

but I'm not getting the data. Could anyone help me out on this?

I've completed the angularfire2 setup and able to write the data to the real time database. It's the issue with getting the data from db.

答:
You need to call a subscribe method on the list. As such:

```<code>this.items = af.list('/projects').valueChanges().subscribe(items => {
    console.log(items);
}));
</code>```

I see that u are using a the database-deprecated package. The code should be as such:

```<code>this.firebaseList = af.list('/projects'); // This is of type FirebaseListObservable

this.items = this.firebaseList.subscribe(items => {
    console.log(items);
})); // This is of type subscription.

this.firebaseList.push({...data}); // Now you can push.
</code>```

Body:
Below is my firebase database screenshot:

Below is the code in the "app.component":

import { AngularFireDatabase, FirebaseListObservable } from "angularfire2/database-deprecated";
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';

@Component ....

items: FirebaseListObservable<any[]>;

constructor(public af: AngularFireDatabase) {
   this.items = af.list('/projects', {
     query: {
       limitToLast: 10
     }
   });
   console.log(this.items);
}

but I'm not getting the data. Could anyone help me out on this?

I've completed the angularfire2 setup and able to write the data to the real time database. It's the issue with getting the data from db.

Body:
You need to call a subscribe method on the list. As such:

this.items = af.list('/projects').valueChanges().subscribe(items => {
    console.log(items);
}));

I see that u are using a the database-deprecated package. The code should be as such:

this.firebaseList = af.list('/projects'); // This is of type FirebaseListObservable

this.items = this.firebaseList.subscribe(items => {
    console.log(items);
})); // This is of type subscription.

this.firebaseList.push({...data}); // Now you can push.


问:
How to access all the MapView.Markers of a react-native-maps MapView?
In a react-native app usig react-native-maps, I'm trying to programmatically show the MapView.Callout of a specific MapView.Marker amongst many. I'm planning to use the showCallout-method, but haven't yet found out how to access all of the MapView's markers, from where I could select the correct one based on it's id/key/ref.

The markers are rendered onto the MapView in a map-loop as below.

Sofar I've tried without success to get hold of all the MapView's markers using this.refs.mapView.refs / this.refs.mapView.children but I don't get anything there.

```<code><MapView>
    ref={'mapView'}
    ...
>
    {this.props.screenProps.appState.cachedDeviations.map(deviation => {
        return (
            <MapView.Marker
                coordinate={
                    deviation.position
                }
                key={deviation.Id}
                ref={deviation.Id}
            >
                <MapView.Callout style={styles.callout}>
                    <DeviationCallout
                        ...
                    />
                </MapView.Callout>
            </MapView.Marker>
        )
    })
}
</MapView>
</code>```

Any hints?

答:
You can use functional ref.

Example

```<code><MapView.Marker
    coordinate={ deviation.position }
    key={deviation.Id}
    ref={(ref) => this.markers[deviation.Id] = ref}
>
  // ...
</<MapView.Marker>

// ...

this.markers[someId].showCallout();
</code>```

Body:
In a react-native app usig react-native-maps, I'm trying to programmatically show the MapView.Callout of a specific MapView.Marker amongst many. I'm planning to use the showCallout-method, but haven't yet found out how to access all of the MapView's markers, from where I could select the correct one based on it's id/key/ref.

The markers are rendered onto the MapView in a map-loop as below.

Sofar I've tried without success to get hold of all the MapView's markers using this.refs.mapView.refs / this.refs.mapView.children but I don't get anything there.

<MapView>
    ref={'mapView'}
    ...
>
    {this.props.screenProps.appState.cachedDeviations.map(deviation => {
        return (
            <MapView.Marker
                coordinate={
                    deviation.position
                }
                key={deviation.Id}
                ref={deviation.Id}
            >
                <MapView.Callout style={styles.callout}>
                    <DeviationCallout
                        ...
                    />
                </MapView.Callout>
            </MapView.Marker>
        )
    })
}
</MapView>

Any hints?

Body:
You can use functional ref.

Example

<MapView.Marker
    coordinate={ deviation.position }
    key={deviation.Id}
    ref={(ref) => this.markers[deviation.Id] = ref}
>
  // ...
</<MapView.Marker>

// ...

this.markers[someId].showCallout();