问:
upgrading to Android Studio 3.0 Canary 5 causing "IllegalArgumentException: AppCompat does not support the current theme features.."
I was running my app fine using Android Studio 3.0 Canary 4 but after updating to Canary 5 the app now crashes on start with:

```<code>Caused by: java.lang.IllegalArgumentException: AppCompat does not support the current theme features: { windowActionBar: false, windowActionBarOverlay: false, android:windowIsFloating: false, windowActionModeOverlay: false, windowNoTitle: false }
at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:474)
at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.bleachr.fan_engine.activities.BaseActivity.setContentView(BaseActivity.java:138)
</code>```

I've narrowed it down to what I think is an issue loading the app styles..

the Exception mentions windowNoTitle: false when I'm setting this flag to true. Here's the relevant xml lines I can think of:

styles.xml:

```<code><style name="AppTheme.Base" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>
</style>

<style name="AppTheme" parent="AppTheme.Base"/>
</code>```

AndroidManifest.xml

```<code>    <application
...
        android:theme="@style/AppTheme"
</code>```

I'm not overriding the theme for this Activity in any other way so that should be it..

My initial thought is somehow the windowNoTitle isn't being loaded - otherwise it'd be logged as true in the Exception. Does that make sense?

Any thoughts? I'm not sure if/how I can downgrade to Canary 4 again.. I'm sure I can use the stable build but I'd rather figure out this issue if possible.

Update: I removed android:theme="@style/AppTheme" from AndroidManifest and still getting the same Exception!

Note I've done the 'invalidate and restart' option in Android Studio as well as about everything else I've seen in other similar Stack Overflow posts.

Also - there's no v21/styles.xml or anything else that should be in the way here either in case you were wondering..

答:
Do you have android.enableAapt2=false in gradle.properties?
Removing it - solves the issue.

Looks like starting with Canary 5, aapt1 does not merge styles items properly. I've digged into AppCompatDelegateImplV9.createSubDecor and this.mWindowNoTitle does not match value set for style with:
<item name="windowNoTitle">true</item>

```<code>// AppCompatDelegateImplV9
private ViewGroup createSubDecor() {
    TypedArray a = this.mContext.obtainStyledAttributes(styleable.AppCompatTheme);

    // ~~~~ERROR:  false returned (ignoring value from xml)
    if(a.getBoolean(styleable.AppCompatTheme_windowNoTitle, false)) {
        this.requestWindowFeature(1);
    }
</code>```

Did anyone raised an issue on issuetracker.google.com?

Body:
I was running my app fine using Android Studio 3.0 Canary 4 but after updating to Canary 5 the app now crashes on start with:

Caused by: java.lang.IllegalArgumentException: AppCompat does not support the current theme features: { windowActionBar: false, windowActionBarOverlay: false, android:windowIsFloating: false, windowActionModeOverlay: false, windowNoTitle: false }
at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:474)
at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.bleachr.fan_engine.activities.BaseActivity.setContentView(BaseActivity.java:138)

I've narrowed it down to what I think is an issue loading the app styles..

the Exception mentions windowNoTitle: false when I'm setting this flag to true. Here's the relevant xml lines I can think of:

styles.xml:

Body:
Do you have android.enableAapt2=false in gradle.properties?
Removing it - solves the issue.

Looks like starting with Canary 5, aapt1 does not merge styles items properly. I've digged into AppCompatDelegateImplV9.createSubDecor and this.mWindowNoTitle does not match value set for style with:
<item name="windowNoTitle">true</item>

// AppCompatDelegateImplV9
private ViewGroup createSubDecor() {
    TypedArray a = this.mContext.obtainStyledAttributes(styleable.AppCompatTheme);

    // ~~~~ERROR:  false returned (ignoring value from xml)
    if(a.getBoolean(styleable.AppCompatTheme_windowNoTitle, false)) {
        this.requestWindowFeature(1);
    }

Did anyone raised an issue on issuetracker.google.com?


来源: stackexchange

问:
Is it possible to cancel a SqlBulkCopy.WriteToServer (c#)?
I am using SqlBulkCopy.WriteToServer (C#) to copy billions of rows, and which takes hours to complete. Sometimes I need to stop the operation for some urgent tasks, but I don't know how to do so. Can I do something on the arriving of the notification event (with SqlBulkCopy.NotifyAfter and SqlBulkCopy.SqlRowsCopied)?</p>

答:
You can try to modify your sql query and process data in chunks, for example, 1 thousand per request. If you need to stop operation, remember chunk size and number, stop sql operation, do what you need, and continue sql operations.
Also you can make your own PaueOperationToken like CancelToken.
Here is example of CancelToken.

ContentLicense: CC BY-SA 3.0


问:
How can I make the font-awesome can take the full area of its parent container
As you can see the thumbs are over its parent area.
The UI layout is not acceptable.

The following is the expected result.
I tried to put margin-bottom with a negative number,
Or tried to make them in FLEX layout.
None of them works.
Any ideas?

Parent container

```<code>#vote-buttons-section .iconic-button#upvote {
  background: #7f7f7f !important;
  width: 75px;
  height: 55px; }
#vote-buttons-section .iconic-button#downvote {
  background: #7f7f7f;
  height: 55px;
  width: 75px; }
</code>```

Font-awesome icons appear on the BEFORE attribute

```<code>.ui-button.iconic-button.iconic-button-upvote:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-hover:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-focus:before {
  font-family: FontAwesome;
  content: "\f087";
  font-size: 55px;
  color: white;
  vertical-align: middle;
  line-height: 55px;
  }

.ui-button.iconic-button.iconic-button-downvote:before,
.ui-button.iconic-button.iconic-button-downvote.ui-state-hover:before,
.ui-button.iconic-button.iconic-button-downvote.ui-state-focus:before {
  font-family: FontAwesome;
  content: "\f088";
  font-size: 64px;
  color: white;
  vertical-align: middle; }
</code>```

答:
What I would do, is to add the height: inherit; and some padding like this:

```<code>#vote-buttons-section .iconic-button#upvote {
   height: inherit;
   padding: 10px 10px;
}
</code>```

If it doesn't work, add the !important to the CSS properties, like this:

```<code>#vote-buttons-section .iconic-button#upvote {
   height: inherit !important;
   padding: 10px 10px !important;
}
</code>```

Hope this helps.

EDIT: I didn't see that you solved the problem by a user that gave the answer before me. I'm glad that you fixed your issue with user Gustaf Gunér.

Body:
As you can see the thumbs are over its parent area.
The UI layout is not acceptable.

The following is the expected result.
I tried to put margin-bottom with a negative number,
Or tried to make them in FLEX layout.
None of them works.
Any ideas?

Parent container

#vote-buttons-section .iconic-button#upvote {
  background: #7f7f7f !important;
  width: 75px;
  height: 55px; }
#vote-buttons-section .iconic-button#downvote {
  background: #7f7f7f;
  height: 55px;
  width: 75px; }

Font-awesome icons appear on the BEFORE attribute

.ui-button.iconic-button.iconic-button-upvote:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-hover:before,
.ui-button.iconic-button.iconic-button-upvote.ui-state-focus:before {
  font-family: FontAwesome;
  content: "\f087";
  font-size: 55px;
  color: white;
  vertical-align: middle;
  line-height: 55px;
  }

.ui-button.iconic-button.iconic-button-downvote:before,
.ui-button.iconic-button.iconic-button-downvote.ui-state-hover:before,
.ui-button.iconic-button.iconic-button-downvote.ui-state-focus:before {
  font-family: FontAwesome;
  content: "\f088";
  font-size: 64px;
  color: white;
  vertical-align: middle; }

Body:
What I would do, is to add the height: inherit; and some padding like this:

#vote-buttons-section .iconic-button#upvote {
   height: inherit;
   padding: 10px 10px;
}

If it doesn't work, add the !important to the CSS properties, like this:

#vote-buttons-section .iconic-button#upvote {
   height: inherit !important;
   padding: 10px 10px !important;
}

Hope this helps.

EDIT: I didn't see that you solved the problem by a user that gave the answer before me. I'm glad that you fixed your issue with user Gustaf Gunér.


问:
How to set a time limit for a Kubernetes job?
I'd like to launch a Kubernetes job and give it a fixed deadline to finish. If the pod is still running when the deadline comes, I'd like the job to automatically be killed.

Does something like this exist? (At first I thought that the Job spec's activeDeadlineSeconds covered this use case, but now I see that activeDeadlineSeconds only places a limit on when a job is re-tried; it doesn't actively kill a slow/runaway job.)

答:
You can self-impose timeouts on the container's entrypoint command by using GNU timeout utility.

For example the following Job that computes first 4000 digits of pi will time out after 10 seconds:

```<code>apiVersion: batch/v1
kind: Job
metadata:
  name: pi
spec:
  template:
    metadata:
      name: pi
    spec:
      containers:
      - name: pi
        image: perl
        command: ["/usr/bin/timeout", "10", "perl", "-Mbignum=bpi", "-wle", "print bpi(4000)"]
      restartPolicy: Never
</code>```

(Manifest adopted from https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#running-an-example-job)

You can play with the numbers and see it timeout or not. Typically computing 4000 digits of pi takes ~23 seconds on my workstation, so if you set it to 5 seconds it'll probably always fail and if you set it to 120 seconds it will always work.

Body:
You can self-impose timeouts on the container's entrypoint command by using GNU timeout utility.

For example the following Job that computes first 4000 digits of pi will time out after 10 seconds:

apiVersion: batch/v1
kind: Job
metadata:
  name: pi
spec:
  template:
    metadata:
      name: pi
    spec:
      containers:
      - name: pi
        image: perl
        command: ["/usr/bin/timeout", "10", "perl", "-Mbignum=bpi", "-wle", "print bpi(4000)"]
      restartPolicy: Never

(Manifest adopted from https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#running-an-example-job)

You can play with the numbers and see it timeout or not. Typically computing 4000 digits of pi takes ~23 seconds on my workstation, so if you set it to 5 seconds it'll probably always fail and if you set it to 120 seconds it will always work.


问:
Fetch with headers
When use fetch for request in server using headers return

```<code>SyntaxError: Unexpected end of input
    at index.js:50
    at <anonymous>
</code>```

Line of code 50 is }).then(res => res.json())

What can be wrong?

This code fetch.

```<code>fetch(api-url, {
          mode: 'no-cors',
          method: "POST",
          headers: {
              'Accept': 'application/json',
                        'Content-Type': ' application/json',
                        'X-API-SERVER': '85499f9f'
                    },
        }).then(res => res.json())
          .then(res => {
            if (res.status === 200){
              console.log("accepted");
            }else {
              console.log(res.error);
            }

             console.log(res.error)
          }).catch(err => console.log(err))
</code>```

答: Since you're requesting an API, you don't want to disable CORS. It's probably enough to just remove mode: 'no-cors' in your fetch request to fix this, as long as your API server sends the correct headers as well (Access-Control-Allow-Origin).

Title: Fetch with headers

Body:
When use fetch for request in server using headers return

SyntaxError: Unexpected end of input
    at index.js:50
    at <anonymous>

Line of code 50 is }).then(res => res.json())

What can be wrong?

This code fetch.

fetch(api-url, {
          mode: 'no-cors',
          method: "POST",
          headers: {
              'Accept': 'application/json',
                        'Content-Type': ' application/json',
                        'X-API-SERVER': '85499f9f'
                    },
        }).then(res => res.json())
          .then(res => {
            if (res.status === 200){
              console.log("accepted");
            }else {
              console.log(res.error);
            }

             console.log(res.error)
          }).catch(err => console.log(err))


问:
Send mail when Outlook is not already open
My situation:

I'm trying to send e-mails while Outlook is not open. This code will work if Outlook is running. If Outlook is closed the code will create a non-visible process that you can see running in Task Manager.

The code encounters an error during the .Send. It returns runtime error 287.

From my experience that are certain VBA methods that will only work when the object is either visible or active.

My work around is to use .Display(False) before calling .Send.

After calling .Send it immediately terminates the Outlook process. (Please point me to the right direction why.) Then the e-mail gets stuck in the Outbox.

I have to apply another work around by calling another CreateObject("Outlook.Application") and either looping through the Outbox While Outbox.Items.Count > 0

or

Looping through SyncObjects and manually calling .Start to run Send/Receive on the Outbox.

My question:

Is there a way to directly use the .Send method instead of using work arounds while also not having to open Outlook.

My code:

```<code>Sub emailer()

Dim OutApp As Object
Dim OutMail As Object

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

With OutMail
    .to = "f@r.com"
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .Body = "Hi there"
    .Send   'or use .Display
End With

Set OutMail = Nothing
Set OutApp = Nothing

End Sub
</code>```

答:
Use Namespace.SendAndReceive. Keep in mind that Send/Receive is asynchronous and you need to wait to the sync to finish. You can use Namespace.SyncObjects collection, start a sync using SyncObject.Start, then wait for the SyncObject.SyncEnd event.

To prevent Outlook from closing, you need to keep a live reference to an Outlook Explorer or Inspector object. You can retrieve the Inbox folder using Namespace.GetDefaultFolder, then use MAPIFolder.GetExplorer method to get a pointer to an Explorer object.

UPDATE:

You might also want to make sure that you log to a MAPI profile before you create and send a message. After the CreateObject line, try to add the following

```<code>set NS = OutApp.GetNamespace("MAPI")
NS.Logon
</code>```

Body:
My situation:

I'm trying to send e-mails while Outlook is not open. This code will work if Outlook is running. If Outlook is closed the code will create a non-visible process that you can see running in Task Manager.

The code encounters an error during the .Send. It returns runtime error 287.

From my experience that are certain VBA methods that will only work when the object is either visible or active.

My work around is to use .Display(False) before calling .Send.

After calling .Send it immediately terminates the Outlook process. (Please point me to the right direction why.) Then the e-mail gets stuck in the Outbox.

I have to apply another work around by calling another CreateObject("Outlook.Application") and either looping through the Outbox While Outbox.Items.Count > 0

or

Looping through SyncObjects and manually calling .Start to run Send/Receive on the Outbox.

My question:

Is there a way to directly use the .Send method instead of using work arounds while also not having to open Outlook.

My code:

Sub emailer()

Dim OutApp As Object
Dim OutMail As Object

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

With OutMail
    .to = "f@r.com"
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .Body = "Hi there"
    .Send   'or use .Display
End With

Set OutMail = Nothing
Set OutApp = Nothing

End Sub

Body:
Use Namespace.SendAndReceive. Keep in mind that Send/Receive is asynchronous and you need to wait to the sync to finish. You can use Namespace.SyncObjects collection, start a sync using SyncObject.Start, then wait for the SyncObject.SyncEnd event.

To prevent Outlook from closing, you need to keep a live reference to an Outlook Explorer or Inspector object. You can retrieve the Inbox folder using Namespace.GetDefaultFolder, then use MAPIFolder.GetExplorer method to get a pointer to an Explorer object.

UPDATE:

You might also want to make sure that you log to a MAPI profile before you create and send a message. After the CreateObject line, try to add the following

set NS = OutApp.GetNamespace("MAPI")
NS.Logon

ContentLicense: CC BY-SA 4.0


问:
How to center an image within a col element
having issues making an image centre
css on same .php file as the code

答:
You need to give the parent element of the image the margin auto. Not the image itself. </p>

```<code>div.item {
    height: 300px;
    width: 300px;
    margin: 0 auto;
    text-align: center;
}
.item img {
    width: 100%;
}
</code>```

Body:
You need to give the parent element of the image the margin auto. Not the image itself.

div.item {
    height: 300px;
    width: 300px;
    margin: 0 auto;
    text-align: center;
}
.item img {
    width: 100%;
}


问:
Writing stream of inputted Byte Arrays to file over several minutes (C#)
I'm creating a GUI tool that extracts data from a microprocessor via Serial.  I want to save the byte arrays that I am extracting into a .dat file in chunks as they are extracted.  I tried using a filestream, but the process takes several minutes so the GUI freezes while the filestream is open.

How can I save to a filestream multiple times over a long period without freezing the GUI?

Should I just store the extracted byte arrays and then write to the file after?  I was going to do this but it would require a byte array with over 8 million elements so I thought it wasn't the best idea.

答: if you want to have a file open and throw blocks of data at it one easy way is to use BlockingCollection. You have a thread waiting on the collection that pick the blocks and writes them and in your data gathering thread post the data blocks to the collection</p>


问:
Swift, CLLocationManagerDelegate in NSObject not working
i have problem with getting my location with CLLocationDelegate.
i created new subclass of UIView and work well, but when i created subclass of NSObject, CLLocationDelegate not called. I can find where is problem.
here is my code:

```<code>import UIKit
import CoreLocation

class LocationData: NSObject, CLLocationManagerDelegate {

var locationManager : CLLocationManager = CLLocationManager()

override init() {
    super.init()
    if self.locationManager.respondsToSelector(Selector("requestAlwaysAuthorization")) {
        self.locationManager.requestWhenInUseAuthorization()
    }
    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.distanceFilter = 50
    self.locationManager.startUpdatingLocation()
    println("init LocationData")
}

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println(error.description)
    }

    func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
    println("updated")
    }
}
</code>```

Thanks!

答:
Your code is fine! But when instantiating the class, you need to do like this:

```<code> import UIKit

 class ViewController: UIViewController {

 let LocationData: LocationData = LocationData()  //<- here is the secret to works!!!

 override func viewDidLoad() {
      super.viewDidLoad()
}
</code>```

I also suggest that you change your init to something like this:

```<code>override init() {
    super.init()

    let authorizationStatus: CLAuthorizationStatus = CLLocationManager.authorizationStatus()

    if authorizationStatus == .notDetermined {
        locationManager.requestWhenInUseAuthorization()
    }

    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.distanceFilter = 50
    self.locationManager.startUpdatingLocation()
    print("init LocationData")
}
</code>```

And don't forget to add NSLocationWhenInUseUsageDescription in the info.plist project.

Body:
i have problem with getting my location with CLLocationDelegate.
i created new subclass of UIView and work well, but when i created subclass of NSObject, CLLocationDelegate not called. I can find where is problem.
here is my code:

import UIKit
import CoreLocation

class LocationData: NSObject, CLLocationManagerDelegate {

var locationManager : CLLocationManager = CLLocationManager()

override init() {
    super.init()
    if self.locationManager.respondsToSelector(Selector("requestAlwaysAuthorization")) {
        self.locationManager.requestWhenInUseAuthorization()
    }
    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.distanceFilter = 50
    self.locationManager.startUpdatingLocation()
    println("init LocationData")
}

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println(error.description)
    }

    func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
    println("updated")
    }
}

Thanks!

Body:
Your code is fine! But when instantiating the class, you need to do like this:

 import UIKit

 class ViewController: UIViewController {

 let LocationData: LocationData = LocationData()  //<- here is the secret to works!!!

 override func viewDidLoad() {
      super.viewDidLoad()
}

I also suggest that you change your init to something like this:

override init() {
    super.init()

    let authorizationStatus: CLAuthorizationStatus = CLLocationManager.authorizationStatus()

    if authorizationStatus == .notDetermined {
        locationManager.requestWhenInUseAuthorization()
    }

    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.distanceFilter = 50
    self.locationManager.startUpdatingLocation()
    print("init LocationData")
}

And don't forget to add NSLocationWhenInUseUsageDescription in the info.plist project.


问:
Slow prediction: Scikit Gaussian Process classification
Following is the code to evaluate to train a Gaussian Process (GP) and use to classify the images from MNIST dataset.

```<code>import numpy as np

from sklearn.metrics.classification import accuracy_score, log_loss
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn import datasets
from sklearn.datasets import fetch_mldata

import random

SAMPLE_SIZE = 2000

def build_and_optimize(hp_space):
    build_train()
    return

def build_train(hp_space):
    l_scale = hp_space['l_scale']
    bias = hp_space['bias']
    gp_fix = GaussianProcessClassifier(kernel=bias * RBF(length_scale=l_scale), optimizer=None, multi_class='one_vs_rest')

    X_train, X_test, y_train, y_test = prepare_data()

    gp_fix.fit(X_train, y_train)

    print("Log Marginal Likelihood (initial): %.3f"
        % gp_fix.log_marginal_likelihood(gp_fix.kernel_.theta))

    y_ = gp_fix.predict(X_test[0:500])
    print(y_)
    print(y_test[0:500])
    print("Accuracy: %.3f (initial)"
        % (accuracy_score(y_test[0:500], y_)))

    return

def prepare_data():
    mnist = fetch_mldata('MNIST original', data_home='./')
    mnist.keys()

    images = mnist.data
    targets = mnist.target

    X_data = images/255.0
    Y = targets
   shuf = random.sample(range(len(X_data)), SAMPLE_SIZE)

    X_train = []
    for x in shuf: X_train.append(X_data[x])

    y_train = []
    for x in shuf: y_train.append(Y[x])

    c_shuf = set(range(len(X_data))) - set(shuf)

    X_test = []
    for x in c_shuf: X_test.append(X_data[x])

    y_test = []
    for x in c_shuf: y_test.append(Y[x])

    return X_train, X_test, y_train, y_test

if __name__ == "__main__":
    hp_space = {}
    hp_space['l_scale'] = 1.0
    hp_space['bias'] = 1.0

    build_train(hp_space)
</code>```

It seems the training of the model takes decent amount of time. However, the prediction takes ages. Any pointers as what could be the reason?

答:
You can think of Gaussian processes and SVMs are somewhat similar models, both do use the kernel trick to build a model. Lik SVMs, GPs take O(n^3) time to train, where n is the number of data points in the training set. Thus you should naturally expect it to take a while to train, and for it to grow quickly as you increase the dataset size.

Similarly, the GP prediction takes O(n) time per prediction, similar to a nearest neighbor search and SVMS. However, the GP solution is dense, meaning it uses all the training points for prediction - where the SVM is sparse, so it gets to throw some away.

Body:
Following is the code to evaluate to train a Gaussian Process (GP) and use to classify the images from MNIST dataset.

import numpy as np

from sklearn.metrics.classification import accuracy_score, log_loss
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn import datasets
from sklearn.datasets import fetch_mldata

import random

SAMPLE_SIZE = 2000

def build_and_optimize(hp_space):
    build_train()
    return

def build_train(hp_space):
    l_scale = hp_space['l_scale']
    bias = hp_space['bias']
    gp_fix = GaussianProcessClassifier(kernel=bias * RBF(length_scale=l_scale), optimizer=None, multi_class='one_vs_rest')

    X_train, X_test, y_train, y_test = prepare_data()

    gp_fix.fit(X_train, y_train)

    print("Log Marginal Likelihood (initial): %.3f"
        % gp_fix.log_marginal_likelihood(gp_fix.kernel_.theta))

    y_ = gp_fix.predict(X_test[0:500])
    print(y_)
    print(y_test[0:500])
    print("Accuracy: %.3f (initial)"
        % (accuracy_score(y_test[0:500], y_)))

    return

def prepare_data():
    mnist = fetch_mldata('MNIST original', data_home='./')
    mnist.keys()

    images = mnist.data
    targets = mnist.target

    X_data = images/255.0
    Y = targets
   shuf = random.sample(range(len(X_data)), SAMPLE_SIZE)

    X_train = []
    for x in shuf: X_train.append(X_data[x])

    y_train = []
    for x in shuf: y_train.append(Y[x])

    c_shuf = set(range(len(X_data))) - set(shuf)

    X_test = []
    for x in c_shuf: X_test.append(X_data[x])

    y_test = []
    for x in c_shuf: y_test.append(Y[x])

    return X_train, X_test, y_train, y_test

if __name__ == "__main__":
    hp_space = {}
    hp_space['l_scale'] = 1.0
    hp_space['bias'] = 1.0

    build_train(hp_space)

It seems the training of the model takes decent amount of time. However, the prediction takes ages. Any pointers as what could be the reason?


问:
How to wrap a function with a varying number of default arguments to have only one argument?
I have a template function, let's call it the "client":

```<code>template<typename T>
void client(T (*func)(const std::string&), const std::string& s) {}
</code>```

Then there are a number of "adaptee" functions that all have an identical type of the first, non-default argument, but the following arguments vary in number and have default values:

```<code>void adaptee_one(const std::string&, int i = 1, char* c = nullptr) {}
void adaptee_two(const std::string&, float* f = nullptr) {}
</code>```

The above functions are a given. Now what I want to do is to pass them to the above client<>() function as the first parameter, and I only care about passing the first argument, const std::string&. So I do the following:

```<code>void bindAdapteeOne(const std::string& s) {
    return adaptee_one(s);
}

void bindAdapteeTwo(const std::string& s) {
    return adaptee_two(s);
}
</code>```

And then pass bindAdapteeX() to client<>().

What I'd like to do is to automate the wrapping or have one (templated) wrapper instead of one per adaptee. I feel this might be the case for variadics, but have little idea about how to apply them exactly.

C++11 is fine, C++14 is fine if absolutely necessary.

答:
I'm thinking I would create a class that wraps your parameters and have the client accept an instance of that class.  That way,  you only have one parameter, which contains however many parameters you so desire.

That parameter wrapper would provide the default values as well, and allow you to refine them in derived classes for specific purposes.

This is probably a little more self-documenting as well when compared to lambdas.

And who knows, when its time to read and write the parameters from a file, then the wrapper class would be the perfect place to do it.

Body:
I have a template function, let's call it the "client":

template<typename T>
void client(T (*func)(const std::string&), const std::string& s) {}

Then there are a number of "adaptee" functions that all have an identical type of the first, non-default argument, but the following arguments vary in number and have default values:

void adaptee_one(const std::string&, int i = 1, char* c = nullptr) {}
void adaptee_two(const std::string&, float* f = nullptr) {}

The above functions are a given. Now what I want to do is to pass them to the above client<>() function as the first parameter, and I only care about passing the first argument, const std::string&. So I do the following:

void bindAdapteeOne(const std::string& s) {
    return adaptee_one(s);
}

void bindAdapteeTwo(const std::string& s) {
    return adaptee_two(s);
}

And then pass bindAdapteeX() to client<>().

What I'd like to do is to automate the wrapping or have one (templated) wrapper instead of one per adaptee. I feel this might be the case for variadics, but have little idea about how to apply them exactly.

C++11 is fine, C++14 is fine if absolutely necessary.


问:
How to update image src from static method in code behind?
I am trying to update Image src from code behind but the image doesn't get updated. I have a Default.aspx page with Image control added to it. The control is placed inside an update panel.

```<code><asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
    <div id="targetDiv" class="auto-style2" runat="server">
      <img id="testID" src="Images/Locations/PERRAN_SANDS.svg" runat="server" />
    </div>
  </ContentTemplate>
</asp:UpdatePanel>
</code>```

I have a static method in my code behind and I am trying to update the image src from it.

```<code>protected void Page_Load(object sender, EventArgs e)
{
  Session["ImageControl"] = Page.FindControl("testID");
}

[WebMethod]
public static void GetLocationNames()
{
     String siteName = Database.GetsiteNameforTopPlayer();
    UpdateImage(siteName);
}

public static string UpdateImage(string imgName)
{
  string filename = imgName+ ".svg";
  string path = @"Images/Locations/" + filename;

  System.Web.UI.HtmlControls.HtmlImage imgControl = new System.Web.UI.HtmlControls.HtmlImage();
  imgControl = System.Web.HttpContext.Current.Session["ImageControl"] as System.Web.UI.HtmlControls.HtmlImage;
  imgControl.Src = path;
  imgControl.DataBind();
}
</code>```

GetLocationNames() is called from a jquery function. I have breakpoints set in my Code and the value of Src gets updated but the change is not reflected on the webpage

答:
even can do in the page_Load event , by using </p>

```<code> string filename = imgName+ ".svg";
  string path = @"Images/Locations/" + filename;
testID.Src=path;
</code>```

Body:
I am trying to update Image src from code behind but the image doesn't get updated. I have a Default.aspx page with Image control added to it. The control is placed inside an update panel.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>

  </ContentTemplate>
</asp:UpdatePanel>

I have a static method in my code behind and I am trying to update the image src from it.

protected void Page_Load(object sender, EventArgs e)
{
  Session["ImageControl"] = Page.FindControl("testID");
}

[WebMethod]
public static void GetLocationNames()
{
     String siteName = Database.GetsiteNameforTopPlayer();
    UpdateImage(siteName);
}

public static string UpdateImage(string imgName)
{
  string filename = imgName+ ".svg";
  string path = @"Images/Locations/" + filename;

  System.Web.UI.HtmlControls.HtmlImage imgControl = new System.Web.UI.HtmlControls.HtmlImage();
  imgControl = System.Web.HttpContext.Current.Session["ImageControl"] as System.Web.UI.HtmlControls.HtmlImage;
  imgControl.Src = path;
  imgControl.DataBind();
}

GetLocationNames() is called from a jquery function. I have breakpoints set in my Code and the value of Src gets updated but the change is not reflected on the webpage

Body:
even can do in the page_Load event , by using

 string filename = imgName+ ".svg";
  string path = @"Images/Locations/" + filename;
testID.Src=path;


问:
React Native - Display datas from async AsyncStorage.getItems
Basically, on my app people have to validate when they succeed on a challenge.
When they click on the validation button, I save the "key":"value" of the challenge with the function :

```<code>async function validate(challenge_nb)
{
 try {
   await AsyncStorage.setItem(challenge_nb, 'OK');
 } catch (error) {
   console.log("error")
 }
}
</code>```

It works fine.

Now, I would like to get back that data and display it in a list... And I've no idea about how to do that.

I was trying to use that kind of function to get all key/value that I saved :

```<code>async function getalldatas()
{
AsyncStorage.getAllKeys((err, keys) => {
AsyncStorage.multiGet(keys, (err, stores) => {
 stores.map((result, i, store) => {
   // get at each store's key/value so you can work with it
   let key = store[i][0];
   let value = store[i][1];
   console.log(value);
  });
});
</code>```

});
}

But I don't know how to display that in my render() function... Moreover cause it's async

Actually, I would like to do a kind of :

render (
   For each key/value :
     key : value
   end_foreach
)

Thanks a lot !!

答:
You can store it to a state value then have a conditional render, p.s. never put stuff like this in your render, make it a method of your component:</p>

```<code>getAllDatas = () => {
  AsyncStorage.getAllKeys((err, keys) => {
    AsyncStorage.multiGet(keys, (err, stores) => {
      this.setState({ stores });
    });
  });
}

render() {
  return (
    <View>
      {this.state.stores.length && this.state.stores.map(item =>
        <Text>{`${item[0]}: ${item[1}`}</Text>)}
    </View>
  )
}
</code>```

Body:
Basically, on my app people have to validate when they succeed on a challenge.
When they click on the validation button, I save the "key":"value" of the challenge with the function :

async function validate(challenge_nb)
{
 try {
   await AsyncStorage.setItem(challenge_nb, 'OK');
 } catch (error) {
   console.log("error")
 }
}

It works fine.

Now, I would like to get back that data and display it in a list... And I've no idea about how to do that.

I was trying to use that kind of function to get all key/value that I saved :

async function getalldatas()
{
AsyncStorage.getAllKeys((err, keys) => {
AsyncStorage.multiGet(keys, (err, stores) => {
 stores.map((result, i, store) => {
   // get at each store's key/value so you can work with it
   let key = store[i][0];
   let value = store[i][1];
   console.log(value);
  });
});

});
}

But I don't know how to display that in my render() function... Moreover cause it's async

Actually, I would like to do a kind of :

render (
   For each key/value :
     key : value
   end_foreach
)

Thanks a lot !!

Body:
You can store it to a state value then have a conditional render, p.s. never put stuff like this in your render, make it a method of your component:

getAllDatas = () => {
  AsyncStorage.getAllKeys((err, keys) => {
    AsyncStorage.multiGet(keys, (err, stores) => {
      this.setState({ stores });
    });
  });
}

render() {
  return (
    <View>
      {this.state.stores.length && this.state.stores.map(item =>
        <Text>{`${item[0]}: ${item[1}`}</Text>)}
    </View>
  )
}


问:
Using threads with Observer Pattern
I have this code:

```<code>public class classExample implements Observer Runnable {

    public classExample() {
    //...
    }

    @Override
    public void run() {
        while (true) {
           //wait for EVENT;
           //do something;
        }
    }

    @Override
    public void update(Observable arg0, Object arg1) {
    //signal EVENT;
    }

}
</code>```

Basically, i want my thread to do something every time the update() method is called. I can't do in the update() method itself cause it would be executed in the same thread of the Observable calling notifyObservers().
Are there any ways to "signal" an event to the run() method?

答:
While the blocking queue as suggested by others would work, I'm not a big fan of it because it requires a busy wait (the consumer loops infinitely polling for a message). An alternative would be to submit a task every time the Observer receives a notification.

```<code>public class Main extends Observable implements Observer {
    private final int numCores = Runtime.getRuntime().availableProcessors();
    private final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numCores);

    public Main() {
        addObserver(this);
    }

    public static void main(String[] args) throws InterruptedException {
        new Main().execute();
    }

    private void execute() {
        for (int i = 0; i < 5; ++i) {
            this.setChanged();
            this.notifyObservers(i);

            try {
                Thread.sleep(1000l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        executor.shutdown();
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.printf("Received notification on thread: %s.\n", Thread.currentThread().getName());
        executor.submit(() -> System.out.printf("Running in thread: %s, result: %s.\n",
                Thread.currentThread().getName(), arg));
    }
}
</code>```

Output:

```<code>Received notification on thread: main.
Running in thread: pool-1-thread-1, result: 0.
Received notification on thread: main.
Running in thread: pool-1-thread-2, result: 1.
Received notification on thread: main.
Running in thread: pool-1-thread-3, result: 2.
Received notification on thread: main.
Running in thread: pool-1-thread-4, result: 3.
Received notification on thread: main.
Running in thread: pool-1-thread-5, result: 4.
</code>```

Title: Using threads with Observer Pattern

Body:
I have this code:

public class classExample implements Observer Runnable {

    public classExample() {
    //...
    }

    @Override
    public void run() {
        while (true) {
           //wait for EVENT;
           //do something;
        }
    }

    @Override
    public void update(Observable arg0, Object arg1) {
    //signal EVENT;
    }

}

Basically, i want my thread to do something every time the update() method is called. I can't do in the update() method itself cause it would be executed in the same thread of the Observable calling notifyObservers().
Are there any ways to "signal" an event to the run() method?

Body:
While the blocking queue as suggested by others would work, I'm not a big fan of it because it requires a busy wait (the consumer loops infinitely polling for a message). An alternative would be to submit a task every time the Observer receives a notification.

public class Main extends Observable implements Observer {
    private final int numCores = Runtime.getRuntime().availableProcessors();
    private final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(numCores);

    public Main() {
        addObserver(this);
    }

    public static void main(String[] args) throws InterruptedException {
        new Main().execute();
    }

    private void execute() {
        for (int i = 0; i < 5; ++i) {
            this.setChanged();
            this.notifyObservers(i);

            try {
                Thread.sleep(1000l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        executor.shutdown();
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.printf("Received notification on thread: %s.\n", Thread.currentThread().getName());
        executor.submit(() -> System.out.printf("Running in thread: %s, result: %s.\n",
                Thread.currentThread().getName(), arg));
    }
}

Output:

Received notification on thread: main.
Running in thread: pool-1-thread-1, result: 0.
Received notification on thread: main.
Running in thread: pool-1-thread-2, result: 1.
Received notification on thread: main.
Running in thread: pool-1-thread-3, result: 2.
Received notification on thread: main.
Running in thread: pool-1-thread-4, result: 3.
Received notification on thread: main.
Running in thread: pool-1-thread-5, result: 4.


问:
react-test-renderer incorrect peer dependency
Doing a yarn upgrade today I am seeing the warning:

warning "react-test-renderer@15.6.1" has incorrect peer dependency "react@^15.6.1"

I've tried upgrading react-test-renderer, but that didn't change anything.

What do I need to do?

答:
react-test-renderer is supposed to work with react@^15.6.1 or higher, check your package.json to ensure you're React version is high enough.

Upgrading your react version to react@^15.6.1 will remove this warning.


问:
HTML5 acronym tag replacement using jQuery
Using jQuery, how would you replace every <acronym> tag with ?

答:
```<code>$("acronym").each(function(idx,HTML) {
  $(this).replaceWith('<abbr title="'+this.title+'">'+HTML+'</abbr>');
});
</code>```

ContentLicense: CC BY-SA 2.5


问:
Flex box Vertical Navigation Issue
So I recently started dabbing in Flexbox and I am trying to create a page that has a vertical navigation area on the side. My issue is that my content is appear UNDER the navigation area. Not to the side of it. I want to know how I can use Flex box to have my content appear next to the navigation like in this page:

http://cocoonstudio.ph/

Here is my page so far:

https://jorgeg1105.github.io/JG-Photography/

Thanks for your help!

body {
  margin: 0;
  padding: 0;
}

ul {
  list-style-type: none;
}

/*--------------Side Navigation Styles--------------------*/

#sidenav {
  background-color: black;
  color: white;
  width: 60px;
  height: 100%;
  text-align: center;
  position: fixed;
  border-right: 6px solid #766E6B;
  display: flex;
  flex-direction: column;
}

#sidenav ul {
  display: flex;
  flex-direction: column;
  padding: 0;
  margin: 0;
}

#sidenav li:nth-child(1) {
  margin-bottom: 120px;
}

#sidenav li:nth-child(6) {
  margin-top: 195px;
}

#sidenav a {
  display: block;
  padding: 20px;
}

#sidenav a:visited {
  color: white;
}

#sidenav a:hover {
  color: black;
  background-color: white;
}

/*-------------Header Styles-------------------------------*/

header {}

/*------------------Main Navigation-----------------------*/

#mainnav {}

/*--------------------Container Area------------------------*/

#container {}

/*-----------------------Footer Styles---------------------*/

footer {}

/*-------------------Flexbox-----------------------*/

.col {
  flex: 1;
}

.row {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav id="sidenav" class="row">
  <ul class>
    <li><i class="fa fa-home" aria-hidden="true"></i></li>
    <li><i class="fa fa-facebook" aria-hidden="true"></i></li>
    <li><i class="fa fa-twitter" aria-hidden="true"></i></li>
    <li><i class="fa fa-pinterest-p" aria-hidden="true"></i></li>
    <li><i class="fa fa-envelope" aria-hidden="true"></i></li>
    <li><i class="fa fa-arrow-up" aria-hidden="true"></i></li>
  </ul>
</nav>
<header>
  <div class="row">
    <div class="col">
      <ul>
        <li>
          <div>

              <p>Gallery</p>
              <span>Our Work</span>

          </div>
        </li>
        <li>
          <div>

              <p>About</p>
              <span>J&G Photography</span>

          </div>
        </li>
        <li>
          <div>

              <p>Questions</p>
              <span>Facts</span>

          </div>
        </li>
      </ul>
    </div>
    <div class="col">
      <h1>J&G Photography</h1>
      <h3><em>"Explore. Create. Inspire."</em></h3>
    </div>
    <div class="col">
      <ul>
        <li>
          <div>

              <p>Rates</p>
              <span>Your Investment</span>

          </div>
        </li>
        <li>
          <div>

              <p>Contact</p>
              <span>Get In Touch</span>

          </div>
        </li>
      </ul>
    </div>
  </div>
</header>

<!--Font Awesome-->
<script src="https://use.fontawesome.com/d579f311e9.js"></script></code>```

答:
I would make body the flex parent, remove the fixed positioning from the nav, then introduce a sibling to the navigation that will fill the rest of the page, set to flex-grow: 1 (or flex: 1 0 0 for short) and set overflow-y: scroll so the content area will scroll vertically.

I would also re-work the navigation a little. Set it to justify-content: center so the icons are centered in the middle of the nav, then use an auto margin value for the top/bottom links to push them to the edges of the nav. Also added a min-height to your #sidenav ul so that all of the icons are visible, and overflow-y: auto in case it overflows so you can scroll that menu on a super short screen.

body {
  margin: 0;
  padding: 0;
  display: flex;
  height: 100vh;
  overflow: hidden;
}

ul {
  list-style-type: none;
}

/*--------------Side Navigation Styles--------------------*/
#sidenav {
  background-color: black;
  color: white;
  width: 60px;
  text-align: center;
  border-right: 6px solid #766E6B;
  overflow-y: auto;
  height: 100%;
}

#sidenav ul {
  display: flex;
  flex-direction: column;
  padding: 0;
  margin: 0;
  justify-content: center;
  min-height: 400px;
}

#sidenav ul li:first-child {
  margin-bottom: auto;
}
#sidenav ul li:last-child {
  margin-top: auto;
}

#sidenav a {
  display: block;
  padding: 20px;
}

#sidenav a:visited {
  color: white;
}

#sidenav a:hover {
  color: black;
  background-color: white;
}

/*-------------Header Styles-------------------------------*/
header {
}

/*------------------Main Navigation-----------------------*/

#mainnav {
}

/*--------------------Container Area------------------------*/

#container {
  flex: 1 0 0;
  overflow-y: auto;
}

/*-----------------------Footer Styles---------------------*/

footer {
}

/*-------------------Flexbox-----------------------*/
.col {
  flex: 1;
}

.row {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>| J&G |</title>
  <link rel="stylesheet" type="text/css" href="Styles/styles.css">
</head>

<body>
  <nav id="sidenav" class="row">
    <ul class>
      <li><i class="fa fa-home" aria-hidden="true"></i></li>
      <li><i class="fa fa-facebook" aria-hidden="true"></i></li>
      <li><i class="fa fa-twitter" aria-hidden="true"></i></li>
      <li><i class="fa fa-pinterest-p" aria-hidden="true"></i></li>
      <li><i class="fa fa-envelope" aria-hidden="true"></i></li>
      <li><i class="fa fa-arrow-up" aria-hidden="true"></i></li>
    </ul>
  </nav>
  <div id="container">
    <header>
      <div class="row">
        <div class="col">
          <ul>
            <li>
              <div>

                  <p>Gallery</p>
                  <span>Our Work</span>

              </div>
            </li>
            <li>
              <div>

                  <p>About</p>
                  <span>J&G Photography</span>

              </div>
            </li>
            <li>
              <div>

                  <p>Questions</p>
                  <span>Facts</span>

              </div>
            </li>
          </ul>
        </div>
        <div class="col">
          <h1>J&G Photography</h1>
          <h3><em>"Explore. Create. Inspire."</em></h3>
        </div>
        <div class="col">
          <ul>
            <li>
              <div>

                  <p>Rates</p>
                  <span>Your Investment</span>

              </div>
            </li>
            <li>
              <div>

                  <p>Contact</p>
                  <span>Get In Touch</span>

              </div>
            </li>
          </ul>
        </div>
      </div>
    </header>
    <main>
      foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>
    </main>
  </div>

  <!--Font Awesome-->
  <script src="https://use.fontawesome.com/d579f311e9.js"></script>
</body>

</html></code>```

Title: Flex box Vertical Navigation Issue

Body:
So I recently started dabbing in Flexbox and I am trying to create a page that has a vertical navigation area on the side. My issue is that my content is appear UNDER the navigation area. Not to the side of it. I want to know how I can use Flex box to have my content appear next to the navigation like in this page:

http://cocoonstudio.ph/

Here is my page so far:

https://jorgeg1105.github.io/JG-Photography/

Thanks for your help!

body {
  margin: 0;
  padding: 0;
}

ul {
  list-style-type: none;
}

/*--------------Side Navigation Styles--------------------*/

#sidenav {
  background-color: black;
  color: white;
  width: 60px;
  height: 100%;
  text-align: center;
  position: fixed;
  border-right: 6px solid #766E6B;
  display: flex;
  flex-direction: column;
}

#sidenav ul {
  display: flex;
  flex-direction: column;
  padding: 0;
  margin: 0;
}

#sidenav li:nth-child(1) {
  margin-bottom: 120px;
}

#sidenav li:nth-child(6) {
  margin-top: 195px;
}

#sidenav a {
  display: block;
  padding: 20px;
}

#sidenav a:visited {
  color: white;
}

#sidenav a:hover {
  color: black;
  background-color: white;
}

/*-------------Header Styles-------------------------------*/

header {}

/*------------------Main Navigation-----------------------*/

#mainnav {}

/*--------------------Container Area------------------------*/

#container {}

/*-----------------------Footer Styles---------------------*/

footer {}

/*-------------------Flexbox-----------------------*/

.col {
  flex: 1;
}

.row {
  display: flex;
}

Gallery

              Our Work

About

              J&G Photography

Questions

              Facts

J&G Photography

"Explore. Create. Inspire."

Rates

              Your Investment

Contact

              Get In Touch

Body:
I would make body the flex parent, remove the fixed positioning from the nav, then introduce a sibling to the navigation that will fill the rest of the page, set to flex-grow: 1 (or flex: 1 0 0 for short) and set overflow-y: scroll so the content area will scroll vertically.

I would also re-work the navigation a little. Set it to justify-content: center so the icons are centered in the middle of the nav, then use an auto margin value for the top/bottom links to push them to the edges of the nav. Also added a min-height to your #sidenav ul so that all of the icons are visible, and overflow-y: auto in case it overflows so you can scroll that menu on a super short screen.

body {
  margin: 0;
  padding: 0;
  display: flex;
  height: 100vh;
  overflow: hidden;
}

ul {
  list-style-type: none;
}

/*--------------Side Navigation Styles--------------------*/
#sidenav {
  background-color: black;
  color: white;
  width: 60px;
  text-align: center;
  border-right: 6px solid #766E6B;
  overflow-y: auto;
  height: 100%;
}

#sidenav ul {
  display: flex;
  flex-direction: column;
  padding: 0;
  margin: 0;
  justify-content: center;
  min-height: 400px;
}

#sidenav ul li:first-child {
  margin-bottom: auto;
}
#sidenav ul li:last-child {
  margin-top: auto;
}

#sidenav a {
  display: block;
  padding: 20px;
}

#sidenav a:visited {
  color: white;
}

#sidenav a:hover {
  color: black;
  background-color: white;
}

/*-------------Header Styles-------------------------------*/
header {
}

/*------------------Main Navigation-----------------------*/

#mainnav {
}

/*--------------------Container Area------------------------*/

#container {
  flex: 1 0 0;
  overflow-y: auto;
}

/*-----------------------Footer Styles---------------------*/

footer {
}

/*-------------------Flexbox-----------------------*/
.col {
  flex: 1;
}

.row {
  display: flex;
}

<!DOCTYPE html>
<html>

<head>
  <title>| J&amp;G |</title>
  <link rel="stylesheet" type="text/css" href="Styles/styles.css">
</head>

<body>
  <nav id="sidenav" class="row">
    <ul class>
      <li><a href="index.html"><i class="fa fa-home" aria-hidden="true"></i></a></li>
      <li><a href="https://www.facebook.com" target="_blank"><i class="fa fa-facebook" aria-hidden="true"></i></a></li>
      <li><a href="https://twitter.com/" target="_blank"><i class="fa fa-twitter" aria-hidden="true"></i></a></li>
      <li><a href="https://www.pinterest.com/" target="_blank"><i class="fa fa-pinterest-p" aria-hidden="true"></i></a></li>
      <li><a href="#"><i class="fa fa-envelope" aria-hidden="true"></i></a></li>
      <li><a href="#"><i class="fa fa-arrow-up" aria-hidden="true"></i></a></li>
    </ul>
  </nav>
  <div id="container">
    <header>
      <div class="row">
        <div class="col">
          <ul>
            <li>
              <div>
                <a href="#">
                  <p>Gallery</p>
                  <span>Our Work</span>
                </a>
              </div>
            </li>
            <li>
              <div>
                <a href="#">
                  <p>About</p>
                  <span>J&amp;G Photography</span>
                </a>
              </div>
            </li>
            <li>
              <div>
                <a href="#">
                  <p>Questions</p>
                  <span>Facts</span>
                </a>
              </div>
            </li>
          </ul>
        </div>
        <div class="col">
          <h1>J&amp;G Photography</h1>
          <h3><em>"Explore. Create. Inspire."</em></h3>
        </div>
        <div class="col">
          <ul>
            <li>
              <div>
                <a href="#">
                  <p>Rates</p>
                  <span>Your Investment</span>
                </a>
              </div>
            </li>
            <li>
              <div>
                <a href="#">
                  <p>Contact</p>
                  <span>Get In Touch</span>
                </a>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </header>
    <main>
      foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>
    </main>
  </div>

  <!--Font Awesome-->
  <script src="https://use.fontawesome.com/d579f311e9.js"></script>
</body>

</html>


问:
How to create a link in React Data Grid?
I'm using this adazzle component: https://github.com/adazzle/react-data-grid

I am trying to figure out how to create a clickable link. They have an example of a cell formatter here: http://adazzle.github.io/react-data-grid/examples.html#/custom-formatters

However, the formatter only gets passed a single value. Since the formatter only gets one value passed to it, I have no way of creating a link in the format:

```<code>const formatter = ({ value }) => (
  <a href=`${value.id}`>{value.name}</a>
)
</code>```

The problem with the above code is value is not an object. It only passes down a single string, etc.

Does anyone using react-data-grid know how to solve this problem?

答:
here is how i was able to make it work to work... custom formatter specified and adding the getRowMetaData attribute to the column definition.  you could even add props to the data in the getRowMetaData value.</p>

```<code>const MyFormatter = React.createClass({
  render(){
    return(
      <a href={this.props.dependentValues.url}>{this.props.dependentValues.name}</a>
    );
  }
});

function MyFunctionalDataTable(props){
  const myCols = [
    {key: "link", name: "Link", width: 200, formatter: MyFormatter, getRowMetaData: (data)=>(data)},
    ...
   ];

  const createRowData = !props.mydata? '' :
    props.mydata.map(function(obj, index){
      ...
      return {"blah": obj.blah,
              "url": obj.url, //doesn't have to match a GUI column
              "name": obj.name, //doesn't have to match a GUI column
              "column2stuff": obj.blahblah,
      }
  });

  const rowGetter = rowNumber => createRowData[rowNumber];

  return (
    <ReactDataGrid
      columns={myCols}
      rowGetter={rowGetter}
      rowsCount={createRowData.length}
      headerRowHeight={35}
      rowHeight={35}
      minHeight={createRowData.length<15? (37+(35*createRowData.length)) : 500}
    />

  )
}
</code>```

Body:
I'm using this adazzle component: https://github.com/adazzle/react-data-grid

I am trying to figure out how to create a clickable link. They have an example of a cell formatter here: http://adazzle.github.io/react-data-grid/examples.html#/custom-formatters

However, the formatter only gets passed a single value. Since the formatter only gets one value passed to it, I have no way of creating a link in the format:

const formatter = ({ value }) => (
  <a href=`${value.id}`>{value.name}
)

The problem with the above code is value is not an object. It only passes down a single string, etc.

Does anyone using react-data-grid know how to solve this problem?

Body:
here is how i was able to make it work to work... custom formatter specified and adding the getRowMetaData attribute to the column definition.  you could even add props to the data in the getRowMetaData value.

const MyFormatter = React.createClass({
  render(){
    return(
      <a href={this.props.dependentValues.url}>{this.props.dependentValues.name}</a>
    );
  }
});

function MyFunctionalDataTable(props){
  const myCols = [
    {key: "link", name: "Link", width: 200, formatter: MyFormatter, getRowMetaData: (data)=>(data)},
    ...
   ];

  const createRowData = !props.mydata? '' :
    props.mydata.map(function(obj, index){
      ...
      return {"blah": obj.blah,
              "url": obj.url, //doesn't have to match a GUI column
              "name": obj.name, //doesn't have to match a GUI column
              "column2stuff": obj.blahblah,
      }
  });

  const rowGetter = rowNumber => createRowData[rowNumber];

  return (
    <ReactDataGrid
      columns={myCols}
      rowGetter={rowGetter}
      rowsCount={createRowData.length}
      headerRowHeight={35}
      rowHeight={35}
      minHeight={createRowData.length<15? (37+(35*createRowData.length)) : 500}
    />

  )
}


问:
prevent react-router from detecting location change
In my React/Redux based application, I have implemented logout like following

In reducers/index.js where I do combineReducers, I have created an app level reducer called appReducer. There I check for LOGOUT action and then return undefined.

All this works fine. What I want to do is, that for LOGOUT action, I also want to clear localStorage and redirect to login page. Please note that I want to redirect native browser way, not using react-router. If I do window.location = '/'. First its detected by react-router and I see login page for a bit and then it refreshes which is a bit odd.

Is there a way to prevent react-router from being notified on location change!?

答:
You cannot prevent it completely but you can control it with the access to
history.listen function.

With React-Router 4 you can wrap top level components using the HOC withRouter.

```<code>export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
</code>```

This allows accessing this.props.history and controlling it

```<code>  class App extends Component {
  constructor(props) {
    super(props);

    this.props.history.listen((location, action) => {
      //here you can control the location change
    });
  }

  render() {
     return (
         </div>
      );
  }
}
</code>```

And you also have the listenBefore event on the history object and you can use this event to control the navigation and add your own custom navigation logic:

```<code>history.listenBefore( (location, done) => doSomething(location).then(done) )
</code>```

Body:
You cannot prevent it completely but you can control it with the access to
history.listen function.

With React-Router 4 you can wrap top level components using the HOC withRouter.

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));

This allows accessing this.props.history and controlling it

  class App extends Component {
  constructor(props) {
    super(props);

    this.props.history.listen((location, action) => {
      //here you can control the location change
    });
  }

  render() {
     return (
         </div>
      );
  }
}

And you also have the listenBefore event on the history object and you can use this event to control the navigation and add your own custom navigation logic:

history.listenBefore( (location, done) => doSomething(location).then(done) )


问:
Access denied Drive App when trying to delete file
I wrote a little script to convert all the .xls and .xlsx files in my google drive to google sheets. However, the results of the script are very unreliable, sometimes I get an error, in some random part of the code, saying: "We're sorry, a server error occurred. Please wait a bit and try again.". And other times I get an error saying "Access denied Drive App" on the line where I try to delete my converted .xls or .xlsx files. I have enabled the Advance Google Services for the Drive API.

```<code>function convertFolder(folder){
  Logger.log('Folder name '+folder.getName());
  var files = folder.searchFiles('(title contains ".xlsx" or title contains ".xls") and (not title contains ".~lock")');
  while(files.hasNext()){
    var xFile = files.next();
    var name = xFile.getName().replace(/\.[^/.]+$/, "");
    Logger.log('File name '+name);
    if (name.indexOf(".~lock")!=-1)
      continue; //for some reason the "and (not title contains ".~lock")" didn't do the trick - why!?!
    var parents = xFile.getParents();
    var parents_arr = new Array();
    while (parents.hasNext()){
      parents_arr.push({'kind':"drive#fileLink",'id':parents.next().getId()});
    }

    var ID = xFile.getId();
    var xBlob = xFile.getBlob();
    var newFile = { title : name+'.gsheet',key : ID, parents: parents_arr, mimeType: "application/vnd.google-apps.spreadsheet"};
    file = Drive.Files.insert(newFile, xBlob, {convert: true});
    xFile.setTrashed(true);
  }
  var folders = folder.getFolders();
  while (folders.hasNext())
    convertFolder(folders.next());
}

function convertAllExcel(){
  var folders = DriveApp.getFoldersByName('Data');
  while (folders.hasNext()){
    var folder = folders.next();
    convertFolder(folder);
  }
  SpreadsheetApp.getUi().alert("done");
}
</code>```

答:
I suspect you're hitting a rate limit. If you are doing more than 20 write operations (create, update, delete) in rapid succession, you need to throttle the requests to approximately one every 1.5 seconds.

You're probably thinking "wtf", but that's seriously the maximum throughput you can achieve with Drive.

Body:
I wrote a little script to convert all the .xls and .xlsx files in my google drive to google sheets. However, the results of the script are very unreliable, sometimes I get an error, in some random part of the code, saying: "We're sorry, a server error occurred. Please wait a bit and try again.". And other times I get an error saying "Access denied Drive App" on the line where I try to delete my converted .xls or .xlsx files. I have enabled the Advance Google Services for the Drive API.

function convertFolder(folder){
  Logger.log('Folder name '+folder.getName());
  var files = folder.searchFiles('(title contains ".xlsx" or title contains ".xls") and (not title contains ".~lock")');
  while(files.hasNext()){
    var xFile = files.next();
    var name = xFile.getName().replace(/\.[^/.]+$/, "");
    Logger.log('File name '+name);
    if (name.indexOf(".~lock")!=-1)
      continue; //for some reason the "and (not title contains ".~lock")" didn't do the trick - why!?!
    var parents = xFile.getParents();
    var parents_arr = new Array();
    while (parents.hasNext()){
      parents_arr.push({'kind':"drive#fileLink",'id':parents.next().getId()});
    }

    var ID = xFile.getId();
    var xBlob = xFile.getBlob();
    var newFile = { title : name+'.gsheet',key : ID, parents: parents_arr, mimeType: "application/vnd.google-apps.spreadsheet"};
    file = Drive.Files.insert(newFile, xBlob, {convert: true});
    xFile.setTrashed(true);
  }
  var folders = folder.getFolders();
  while (folders.hasNext())
    convertFolder(folders.next());
}

function convertAllExcel(){
  var folders = DriveApp.getFoldersByName('Data');
  while (folders.hasNext()){
    var folder = folders.next();
    convertFolder(folder);
  }
  SpreadsheetApp.getUi().alert("done");
}


问:
Horizontal XOR in AVX
Is there a way to XOR horizontally an AVX register—specifically, to XOR the four 64-bit components of a 256-bit register?

The goal is to get the XOR of all 4 64-bit components of an AVX register. It would essentially be doing the same thing as a horizontal add (_mm256_hadd_epi32()), except that I want to XOR instead of ADD.

The scalar code is:

```<code>inline uint64_t HorizontalXor(__m256i t) {
  return t.m256i_u64[0] ^ t.m256i_u64[1] ^ t.m256i_u64[2] ^ t.m256i_u64[3];
}
</code>```

答:
Vectorization is likely to be useful if the input of the horizontal xor-function is already in
an AVX register, i.e. your t is the result of some SIMD computation.
Otherwise, scalar code is likely to be faster, as already mentioned by @Cody Gray.
Often you can do horizontal SIMD operations in about log_2(SIMD_width) 'steps'.
In this case one step is a 'shuffle/permute' and a 'xor'. This is slightly more efficient than @Cody Gray 's _mm256_hxor function:

```<code>__m256i _mm256_hxor_v2(__m256i x)
{
    __m256i x0 = _mm256_permute2x128_si256(x,x,1);       // swap the 128 bit high and low lane
    __m256i x1 = _mm256_xor_si256(x,x0);
    __m256i x2 = _mm256_shuffle_epi32(x1,0b01001110);    // swap 64 bit lanes
    __m256i x3 = _mm256_xor_si256(x1,x2);
    return x3;
}
</code>```

This compiles to:

```<code>vperm2i128  $1, %ymm0, %ymm0, %ymm1
vpxor   %ymm1, %ymm0, %ymm0
vpshufd $78, %ymm0, %ymm1
vpxor   %ymm1, %ymm0, %ymm0
</code>```

If you want the result in a scalar register:

```<code>uint64_t _mm256_hxor_v2_uint64(__m256i x)
{
    __m256i x0 = _mm256_permute2x128_si256(x,x,1);
    __m256i x1 = _mm256_xor_si256(x,x0);
    __m256i x2 = _mm256_shuffle_epi32(x1,0b01001110);
    __m256i x3 = _mm256_xor_si256(x1,x2);
    return _mm_cvtsi128_si64x(_mm256_castsi256_si128(x3)) ;
}
</code>```

Which compiles to:

```<code>vperm2i128  $1, %ymm0, %ymm0, %ymm1
vpxor   %ymm1, %ymm0, %ymm0
vpshufd $78, %ymm0, %ymm1
vpxor   %ymm1, %ymm0, %ymm0
vmovq   %xmm0, %rax
</code>```

Full test code:

```<code>#include <stdio.h>
#include <x86intrin.h>
#include <stdint.h>
/*  gcc -O3 -Wall -m64 -march=broadwell hor_xor.c   */
int print_vec_uint64(__m256i v);

__m256i _mm256_hxor_v2(__m256i x)
{
    __m256i x0 = _mm256_permute2x128_si256(x,x,1);
    __m256i x1 = _mm256_xor_si256(x,x0);
    __m256i x2 = _mm256_shuffle_epi32(x1,0b01001110);
    __m256i x3 = _mm256_xor_si256(x1,x2);
/* Uncomment the next few lines to print the values of the intermediate variables */
/*
    printf("3...0        =          3          2          1          0\n");
    printf("x            = ");print_vec_uint64(x        );
    printf("x0           = ");print_vec_uint64(x0        );
    printf("x1           = ");print_vec_uint64(x1        );
    printf("x2           = ");print_vec_uint64(x2        );
    printf("x3           = ");print_vec_uint64(x3        );
*/
    return x3;
}

uint64_t _mm256_hxor_v2_uint64(__m256i x)
{
    __m256i x0 = _mm256_permute2x128_si256(x,x,1);
    __m256i x1 = _mm256_xor_si256(x,x0);
    __m256i x2 = _mm256_shuffle_epi32(x1,0b01001110);
    __m256i x3 = _mm256_xor_si256(x1,x2);
    return _mm_cvtsi128_si64x(_mm256_castsi256_si128(x3)) ;
}

int main() {
    __m256i x = _mm256_set_epi64x(0x7, 0x5, 0x2, 0xB);
//    __m256i x = _mm256_set_epi64x(4235566778345231, 1123312566778345423, 72345566778345673, 967856775433457);

    printf("x            = ");print_vec_uint64(x);

    __m256i y = _mm256_hxor_v2(x);

    printf("y            = ");print_vec_uint64(y);

    uint64_t z = _mm256_hxor_v2_uint64(x);

    printf("z =  %10lX  \n",z);

    return 0;
}

int print_vec_uint64(__m256i v){
    uint64_t t[4];
    _mm256_storeu_si256((__m256i *)t,v);
    printf("%10lX %10lX %10lX %10lX \n",t[3],t[2],t[1],t[0]);
    return 0;
}
</code>```

Title: Horizontal XOR in AVX

Body:
Is there a way to XOR horizontally an AVX register—specifically, to XOR the four 64-bit components of a 256-bit register?

The goal is to get the XOR of all 4 64-bit components of an AVX register. It would essentially be doing the same thing as a horizontal add (_mm256_hadd_epi32()), except that I want to XOR instead of ADD.

The scalar code is:

inline uint64_t HorizontalXor(__m256i t) {
  return t.m256i_u64[0] ^ t.m256i_u64[1] ^ t.m256i_u64[2] ^ t.m256i_u64[3];
}

Body:
Vectorization is likely to be useful if the input of the horizontal xor-function is already in
an AVX register, i.e. your t is the result of some SIMD computation.
Otherwise, scalar code is likely to be faster, as already mentioned by @Cody Gray.
Often you can do horizontal SIMD operations in about log_2(SIMD_width) 'steps'.
In this case one step is a 'shuffle/permute' and a 'xor'. This is slightly more efficient than @Cody Gray 's _mm256_hxor function:

__m256i _mm256_hxor_v2(__m256i x)
{
    __m256i x0 = _mm256_permute2x128_si256(x,x,1);       // swap the 128 bit high and low lane
    __m256i x1 = _mm256_xor_si256(x,x0);
    __m256i x2 = _mm256_shuffle_epi32(x1,0b01001110);    // swap 64 bit lanes
    __m256i x3 = _mm256_xor_si256(x1,x2);
    return x3;
}

This compiles to:

vperm2i128  $1, %ymm0, %ymm0, %ymm1
vpxor   %ymm1, %ymm0, %ymm0
vpshufd $78, %ymm0, %ymm1
vpxor   %ymm1, %ymm0, %ymm0

If you want the result in a scalar register:

uint64_t _mm256_hxor_v2_uint64(__m256i x)
{
    __m256i x0 = _mm256_permute2x128_si256(x,x,1);
    __m256i x1 = _mm256_xor_si256(x,x0);
    __m256i x2 = _mm256_shuffle_epi32(x1,0b01001110);
    __m256i x3 = _mm256_xor_si256(x1,x2);
    return _mm_cvtsi128_si64x(_mm256_castsi256_si128(x3)) ;
}

Which compiles to:

vperm2i128  $1, %ymm0, %ymm0, %ymm1
vpxor   %ymm1, %ymm0, %ymm0
vpshufd $78, %ymm0, %ymm1
vpxor   %ymm1, %ymm0, %ymm0
vmovq   %xmm0, %rax

Full test code:

#include <stdio.h>
#include <x86intrin.h>
#include <stdint.h>
/*  gcc -O3 -Wall -m64 -march=broadwell hor_xor.c   */
int print_vec_uint64(__m256i v);

__m256i _mm256_hxor_v2(__m256i x)
{
    __m256i x0 = _mm256_permute2x128_si256(x,x,1);
    __m256i x1 = _mm256_xor_si256(x,x0);
    __m256i x2 = _mm256_shuffle_epi32(x1,0b01001110);
    __m256i x3 = _mm256_xor_si256(x1,x2);
/* Uncomment the next few lines to print the values of the intermediate variables */
/*
    printf("3...0        =          3          2          1          0\n");
    printf("x            = ");print_vec_uint64(x        );
    printf("x0           = ");print_vec_uint64(x0        );
    printf("x1           = ");print_vec_uint64(x1        );
    printf("x2           = ");print_vec_uint64(x2        );
    printf("x3           = ");print_vec_uint64(x3        );
*/
    return x3;
}

uint64_t _mm256_hxor_v2_uint64(__m256i x)
{
    __m256i x0 = _mm256_permute2x128_si256(x,x,1);
    __m256i x1 = _mm256_xor_si256(x,x0);
    __m256i x2 = _mm256_shuffle_epi32(x1,0b01001110);
    __m256i x3 = _mm256_xor_si256(x1,x2);
    return _mm_cvtsi128_si64x(_mm256_castsi256_si128(x3)) ;
}

int main() {
    __m256i x = _mm256_set_epi64x(0x7, 0x5, 0x2, 0xB);
//    __m256i x = _mm256_set_epi64x(4235566778345231, 1123312566778345423, 72345566778345673, 967856775433457);

    printf("x            = ");print_vec_uint64(x);

    __m256i y = _mm256_hxor_v2(x);

    printf("y            = ");print_vec_uint64(y);

    uint64_t z = _mm256_hxor_v2_uint64(x);

    printf("z =  %10lX  \n",z);

    return 0;
}

int print_vec_uint64(__m256i v){
    uint64_t t[4];
    _mm256_storeu_si256((__m256i *)t,v);
    printf("%10lX %10lX %10lX %10lX \n",t[3],t[2],t[1],t[0]);
    return 0;
}


问:
unable to get powershell to check through folders to find file amended in last hour
pulling my hair out over this line.
the only thing I can think of is it is a formatting problem.

foreach ($file in (Get-ChildItem $CompanyDir)) {

Check if the files have been modified in the past hour

```<code>if ($file.LastWriteTime -ge [datetime]::Now.AddMinutes(-60))
</code>```

this seems to have a mind of its own
some times it works other times it doesn't
every time I try I get a different result
basically it searches through the folder and if there is a file amended in last hour it will zip the whole folder.
it seems to be zipping now even though there is no file amended in the past hour
earlier today it wasn't zipping but if I moved the minutes to something ridiculous like 6000 it would zip
I know this is correct because when I put it into a variable and output it, it is the time an hour before
($file.LastWriteTime -ge [datetime]::Now.AddMinutes(-60))

it wasn't working at all before. I moved the folder structure to another drive and it started working. No idea why this would be the case as the folders should have the same attributes regardless of their location.
I could be way off on this  but I'm out of ideas right now so any input would be of great help.

Thanks

答:
it's kinda hard to tell what's going on from the little bits you've posted here, but...
You could be more explicit about what each $file is, you might be getting things you're not interested in.

Do you mean for it to recurse through subs?
Do you want to examine every manner of file, or just the "real" files?

Get-ChildItem [[-Filter] ] [-Attributes
     {ReadOnly | Hidden | System |
    Directory | Archive | Device | Normal | Temporary | SparseFile | ReparsePoint | Compressed | Offline |
    NotContentIndexed | Encrypted | IntegrityStream | NoScrubData}]

Body:
pulling my hair out over this line.
the only thing I can think of is it is a formatting problem.

foreach ($file in (Get-ChildItem $CompanyDir)) {

Check if the files have been modified in the past hour

if ($file.LastWriteTime -ge [datetime]::Now.AddMinutes(-60))

this seems to have a mind of its own
some times it works other times it doesn't
every time I try I get a different result
basically it searches through the folder and if there is a file amended in last hour it will zip the whole folder.
it seems to be zipping now even though there is no file amended in the past hour
earlier today it wasn't zipping but if I moved the minutes to something ridiculous like 6000 it would zip
I know this is correct because when I put it into a variable and output it, it is the time an hour before
($file.LastWriteTime -ge [datetime]::Now.AddMinutes(-60))

it wasn't working at all before. I moved the folder structure to another drive and it started working. No idea why this would be the case as the folders should have the same attributes regardless of their location.
I could be way off on this  but I'm out of ideas right now so any input would be of great help.

Thanks


问:
How to touch a file and mkdir if needed in one line
I need to touch a file with an absolute file name such as: /opt/test/test.txt, but I'm not sure if there is /opt/test existed on the system. So the code should similar with this:

```<code>if (-d '/opt/test') {
    touch '/opt/test/test.txt';
} else {
    mkdir -p '/opt/test';
    touch '/opt/test/test.txt'
}
</code>```

Is there any better way to simplify the code? I hope there is some system commands that can do the same job with only one line.

答:
I defined a touchp in my ~/.bash_aliases:

```<code>function touchp() {
  /bin/mkdir -p "$(dirname "$1")/" && /usr/bin/touch "$1"
}
</code>```

It silently creates the structure above the file if not present, and is perfectly safe to use when passed a single filename without any directory in front of it.

Body:
I need to touch a file with an absolute file name such as: /opt/test/test.txt, but I'm not sure if there is /opt/test existed on the system. So the code should similar with this:

if (-d '/opt/test') {
    touch '/opt/test/test.txt';
} else {
    mkdir -p '/opt/test';
    touch '/opt/test/test.txt'
}

Is there any better way to simplify the code? I hope there is some system commands that can do the same job with only one line.

Body:
I defined a touchp in my ~/.bash_aliases:

function touchp() {
  /bin/mkdir -p "$(dirname "$1")/" && /usr/bin/touch "$1"
}

It silently creates the structure above the file if not present, and is perfectly safe to use when passed a single filename without any directory in front of it.


问:
How can multithreading give a factor of speeedup that is larger than the number of cores?
I am using pthreads with gcc. The simple code example takes the number of threads "N" as a user-supplied input. It splits up a long array into N roughly equally sized subblocks. Each subblock is written into by individual threads.

The dummy processing for this example really involves sleeping for a fixed amount of time for each array index and then writing a number into that array location.

Here's the code:

```<code>/******************************************************************************
* FILE: threaded_subblocks_processing
* DESCRIPTION:
* We have a bunch of parallel processing to do and store the results in a
* large array. Let's try to use threads to speed it up.
******************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>

#define BIG_ARR_LEN 10000

typedef struct thread_data{
  int start_idx;
  int end_idx;
  int id;
} thread_data_t;

int big_result_array[BIG_ARR_LEN] = {0};

void* process_sub_block(void *td)
{
   struct thread_data *current_thread_data = (struct thread_data*)td;
   printf("[%d] Hello World! It's me, thread #%d!\n", current_thread_data->id, current_thread_data->id);
   printf("[%d] I'm supposed to work on indexes %d through %d.\n", current_thread_data->id,
       current_thread_data->start_idx,
       current_thread_data->end_idx-1);

   for(int i=current_thread_data->start_idx; i<current_thread_data->end_idx; i++)
   {
       int retval = usleep(1000.0*1000.0*10.0/BIG_ARR_LEN);
       if(retval)
       {
         printf("sleep failed");
       }

       big_result_array[i] = i;
   }

   printf("[%d] Thread #%d done, over and out!\n", current_thread_data->id, current_thread_data->id);
   pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
   if (argc!=2)
   {
     printf("usage: ./a.out number_of_threads\n");
     return(1);
   }

   int NUM_THREADS = atoi(argv[1]);

   if (NUM_THREADS<1)
   {
     printf("usage: ./a.out number_of_threads (where number_of_threads is at least 1)\n");
     return(1);
   }

   pthread_t *threads = malloc(sizeof(pthread_t)*NUM_THREADS);
   thread_data_t *thread_data_array = malloc(sizeof(thread_data_t)*NUM_THREADS);

   int block_size = BIG_ARR_LEN/NUM_THREADS;
   for(int i=0; i<NUM_THREADS-1; i++)
   {
     thread_data_array[i].start_idx = i*block_size;
     thread_data_array[i].end_idx = (i+1)*block_size;
     thread_data_array[i].id = i;
   }
   thread_data_array[NUM_THREADS-1].start_idx = (NUM_THREADS-1)*block_size;
   thread_data_array[NUM_THREADS-1].end_idx = BIG_ARR_LEN;
   thread_data_array[NUM_THREADS-1].id = NUM_THREADS;

   int ret_code;
   long t;
   for(t=0;t<NUM_THREADS;t++){
     printf("[main] Creating thread %ld\n", t);
     ret_code = pthread_create(&threads[t], NULL, process_sub_block, (void *)&thread_data_array[t]);
     if (ret_code){
       printf("[main] ERROR; return code from pthread_create() is %d\n", ret_code);
       exit(-1);
       }
     }

   printf("[main] Joining threads to wait for them.\n");
   void* status;
   for(int i=0; i<NUM_THREADS; i++)
   {
     pthread_join(threads[i], &status);
   }

   pthread_exit(NULL);
}
</code>```

and I compile it with

```<code>gcc -pthread threaded_subblock_processing.c
</code>```

and then I call it from command line like so:

```<code>$ time ./a.out 4
</code>```

I see a speed up when I increase the number of threads. With 1 thread the process takes just a little over 10 seconds. This makes sense because I sleep for 1000 usec per array element, and there are 10,000 array elements. Next when I go to 2 threads, it goes down to a little over 5 seconds, and so on.

What I don't understand is that I get a speed-up even after my number of threads exceeds the number of cores on my computer! I have 4 cores, so I was expecting no speed-up for >4 threads. But, surprisingly, when I run

```<code>$ time ./a.out 100
</code>```

I get a 100x speedup and the processing completes in ~0.1 seconds! How is this possible?

答:
Some general background

A program's progress can be slowed by many things, but, in general, you can slow spots (otherwise known as hot spots) into two categories:

CPU Bound: In this case, the processor is doing some heavy number crunching (like trigonometric functions). If all the CPU's cores are engaged in such tasks, other processes must wait.

Memory bound: In this case, the processor is waiting for information to be retrieved from the hard disk or RAM. Since these are typically orders of magnitude slower than the processor, from the CPU's perspective this takes forever.

But you can also imagine other situations in which a process must wait, such as for a network response.

In many of these memory-/network-bound situations, it is possible to put a thread "on hold" while the memory crawls towards the CPU and do other useful work in the meantime. If this is done well then a multi-threaded program can well out-perform its single-threaded equivalent. Node.js makes use of such asynchronous programming techniques to achieve good performance.

Here's a handy depiction of various latencies:

Your question

Now, getting back to your question: you have multiple threads going, but they are performing neither CPU-intensive nor memory-intensive work: there's not much there to take up time. In fact, the sleep function is essentially telling the operating system that no work is being done. In this case, the OS can do work in other threads while your threads sleep. So, naturally, the apparent performance increases significantly.

Note that for low-latency applications, such as MPI, busy waiting is sometimes used instead of a sleep function. In this case, the program goes into a tight loop and repeatedly checks a condition. Externally, the effect looks similar, but sleep uses no CPU while the busy wait uses ~100% of the CPU.

Body:
I am using pthreads with gcc. The simple code example takes the number of threads "N" as a user-supplied input. It splits up a long array into N roughly equally sized subblocks. Each subblock is written into by individual threads.

The dummy processing for this example really involves sleeping for a fixed amount of time for each array index and then writing a number into that array location.

Here's the code:

/******************************************************************************
* FILE: threaded_subblocks_processing
* DESCRIPTION:
* We have a bunch of parallel processing to do and store the results in a
* large array. Let's try to use threads to speed it up.
******************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>

#define BIG_ARR_LEN 10000

typedef struct thread_data{
  int start_idx;
  int end_idx;
  int id;
} thread_data_t;

int big_result_array[BIG_ARR_LEN] = {0};

void* process_sub_block(void *td)
{
   struct thread_data *current_thread_data = (struct thread_data*)td;
   printf("[%d] Hello World! It's me, thread #%d!\n", current_thread_data->id, current_thread_data->id);
   printf("[%d] I'm supposed to work on indexes %d through %d.\n", current_thread_data->id,
       current_thread_data->start_idx,
       current_thread_data->end_idx-1);

   for(int i=current_thread_data->start_idx; i<current_thread_data->end_idx; i++)
   {
       int retval = usleep(1000.0*1000.0*10.0/BIG_ARR_LEN);
       if(retval)
       {
         printf("sleep failed");
       }

       big_result_array[i] = i;
   }

   printf("[%d] Thread #%d done, over and out!\n", current_thread_data->id, current_thread_data->id);
   pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
   if (argc!=2)
   {
     printf("usage: ./a.out number_of_threads\n");
     return(1);
   }

   int NUM_THREADS = atoi(argv[1]);

   if (NUM_THREADS<1)
   {
     printf("usage: ./a.out number_of_threads (where number_of_threads is at least 1)\n");
     return(1);
   }

   pthread_t *threads = malloc(sizeof(pthread_t)*NUM_THREADS);
   thread_data_t *thread_data_array = malloc(sizeof(thread_data_t)*NUM_THREADS);

   int block_size = BIG_ARR_LEN/NUM_THREADS;
   for(int i=0; i<NUM_THREADS-1; i++)
   {
     thread_data_array[i].start_idx = i*block_size;
     thread_data_array[i].end_idx = (i+1)*block_size;
     thread_data_array[i].id = i;
   }
   thread_data_array[NUM_THREADS-1].start_idx = (NUM_THREADS-1)*block_size;
   thread_data_array[NUM_THREADS-1].end_idx = BIG_ARR_LEN;
   thread_data_array[NUM_THREADS-1].id = NUM_THREADS;

   int ret_code;
   long t;
   for(t=0;t<NUM_THREADS;t++){
     printf("[main] Creating thread %ld\n", t);
     ret_code = pthread_create(&threads[t], NULL, process_sub_block, (void *)&thread_data_array[t]);
     if (ret_code){
       printf("[main] ERROR; return code from pthread_create() is %d\n", ret_code);
       exit(-1);
       }
     }

   printf("[main] Joining threads to wait for them.\n");
   void* status;
   for(int i=0; i<NUM_THREADS; i++)
   {
     pthread_join(threads[i], &status);
   }

   pthread_exit(NULL);
}

and I compile it with

gcc -pthread threaded_subblock_processing.c

and then I call it from command line like so:

$ time ./a.out 4

I see a speed up when I increase the number of threads. With 1 thread the process takes just a little over 10 seconds. This makes sense because I sleep for 1000 usec per array element, and there are 10,000 array elements. Next when I go to 2 threads, it goes down to a little over 5 seconds, and so on.

What I don't understand is that I get a speed-up even after my number of threads exceeds the number of cores on my computer! I have 4 cores, so I was expecting no speed-up for >4 threads. But, surprisingly, when I run

$ time ./a.out 100

I get a 100x speedup and the processing completes in ~0.1 seconds! How is this possible?


问:
I can't access localhost in Android
I setup a localhost and it works fine on macos sierra.

```<code>localhost/~username
</code>```

But now I'm trying to acces from Chrome Browser on my Android

```<code>192.168.x.x/~username
</code>```

and got this message.

```<code>Forbidden. You don't have permission to access /~username from this server
</code>```

My phone and mac are connected to the same wifi.

And also edit the httpd.conf

```<code><Directory />
   AllowOverride All
   Require all granted
</Directory>
</code>```

And it´s not working.

答:
open your terminal and type this command :</p>

```<code>chmod 777 parent_directory/localhost
</code>```

Title: I can't access localhost in Android

Body:
I setup a localhost and it works fine on macos sierra.

localhost/~username

But now I'm trying to acces from Chrome Browser on my Android

192.168.x.x/~username

and got this message.

Forbidden. You don't have permission to access /~username from this server

My phone and mac are connected to the same wifi.

And also edit the httpd.conf

<Directory />
   AllowOverride All
   Require all granted
</Directory>

And it´s not working.

Body:
open your terminal and type this command :

chmod 777 parent_directory/localhost


问:
Why is the size of this struct 32?
This is the struct.

```<code>//Structure pour communiquer les paramètres de traitement à travers le MMF
struct params_traitement_mmf
{
    int brilliance;
    double contraste;
    char convolution[9];
};
</code>```

This is my code to display the size of this struct :

```<code>    char valeur[10];
    sprintf(valeur, "%d", sizeof(params_traitement_mmf));
    MessageBoxA(NULL, valeur, "rien", MB_OK);
</code>```

The MessageBox displays 32.
Thank you!

答:
It is likely that the payload is 21 bytes (int=4, double=8, chars=9), but that your compiler adds padding between int and double to make the double 8-byte aligned. Also there is some padding at the end, to make sure the double is 8-byte aligned even if the struct is put in an array.

If you instead change definition so that double is moved first:

```<code>struct params_traitement_mmf {
    double contraste;
    int brilliance;
    char convolution[9];
};
</code>```

...it is likely that the need to add padding between int and double disappears, and sizeof(params_traitment_mmf) may go down to 24.

Of course, what happens in practice is platform specific.

Title: Why is the size of this struct 32?

Body:
This is the struct.

//Structure pour communiquer les paramètres de traitement à travers le MMF
struct params_traitement_mmf
{
    int brilliance;
    double contraste;
    char convolution[9];
};

This is my code to display the size of this struct :

    char valeur[10];
    sprintf(valeur, "%d", sizeof(params_traitement_mmf));
    MessageBoxA(NULL, valeur, "rien", MB_OK);

The MessageBox displays 32.
Thank you!

Body:
It is likely that the payload is 21 bytes (int=4, double=8, chars=9), but that your compiler adds padding between int and double to make the double 8-byte aligned. Also there is some padding at the end, to make sure the double is 8-byte aligned even if the struct is put in an array.

If you instead change definition so that double is moved first:

struct params_traitement_mmf {
    double contraste;
    int brilliance;
    char convolution[9];
};

...it is likely that the need to add padding between int and double disappears, and sizeof(params_traitment_mmf) may go down to 24.

Of course, what happens in practice is platform specific.


问:
Check user logged in Joomla 2.5 from external script (reiterated)
I'm well familiar with coding in PHP and other languages, but I'm totally unfamiliar with Joomla.

What I want to accomplish is to know when a user has logged in on the Joomla site (under /web) and differentiate this script's behaviour accordingly.

I have a Joomla 2.5 site under /web/ and I have a script under /web/test/index.php, where the following code lies (collected from other replies in here and elsewhere):

```<code>define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
echo dirname(dirname(__FILE__)) . "\n";
if (file_exists(dirname(dirname(__FILE__)) . '/defines.php'))
    include_once dirname(dirname(__FILE__)) . '/defines.php';

if (!defined('_JDEFINES')) {
    define('JPATH_BASE', dirname(dirname(__FILE__)));
    require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
$app = JFactory::getApplication('site');
$app->initialise();

print_r(JFactory::getUser());
</code>```

What I get back is

```<code>/web
JUser Object
(
    [isRoot:protected] =>
    [id] => 0
    [name] =>
    ...
</code>```

Thank you,

答:
Use this code it's working:</p>

```<code>define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/' ));

require_once( JPATH_BASE . DS . 'includes' . DS . 'defines.php' );
require_once( JPATH_BASE . DS . 'includes' . DS . 'framework.php' );
require_once( JPATH_BASE . DS . 'libraries' . DS . 'joomla' . DS . 'factory.php' );
$mainframe = JFactory::getApplication('site');

var_dump(JFactory::getUser());
</code>```

Body:
I'm well familiar with coding in PHP and other languages, but I'm totally unfamiliar with Joomla.

What I want to accomplish is to know when a user has logged in on the Joomla site (under /web) and differentiate this script's behaviour accordingly.

I have a Joomla 2.5 site under /web/ and I have a script under /web/test/index.php, where the following code lies (collected from other replies in here and elsewhere):

define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
echo dirname(dirname(__FILE__)) . "\n";
if (file_exists(dirname(dirname(__FILE__)) . '/defines.php'))
    include_once dirname(dirname(__FILE__)) . '/defines.php';

if (!defined('_JDEFINES')) {
    define('JPATH_BASE', dirname(dirname(__FILE__)));
    require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
$app = JFactory::getApplication('site');
$app->initialise();

print_r(JFactory::getUser());

What I get back is

/web
JUser Object
(
    [isRoot:protected] =>
    [id] => 0
    [name] =>
    ...

Thank you,

Body:
Use this code it's working:

define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/' ));

require_once( JPATH_BASE . DS . 'includes' . DS . 'defines.php' );
require_once( JPATH_BASE . DS . 'includes' . DS . 'framework.php' );
require_once( JPATH_BASE . DS . 'libraries' . DS . 'joomla' . DS . 'factory.php' );
$mainframe = JFactory::getApplication('site');

var_dump(JFactory::getUser());


问:
Wordpress/WooCommerce: woocommerce_thankyou not working with Stripe payments
In the latest update, it appears that Stripe payment processing is done by the user of separate WC/Stripe plugin. Since then, my wp_enqueue_script() stopping working on my confirmation page. It still works for Cash on Delivery payments.

Here is what I have for COD payments (this works):

add_action( 'woocommerce_thankyou', array( 'MyApp', 'myapp_woocommerce_thankyou' ), 1000 );

Here is what I have to track the Stripe payments (DOESN'T work):

add_action( 'wc_gateway_stripe_process_payment', array( 'MyApp', 'myapp_woocommerce_thankyou_wc3_stripe' ), 1000, 2 );

Then I have these functions. One for Stripe and one for all else:

```<code>public static function myapp_woocommerce_thankyou($order_id) {

    echo 'Test'; // Works on both payment methods

    $myapp_vars = array( 'num' => rand() ); // Dummy data

    // Load the JS
    wp_register_script( "scripts" , plugin_dir_url( __FILE__ ) . "/myapp.js" );
    wp_enqueue_script( "scripts" );
    wp_localize_script( "scripts" , "myapp_vars", $myapp_vars );

}

public static function myapp_woocommerce_thankyou_wc3_stripe( $stripe_response, $order ) {

    MyApp::myapp_woocommerce_thankyou( $order->get_id() );

}
</code>```

I am able to echo out data in myapp_woocommerce_thankyou(), but the wp_localize_script part simply won't run when the customer pays via Stripe.

答: I figured it out. I am using WooCommerce and they changed their API. Unfortunately WP/WC wasn't reporting back the errors by default. I had to go hunt them down like a lion in heat looking for a mate.</p>

Body:
In the latest update, it appears that Stripe payment processing is done by the user of separate WC/Stripe plugin. Since then, my wp_enqueue_script() stopping working on my confirmation page. It still works for Cash on Delivery payments.

Here is what I have for COD payments (this works):

add_action( 'woocommerce_thankyou', array( 'MyApp', 'myapp_woocommerce_thankyou' ), 1000 );

Here is what I have to track the Stripe payments (DOESN'T work):

add_action( 'wc_gateway_stripe_process_payment', array( 'MyApp', 'myapp_woocommerce_thankyou_wc3_stripe' ), 1000, 2 );

Then I have these functions. One for Stripe and one for all else:

public static function myapp_woocommerce_thankyou($order_id) {

    echo 'Test'; // Works on both payment methods

    $myapp_vars = array( 'num' => rand() ); // Dummy data

    // Load the JS
    wp_register_script( "scripts" , plugin_dir_url( __FILE__ ) . "/myapp.js" );
    wp_enqueue_script( "scripts" );
    wp_localize_script( "scripts" , "myapp_vars", $myapp_vars );

}

public static function myapp_woocommerce_thankyou_wc3_stripe( $stripe_response, $order ) {

    MyApp::myapp_woocommerce_thankyou( $order->get_id() );

}

I am able to echo out data in myapp_woocommerce_thankyou(), but the wp_localize_script part simply won't run when the customer pays via Stripe.