问:
Efficient way to upload multiple images to S3 from iOS
I'm using Amazon S3 as my file storage system in the app. All my item objects have several images associated with them, and each stores only the image urls to keep my database lightweight. As such I need an efficient way to upload multiple images to S3 directly from iOS, and upon successful completion store their urls in the object I send to the server. I've perused the SDK and sample app Amazon provides, but the only example I've come across is for a single image upload, and goes as follows:

```<code> func uploadData(data: NSData) {
    let expression = AWSS3TransferUtilityUploadExpression()
    expression.progressBlock = progressBlock

    let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()

    transferUtility.uploadData(
        data,
        bucket: S3BucketName,
        key: S3UploadKeyName,
        contentType: "text/plain",
        expression: expression,
        completionHander: completionHandler).continueWithBlock { (task) -> AnyObject! in
            if let error = task.error {
                NSLog("Error: %@",error.localizedDescription);
                self.statusLabel.text = "Failed"
            }
            if let exception = task.exception {
                NSLog("Exception: %@",exception.description);
                self.statusLabel.text = "Failed"
            }
            if let _ = task.result {
                self.statusLabel.text = "Generating Upload File"
                NSLog("Upload Starting!")
                // Do something with uploadTask.
            }

            return nil;
    }
}
</code>```

For upwards of 5 images this will become a nested mess since I'd have to wait for each upload to return successfully before initiating the next, and then finally sending the object to my DB. Is there an efficient, code-clean for me to accomplish my goal?

URL to Amazon's sample app github: https://github.com/awslabs/aws-sdk-ios-samples/tree/master/S3TransferUtility-Sample/Swift

答:
As I said on H. Al-Amri's response, if you need to know when the last upload is complete you can't simply iterate through an array of data and upload them all at once.

In Javascript there is a library (Async.js I think) that will make it easy to do background operations on individual elements of an array, and to get callbacks when each one finishes and when the entire array is finished. Since I'm not aware of anything like that for Swift, your intuition that you have to chain the uploads is correct.

As @DavidTamrazov explained in comments, you can chain your calls together using recursion. The way I solved this problem was a little more complicated since my network operations are done using NSOperationQueue to chain NSOperations. I pass an array of images to a custom NSOperation that uploads the first image from the array. When it completes, it adds another NSOperation to my NSOperationsQueue with the array of remaining images. When the array runs out of images, I know I'm complete.

Following is an example I chopped out of a much much larger chunk I use. Treat it as pseudocode because I edited it heavily and didn't have time to even compile it. But hopefully it's clear enough on the framework for how to do this with NSOperations.

```<code>class NetworkOp : Operation {
    var isRunning = false

    override var isAsynchronous: Bool {
        get {
            return true
        }
    }

    override var isConcurrent: Bool {
        get {
            return true
        }
    }

    override var isExecuting: Bool {
        get {
            return isRunning
        }
    }

    override var isFinished: Bool {
        get {
            return !isRunning
        }
    }

    override func start() {
        if self.checkCancel() {
            return
        }
        self.willChangeValue(forKey: "isExecuting")
        self.isRunning = true
        self.didChangeValue(forKey: "isExecuting")
        main()
    }

    func complete() {
        self.willChangeValue(forKey: "isFinished")
        self.willChangeValue(forKey: "isExecuting")
        self.isRunning = false
        self.didChangeValue(forKey: "isFinished")
        self.didChangeValue(forKey: "isExecuting")
        print( "Completed net op: \(self.className)")
    }

    // Always resubmit if we get canceled before completion
    func checkCancel() -> Bool {
        if self.isCancelled {
            self.retry()
            self.complete()
        }
        return self.isCancelled
    }

    func retry() {
        // Create a new NetworkOp to match and resubmit since we can't reuse existing.
    }

    func success() {
        // Success means reset delay
        NetOpsQueueMgr.shared.resetRetryIncrement()
    }
}

class ImagesUploadOp : NetworkOp {
    var imageList : [PhotoFileListMap]

    init(imageList : [UIImage]) {
        self.imageList = imageList
    }

    override func main() {
        print( "Photos upload starting")
        if self.checkCancel() {
            return
        }

        // Pop image off front of array
        let image = imageList.remove(at: 0)

        // Now call function that uses AWS to upload image, mine does save to file first, then passes
        // an error message on completion if it failed, nil if it succceeded
        ServerMgr.shared.uploadImage(image: image, completion: {  errorMessage ) in
            if let error = errorMessage {
                print("Failed to upload file - " + error)
                self.retry()
            } else {
                print("Uploaded file")
                if !self.isCancelled {
                    if self.imageList.count == 0 {
                        // All images done, here you could call a final completion handler or somthing.
                    } else {
                        // More images left to do, let's put another Operation on the barbie:)
                        NetOpsQueueMgr.shared.submitOp(netOp: ImagesUploadOp(imageList: self.imageList))
                    }
                }
            }
            self.complete()
         })
    }

    override func retry() {
        NetOpsQueueMgr.shared.retryOpWithDelay(op: ImagesUploadOp(form: self.form, imageList: self.imageList))
    }
}

// MARK: NetOpsQueueMgr  -------------------------------------------------------------------------------

class NetOpsQueueMgr {
    static let shared = NetOpsQueueMgr()

    lazy var opsQueue :OperationQueue = {
        var queue = OperationQueue()
        queue.name = "myQueName"
        queue.maxConcurrentOperationCount = 1
        return queue
    }()

    func submitOp(netOp : NetworkOp) {
         opsQueue.addOperation(netOp)
    }

   func uploadImages(imageList : [UIImage]) {
        let imagesOp = ImagesUploadOp(form: form, imageList: imageList)
        self.submitOp(netOp: imagesOp)
    }
}
</code>```

Body:
I'm using Amazon S3 as my file storage system in the app. All my item objects have several images associated with them, and each stores only the image urls to keep my database lightweight. As such I need an efficient way to upload multiple images to S3 directly from iOS, and upon successful completion store their urls in the object I send to the server. I've perused the SDK and sample app Amazon provides, but the only example I've come across is for a single image upload, and goes as follows:

 func uploadData(data: NSData) {
    let expression = AWSS3TransferUtilityUploadExpression()
    expression.progressBlock = progressBlock

    let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()

    transferUtility.uploadData(
        data,
        bucket: S3BucketName,
        key: S3UploadKeyName,
        contentType: "text/plain",
        expression: expression,
        completionHander: completionHandler).continueWithBlock { (task) -> AnyObject! in
            if let error = task.error {
                NSLog("Error: %@",error.localizedDescription);
                self.statusLabel.text = "Failed"
            }
            if let exception = task.exception {
                NSLog("Exception: %@",exception.description);
                self.statusLabel.text = "Failed"
            }
            if let _ = task.result {
                self.statusLabel.text = "Generating Upload File"
                NSLog("Upload Starting!")
                // Do something with uploadTask.
            }

            return nil;
    }
}

For upwards of 5 images this will become a nested mess since I'd have to wait for each upload to return successfully before initiating the next, and then finally sending the object to my DB. Is there an efficient, code-clean for me to accomplish my goal?

URL to Amazon's sample app github: https://github.com/awslabs/aws-sdk-ios-samples/tree/master/S3TransferUtility-Sample/Swift

Body:
As I said on H. Al-Amri's response, if you need to know when the last upload is complete you can't simply iterate through an array of data and upload them all at once.

In Javascript there is a library (Async.js I think) that will make it easy to do background operations on individual elements of an array, and to get callbacks when each one finishes and when the entire array is finished. Since I'm not aware of anything like that for Swift, your intuition that you have to chain the uploads is correct.

As @DavidTamrazov explained in comments, you can chain your calls together using recursion. The way I solved this problem was a little more complicated since my network operations are done using NSOperationQueue to chain NSOperations. I pass an array of images to a custom NSOperation that uploads the first image from the array. When it completes, it adds another NSOperation to my NSOperationsQueue with the array of remaining images. When the array runs out of images, I know I'm complete.

Following is an example I chopped out of a much much larger chunk I use. Treat it as pseudocode because I edited it heavily and didn't have time to even compile it. But hopefully it's clear enough on the framework for how to do this with NSOperations.

class NetworkOp : Operation {
    var isRunning = false

    override var isAsynchronous: Bool {
        get {
            return true
        }
    }

    override var isConcurrent: Bool {
        get {
            return true
        }
    }

    override var isExecuting: Bool {
        get {
            return isRunning
        }
    }

    override var isFinished: Bool {
        get {
            return !isRunning
        }
    }

    override func start() {
        if self.checkCancel() {
            return
        }
        self.willChangeValue(forKey: "isExecuting")
        self.isRunning = true
        self.didChangeValue(forKey: "isExecuting")
        main()
    }

    func complete() {
        self.willChangeValue(forKey: "isFinished")
        self.willChangeValue(forKey: "isExecuting")
        self.isRunning = false
        self.didChangeValue(forKey: "isFinished")
        self.didChangeValue(forKey: "isExecuting")
        print( "Completed net op: \(self.className)")
    }

    // Always resubmit if we get canceled before completion
    func checkCancel() -> Bool {
        if self.isCancelled {
            self.retry()
            self.complete()
        }
        return self.isCancelled
    }

    func retry() {
        // Create a new NetworkOp to match and resubmit since we can't reuse existing.
    }

    func success() {
        // Success means reset delay
        NetOpsQueueMgr.shared.resetRetryIncrement()
    }
}

class ImagesUploadOp : NetworkOp {
    var imageList : [PhotoFileListMap]

    init(imageList : [UIImage]) {
        self.imageList = imageList
    }

    override func main() {
        print( "Photos upload starting")
        if self.checkCancel() {
            return
        }

        // Pop image off front of array
        let image = imageList.remove(at: 0)

        // Now call function that uses AWS to upload image, mine does save to file first, then passes
        // an error message on completion if it failed, nil if it succceeded
        ServerMgr.shared.uploadImage(image: image, completion: {  errorMessage ) in
            if let error = errorMessage {
                print("Failed to upload file - " + error)
                self.retry()
            } else {
                print("Uploaded file")
                if !self.isCancelled {
                    if self.imageList.count == 0 {
                        // All images done, here you could call a final completion handler or somthing.
                    } else {
                        // More images left to do, let's put another Operation on the barbie:)
                        NetOpsQueueMgr.shared.submitOp(netOp: ImagesUploadOp(imageList: self.imageList))
                    }
                }
            }
            self.complete()
         })
    }

    override func retry() {
        NetOpsQueueMgr.shared.retryOpWithDelay(op: ImagesUploadOp(form: self.form, imageList: self.imageList))
    }
}

// MARK: NetOpsQueueMgr  -------------------------------------------------------------------------------

class NetOpsQueueMgr {
    static let shared = NetOpsQueueMgr()

    lazy var opsQueue :OperationQueue = {
        var queue = OperationQueue()
        queue.name = "myQueName"
        queue.maxConcurrentOperationCount = 1
        return queue
    }()

    func submitOp(netOp : NetworkOp) {
         opsQueue.addOperation(netOp)
    }

   func uploadImages(imageList : [UIImage]) {
        let imagesOp = ImagesUploadOp(form: form, imageList: imageList)
        self.submitOp(netOp: imagesOp)
    }
}


来源: stackexchange

问:
react-native No bundle URL present
I get the following error when trying to do react-native run-ios (see screenshot below).  I have checked this answer as well as the github thread but neither were helpful.

Any ideas on what to look at or how to make this work? The problem seems to be isolated to ios, as the android emulator works ok.  Looks like maybe it's some sort of bug with the facebook code.

答:
Try this after the simulator is already running:

npm install

react-native run-ios

ContentLicense: CC BY-SA 3.0

Title: react-native No bundle URL present


问:
How to make a CroppedBitmap transparent?
I have a cropped bitmap:

```<code> CroppedBitmap crop = new CroppedBitmap(rtb, new Int32Rect(MapOffset, MapOffset, BOARD_WIDTH - 1 - MapOffset, BOARD_HEIGHT - 1 - MapOffset));
</code>```

and I need to set white to transparent. Unfortunately, this does not work (CroppedBitmap does not contain a definition for 'MakeTransparent'):

```<code>crop.MakeTransparent(Colors.White);
</code>```

Anybody have any ideas / suggestions?

Thanks in advance.

~~~~~~~~~~~~~~~

I found this code How can I make all white (FFFFFFFF) pixel in an image(ImageBrush) to be transparent

But when I implement it

```<code>    public void SaveMainCanvas2BMP(string filename)
    {

        // Write BMP
        VisualBrush sourceBrush = new VisualBrush(MainCanvas);
        DrawingVisual drawingVisual = new DrawingVisual();
        DrawingContext drawingContext = drawingVisual.RenderOpen();
        using (drawingContext)
        {
            drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(- MapOffset, - MapOffset), new Point(BOARD_WIDTH - 1 + MapOffset, BOARD_HEIGHT - 1 + MapOffset)));
        }

        RenderTargetBitmap rtb = new RenderTargetBitmap(BOARD_WIDTH - 1, BOARD_HEIGHT - 1, 96, 96, PixelFormats.Default);
        rtb.Render(drawingVisual);

        //crops  rectangle at position (0,0).
        CroppedBitmap crop = new CroppedBitmap(rtb, new Int32Rect(0, 0, BOARD_WIDTH - 1, BOARD_HEIGHT - 1));

        WriteableBitmap writeable = new WriteableBitmap(crop);

        // Code to turn WHITE pixels TRANSPARENT
        int pixelWidth = (int)writeable.Width;
        int pixelHeight = (int)writeable.Height;
        int Stride = pixelWidth * 4;

        BitmapSource imgSource = (BitmapSource)writeable;
        byte[] pixels = new byte[pixelHeight * Stride];
        imgSource.CopyPixels(pixels, Stride, 0);
        byte TransparentByte = byte.Parse("0");
        byte Byte255 = byte.Parse("255");
        int N = pixelWidth * pixelHeight;
        //Operate the pixels directly
        for (int i = 0; i < N; i++)
        {
            byte a = pixels[i * 4];
            byte b = pixels[i * 4 + 1];
            byte c = pixels[i * 4 + 2];
            byte d = pixels[i * 4 + 3];
            if (a == Byte255 && b == Byte255 && c == Byte255 && d == Byte255)
            {
                pixels[i * 4] = TransparentByte;
                pixels[i * 4 + 1] = TransparentByte;
                pixels[i * 4 + 2] = TransparentByte;
                pixels[i * 4 + 3] = TransparentByte;
            }
        }
        WriteableBitmap writeableBitmap = new WriteableBitmap(pixelWidth, pixelHeight, 96, 96,
            PixelFormats.Pbgra32, BitmapPalettes.Halftone256Transparent);
        writeableBitmap.WritePixels(new Int32Rect(0, 0, pixelWidth, pixelHeight), pixels, Stride, 0);

        //encode as BMP
        BitmapEncoder bmpEncoder = new BmpBitmapEncoder();

        bmpEncoder.Frames.Add(BitmapFrame.Create(writeableBitmap));

        //save to memory stream
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        bmpEncoder.Save(ms);
        ms.Close();
        System.IO.File.WriteAllBytes(filename, ms.ToArray());
    }
</code>```

It doesn't make WHITE transparent; it replaces WHITE with BLACK:

EDIT
SOLUTION

The solution is over here (the problem has to do with WPF and transparency):
Solution to transparency problem

答:
The problem was with the way WPF handles transparency (BMPs are not the way to go, PNGs are).

Solution here:
Solution to transparency problem

Body:
I have a cropped bitmap:

 CroppedBitmap crop = new CroppedBitmap(rtb, new Int32Rect(MapOffset, MapOffset, BOARD_WIDTH - 1 - MapOffset, BOARD_HEIGHT - 1 - MapOffset));

and I need to set white to transparent. Unfortunately, this does not work (CroppedBitmap does not contain a definition for 'MakeTransparent'):

crop.MakeTransparent(Colors.White);

Anybody have any ideas / suggestions?

Thanks in advance.

~~~~~~~~~~~~~~~

I found this code How can I make all white (FFFFFFFF) pixel in an image(ImageBrush) to be transparent

But when I implement it

    public void SaveMainCanvas2BMP(string filename)
    {

        // Write BMP
        VisualBrush sourceBrush = new VisualBrush(MainCanvas);
        DrawingVisual drawingVisual = new DrawingVisual();
        DrawingContext drawingContext = drawingVisual.RenderOpen();
        using (drawingContext)
        {
            drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(- MapOffset, - MapOffset), new Point(BOARD_WIDTH - 1 + MapOffset, BOARD_HEIGHT - 1 + MapOffset)));
        }

        RenderTargetBitmap rtb = new RenderTargetBitmap(BOARD_WIDTH - 1, BOARD_HEIGHT - 1, 96, 96, PixelFormats.Default);
        rtb.Render(drawingVisual);

        //crops  rectangle at position (0,0).
        CroppedBitmap crop = new CroppedBitmap(rtb, new Int32Rect(0, 0, BOARD_WIDTH - 1, BOARD_HEIGHT - 1));

        WriteableBitmap writeable = new WriteableBitmap(crop);

        // Code to turn WHITE pixels TRANSPARENT
        int pixelWidth = (int)writeable.Width;
        int pixelHeight = (int)writeable.Height;
        int Stride = pixelWidth * 4;

        BitmapSource imgSource = (BitmapSource)writeable;
        byte[] pixels = new byte[pixelHeight * Stride];
        imgSource.CopyPixels(pixels, Stride, 0);
        byte TransparentByte = byte.Parse("0");
        byte Byte255 = byte.Parse("255");
        int N = pixelWidth * pixelHeight;
        //Operate the pixels directly
        for (int i = 0; i < N; i++)
        {
            byte a = pixels[i * 4];
            byte b = pixels[i * 4 + 1];
            byte c = pixels[i * 4 + 2];
            byte d = pixels[i * 4 + 3];
            if (a == Byte255 && b == Byte255 && c == Byte255 && d == Byte255)
            {
                pixels[i * 4] = TransparentByte;
                pixels[i * 4 + 1] = TransparentByte;
                pixels[i * 4 + 2] = TransparentByte;
                pixels[i * 4 + 3] = TransparentByte;
            }
        }
        WriteableBitmap writeableBitmap = new WriteableBitmap(pixelWidth, pixelHeight, 96, 96,
            PixelFormats.Pbgra32, BitmapPalettes.Halftone256Transparent);
        writeableBitmap.WritePixels(new Int32Rect(0, 0, pixelWidth, pixelHeight), pixels, Stride, 0);

        //encode as BMP
        BitmapEncoder bmpEncoder = new BmpBitmapEncoder();

        bmpEncoder.Frames.Add(BitmapFrame.Create(writeableBitmap));

        //save to memory stream
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        bmpEncoder.Save(ms);
        ms.Close();
        System.IO.File.WriteAllBytes(filename, ms.ToArray());
    }

It doesn't make WHITE transparent; it replaces WHITE with BLACK:

EDIT
SOLUTION

The solution is over here (the problem has to do with WPF and transparency):
Solution to transparency problem


问:
Pointers to Interfaces c++
Disclaimer: I am a complete C++ beginner, and if there is a similar answer to this question, please direct me to it, as I may have missed it, not knowing much in the way of theory.

So I was looking through some c++ code, and I found something like this:

shared_ptr<anObjectsInterface>

Which got me wondering, how can there be a pointer to an interface? Surely a pointer points to an object in memory, or am I reading something wrong here.

Thank you

答:
anObjectsInterface is most possibly an abstract base class created exactly for a purpose like this : in order to pass an object around without having to specify which class actually implements the abstract class' methods.

A minimal example (using the naming you provided) would be something like this - you can find tons of these in any tutorial that mentions class hierarchies and/or virtual functions :

```<code>#include <memory>

struct anObjectsInterface {
  virtual int doStuff() const = 0;
};

struct anImplementation : public anObjectsInterface {
  int doStuff() const override {
    return 5;
  }
};

void doStuffWithObject(const std::shared_ptr<anObjectsInterface>& x) {
  x->doStuff();
}

int main() {
  auto object = std::make_shared<anImplementation>();
  doStuffWithObject(object);
}
</code>```

You'll see that doStuffWithObject takes a std::shared_ptr<anObjectsInterface> and thus has no knowledge that this shared_ptr actually points to an instance of the anImplementation class.

Also, keep in mind that using shared_ptr in a scenario like this is needless : a unique_ptr would be much more fitting.

Title: Pointers to Interfaces c++

Body:
anObjectsInterface is most possibly an abstract base class created exactly for a purpose like this : in order to pass an object around without having to specify which class actually implements the abstract class' methods.

A minimal example (using the naming you provided) would be something like this - you can find tons of these in any tutorial that mentions class hierarchies and/or virtual functions :

#include <memory>

struct anObjectsInterface {
  virtual int doStuff() const = 0;
};

struct anImplementation : public anObjectsInterface {
  int doStuff() const override {
    return 5;
  }
};

void doStuffWithObject(const std::shared_ptr<anObjectsInterface>& x) {
  x->doStuff();
}

int main() {
  auto object = std::make_shared<anImplementation>();
  doStuffWithObject(object);
}

You'll see that doStuffWithObject takes a std::shared_ptr<anObjectsInterface> and thus has no knowledge that this shared_ptr actually points to an instance of the anImplementation class.

Also, keep in mind that using shared_ptr in a scenario like this is needless : a unique_ptr would be much more fitting.


问:
Android, java rx, asynchronous
I have a screen that shows a list of items.

First I want to show the elements from the local database.

After the  user is viewing the local elements, check the internet and
update  them (if the device has internet).

I have the following code fragments

```<code>Observable<Data> fetchFromdisk = ...;
Observable<Data> fetchFromNetwork = ...;

Observable<Data>  fetchData= Observable.concat (fetchFromdisk ,fetchFromNetwork);
</code>```

Then I'm doing the following

```<code>mSubscriptions.clear();
Subscription subscription = fetchData
        .subscribeOn(mSchedulerProvider.computation())
        .observeOn(mSchedulerProvider.ui())
        .subscribe(
                new Subscriber<List<Data>>() {
                    @Override
                    public void onCompleted() {
                        view.setLoadingIndicator(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        processError(e);
                    }

                    @Override
                    public void onNext(List<Data> data) {
                        processData(data);
                    }
                }

        );
mSubscriptions.add(subscription);
</code>```

But what is happening is that fetchFromdisk is first run, then FetchFromNetwork is executed. Once emitting elements ends the execution of ProcessData begins.

That is quite the opposite of what I want to achieve.
I want to prioritize the user to see the data quickly and then go to the internet.
what am I doing wrong?

答:
You can call the method .doOnCompleted to execute your code once the cache has been extracted.

```<code>mSubscriptions.clear();
Subscription subscription = fetchData
    .subscribeOn(mSchedulerProvider.computation())
    .doOnCompleted( new Action0<List<Notification>>() {
                @Override
                public void call(List<Data> cachedData) {
                      // Get data from server here.

                      // Compare new data against cached data.

                      // Update cache.

                      // Process new data.
                }
            })
    .observeOn(mSchedulerProvider.ui())
    .subscribe(
            new Subscriber<List<Data>>() {
                @Override
                public void onCompleted() {
                    view.setLoadingIndicator(false);
                }

                @Override
                public void onError(Throwable e) {
                    processError(e);
                }

                @Override
                public void onNext(List<Data> data) {
                    processData(data);
                }
            }

    );
    mSubscriptions.add(subscription);
</code>```

///////// Non Solution Tip ////////

Try using a Single instead of an Observable, it can get rid of the onCompleted.
https://github.com/lettuce-io/lettuce-core/issues/139

Title: Android, java rx, asynchronous

Body:
I have a screen that shows a list of items.

First I want to show the elements from the local database.

After the  user is viewing the local elements, check the internet and
update  them (if the device has internet).

I have the following code fragments

Observable<Data> fetchFromdisk = ...;
Observable<Data> fetchFromNetwork = ...;

Observable<Data>  fetchData= Observable.concat (fetchFromdisk ,fetchFromNetwork);

Then I'm doing the following

mSubscriptions.clear();
Subscription subscription = fetchData
        .subscribeOn(mSchedulerProvider.computation())
        .observeOn(mSchedulerProvider.ui())
        .subscribe(
                new Subscriber<List<Data>>() {
                    @Override
                    public void onCompleted() {
                        view.setLoadingIndicator(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        processError(e);
                    }

                    @Override
                    public void onNext(List<Data> data) {
                        processData(data);
                    }
                }

        );
mSubscriptions.add(subscription);

But what is happening is that fetchFromdisk is first run, then FetchFromNetwork is executed. Once emitting elements ends the execution of ProcessData begins.

That is quite the opposite of what I want to achieve.
I want to prioritize the user to see the data quickly and then go to the internet.
what am I doing wrong?

Body:
You can call the method .doOnCompleted to execute your code once the cache has been extracted.

mSubscriptions.clear();
Subscription subscription = fetchData
    .subscribeOn(mSchedulerProvider.computation())
    .doOnCompleted( new Action0<List<Notification>>() {
                @Override
                public void call(List<Data> cachedData) {
                      // Get data from server here.

                      // Compare new data against cached data.

                      // Update cache.

                      // Process new data.
                }
            })
    .observeOn(mSchedulerProvider.ui())
    .subscribe(
            new Subscriber<List<Data>>() {
                @Override
                public void onCompleted() {
                    view.setLoadingIndicator(false);
                }

                @Override
                public void onError(Throwable e) {
                    processError(e);
                }

                @Override
                public void onNext(List<Data> data) {
                    processData(data);
                }
            }

    );
    mSubscriptions.add(subscription);

///////// Non Solution Tip ////////

Try using a Single instead of an Observable, it can get rid of the onCompleted.
https://github.com/lettuce-io/lettuce-core/issues/139


问:
Get attribute values from matching XML nodes using XPath query
This doesn't seem like it should be difficult, but I'm stuck currently.  I'm trying to get the attribute values for a particular attribute from nodes that match a given XPath query string.  Here's what I have so far:

```<code>    public static IEnumerable<string> GetAttributes(this XmlDocument xml,
        string xpathQuery, string attributeName)
    {
        var doc = new XPathDocument(new XmlNodeReader(xml));
        XPathNavigator nav = doc.CreateNavigator();
        XPathExpression expr = nav.Compile(xpathQuery);
        XPathNodeIterator iterator = nav.Select(expr);
        while (iterator.MoveNext())
        {
            XPathNavigator curNav = iterator.Current;
            if (curNav.HasAttributes)
            {
                XmlNode curNode = ((IHasXmlNode)curNav).GetNode();
                if (null != curNode)
                {
                    XmlAttribute attrib = curNode.Attributes[attributeName];
                    if (null != attrib)
                    {
                        yield return attrib.Value;
                    }
                }
            }
        }
    }
</code>```

This currently throws an exception:

System.InvalidCastException: Unable to cast object of type 'MS.Internal.Xml.Cache.XPathDocumentNavigator' to type 'System.Xml.IHasXmlNode'.

Am I going about this wrong?  Is there a simpler way to get attribute values from matching nodes?

答:
For the following xml:

```<code><root>
  <elem att='the value' />
</root>
</code>```

You can get the "the value" text with this C# code

```<code>    XmlDocument xdoc = new XmlDocument();
    xdoc.LoadXml(text);
    Console.WriteLine(xdoc.SelectSingleNode("/root/elem/@att").Value);
</code>```

Body:
This doesn't seem like it should be difficult, but I'm stuck currently.  I'm trying to get the attribute values for a particular attribute from nodes that match a given XPath query string.  Here's what I have so far:

    public static IEnumerable<string> GetAttributes(this XmlDocument xml,
        string xpathQuery, string attributeName)
    {
        var doc = new XPathDocument(new XmlNodeReader(xml));
        XPathNavigator nav = doc.CreateNavigator();
        XPathExpression expr = nav.Compile(xpathQuery);
        XPathNodeIterator iterator = nav.Select(expr);
        while (iterator.MoveNext())
        {
            XPathNavigator curNav = iterator.Current;
            if (curNav.HasAttributes)
            {
                XmlNode curNode = ((IHasXmlNode)curNav).GetNode();
                if (null != curNode)
                {
                    XmlAttribute attrib = curNode.Attributes[attributeName];
                    if (null != attrib)
                    {
                        yield return attrib.Value;
                    }
                }
            }
        }
    }

This currently throws an exception:

System.InvalidCastException: Unable to cast object of type 'MS.Internal.Xml.Cache.XPathDocumentNavigator' to type 'System.Xml.IHasXmlNode'.

Am I going about this wrong?  Is there a simpler way to get attribute values from matching nodes?

Body:
For the following xml:

<root>
  <elem att='the value' />
</root>

You can get the "the value" text with this C# code

    XmlDocument xdoc = new XmlDocument();
    xdoc.LoadXml(text);
    Console.WriteLine(xdoc.SelectSingleNode("/root/elem/@att").Value);

ContentLicense: CC BY-SA 2.5


问:
"InvalidRequestError: no property" with composite primary and foreign keys
I am trying to create a relationship between two tables using declarative SQLAlchemy (v1.1.5) where the tables have composite primary and foreign keys.

This is One-To-Many relationship between two tables, where Resource defines the parent, and each resource has multiple segments, defined in the Resourcesegment table. I've added a VersionID column to both tables, so I can use the database with multiple versions of the data.

```<code>from sqlalchemy import Column, String, Integer, ForeignKeyConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()

class Resource(Base):
    __tablename__ = 'resource'
    VersionID = Column(String, primary_key=True)
    ResourceID = Column(String, primary_key=True)
    ResourceProperty = Column(String)
    segments = relationship("Resourcesegment", back_populates="resource")

class Resourcesegment(Base):
    __tablename__ = 'resourcesegment'
    VersionID = Column(String, primary_key=True)
    ResourceID = Column(String, primary_key=True)
    Segment_Type = Column(String, primary_key=True)
    Segment_Number = Column(Integer, primary_key=True)
    Segment_Property = Column(String)
    resource = relationship("Resource", foreign_keys=[VersionID, ResourceID], back_populates="segments")

    __table_args__ = (ForeignKeyConstraint([VersionID, ResourceID], [Resource.VersionID, Resource.ResourceID]),)
</code>```

The error message I am getting is:

InvalidRequestError: Mapper 'Mapper|Resourcesegment|resourcesegment' has no property 'resource'

答:
The code posted above is correct. One of the other tables had a problem, throwing an error making it look like the problem was with the above tables. When I stripped everything away I got my simplified model to work and was able to isolate the problem to another part of the bigger model.

The error messages coming out of SQLAlchemy can be quite confusing, and one is not necessarily able to pinpoint the actual problem without extra debug work.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a relationship between two tables using declarative SQLAlchemy (v1.1.5) where the tables have composite primary and foreign keys.

This is One-To-Many relationship between two tables, where Resource defines the parent, and each resource has multiple segments, defined in the Resourcesegment table. I've added a VersionID column to both tables, so I can use the database with multiple versions of the data.

from sqlalchemy import Column, String, Integer, ForeignKeyConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()

class Resource(Base):
    __tablename__ = 'resource'
    VersionID = Column(String, primary_key=True)
    ResourceID = Column(String, primary_key=True)
    ResourceProperty = Column(String)
    segments = relationship("Resourcesegment", back_populates="resource")

class Resourcesegment(Base):
    __tablename__ = 'resourcesegment'
    VersionID = Column(String, primary_key=True)
    ResourceID = Column(String, primary_key=True)
    Segment_Type = Column(String, primary_key=True)
    Segment_Number = Column(Integer, primary_key=True)
    Segment_Property = Column(String)
    resource = relationship("Resource", foreign_keys=[VersionID, ResourceID], back_populates="segments")

    __table_args__ = (ForeignKeyConstraint([VersionID, ResourceID], [Resource.VersionID, Resource.ResourceID]),)

The error message I am getting is:

InvalidRequestError: Mapper 'Mapper|Resourcesegment|resourcesegment' has no property 'resource'


答: In C++, "interface" is just a non-technical term for a class containing only or mostly pure virtual functions.  An implementation of that interface will inherit the interface class, and the interface class has a "real" base class subobject within the complete object.  The base class subobject has an address and occupies memory like any other object, so we can have a pointer to it.</p>

Title: Pointers to Interfaces c++

Body:
Disclaimer: I am a complete C++ beginner, and if there is a similar answer to this question, please direct me to it, as I may have missed it, not knowing much in the way of theory.

So I was looking through some c++ code, and I found something like this:

shared_ptr<anObjectsInterface>

Which got me wondering, how can there be a pointer to an interface? Surely a pointer points to an object in memory, or am I reading something wrong here.

Thank you


问:
Simple way to count number of specific elements in 2D array Python
I'm looking for a way to count how many instances of a specific character there are in a 2D array that I'm working with. For example, when I print the array out, it can look like this:

```<code>[['.', '.'], ['.', 'R']]
</code>```

Occasionally this array will be much larger, and I'm looking for a nice way to get the number of instances of something like 'R' for example, so that I can use it in a future if statement.

答:
Unless I completely misunderstood your question, this should fit you nicely.

```<code>def count_chars(char, list):
    count = 0
    for element in list:
        count += element.count(char)
    return count
</code>```

I'm sure there is a more performant way of doing this but I'll leave that for you to explore ;)

Body:
I'm looking for a way to count how many instances of a specific character there are in a 2D array that I'm working with. For example, when I print the array out, it can look like this:

[['.', '.'], ['.', 'R']]

Occasionally this array will be much larger, and I'm looking for a nice way to get the number of instances of something like 'R' for example, so that I can use it in a future if statement.

Body:
Unless I completely misunderstood your question, this should fit you nicely.

def count_chars(char, list):
    count = 0
    for element in list:
        count += element.count(char)
    return count

I'm sure there is a more performant way of doing this but I'll leave that for you to explore ;)


问:
using prepared statments with MYSQL http plugin
I am interested in using the MySQL HTTP plugin, using the sql endpoint to execute arbitrary sql via a web request.  However, is there any way to used prepared statements with the HTTP plugin sql endpoint?  I can't seem to find any information about this

This is MySQL http plugin :  https://scriptingmysql.wordpress.com/2015/01/15/mysql-5-7-labs-and-the-http-plugin-inserting-updating-and-deleting-records-in-mysql-via-http/

答:
It looks like for now the answer is no. From the documentation:

The HTTP SQL endpoint does not support prepared statements. Prepared statements prepare a statement once, then allow multiple executions. For this, a client sends a statement to the server to be prepared. The server replies with a handle for the prepared statement. Then, the client sends parameter values for bound parameters, if any, before the statement gets executed. This prepared statement protocol requires session support, which is not available.

The documentation seems to be provided only as a PDF file, so that's highly annoying, but you can download it from the Labs site.


问:
Can I self submit back to a textarea box?
I am able to create a textarea box that will accept text and store that text to the $_POST super global, but I can't get the text to "come back" to the box once I submit it.  (The form is self submitting).  If I run a simple echo on the submitted data, however, it displays fine (as shown toward the end of the script below.

```<code><!DOCTYPE html> <body> <?php require("Connection_to_WS.php");
echo ("<form action='Edit_Thread_Description.php' method='post'>");

IF (ISSET($_POST['revised_thread_descr'])) {
$revised_thread_descr=($_POST['revised_thread_descr']);
ECHO "Edit the Revised_Thread_Description here: <br> <textarea name='revised_thread_descr' rows='5' cols='50' value= $_POST[revised_thread_descr]";      // Fails to return any text on Submit.
?><p></textarea></p><br><?php
}
ELSE {$revised_thread_descr= '[some default]';
ECHO "Edit the Revised_Thread_Description here: <br> <textarea name= 'revised_thread_descr' rows='5' cols='50' value= $revised_thread_descr";
?><p></textarea></p><br><?php
}
ECHO '<br>';
echo $_POST['revised_thread_descr'];  // Succeeds in returning POST text from the textarea box upon Submit (but outside of the textarea box).
ECHO '<br>';
echo "Click 'Submit': <input type='Submit' name='submit' value='Submit'/>";
echo '<br>';
mysqli_close($connection);
?>
</body> </html>
</code>```

Doing the same sort of thing was a breeze using "<input type", but I've sunk hours into getting <textarea to cooperate.  I   I'd be grateful for any assistance.

答:
Bless you!  I'd given up and was going for a workaround.  I put in that tag caret as you suggested and it all worked.  Here is the gist of it, with everything working, and the textarea box populating correctly.  Thank you so much for your patience and persistence.  Tell me it gets easier... .</p>

```<code><!DOCTYPE html> <body>
<?php
echo ("<form action='Textarea_Example.php' method='post'>");

// The first IF only executes after the script has run once and created a POST value.  On the second run, the first IF executes and successfully populates the textarea box with the latest POSTed value
IF (ISSET($_POST['revised_thread_descr'])): ?>
<p>Edit current thread description:<p>
<textarea name= 'revised_thread_descr' rows='5' cols='50'>
<?php echo $_POST['revised_thread_descr'] ?>
</textarea>

<?php ELSE:
$revised_thread_descr = 'some default'; ?>
<p>Edit current thread description:<p>
<p><textarea name= 'revised_thread_descr' rows='5' cols='50'>
The textarea box opens with this in it, but only on the first run.  Then it successfully switches to the value typed to the textarea box and saved to POST
</textarea>
<?php ENDIF; ?>
</p>
<?php
// here's the submit button
echo "Click 'Submit': <input type='Submit' name='submit' value='Submit'/>";
?>
</body> </html>
</code>```

Body:
I am able to create a textarea box that will accept text and store that text to the $_POST super global, but I can't get the text to "come back" to the box once I submit it.  (The form is self submitting).  If I run a simple echo on the submitted data, however, it displays fine (as shown toward the end of the script below.

<!DOCTYPE html>  <?php require("Connection_to_WS.php");
echo ("<form action='Edit_Thread_Description.php' method='post'>");

IF (ISSET($_POST['revised_thread_descr'])) {
$revised_thread_descr=($_POST['revised_thread_descr']);
ECHO "Edit the Revised_Thread_Description here:
 <textarea name='revised_thread_descr' rows='5' cols='50' value= $_POST[revised_thread_descr]";      // Fails to return any text on Submit.
?>
</textarea>

<?php
}
ELSE {$revised_thread_descr= '[some default]';
ECHO "Edit the Revised_Thread_Description here:
 <textarea name= 'revised_thread_descr' rows='5' cols='50' value= $revised_thread_descr";
?>
</textarea>

<?php
}
ECHO '
';
echo $_POST['revised_thread_descr'];  // Succeeds in returning POST text from the textarea box upon Submit (but outside of the textarea box).
ECHO '
';
echo "Click 'Submit': <input type='Submit' name='submit' value='Submit'/>";
echo '
';
mysqli_close($connection);
?>

Doing the same sort of thing was a breeze using "<input type", but I've sunk hours into getting <textarea to cooperate.  I   I'd be grateful for any assistance.

Body:
Bless you!  I'd given up and was going for a workaround.  I put in that tag caret as you suggested and it all worked.  Here is the gist of it, with everything working, and the textarea box populating correctly.  Thank you so much for your patience and persistence.  Tell me it gets easier... .

<!DOCTYPE html> <body>
<?php
echo ("<form action='Textarea_Example.php' method='post'>");

// The first IF only executes after the script has run once and created a POST value.  On the second run, the first IF executes and successfully populates the textarea box with the latest POSTed value
IF (ISSET($_POST['revised_thread_descr'])): ?>
<p>Edit current thread description:<p>
<textarea name= 'revised_thread_descr' rows='5' cols='50'>
<?php echo $_POST['revised_thread_descr'] ?>
</textarea>

<?php ELSE:
$revised_thread_descr = 'some default'; ?>
<p>Edit current thread description:<p>
<p><textarea name= 'revised_thread_descr' rows='5' cols='50'>
The textarea box opens with this in it, but only on the first run.  Then it successfully switches to the value typed to the textarea box and saved to POST
</textarea>
<?php ENDIF; ?>
</p>
<?php
// here's the submit button
echo "Click 'Submit': <input type='Submit' name='submit' value='Submit'/>";
?>
</body> </html>


问:
first request to ActiveRecord boolean field with false value gives true in rails 3
I have such code in my view:

```<code><% @items.each do |item| %>
<tr<%= raw(item.presence ? '' : ' class="opaque"') %>>
...
<td><%= item.presence ? 'Yes' : 'No' %></td>
</tr>
<% end %>
</code>```

this is request in controller:

```<code>@items = Item.where(:type_id => @type.id).order('brand ASC, name ASC').limit(limit).offset((@page-1)*limit)
</code>```

'presence' field is just bool, nil in first item
Despite the fact that the first acquired item's presence field is nil, it doesn't return class attr for the first row (like it is not nil or true), but the second check returns right value ('No'). In the other rows with false or nil values it returns right values in both checks. Is it a bug, or I'm doing smth wrong?

Rails 3.0.0, Postgres 8.4

答:
does adding the ? to presence  help...</p>

```<code><% @items.each do |item| %>
<tr<%= raw(item.presence? ? '' : ' class="opaque"') %>>
...
<td><%= item.presence? ? 'Yes' : 'No' %></td>
</tr>
<% end %>
</code>```

Body:
I have such code in my view:

<% @items.each do |item| %>
<tr<%= raw(item.presence ? '' : ' class="opaque"') %>>
...
<%= item.presence ? 'Yes' : 'No' %>

<% end %>

this is request in controller:

@items = Item.where(:type_id => @type.id).order('brand ASC, name ASC').limit(limit).offset((@page-1)*limit)

'presence' field is just bool, nil in first item
Despite the fact that the first acquired item's presence field is nil, it doesn't return class attr for the first row (like it is not nil or true), but the second check returns right value ('No'). In the other rows with false or nil values it returns right values in both checks. Is it a bug, or I'm doing smth wrong?

Rails 3.0.0, Postgres 8.4

Body:
does adding the ? to presence  help...

<% @items.each do |item| %>
<tr<%= raw(item.presence? ? '' : ' class="opaque"') %>>
...
<td><%= item.presence? ? 'Yes' : 'No' %></td>
</tr>
<% end %>


问:
How to draw on top of an image in Java?
I used JFrame to import and display an image, and used mousemotionlistener to detect the mouse clicks, and I want to be able to draw on top of the image. I want to be able to, if the user makes a click, make that pixel a certain color while preserving the rest of the image, however, I couldn't find out how to use Graphics to do so without deleting the rest of the image or opening a new window. </p>

```<code>public class Simple extends JFrame{
  static ImageIcon icon;
  static JFrame myframe;
  static JLabel mylabel;
  static BufferedImage image = null;
  public static void main(String[] args) {
    try{
      image = ImageIO.read(new File("mypic.png"));
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    icon=new ImageIcon(image);
    myframe=new JFrame();
    myframe.setSize(200,200);
    myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mylabel=new JLabel();
    mylabel.setIcon(icon);
    myframe.getContentPane().add(mylabel);
    myframe.pack();
    Container container = myframe.getContentPane();
    MouseMotionEvents3 mousemotion = new MouseMotionEvents3();
    container.add(mousemotion);
    myframe.setVisible(true);
    while(1 == 1) {
      if(mousemotion.signal == true) {
        System.out.println("second message");
        mousemotion.signal = false;
      }
    }
  }
}
  class MouseMotionEvents3 extends JPanel implements MouseListener,
    MouseMotionListener {
    public boolean signal;
    public MouseMotionEvents3() {
      addMouseListener(this);
      addMouseMotionListener(this);
      signal = false;
    }
    public void mouseClicked(MouseEvent me) {
     // System.out.println("i hate you");
    }

    public void mouseEntered(MouseEvent me) {
    }

    public void mouseExited(MouseEvent me) {
    }

    public void mousePressed(MouseEvent me) {
      signal = true;
      System.out.println("message");
    }

    public void mouseReleased(MouseEvent me) {
    }

    public void mouseDragged(MouseEvent me) {
    }

    public void mouseMoved(MouseEvent me) {
    }
  }
</code>```

答:
I figured it out, I can use the getGraphics() method of the JFrame to allow myself to draw on top of the image.

edit: Andrew Thompson is right, minimizing the window removes the changes.

Title: How to draw on top of an image in Java?

Body:
I used JFrame to import and display an image, and used mousemotionlistener to detect the mouse clicks, and I want to be able to draw on top of the image. I want to be able to, if the user makes a click, make that pixel a certain color while preserving the rest of the image, however, I couldn't find out how to use Graphics to do so without deleting the rest of the image or opening a new window.

public class Simple extends JFrame{
  static ImageIcon icon;
  static JFrame myframe;
  static JLabel mylabel;
  static BufferedImage image = null;
  public static void main(String[] args) {
    try{
      image = ImageIO.read(new File("mypic.png"));
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    icon=new ImageIcon(image);
    myframe=new JFrame();
    myframe.setSize(200,200);
    myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mylabel=new JLabel();
    mylabel.setIcon(icon);
    myframe.getContentPane().add(mylabel);
    myframe.pack();
    Container container = myframe.getContentPane();
    MouseMotionEvents3 mousemotion = new MouseMotionEvents3();
    container.add(mousemotion);
    myframe.setVisible(true);
    while(1 == 1) {
      if(mousemotion.signal == true) {
        System.out.println("second message");
        mousemotion.signal = false;
      }
    }
  }
}
  class MouseMotionEvents3 extends JPanel implements MouseListener,
    MouseMotionListener {
    public boolean signal;
    public MouseMotionEvents3() {
      addMouseListener(this);
      addMouseMotionListener(this);
      signal = false;
    }
    public void mouseClicked(MouseEvent me) {
     // System.out.println("i hate you");
    }

    public void mouseEntered(MouseEvent me) {
    }

    public void mouseExited(MouseEvent me) {
    }

    public void mousePressed(MouseEvent me) {
      signal = true;
      System.out.println("message");
    }

    public void mouseReleased(MouseEvent me) {
    }

    public void mouseDragged(MouseEvent me) {
    }

    public void mouseMoved(MouseEvent me) {
    }
  }


问:
DateTimPicker Validation (Yesterday)
I would like to ask a question
So i have a datetimepicker
So if i put the date from yesterday it will show a message that is "Invalid Date"

My aim is the date that should use is the only date today and the yesterday date cannot be use anymore

答:
this will accept only date today:</p>

```<code>private void dt_ValueChanged(object sender, EventArgs e)
{
            String dtnow = DateTime.Now.ToString("yyyy-MM-dd");
            if (DateTime.Parse(dt.Text) < DateTime.Parse(dtnow))
            {
                MessageBox.Show("Invalid Date");
                //Return the date now
                dt.Text = DateTime.Parse(dtnow).ToString("yyyy-MM-dd");
            }
}
</code>```

Title: DateTimPicker Validation (Yesterday)

Body:
this will accept only date today:

private void dt_ValueChanged(object sender, EventArgs e)
{
            String dtnow = DateTime.Now.ToString("yyyy-MM-dd");
            if (DateTime.Parse(dt.Text) < DateTime.Parse(dtnow))
            {
                MessageBox.Show("Invalid Date");
                //Return the date now
                dt.Text = DateTime.Parse(dtnow).ToString("yyyy-MM-dd");
            }
}


问:
How do I implement no hold and wait to prevent a deadlock
I have written an intentionally deadlocked code which has 2 locks and the way I'm deadlocking the program is like this:

```<code>void ThreadAtWork1(){
  m1.lock();
  cout<<"Thread 1 has been called\n";
  m2.lock();
  m1.unlock();
  m2.unlock();
}

void ThreatAtWork2(){
  m2.lock();
  cout<<"Thread 2 has been called\n";
  m1.lock();
  m2.unlock();
  m1.unlock();

}
</code>```

How can I implement a no 'hold and wait' solution to stop the program from deadlocking? I know I can just re-order the locks but that won't solve the no hold and wait solution.

My main function:

```<code>int main(int argc, const char * argv[]) {

thread t1(ThreadAtWork1);
thread t2(ThreatAtWork2);

t1.join();
t2.join();

cout<<"\nMain exited...\n";

return 0;
}
</code>```

Thanks.

答:
I suspect the "no hold and wait" is a general principle where you try to avoid making blocking calls while having a mutex locked. Doing that may easily cause a deadlock unless you are very careful.

If you do have to have two mutexes locked at the same time, "no hold and wait" is not an option for you.

Often you can re-design your system not to require having two mutexes locked at the same time. For instance, it's totally OK to have more than one condition variable associated with the same mutex.

Body:
I have written an intentionally deadlocked code which has 2 locks and the way I'm deadlocking the program is like this:

void ThreadAtWork1(){
  m1.lock();
  cout<<"Thread 1 has been called\n";
  m2.lock();
  m1.unlock();
  m2.unlock();
}

void ThreatAtWork2(){
  m2.lock();
  cout<<"Thread 2 has been called\n";
  m1.lock();
  m2.unlock();
  m1.unlock();

}

How can I implement a no 'hold and wait' solution to stop the program from deadlocking? I know I can just re-order the locks but that won't solve the no hold and wait solution.

My main function:

int main(int argc, const char * argv[]) {

thread t1(ThreadAtWork1);
thread t2(ThreatAtWork2);

t1.join();
t2.join();

cout<<"\nMain exited...\n";

return 0;
}

Thanks.


问:
jQuery add # to all internal links
Can someone tell me how to add hashes to all the internal links on a page?

For example:

```<code>page.html > page.html#
</code>```

Thank you,
d

答:
You can pass a function to .attr() like this:

```<code>$("a").attr("href", function(i, href) { return href + "#"; });
</code>```

Though...I'm not sure on your reasoning for this, do you want to scroll to the top of the current page?  In that case you can use .scrollTop() with a setter, like this:

```<code>$("a").click(function() { $("html, body").scrollTop(0); });
</code>```

Or .animate() it:

```<code>$("a").click(function() { $("html, body").animate({scrollTop: 0 }, 500); });
</code>```

Title: jQuery add # to all internal links

Body:
Can someone tell me how to add hashes to all the internal links on a page?

For example:

page.html > page.html#

Thank you,
d

Body:
You can pass a function to .attr() like this:

$("a").attr("href", function(i, href) { return href + "#"; });

Though...I'm not sure on your reasoning for this, do you want to scroll to the top of the current page?  In that case you can use .scrollTop() with a setter, like this:

$("a").click(function() { $("html, body").scrollTop(0); });

Or .animate() it:

$("a").click(function() { $("html, body").animate({scrollTop: 0 }, 500); });


问:
Execution fail with Value::getName and Value::HasName (LLVM)
Im doing a program to list all function calls of .ll files.

Here is my code:

```<code>void foo (const Module *M) {
    for (const Function &F : *M) {
        for (const BasicBlock &BB : F) {
            for (const Instruction &I : BB) {
                // CallInst: represents a function call
                if (dyn_cast<CallInst>(&I)) {
                    StringRef name = dyn_cast<CallInst>(&I)->getCalledFunction()->getName();
                    std::cout << name.str() << "\n";
                ...
                ...
</code>```

The problem is in line 7.
In this file: https://pastebin.com/vYhVf4qS

When my program with all my test files, there is no problem, but when I test with this one, this error appears:

```<code>#0 0x0000000000427d10 llvm::sys::PrintStackTrace(llvm::raw_ostream&) /ubuntu/llvm/llvm-3.9.0.src/lib/Support/Unix/Signals.inc:402:0
#1 0x00000000004280af PrintStackTraceSignalHandler(void*) /ubuntu/llvm/llvm-3.9.0.src/lib/Support/Unix/Signals.inc:470:0
#2 0x0000000000426157 llvm::sys::RunSignalHandlers() /ubuntu/llvm/llvm-3.9.0.src/lib/Support/Signals.cpp:44:0
#3 0x0000000000427557 SignalHandler(int) /ubuntu/llvm/llvm-3.9.0.src/lib/Support/Unix/Signals.inc:256:0
#4 0x00007fbde269c390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390)
#5 0x000000000040b402 llvm::Value::hasName() const /ubuntu/llvm/llvm-3.9.0.src/include/llvm/IR/Value.h:233:0
#6 0x000000000040afa7 buildFunctionsCallMap[abi:cxx11](llvm::Module const*) /foo/PrintCallingFunctions.cpp:50:0
#7 0x000000000040b168 printCallingFuntions(llvm::Module const*) /foo/PrintCallingFunctions.cpp:75:0
#8 0x00000000004070bf main ...../main.cpp:76:0
#9 0x00007fbde15f3830 __libc_start_main /build/glibc-9tT8Do/glibc-2.23/csu/../csu/libc-start.c:325:0
#10 0x0000000000406bb9 _start (../../../build/bin/foo+0x406bb9)
Stack dump:
0.  Program arguments: ../../../build/bin/foo QLA_D3_c1_veq_V_dot_V.ll
</code>```

The problem seems to be when I call to getName() function, that calls hasName(), and this last one gives the error, but I dont understand why and I dont know to solve

答:
It's possible that getCalledFunction() returns null if the call is an indirect call through a function pointer. I looked in your IR file and the calls look like this:

```<code>%14 = call i32 (i32, { double, double }*, ...) bitcast (i32 (...)* @__alignx to i32 (i32, { double, double }*, ...)*)(i32 16, { double, double }* %13)
</code>```

The call target is a bitcast constant expression, so that's likely the issue. You can use getCalledValue() instead -- in this case it would return a ConstantExpr representing the bitcast, and you could try to use stripPointerCasts() to get at the function itself.

Body:
Im doing a program to list all function calls of .ll files.

Here is my code:

void foo (const Module *M) {
    for (const Function &F : *M) {
        for (const BasicBlock &BB : F) {
            for (const Instruction &I : BB) {
                // CallInst: represents a function call
                if (dyn_cast<CallInst>(&I)) {
                    StringRef name = dyn_cast<CallInst>(&I)->getCalledFunction()->getName();
                    std::cout << name.str() << "\n";
                ...
                ...

The problem is in line 7.
In this file: https://pastebin.com/vYhVf4qS

When my program with all my test files, there is no problem, but when I test with this one, this error appears:

#0 0x0000000000427d10 llvm::sys::PrintStackTrace(llvm::raw_ostream&) /ubuntu/llvm/llvm-3.9.0.src/lib/Support/Unix/Signals.inc:402:0
#1 0x00000000004280af PrintStackTraceSignalHandler(void*) /ubuntu/llvm/llvm-3.9.0.src/lib/Support/Unix/Signals.inc:470:0
#2 0x0000000000426157 llvm::sys::RunSignalHandlers() /ubuntu/llvm/llvm-3.9.0.src/lib/Support/Signals.cpp:44:0
#3 0x0000000000427557 SignalHandler(int) /ubuntu/llvm/llvm-3.9.0.src/lib/Support/Unix/Signals.inc:256:0
#4 0x00007fbde269c390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390)
#5 0x000000000040b402 llvm::Value::hasName() const /ubuntu/llvm/llvm-3.9.0.src/include/llvm/IR/Value.h:233:0
#6 0x000000000040afa7 buildFunctionsCallMap[abi:cxx11](llvm::Module const*) /foo/PrintCallingFunctions.cpp:50:0
#7 0x000000000040b168 printCallingFuntions(llvm::Module const*) /foo/PrintCallingFunctions.cpp:75:0
#8 0x00000000004070bf main ...../main.cpp:76:0
#9 0x00007fbde15f3830 __libc_start_main /build/glibc-9tT8Do/glibc-2.23/csu/../csu/libc-start.c:325:0
#10 0x0000000000406bb9 _start (../../../build/bin/foo+0x406bb9)
Stack dump:
0.  Program arguments: ../../../build/bin/foo QLA_D3_c1_veq_V_dot_V.ll

The problem seems to be when I call to getName() function, that calls hasName(), and this last one gives the error, but I dont understand why and I dont know to solve

Body:
It's possible that getCalledFunction() returns null if the call is an indirect call through a function pointer. I looked in your IR file and the calls look like this:

%14 = call i32 (i32, { double, double }*, ...) bitcast (i32 (...)* @__alignx to i32 (i32, { double, double }*, ...)*)(i32 16, { double, double }* %13)

The call target is a bitcast constant expression, so that's likely the issue. You can use getCalledValue() instead -- in this case it would return a ConstantExpr representing the bitcast, and you could try to use stripPointerCasts() to get at the function itself.


问:
Letter guessing game Java
I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!

I want the user to try and guess the letter and not the number, but i cannot workout how to do this!

(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)

```<code>Random r = new Random();

char targetLetter = (char)(r.nextInt(26) + 'a');
</code>```

Any help would be greatly appreciated! And i can display my code if it is needed

```<code>public class Stack {

    public static void main(String[] args) {

        Random rand = new Random(); //This is were the computer selects the Target

        int guess;
        int numGuesses = 0;
        int Target;
        String userName;
        String playagain;
        boolean play = true;
        int session = 0;
        int sessions = 0;
        int bestScore = 0;

        Scanner consoleIn = new Scanner(System.in);
        Scanner name = new Scanner(System.in);

        System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
        userName = name.nextLine();

        System.out.println("Hello " + userName + " :) Welcome to the game!\n");

        while (play = true) {
            session++;
            Target = rand.nextInt(26) + 1;
            System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

            do {
                guess = consoleIn.nextInt();
                numGuesses++;

                if (guess > 26)
                    System.out.println("Error! Above MAXIMUM range");
                else if (guess <= 0)
                    System.out.println("Error! Below MINIMUM range");
                else if (guess > Target)
                    System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
                else if (guess < Target)
                    System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
            } while (guess != Target && numGuesses < 5);

            if (guess == Target) {
                System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                sessions++;
            } else {
                System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer
            }
            {
                Scanner answer = new Scanner(System.in);
                System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
                playagain = answer.nextLine();
                if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
                    play = true;
                    numGuesses = 0;
                } else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
                    play = false;
                    System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
                    System.out.println("You had  " + session + " Goes");
                    System.out.println("The number of times you guessed correctly: " + sessions + "");
                    break;
                }
            }
        }
    }
}
</code>```

答:
You can implement it in this approach :

1- Create a String alphabet with the characters that you want.

2- declare the size of alphabet as n variable which will control the random generator range.

3- alphabet.charAt(random.nextInt(n)) is a random char from the alphabet.

program code will be :

```<code>String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int n = alphabet.length();

Random r = new Random();

System.out.println(alphabet.charAt(r.nextInt(n)));
</code>```

hope will help solve your problem.

Title: Letter guessing game Java

Body:
I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!

I want the user to try and guess the letter and not the number, but i cannot workout how to do this!

(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)

Random r = new Random();

char targetLetter = (char)(r.nextInt(26) + 'a');

Any help would be greatly appreciated! And i can display my code if it is needed

public class Stack {

    public static void main(String[] args) {

        Random rand = new Random(); //This is were the computer selects the Target

        int guess;
        int numGuesses = 0;
        int Target;
        String userName;
        String playagain;
        boolean play = true;
        int session = 0;
        int sessions = 0;
        int bestScore = 0;

        Scanner consoleIn = new Scanner(System.in);
        Scanner name = new Scanner(System.in);

        System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
        userName = name.nextLine();

        System.out.println("Hello " + userName + " :) Welcome to the game!\n");

        while (play = true) {
            session++;
            Target = rand.nextInt(26) + 1;
            System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have

            do {
                guess = consoleIn.nextInt();
                numGuesses++;

                if (guess > 26)
                    System.out.println("Error! Above MAXIMUM range");
                else if (guess <= 0)
                    System.out.println("Error! Below MINIMUM range");
                else if (guess > Target)
                    System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
                else if (guess < Target)
                    System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
            } while (guess != Target && numGuesses < 5);

            if (guess == Target) {
                System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
                sessions++;
            } else {
                System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!");  //This tells the player that they failed to find the number and then tells them what the correct answer
            }
            {
                Scanner answer = new Scanner(System.in);
                System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
                playagain = answer.nextLine();
                if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
                    play = true;
                    numGuesses = 0;
                } else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
                    play = false;
                    System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
                    System.out.println("You had  " + session + " Goes");
                    System.out.println("The number of times you guessed correctly: " + sessions + "");
                    break;
                }
            }
        }
    }
}

Body:
You can implement it in this approach :

1- Create a String alphabet with the characters that you want.

2- declare the size of alphabet as n variable which will control the random generator range.

3- alphabet.charAt(random.nextInt(n)) is a random char from the alphabet.

program code will be :

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int n = alphabet.length();

Random r = new Random();

System.out.println(alphabet.charAt(r.nextInt(n)));

hope will help solve your problem.


问:
Making a Callback for AJAX Requests to return the response to the caller
I've looked all over the place and none of the answers I've found have been able to help me out with this problem. Basically I have a function that calls a separate function to make an XMLHttpRequest. The request goes to a server, which generates a random number and returns it to the page.

The problem is that while the request is fetching the data, the caller function continues through its commands. I need to have the data from the request before the caller can move forward. People have mentioned callbacks and promises, neither of which I have been able to grasp with what's available online. I'd rather use callbacks because promises aren't supported in all browsers. Can someone please help walk me through how to use them? I can provide some of the code that I have if needed.

Here's my caller function:

```<code>function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

getRequest();
console.log("x = "+x);
console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
... //rest of the function commands
}
</code>```

Here's my XML Request:

```<code>function getRequest()
{
var request;

if (window.XMLHttpRequest)
{ // Mozilla, Safari, IE7+ ...
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // IE 6 and older
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
    request.onreadystatechange = function()
    {
        console.log('onReady');
        if (request.readyState === XMLHttpRequest.DONE)
        {
            if (request.status === 200)
            {
                random = request.responseText;
                random = parseInt(random);
                random = random/100;
                random = random.toFixed(2);
                console.log("random = " +random);
                data[1] = random;
                console.log("data = "+data[0]+", "+data[1]);
            }
        else
        {
            alert ('There was a problem with the request');
        }

        }
}
request.open("GET", "lak1010_hw05.php", true);
request.send();
}
</code>```

答:
Here is your modified getRequest function with the callback,

```<code>function getRequest(callback)
{
var request;

if (window.XMLHttpRequest)
{ // Mozilla, Safari, IE7+ ...
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // IE 6 and older
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
    request.onreadystatechange = function()
    {
        console.log('onReady');
        if (request.readyState === XMLHttpRequest.DONE)
        {
            if (request.status === 200)
            {
                random = request.responseText;
                random = parseInt(random);
                random = random/100;
                random = random.toFixed(2);
                console.log("random = " +random);
                data[1] = random;
                console.log("data = "+data[0]+", "+data[1]);
                // here call your callback
                callback(random);
            }
        else
        {
            alert ('There was a problem with the request');
        }

        }
}
request.open("GET", "lak1010_hw05.php", true);
request.send();
}
</code>```

Your calling method,

```<code>function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

getRequest(function(random){
   console.log('Random number received:');
   console.log(random);
});
console.log("x = "+x);
console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
... //rest of the function commands
}
</code>```

Body:
I've looked all over the place and none of the answers I've found have been able to help me out with this problem. Basically I have a function that calls a separate function to make an XMLHttpRequest. The request goes to a server, which generates a random number and returns it to the page.

The problem is that while the request is fetching the data, the caller function continues through its commands. I need to have the data from the request before the caller can move forward. People have mentioned callbacks and promises, neither of which I have been able to grasp with what's available online. I'd rather use callbacks because promises aren't supported in all browsers. Can someone please help walk me through how to use them? I can provide some of the code that I have if needed.

Here's my caller function:

function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

getRequest();
console.log("x = "+x);
console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
... //rest of the function commands
}

Here's my XML Request:

function getRequest()
{
var request;

if (window.XMLHttpRequest)
{ // Mozilla, Safari, IE7+ ...
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // IE 6 and older
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
    request.onreadystatechange = function()
    {
        console.log('onReady');
        if (request.readyState === XMLHttpRequest.DONE)
        {
            if (request.status === 200)
            {
                random = request.responseText;
                random = parseInt(random);
                random = random/100;
                random = random.toFixed(2);
                console.log("random = " +random);
                data[1] = random;
                console.log("data = "+data[0]+", "+data[1]);
            }
        else
        {
            alert ('There was a problem with the request');
        }

        }
}
request.open("GET", "lak1010_hw05.php", true);
request.send();
}

Body:
Here is your modified getRequest function with the callback,

function getRequest(callback)
{
var request;

if (window.XMLHttpRequest)
{ // Mozilla, Safari, IE7+ ...
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{ // IE 6 and older
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
    request.onreadystatechange = function()
    {
        console.log('onReady');
        if (request.readyState === XMLHttpRequest.DONE)
        {
            if (request.status === 200)
            {
                random = request.responseText;
                random = parseInt(random);
                random = random/100;
                random = random.toFixed(2);
                console.log("random = " +random);
                data[1] = random;
                console.log("data = "+data[0]+", "+data[1]);
                // here call your callback
                callback(random);
            }
        else
        {
            alert ('There was a problem with the request');
        }

        }
}
request.open("GET", "lak1010_hw05.php", true);
request.send();
}

Your calling method,

function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

getRequest(function(random){
   console.log('Random number received:');
   console.log(random);
});
console.log("x = "+x);
console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
... //rest of the function commands
}


问:
Strange output when running Go Benchmark
I'm trying to write a benchmark function for a simple echo program in Go (Exercise 1.3 from "The Go Programming Language" book). Here is the code:

```<code>package echo

import "testing"

func BenchmarkEcho1(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Echo1()
    }
}
</code>```

When I run go test -bench=. the output is this:

```<code>PASS
BenchmarkEcho1-4    -test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
[...]
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
 1000000          1358 ns/op
ok      gopl.io/ch1/exercise1.3/echo    1.377s
</code>```

There a lot of -test.bench=Echo1 between the first and the last lines. Why is this happening? What can I do to omit these lines?

答:
You understand that b.N has a really big value and thus Echo1 gets executed many many times ?
The only explanation is that Echo1 is printing the text you are seeing.

Your Echo1() function probably contains something like this:

```<code>var s string
for i := 1; i < len(os.Args); i++ {
    s += os.Args[i]
}
fmt.Println(s)
</code>```

https://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go

Body:
I'm trying to write a benchmark function for a simple echo program in Go (Exercise 1.3 from "The Go Programming Language" book). Here is the code:

package echo

import "testing"

func BenchmarkEcho1(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Echo1()
    }
}

When I run go test -bench=. the output is this:

PASS
BenchmarkEcho1-4    -test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
[...]
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
 1000000          1358 ns/op
ok      gopl.io/ch1/exercise1.3/echo    1.377s

There a lot of -test.bench=Echo1 between the first and the last lines. Why is this happening? What can I do to omit these lines?

Body:
You understand that b.N has a really big value and thus Echo1 gets executed many many times ?
The only explanation is that Echo1 is printing the text you are seeing.

Your Echo1() function probably contains something like this:

var s string
for i := 1; i < len(os.Args); i++ {
    s += os.Args[i]
}
fmt.Println(s)

https://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go


问:
d3 v4: Stacking nested data?
I have a bunch of data that can be nested into a few categories, e.g.:

```<code>{id: 1, type: A},
{id: 2, type: A},
{id: 1, type: B},
{id: 1, type: A},
{id: 2, type: B}
</code>```

Nesting this data on id gives me nested data with id as the key and a values array which contains all original values. What I need is a stacked chart showing that id 1 has two type A and one type B occurrences, id 2 has one of each, etc. This is the code I'm using:

```<code>var nested = d3.nest()
                .key( function(d) {
                    return d.Id
                })
                .entries(data);

var stack = d3.stack()
                .keys(['A','B'])
                .offset(d3.stackOffsetExpand);
</code>```

I want these as percentages hence the stackOffsetExpand. However this is giving me null stack values, presumably because the type field that I want the stack function to use is hidden inside the values array. Using the .value function of the stack call I can see that the data it's seeing is indeed the whole chunk of data for each nested array (i.e. key: 1, values: [{all objects with id 1 here}]). I just don't know how to use that function to tell it to start counting on the type property...

答:
This is one way to calculate the percentage from your data. I'm setting the keys first and then rolling up the values in the nest function using rollup. Then, I'm calculating the percentage for each key after that.

```<code>var raw_data = [{id: 1, type: "A"},
{id: 2, type: "A"},
{id: 1, type: "B"},
{id: 1, type: "A"},
{id: 2, type: "B"}];

var data = d3.nest()
    .key(function(d) {return d.id;})
    .rollup(function(d) { return d.length; })
    .entries(raw_data);

    data.forEach(function(d) {
    d.percentage = d.value  / raw_data.length;
    console.log(d.key + ": " + d.percentage*100);
});
</code>```

JSFiddle - https://jsfiddle.net/do4ym1L2/

Title: d3 v4: Stacking nested data?

Body:
I have a bunch of data that can be nested into a few categories, e.g.:

{id: 1, type: A},
{id: 2, type: A},
{id: 1, type: B},
{id: 1, type: A},
{id: 2, type: B}

Nesting this data on id gives me nested data with id as the key and a values array which contains all original values. What I need is a stacked chart showing that id 1 has two type A and one type B occurrences, id 2 has one of each, etc. This is the code I'm using:

var nested = d3.nest()
                .key( function(d) {
                    return d.Id
                })
                .entries(data);

var stack = d3.stack()
                .keys(['A','B'])
                .offset(d3.stackOffsetExpand);

I want these as percentages hence the stackOffsetExpand. However this is giving me null stack values, presumably because the type field that I want the stack function to use is hidden inside the values array. Using the .value function of the stack call I can see that the data it's seeing is indeed the whole chunk of data for each nested array (i.e. key: 1, values: [{all objects with id 1 here}]). I just don't know how to use that function to tell it to start counting on the type property...

Body:
This is one way to calculate the percentage from your data. I'm setting the keys first and then rolling up the values in the nest function using rollup. Then, I'm calculating the percentage for each key after that.

var raw_data = [{id: 1, type: "A"},
{id: 2, type: "A"},
{id: 1, type: "B"},
{id: 1, type: "A"},
{id: 2, type: "B"}];

var data = d3.nest()
    .key(function(d) {return d.id;})
    .rollup(function(d) { return d.length; })
    .entries(raw_data);

    data.forEach(function(d) {
    d.percentage = d.value  / raw_data.length;
    console.log(d.key + ": " + d.percentage*100);
});

JSFiddle - https://jsfiddle.net/do4ym1L2/


问:
DataGrids over ScrollViewer prevent it to scroll
I have multiples DataGrids disposed over a ScrollViewer.
These DataGrids have an "height: auto" property so that I can hide the scrollbar and view all the content.
The only problem is that the DataGrids takes the focus and so I can't scroll the ScrollViewer.
Is that a property to keep the focus on the ScrollViewer but also keeping the behaviour of the DataGrids (so I can select elements) ?

Thank you !

答:
TopMouseScrollPriorityBehavior.TopMouseScrollPriority

You can simply set the following Attached Property to your ScrollViewer

```<code>public class TopMouseScrollPriorityBehavior
{
    public static bool GetTopMouseScrollPriority(DependencyObject obj)
    {
        return (bool)obj.GetValue(TopMouseScrollPriorityProperty);
    }

    public static void SetTopMouseScrollPriority(DependencyObject obj, bool value)
    {
        obj.SetValue(TopMouseScrollPriorityProperty, value);
    }

    public static readonly DependencyProperty TopMouseScrollPriorityProperty =
        DependencyProperty.RegisterAttached("TopMouseScrollPriority", typeof(bool), typeof(TopMouseScrollPriorityBehavior), new PropertyMetadata(false, OnPropertyChanged));

    private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var scrollViewer = d as ScrollViewer;
        if (scrollViewer == null)
            throw new InvalidOperationException($"{nameof(TopMouseScrollPriorityBehavior)}.{nameof(TopMouseScrollPriorityProperty)} can only be applied to controls of type {nameof(ScrollViewer)}");
        if (e.NewValue == e.OldValue)
            return;
        if ((bool)e.NewValue)
            scrollViewer.PreviewMouseWheel += ScrollViewer_PreviewMouseWheel;
        else
            scrollViewer.PreviewMouseWheel -= ScrollViewer_PreviewMouseWheel;
    }

    private static void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
    {
        var scrollViewer = (ScrollViewer)sender;
        scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - e.Delta);
        e.Handled = true;
    }
}
</code>```

Usage

```<code><ScrollViewer b:TopMouseScrollPriorityBehavior.TopMouseScrollPriority="True" VerticalScrollBarVisibility="Auto" Margin="5" PanningMode="VerticalFirst">
    <DataGrid ScrollViewer.PanningMode="None" ItemsSource="{Binding Items}" />
</ScrollViewer>
</code>```

Where b: is the namespace that contains this behavior

Touch Support

To enable touch support you might also want to set ScrollViewer.PanningMode to None on your DataGrid and set the same property to VerticalFirst or other value on your top level ScrollViewer

Example

```<code><ScrollViewer VerticalScrollBarVisibility="Auto" Margin="5" PanningMode="VerticalFirst">
    <DataGrid ScrollViewer.PanningMode="None" ItemsSource="{Binding Items}" />
</ScrollViewer>
</code>```

Body:
TopMouseScrollPriorityBehavior.TopMouseScrollPriority

You can simply set the following Attached Property to your ScrollViewer

public class TopMouseScrollPriorityBehavior
{
    public static bool GetTopMouseScrollPriority(DependencyObject obj)
    {
        return (bool)obj.GetValue(TopMouseScrollPriorityProperty);
    }

    public static void SetTopMouseScrollPriority(DependencyObject obj, bool value)
    {
        obj.SetValue(TopMouseScrollPriorityProperty, value);
    }

    public static readonly DependencyProperty TopMouseScrollPriorityProperty =
        DependencyProperty.RegisterAttached("TopMouseScrollPriority", typeof(bool), typeof(TopMouseScrollPriorityBehavior), new PropertyMetadata(false, OnPropertyChanged));

    private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var scrollViewer = d as ScrollViewer;
        if (scrollViewer == null)
            throw new InvalidOperationException($"{nameof(TopMouseScrollPriorityBehavior)}.{nameof(TopMouseScrollPriorityProperty)} can only be applied to controls of type {nameof(ScrollViewer)}");
        if (e.NewValue == e.OldValue)
            return;
        if ((bool)e.NewValue)
            scrollViewer.PreviewMouseWheel += ScrollViewer_PreviewMouseWheel;
        else
            scrollViewer.PreviewMouseWheel -= ScrollViewer_PreviewMouseWheel;
    }

    private static void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
    {
        var scrollViewer = (ScrollViewer)sender;
        scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - e.Delta);
        e.Handled = true;
    }
}

Usage

<ScrollViewer b:TopMouseScrollPriorityBehavior.TopMouseScrollPriority="True" VerticalScrollBarVisibility="Auto" Margin="5" PanningMode="VerticalFirst">
    <DataGrid ScrollViewer.PanningMode="None" ItemsSource="{Binding Items}" />
</ScrollViewer>

Where b: is the namespace that contains this behavior

Touch Support

To enable touch support you might also want to set ScrollViewer.PanningMode to None on your DataGrid and set the same property to VerticalFirst or other value on your top level ScrollViewer

Example

<ScrollViewer VerticalScrollBarVisibility="Auto" Margin="5" PanningMode="VerticalFirst">
    <DataGrid ScrollViewer.PanningMode="None" ItemsSource="{Binding Items}" />
</ScrollViewer>


问:
How to create table that displays attributes of objects using Flask
I'm trying to make a search that displays results from a SQLAlchemy database query to my users. However, it seems as though what's being returned is an empty list - the table has a header but not other rows. I've checked to make sure I'm getting results, so I don't know what's going wrong. I've tried sending the data in it's original form and as a list of dictionaries but still haven't had any luck. Any insights?

```<code>for result in results:
    resultData = {'system_name':result.system_name,'system_description':result.system_description,'system_tags':[tag.tag_name for tag in result.tags],'system_date_created':result.system_date_created,'system_hits':result.system_hits}
    response.append(resultData)
print response
return render_template('index.html', searchResults=response)
</code>```

index.html

```<code><table class='table table-hover'>
<tr>
<th>Name</th>
<th>Description</th>
<th>Tags</th>
<th>Date Created</th>
<th>Views</th>
</tr>
{% for result in searchResults %}
    <tr>
    <td>{{ result.system_name }}</td>
    <td>{{ result.system_description }}</td>
    <td>Tags</td>
    <td>{{ result.system_date_created }}</td>
    <td>{{ result.system_hits }}</td>
    </tr>
{% endfor %}
</table>
</code>```

答:
Here's a quick example for serving up an html table from some nested data. As suggested, there's also an extra endpoint with jsonify data for debugging.

app.py

```<code>from flask import Flask, render_template, jsonify
import namedtupled as nt  # for debugging

app = Flask(__name__)

# set up some fake data
foo = { 'system_name': 'foo', 'system_description': 'bar',
        'tags': [{'tag_name': 'happy'}, {'tag_name': 'cat'}],
        'system_date_created': 'today', 'system_hits': 100 }
fuu = { 'system_name': 'fuu', 'system_description': 'bor',
        'tags': [{'tag_name': 'cute'}, {'tag_name': 'puppy'}],
        'system_date_created': 'yesterday', 'system_hits': 99 }

# make fake data classy so it fits your example
results = [nt.map(foo), nt.map(fuu)]

def refine_results(results):
    """ Refine some search results. """
    # something here, maybe a request for search results
    data = []
    for result in results:
        resultData = {'system_name': result.system_name,
                      'system_description': result.system_description,
                      'system_tags': [tag.tag_name for tag in result.tags],
                      'system_date_created': result.system_date_created,
                      'system_hits': result.system_hits}
        data.append(resultData)
    return data

@app.route('/json')
def data():
    """ Extra endpoint for debugging expected data. """
    searchResults = refine_results(results)
    return jsonify(searchResults)

@app.route('/table')
def table():
    """ html table with data """
    searchResults = refine_results(results)
    return render_template('index.html', searchResults=searchResults)

if __name__ == '__main__':
    app.run(debug=True)
</code>```

index.html

```<code><table>
  <tr>
    <th>Name</th>
    <th>Description</th>
    <th>Tags</th>
    <th>Date Created</th>
    <th>Views</th>
  </tr>
  {% for result in searchResults %}
      <tr>
        <td>{{ result.system_name }}</td>
        <td>{{ result.system_description }}</td>
        <td>
          {% for tag in result.system_tags %}
            {{tag}}
          {% endfor %}
        </td>
        <td>{{ result.system_date_created }}</td>
        <td>{{ result.system_hits }}</td>
      </tr>
  {% endfor %}
</table>
</code>```

Body:
I'm trying to make a search that displays results from a SQLAlchemy database query to my users. However, it seems as though what's being returned is an empty list - the table has a header but not other rows. I've checked to make sure I'm getting results, so I don't know what's going wrong. I've tried sending the data in it's original form and as a list of dictionaries but still haven't had any luck. Any insights?

for result in results:
    resultData = {'system_name':result.system_name,'system_description':result.system_description,'system_tags':[tag.tag_name for tag in result.tags],'system_date_created':result.system_date_created,'system_hits':result.system_hits}
    response.append(resultData)
print response
return render_template('index.html', searchResults=response)

index.html

Name
Description
Tags
Date Created
Views

{% for result in searchResults %}

    {{ result.system_name }}
    {{ result.system_description }}
    Tags
    {{ result.system_date_created }}
    {{ result.system_hits }}

{% endfor %}

Body:
Here's a quick example for serving up an html table from some nested data. As suggested, there's also an extra endpoint with jsonify data for debugging.

app.py

from flask import Flask, render_template, jsonify
import namedtupled as nt  # for debugging

app = Flask(__name__)

# set up some fake data
foo = { 'system_name': 'foo', 'system_description': 'bar',
        'tags': [{'tag_name': 'happy'}, {'tag_name': 'cat'}],
        'system_date_created': 'today', 'system_hits': 100 }
fuu = { 'system_name': 'fuu', 'system_description': 'bor',
        'tags': [{'tag_name': 'cute'}, {'tag_name': 'puppy'}],
        'system_date_created': 'yesterday', 'system_hits': 99 }

# make fake data classy so it fits your example
results = [nt.map(foo), nt.map(fuu)]

def refine_results(results):
    """ Refine some search results. """
    # something here, maybe a request for search results
    data = []
    for result in results:
        resultData = {'system_name': result.system_name,
                      'system_description': result.system_description,
                      'system_tags': [tag.tag_name for tag in result.tags],
                      'system_date_created': result.system_date_created,
                      'system_hits': result.system_hits}
        data.append(resultData)
    return data

@app.route('/json')
def data():
    """ Extra endpoint for debugging expected data. """
    searchResults = refine_results(results)
    return jsonify(searchResults)

@app.route('/table')
def table():
    """ html table with data """
    searchResults = refine_results(results)
    return render_template('index.html', searchResults=searchResults)

if __name__ == '__main__':
    app.run(debug=True)

index.html

<table>
  <tr>
    <th>Name</th>
    <th>Description</th>
    <th>Tags</th>
    <th>Date Created</th>
    <th>Views</th>
  </tr>
  {% for result in searchResults %}
      <tr>
        <td>{{ result.system_name }}</td>
        <td>{{ result.system_description }}</td>
        <td>
          {% for tag in result.system_tags %}
            {{tag}}
          {% endfor %}
        </td>
        <td>{{ result.system_date_created }}</td>
        <td>{{ result.system_hits }}</td>
      </tr>
  {% endfor %}
</table>


问:
Was javascript argument default?
Is there a way to tell the difference between this

```<code>((a=true)=>{return a})(true)
</code>```

And this?

```<code>((a=true)=>{return a})()
</code>```

They both return true - how can I tell whether that true is coming from the default value of the argument, or from the value passed in to that parameter?

Is it possible from outside the function?

Is it possible from inside the function?

答:
If you really want to use arrow functions, you can achieve a robust (if convoluted) result using Symbol and a wrapping IIFE

```<code>var fn = ((def) =>
    (a = def) => {
        if(a === def) {
            console.log('defaulted');
            a = true;
        }
        console.log('a is', a);
    }
)(Symbol());
</code>```

both fn() and fn(true) will result in a is true - however, fn() will also output defaulted and then set a = true - though this last step I guess doesn't have to done, depends on what the real content of the real function you really want to "detect" this in

Or, a better way as pointed out by @Bergi (I keep forgetting about the block scope in ES6+ :D )

```<code>var fn;
{
    const def = Symbol();
    fn = (a=def) => {
        if(a === def) {
            console.log('defaulted');
            a = true;
        }
        console.log('a is', a);
    };
}
</code>```

Title: Was javascript argument default?

Body:
Is there a way to tell the difference between this

((a=true)=>{return a})(true)

And this?

((a=true)=>{return a})()

They both return true - how can I tell whether that true is coming from the default value of the argument, or from the value passed in to that parameter?

Is it possible from outside the function?

Is it possible from inside the function?

Body:
If you really want to use arrow functions, you can achieve a robust (if convoluted) result using Symbol and a wrapping IIFE

var fn = ((def) =>
    (a = def) => {
        if(a === def) {
            console.log('defaulted');
            a = true;
        }
        console.log('a is', a);
    }
)(Symbol());

both fn() and fn(true) will result in a is true - however, fn() will also output defaulted and then set a = true - though this last step I guess doesn't have to done, depends on what the real content of the real function you really want to "detect" this in

Or, a better way as pointed out by @Bergi (I keep forgetting about the block scope in ES6+ :D )

var fn;
{
    const def = Symbol();
    fn = (a=def) => {
        if(a === def) {
            console.log('defaulted');
            a = true;
        }
        console.log('a is', a);
    };
}


问:
Running Product based on another column
I need to create a "running product" column in Excel. However, the running product is based on another column, a "group". Consider the example below.

Here, Column A is my group, and each group has multiple items in it (column B). Column C is what I need a running product on, and Column D is the output column. Cell D2 is 0.2 because it is the first item in group 0. Cell D3 is 0.02 since it is the product of item 0 and item 1 in group 0. This continues until we get to group 1, which is when the running product "resets" and starts applying the running product only to group 1, so on and so forth.

I'd like to do this with an formula, and not VBA if possible.

答:
In D2 try,

```<code>=PRODUCT(INDEX(C:C, MATCH(A2, A:A, 0)):C2)
</code>```

Title: Running Product based on another column

Body:
In D2 try,

=PRODUCT(INDEX(C:C, MATCH(A2, A:A, 0)):C2)