问:
Save Video Using AVFoundation Swift
Hi I followed a course by Jared Davidson to create a custom camera view and save pictures using AVFoundation.
https://www.youtube.com/watch?v=w0O3ZGUS3pk

However I would like to record and save videos instead of images. Can someone help me here? I'm sure its simple but apple's Documentation is written in Objective-C and I cant decipher it.

This is my code. Thanks.

```<code>import UIKit
import AVFoundation

class ViewController: UIViewController {

    var captureSession = AVCaptureSession()
    var sessionOutput = AVCaptureStillImageOutput()
    var previewLayer = AVCaptureVideoPreviewLayer()

    @IBOutlet var cameraView: UIView!

    override func viewWillAppear(animated: Bool) {

        let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
        for device in devices {
            if device.position == AVCaptureDevicePosition.Front{

                do{

                    let input = try AVCaptureDeviceInput(device: device as! AVCaptureDevice)

                    if captureSession.canAddInput(input){

                        captureSession.addInput(input)
                        sessionOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]

                        if captureSession.canAddOutput(sessionOutput){

                            captureSession.addOutput(sessionOutput)
                            captureSession.startRunning()

                            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                            previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
                            previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
                            cameraView.layer.addSublayer(previewLayer)

                            previewLayer.position = CGPoint(x: self.cameraView.frame.width / 2, y: self.cameraView.frame.height / 2)
                            previewLayer.bounds = cameraView.frame

                        }

                    }

                }
                catch{

                    print("Error")
                }

            }
        }

    }

    @IBAction func TakePhoto(sender: AnyObject) {

        if let videoConnection = sessionOutput.connectionWithMediaType(AVMediaTypeVideo){

            sessionOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
                buffer, error in

                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
                UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData)!, nil, nil, nil)

            })

        }

    }

}
</code>```

答:
For the sound recording issue,

Add this code when creating the captureSession

askMicroPhonePermission(completion: { (isMicrophonePermissionGiven) in

```<code>            if isMicrophonePermissionGiven {
                do {
                    try self.captureSession.addInput(AVCaptureDeviceInput(device: self.captureAudio))
                } catch {
                    print("Error creating the database")
                }
            }
        })
</code>```

////////////////////////////////////////////////////////////////

askMicroPhonePermission function is as follows

```<code>func askMicroPhonePermission(completion: @escaping (_ success: Bool)-> Void) {
    switch AVAudioSession.sharedInstance().recordPermission() {
    case AVAudioSessionRecordPermission.granted:
        completion(true)
    case AVAudioSessionRecordPermission.denied:
        completion(false) //show alert if required
    case AVAudioSessionRecordPermission.undetermined:
        AVAudioSession.sharedInstance().requestRecordPermission({ (granted) in
            if granted {
                completion(true)
            } else {
                completion(false) // show alert if required
            }
        })
    default:
        completion(false)
    }
}
</code>```

And you have to add NSMicrophoneUsageDescription key value in info.plist file.

Title: Save Video Using AVFoundation Swift

Body:
Hi I followed a course by Jared Davidson to create a custom camera view and save pictures using AVFoundation.
https://www.youtube.com/watch?v=w0O3ZGUS3pk

However I would like to record and save videos instead of images. Can someone help me here? I'm sure its simple but apple's Documentation is written in Objective-C and I cant decipher it.

This is my code. Thanks.

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var captureSession = AVCaptureSession()
    var sessionOutput = AVCaptureStillImageOutput()
    var previewLayer = AVCaptureVideoPreviewLayer()

    @IBOutlet var cameraView: UIView!

    override func viewWillAppear(animated: Bool) {

        let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
        for device in devices {
            if device.position == AVCaptureDevicePosition.Front{

                do{

                    let input = try AVCaptureDeviceInput(device: device as! AVCaptureDevice)

                    if captureSession.canAddInput(input){

                        captureSession.addInput(input)
                        sessionOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]

                        if captureSession.canAddOutput(sessionOutput){

                            captureSession.addOutput(sessionOutput)
                            captureSession.startRunning()

                            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                            previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
                            previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
                            cameraView.layer.addSublayer(previewLayer)

                            previewLayer.position = CGPoint(x: self.cameraView.frame.width / 2, y: self.cameraView.frame.height / 2)
                            previewLayer.bounds = cameraView.frame

                        }

                    }

                }
                catch{

                    print("Error")
                }

            }
        }

    }

    @IBAction func TakePhoto(sender: AnyObject) {

        if let videoConnection = sessionOutput.connectionWithMediaType(AVMediaTypeVideo){

            sessionOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
                buffer, error in

                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
                UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData)!, nil, nil, nil)

            })

        }

    }

}

Body:
For the sound recording issue,

Add this code when creating the captureSession

askMicroPhonePermission(completion: { (isMicrophonePermissionGiven) in

            if isMicrophonePermissionGiven {
                do {
                    try self.captureSession.addInput(AVCaptureDeviceInput(device: self.captureAudio))
                } catch {
                    print("Error creating the database")
                }
            }
        })

////////////////////////////////////////////////////////////////

askMicroPhonePermission function is as follows

func askMicroPhonePermission(completion: @escaping (_ success: Bool)-> Void) {
    switch AVAudioSession.sharedInstance().recordPermission() {
    case AVAudioSessionRecordPermission.granted:
        completion(true)
    case AVAudioSessionRecordPermission.denied:
        completion(false) //show alert if required
    case AVAudioSessionRecordPermission.undetermined:
        AVAudioSession.sharedInstance().requestRecordPermission({ (granted) in
            if granted {
                completion(true)
            } else {
                completion(false) // show alert if required
            }
        })
    default:
        completion(false)
    }
}

And you have to add NSMicrophoneUsageDescription key value in info.plist file.


来源: stackexchange

问:
DataInputStream for input text files?
I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?</p>

```<code>import java.io.*;
import java.util.*;

class ReadWriteData
{
    public static void main(String[] args) throws Exception
    {

        //create ouput file
        PrintWriter output = new PrintWriter("output2.txt");

        DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
        DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));

        try
        {

        // read data from file
        while (true)
        {
            double number1 = file1.readDouble();
            double number2 = file2.readDouble();
            double result = number1 * number2 ;
            output.println(result);

        }

        }

        catch (IOException e)
        {
            System.err.println("Error");
            System.exit(1);
        }

        output.close() ;

    }
}
</code>```

答:
Here is an implementation with a BufferedReader that works.

```<code>public static void main(String[] args) throws Exception {
    //create ouput file
    PrintWriter output = new PrintWriter("output2.txt");
    BufferedReader file1 = new BufferedReader(new FileReader("numbers1.txt"));
    BufferedReader file2 = new BufferedReader(new FileReader("numbers2.txt"));

    try {
        // read data from file
        while (true) {
            String number1AsString = file1.readLine();
            String number2AsString = file2.readLine();
            if (number1AsString == null || number2AsString == null) {
                break;
            }
            double number1 = Double.parseDouble(number1AsString);
            double number2 = Double.parseDouble(number2AsString);
            double result = number1 * number2;
            System.out.println("result:" + result);
            output.println(result);
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        output.close();
        file1.close();
        file2.close();
    }
}
</code>```

Edit: Also you may want to modularize your code for instance creating a method that help reduce duplicated code. Also you may be interested to look for NumberFormatException in case any number is not properly formatted or includes letters for example.

```<code>private double readDoubleFromFile(BufferedReader file) throws IOException {
    String numberAsString = file.readLine();
    if (numberAsString == null) {
        throw new IOException();
    }
    double number = Double.parseDouble(numberAsString);
    return number;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: DataInputStream for input text files?

Body:
I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?

import java.io.*;
import java.util.*;

class ReadWriteData
{
    public static void main(String[] args) throws Exception
    {

        //create ouput file
        PrintWriter output = new PrintWriter("output2.txt");

        DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
        DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));

        try
        {

        // read data from file
        while (true)
        {
            double number1 = file1.readDouble();
            double number2 = file2.readDouble();
            double result = number1 * number2 ;
            output.println(result);

        }

        }

        catch (IOException e)
        {
            System.err.println("Error");
            System.exit(1);
        }

        output.close() ;

    }
}

Body:
Here is an implementation with a BufferedReader that works.

public static void main(String[] args) throws Exception {
    //create ouput file
    PrintWriter output = new PrintWriter("output2.txt");
    BufferedReader file1 = new BufferedReader(new FileReader("numbers1.txt"));
    BufferedReader file2 = new BufferedReader(new FileReader("numbers2.txt"));

    try {
        // read data from file
        while (true) {
            String number1AsString = file1.readLine();
            String number2AsString = file2.readLine();
            if (number1AsString == null || number2AsString == null) {
                break;
            }
            double number1 = Double.parseDouble(number1AsString);
            double number2 = Double.parseDouble(number2AsString);
            double result = number1 * number2;
            System.out.println("result:" + result);
            output.println(result);
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        output.close();
        file1.close();
        file2.close();
    }
}

Edit: Also you may want to modularize your code for instance creating a method that help reduce duplicated code. Also you may be interested to look for NumberFormatException in case any number is not properly formatted or includes letters for example.

private double readDoubleFromFile(BufferedReader file) throws IOException {
    String numberAsString = file.readLine();
    if (numberAsString == null) {
        throw new IOException();
    }
    double number = Double.parseDouble(numberAsString);
    return number;
}

ContentLicense: CC BY-SA 2.5


问:
How to continue looping after invalid data type input?
I'm trying to do one check for invalid input data type. If the the input data type is of type char, I want the re-loop over the menu options. But my program terminates instead.

```<code>int menu()
{
    int choice = 15;
    while ((choice > 14) || ( choice < 0))
    {
        cout << "Enter 0 to quit\n";
        cout << "Enter 1 for Addition\n";
        cout << "Enter 2 for Subtraction\n";
        cout << "Enter 3 for Multiplication\n";
        cout << "Enter 4 for Division of two integers\n";
        cout << "Enter 5 for Real Division of two integers\n";
        cout << "Enter 6 for Quotient of a division\n";
        cout << "Enter 7 for Remainder of a division\n";
        cout << "Enter 8 for Factorial of an integer\n";
        cout << "Enter 9 for Exponential of two integers\n";
        cout << "Enter 10 for Finding if number is even or odd\n";
        cout << "Enter 11 for Area of a Square\n";
        cout << "Enter 12 for Area of a Circle\n";
        cout << "Enter 13 for Area of an Isoceles Triangle\n";
        cout << "Enter 14 for Converting Decimal to binary or hexadecimal\n";
        cin >> choice;

        if((choice > 14) || (choice < 0))
        {
            cout << "Invalid entry: Try again" << endl << endl;
        }
        else if ( !choice )
        {
            return choice;
        }
        else if (choice)
        {
            return choice;
        }
    }

    return choice;
}
</code>```

Output after entering char 'f' as cin

答:
Try this instead

```<code>if (cin >> choice)
{
    if((choice > 14) || (choice < 0))
        cout << "Invalid entry: Try again" << endl << endl;
    else
        return choice;
}
else //Fail to cin into choice, user input is not a number
    cout << "Invalid entry: Please key in a number." << endl;
</code>```

Also, the while condition should change to while (true)

Body:
I'm trying to do one check for invalid input data type. If the the input data type is of type char, I want the re-loop over the menu options. But my program terminates instead.

int menu()
{
    int choice = 15;
    while ((choice > 14) || ( choice < 0))
    {
        cout << "Enter 0 to quit\n";
        cout << "Enter 1 for Addition\n";
        cout << "Enter 2 for Subtraction\n";
        cout << "Enter 3 for Multiplication\n";
        cout << "Enter 4 for Division of two integers\n";
        cout << "Enter 5 for Real Division of two integers\n";
        cout << "Enter 6 for Quotient of a division\n";
        cout << "Enter 7 for Remainder of a division\n";
        cout << "Enter 8 for Factorial of an integer\n";
        cout << "Enter 9 for Exponential of two integers\n";
        cout << "Enter 10 for Finding if number is even or odd\n";
        cout << "Enter 11 for Area of a Square\n";
        cout << "Enter 12 for Area of a Circle\n";
        cout << "Enter 13 for Area of an Isoceles Triangle\n";
        cout << "Enter 14 for Converting Decimal to binary or hexadecimal\n";
        cin >> choice;

        if((choice > 14) || (choice < 0))
        {
            cout << "Invalid entry: Try again" << endl << endl;
        }
        else if ( !choice )
        {
            return choice;
        }
        else if (choice)
        {
            return choice;
        }
    }

    return choice;
}

Output after entering char 'f' as cin

Body:
Try this instead

if (cin >> choice)
{
    if((choice > 14) || (choice < 0))
        cout << "Invalid entry: Try again" << endl << endl;
    else
        return choice;
}
else //Fail to cin into choice, user input is not a number
    cout << "Invalid entry: Please key in a number." << endl;

Also, the while condition should change to while (true)


问:
TSQL XML locate particular block(s)
```<code>DECLARE @XMLData XML

SET @XMLData = '<ArrayOfAttributeValueDO>
      <AttributeValueDO>
        <AttributeID>421</AttributeID>
        <AttributeValue>100% cotton pre-shrunk drill</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>422</AttributeID>
        <AttributeValue>190gsm</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>1221</AttributeID>
        <AttributeValue>Long Sleeve</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>1481</AttributeID>
        <AttributeValue>No</AttributeValue>
      </AttributeValueDO>
    </ArrayOfAttributeValueDO>'
</code>```

Given the above example, how can I get a particular <AttributeValueDO> by searching on the <AttributeID> and <AttributeValue>?

I am kind of expecting syntax like this but having error in between "[]"
In fact, I am trying to get any <AttributeValueDO> with attributeID of 422 and attributeValue contains word of 'gsm'

```<code>DECLARE @strAttributeID VARCHAR(1000) = '422'
DECLARE @strAttributeValue VARCHAR(1000) = '190gsm'

SELECT [AttributeValueXML]
FROM [dbo].[tbl_Stock_Master_AttributeValue]
WHERE [AttributeValueXML].exist('(/ArrayOfAttributeValueDO/AttributeValueDO[AttributeID=sql:variable("@strAttributeID") && AttributeValue=sql:variable("@strAttributeValue")])') = 1
</code>```

答:
You can try something like this:

```<code>DECLARE @AttributeID INT = 422
DECLARE @AttrValue VARCHAR(20) = 'gsm'

SELECT
    xc.query('.')
FROM
    @XMLData.nodes('/ArrayOfAttributeValueDO/AttributeValueDO') AS XT(XC)
WHERE
    xc.value('(AttributeID)[1]', 'int') = @AttributeID
    AND xc.value('(AttributeValue)[1]', 'varchar(50)') LIKE '%' + @AttrValue + '%'
</code>```

This basically gives you any XML fragment (the whole <AttributeValueDO> XML element) where those two criteria apply.

Title: TSQL XML locate particular block(s)

Body:
DECLARE @XMLData XML

SET @XMLData = '<ArrayOfAttributeValueDO>
      <AttributeValueDO>
        <AttributeID>421</AttributeID>
        <AttributeValue>100% cotton pre-shrunk drill</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>422</AttributeID>
        <AttributeValue>190gsm</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>1221</AttributeID>
        <AttributeValue>Long Sleeve</AttributeValue>
      </AttributeValueDO>
      <AttributeValueDO>
        <AttributeID>1481</AttributeID>
        <AttributeValue>No</AttributeValue>
      </AttributeValueDO>
    </ArrayOfAttributeValueDO>'

Given the above example, how can I get a particular <AttributeValueDO> by searching on the <AttributeID> and <AttributeValue>?

I am kind of expecting syntax like this but having error in between "[]"
In fact, I am trying to get any <AttributeValueDO> with attributeID of 422 and attributeValue contains word of 'gsm'

DECLARE @strAttributeID VARCHAR(1000) = '422'
DECLARE @strAttributeValue VARCHAR(1000) = '190gsm'

SELECT [AttributeValueXML]
FROM [dbo].[tbl_Stock_Master_AttributeValue]
WHERE [AttributeValueXML].exist('(/ArrayOfAttributeValueDO/AttributeValueDO[AttributeID=sql:variable("@strAttributeID") && AttributeValue=sql:variable("@strAttributeValue")])') = 1

Body:
You can try something like this:

DECLARE @AttributeID INT = 422
DECLARE @AttrValue VARCHAR(20) = 'gsm'

SELECT
    xc.query('.')
FROM
    @XMLData.nodes('/ArrayOfAttributeValueDO/AttributeValueDO') AS XT(XC)
WHERE
    xc.value('(AttributeID)[1]', 'int') = @AttributeID
    AND xc.value('(AttributeValue)[1]', 'varchar(50)') LIKE '%' + @AttrValue + '%'

This basically gives you any XML fragment (the whole <AttributeValueDO> XML element) where those two criteria apply.


问:
How to get walking and running distance using HealthKit in swift
I'm making Health App. I want to get walkingRunningDistance from HealthKit in Swift. But, I have a problem. Return value is 0.0mile.

Why return value is 0 mile?

My code is this.

```<code>func recentSteps3(completion: (Double, NSError?) -> () ){
    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)

    let date = NSDate()

    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!

    let newDate = cal.startOfDayForDate(date)

    let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: HKQueryOptions.StrictStartDate)

    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { query, results, error in

        var distance: Double = 0

        if results?.count > 0
        {
            for result in results as! [HKQuantitySample]
            {
                distance += result.quantity.doubleValueForUnit(HKUnit.mileUnit())
            }
        }

        completion(distance, error)
    }

    healthAuth.healthStore.executeQuery(query)
}
</code>```

答:
```<code>healthStore =[HKHealthStore new];
HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKSampleType *sleepType = [HKSampleType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
HKQuantityType *walkType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
NSArray *arrayType = @[stepType,sleepType,walkType];

[healthStore requestAuthorizationToShareTypes:[NSSet setWithArray:arrayType]
                                    readTypes:[NSSet setWithArray:arrayType] completion:^(BOOL succeeded, NSError *error) {
                                        if (succeeded) {
                                            NSLog(@"Not working");
                                            NSLog(@"error %@",error);
                                        } else {
                                            NSLog(@"Working!");
                                            NSLog(@"error %@",error);
                                        }
                                        [self getStepCount];
                                    }];
</code>```

The above method for requsting access and below method to get count

```<code>-(void)getStepCount{
     NSInteger limit = 0;
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSDate *startDate = [NSDate  dateWithTimeIntervalSince1970:1372418789];
    // Divided by 1000 (i.e. removed three trailing zeros) ^^^^^^^^
    NSString *formattedDateString = [dateFormatter stringFromDate:startDate];
   // Fri, 28 Jun 2013 11:26:29 GMT
   NSLog(@"start Date: %@", formattedDateString);
   NSDateFormatter *dateFormatter1=[[NSDateFormatter alloc] init];
   [dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
   NSLog(@"%@",[dateFormatter1 stringFromDate:[NSDate date]]);
   NSString *dateString =[dateFormatter1 stringFromDate:[NSDate date]];
  NSDate *endDate = [dateFormatter1 dateFromString:dateString];

 NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictEndDate];

HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning]
                        predicate: predicate
                        limit: limit
                        sortDescriptors: nil
                        resultsHandler:^(HKSampleQuery *query, NSArray* results, NSError *error){
                            dispatch_async(dispatch_get_main_queue(), ^{
                                // sends the data using HTTP
                                int dailyAVG = 0;
                                NSLog(@"result : %@",results);
                                for(HKQuantitySample *samples in results)
                                {
                                    NSLog(@"dailyAVG : %@",samples);
                                }
                                NSLog(@"dailyAVG : %d",dailyAVG);

                                NSLog(@"%@",@"Done");
                            });
                        }];
[healthStore executeQuery:query];
</code>```

}

Body:
I'm making Health App. I want to get walkingRunningDistance from HealthKit in Swift. But, I have a problem. Return value is 0.0mile.

Why return value is 0 mile?

My code is this.

func recentSteps3(completion: (Double, NSError?) -> () ){
    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)

    let date = NSDate()

    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!

    let newDate = cal.startOfDayForDate(date)

    let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: HKQueryOptions.StrictStartDate)

    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { query, results, error in

        var distance: Double = 0

        if results?.count > 0
        {
            for result in results as! [HKQuantitySample]
            {
                distance += result.quantity.doubleValueForUnit(HKUnit.mileUnit())
            }
        }

        completion(distance, error)
    }

    healthAuth.healthStore.executeQuery(query)
}

Body:
healthStore =[HKHealthStore new];
HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKSampleType *sleepType = [HKSampleType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
HKQuantityType *walkType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
NSArray *arrayType = @[stepType,sleepType,walkType];

[healthStore requestAuthorizationToShareTypes:[NSSet setWithArray:arrayType]
                                    readTypes:[NSSet setWithArray:arrayType] completion:^(BOOL succeeded, NSError *error) {
                                        if (succeeded) {
                                            NSLog(@"Not working");
                                            NSLog(@"error %@",error);
                                        } else {
                                            NSLog(@"Working!");
                                            NSLog(@"error %@",error);
                                        }
                                        [self getStepCount];
                                    }];

The above method for requsting access and below method to get count

-(void)getStepCount{
     NSInteger limit = 0;
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSDate *startDate = [NSDate  dateWithTimeIntervalSince1970:1372418789];
    // Divided by 1000 (i.e. removed three trailing zeros) ^^^^^^^^
    NSString *formattedDateString = [dateFormatter stringFromDate:startDate];
   // Fri, 28 Jun 2013 11:26:29 GMT
   NSLog(@"start Date: %@", formattedDateString);
   NSDateFormatter *dateFormatter1=[[NSDateFormatter alloc] init];
   [dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
   NSLog(@"%@",[dateFormatter1 stringFromDate:[NSDate date]]);
   NSString *dateString =[dateFormatter1 stringFromDate:[NSDate date]];
  NSDate *endDate = [dateFormatter1 dateFromString:dateString];

 NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictEndDate];

HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning]
                        predicate: predicate
                        limit: limit
                        sortDescriptors: nil
                        resultsHandler:^(HKSampleQuery *query, NSArray* results, NSError *error){
                            dispatch_async(dispatch_get_main_queue(), ^{
                                // sends the data using HTTP
                                int dailyAVG = 0;
                                NSLog(@"result : %@",results);
                                for(HKQuantitySample *samples in results)
                                {
                                    NSLog(@"dailyAVG : %@",samples);
                                }
                                NSLog(@"dailyAVG : %d",dailyAVG);

                                NSLog(@"%@",@"Done");
                            });
                        }];
[healthStore executeQuery:query];

}


问:
install intern of update dojo releases
According to the document install steps, a week ago it works(install success). When I installed and used the same steps today, and run npm test, it displayed the following error:
enter image description here
I think maybe is Dojo releases update(a day ago), cause something has changed.
Now how can I success to install the intern?
Whether the document install steps need to revise and update?
Thanks.</p>

答:
package.json

```<code>"dependencies": {
"tslib": "~1.7.1" }
</code>```

revise

```<code>"dependencies": {
"tslib": "~1.8.0" }
</code>```

package-lock.json
  tslib": "~1.7.1" revise  1.8.0

Title: install intern of update dojo releases

Body:
package.json

"dependencies": {
"tslib": "~1.7.1" }

revise

"dependencies": {
"tslib": "~1.8.0" }

package-lock.json
  tslib": "~1.7.1" revise  1.8.0


问:
How to access headers from a HttpClient response? (Angular / Ionic)
I'm using a login endpoint that returns a bearer token as a response header, as I can see in the "Network" Chrome inspect window:

```<code>Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8100
Authorization:Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJuZWxpby5jdXJzb3NAZ21haWwuY29tIiwiZXhwIjoxNTEyNzA3OTQ3fQ.pOR4WrqkaFXdwbeod1tNlDniFZXTeMXzKz9uU68rLXEWDAVRgWIphvx5F_VCsXDwimD8Q04JrxelkNgZMzBgXA
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:188
(etc...)
</code>```

However, when I try to print "headers" from the response using a HttpClient instance:

```<code>  authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({"Content-Type": "application/json"});
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response'})
      .subscribe(
        (resp) => {
          console.log("resp-ok");
          console.log(resp.headers);
        },
        (resp) => {
          console.log("resp-error");
          console.log(resp);
        }
      );
  }
</code>```

I get a completely different structure:

```<code>HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit : ƒ ()
lazyUpdate : null
normalizedNames : Map(0) {}
</code>```

I also tried the get(headerName) method and got null. What am I missing? How can I get that "Authorization" header from my response?

答:
You are almost there.

The reason it is not working is because you didn't use the .get function of the headers.

Change this

```<code> console.log(resp.headers);
</code>```

To this

```<code> console.log(resp.headers.get('Authorization'))
</code>```

More Info:

Official doc here

Body:
I'm using a login endpoint that returns a bearer token as a response header, as I can see in the "Network" Chrome inspect window:

Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8100
Authorization:Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJuZWxpby5jdXJzb3NAZ21haWwuY29tIiwiZXhwIjoxNTEyNzA3OTQ3fQ.pOR4WrqkaFXdwbeod1tNlDniFZXTeMXzKz9uU68rLXEWDAVRgWIphvx5F_VCsXDwimD8Q04JrxelkNgZMzBgXA
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:188
(etc...)

However, when I try to print "headers" from the response using a HttpClient instance:

  authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({"Content-Type": "application/json"});
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response'})
      .subscribe(
        (resp) => {
          console.log("resp-ok");
          console.log(resp.headers);
        },
        (resp) => {
          console.log("resp-error");
          console.log(resp);
        }
      );
  }

I get a completely different structure:

HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit : ƒ ()
lazyUpdate : null
normalizedNames : Map(0) {}

I also tried the get(headerName) method and got null. What am I missing? How can I get that "Authorization" header from my response?

Body:
You are almost there.

The reason it is not working is because you didn't use the .get function of the headers.

Change this

 console.log(resp.headers);

To this

 console.log(resp.headers.get('Authorization'))

More Info:

Official doc here


问:
Split on period but ignore some words which contains period in java
I want to split a document into paragraphs, for that, I am using.

String paragraphs[] = documentData.split("\.\n");

but it removes .\n from the actual document. I don't want to lose those tokens. Also, I want that, words like Inc. etc. Jr. should not be split by the regular expression.

答:
Here is a very basic script just to point you in the right direction:

```<code>String input = "Sentence one in paragraph one.  Sentence two in paragraph one.\n Sentence one in paragraph two.  Sentence two in paragraph two.";
String[] parts = input.split("(?<=\\.\n)\\s*");
for (String part : parts) {
    System.out.println(part);
}
</code>```

One way to split on dot while not consuming it is to use a lookarounds.  Lookarounds match, but do not consume, making them ideal for what you have in mind.  In this case, I am splitting on the following pattern:

```<code>(?<=\.\n)\s*
</code>```

This asserts that what comes before the current position is a full stop followed by a newline.  Then it consumes any whitespace which might separate paragraphs, before printing the paragraph to the console.

Demo

Body:
Here is a very basic script just to point you in the right direction:

String input = "Sentence one in paragraph one.  Sentence two in paragraph one.\n Sentence one in paragraph two.  Sentence two in paragraph two.";
String[] parts = input.split("(?<=\\.\n)\\s*");
for (String part : parts) {
    System.out.println(part);
}

One way to split on dot while not consuming it is to use a lookarounds.  Lookarounds match, but do not consume, making them ideal for what you have in mind.  In this case, I am splitting on the following pattern:

(?<=\.\n)\s*

This asserts that what comes before the current position is a full stop followed by a newline.  Then it consumes any whitespace which might separate paragraphs, before printing the paragraph to the console.

Demo


问:
I have some problems about lists Python 2.7
Could you tell me what's wrong here?

For some reason there's nothing added into the list.

```<code>textarea = raw_input()
n=0
txa = []
string =""

while(n < len(textarea)):
    if(textarea[n] != ' ' or textarea[n] != ','):

        string += textarea[n]
        n=n+1
        print (string)

    else:
        print "For some reason I'm never here."

        if(string == ' ' or string == ','):
            string = ""
        else:
            txa.append(string)
            string = ""
            n=n+1
print(txa)
</code>```

Sorry for my english.

答:
You need to change the or in your if statement to an and. Currently the condition is always true because it is impossible for textarea[n] to be both ' ' and ','.

You can also use regular expressions to split the string as seen here

Body:
Could you tell me what's wrong here?

For some reason there's nothing added into the list.

textarea = raw_input()
n=0
txa = []
string =""

while(n < len(textarea)):
    if(textarea[n] != ' ' or textarea[n] != ','):

        string += textarea[n]
        n=n+1
        print (string)

    else:
        print "For some reason I'm never here."

        if(string == ' ' or string == ','):
            string = ""
        else:
            txa.append(string)
            string = ""
            n=n+1
print(txa)

Sorry for my english.


问:
Taking the record with the max date
Let's assume I extract some set of data.

i.e.

```<code>SELECT A, date
FROM table
</code>```

I want just the record with the max date (for each value of A). I could write

```<code>SELECT A, col_date
  FROM TABLENAME t_ext
 WHERE col_date = (SELECT MAX (col_date)
                     FROM TABLENAME t_in
                    WHERE t_in.A = t_ext.A)
</code>```

But my query is really long... is there a more compact way using ANALYTIC FUNCTION to do the same?

答:
A is the key, max(date) is the value, we might simplify the query as below:</p>

```<code>SELECT distinct A, max(date) over (partition by A)
  FROM TABLENAME
</code>```

ContentLicense: CC BY-SA 4.0

Title: Taking the record with the max date

Body:
Let's assume I extract some set of data.

i.e.

SELECT A, date
FROM table

I want just the record with the max date (for each value of A). I could write

SELECT A, col_date
  FROM TABLENAME t_ext
 WHERE col_date = (SELECT MAX (col_date)
                     FROM TABLENAME t_in
                    WHERE t_in.A = t_ext.A)

But my query is really long... is there a more compact way using ANALYTIC FUNCTION to do the same?

Body:
A is the key, max(date) is the value, we might simplify the query as below:

SELECT distinct A, max(date) over (partition by A)
  FROM TABLENAME


问:
SQL Server: How to list all CLR functions/procedures/objects for assembly
Question: In SQL Server 2005, how can I list all SQL CLR-functions/procedures that use assembly xy (e.g. MyFirstUdp) ?

For example a function that lists HelloWorld for query parameter MyFirstUdp

```<code>CREATE PROCEDURE HelloWorld
AS EXTERNAL NAME MyFirstUdp.[SQL_CLRdll.MySQLclass].HelloWorld
GO
</code>```

after I ran

```<code>CREATE ASSEMBLY MyFirstUdp FROM 'C:\Users\username\Documents\Visual Studio 2005\Projects\SQL_CLRdll\SQL_CLRdll\bin\Debug\SQL_CLRdll.dll
</code>```

I can list all assemblies and all functions/procedures,
but I seem to be unable to associate the assembly to the functions/procedures...

答:
I use the following SQL:

SELECT      so.name AS [ObjectName],
            so.[type],
            SCHEMA_NAME(so.[schema_id]) AS [SchemaName],
            asmbly.name AS [AssemblyName],
            asmbly.permission_set_desc,
            am.assembly_class,
            am.assembly_method
FROM        sys.assembly_modules am
INNER JOIN  sys.assemblies asmbly
        ON  asmbly.assembly_id = am.assembly_id
        AND asmbly.is_user_defined = 1 -- if using SQL Server 2008 or newer
--      AND asmbly.name NOT LIKE 'Microsoft%' -- if using SQL Server 2005
INNER JOIN  sys.objects so
        ON  so.[object_id] = am.[object_id]
UNION ALL
SELECT      at.name AS [ObjectName],
            'UDT' AS [type],
            SCHEMA_NAME(at.[schema_id]) AS [SchemaName],
            asmbly.name AS [AssemblyName],
            asmbly.permission_set_desc,
            at.assembly_class,
            NULL AS [assembly_method]
FROM        sys.assembly_types at
INNER JOIN  sys.assemblies asmbly
        ON  asmbly.assembly_id = at.assembly_id
        AND asmbly.is_user_defined = 1 -- if using SQL Server 2008 or newer
--      AND asmbly.name NOT LIKE 'Microsoft%' -- if using SQL Server 2005
ORDER BY    [AssemblyName], [type], [ObjectName]
```

Please note:

User-Defined Types (UDTs) are found in: sys.assembly_types

You can only list SQLCLR references that have been used in CREATE { PROCEDURE | FUNCTION | AGGREGATE | TRIGGER | TYPE }  statements. You cannot find SQLCLR methods that have not yet been referenced by a CREATE. Meaning, you cannot say: "give me a list of methods in this assembly that I can create T-SQL objects for".

For more info on working with SQLCLR in general, please visit: SQLCLR Info

Body:
Question: In SQL Server 2005, how can I list all SQL CLR-functions/procedures that use assembly xy (e.g. MyFirstUdp) ?

For example a function that lists HelloWorld for query parameter MyFirstUdp

CREATE PROCEDURE HelloWorld
AS EXTERNAL NAME MyFirstUdp.[SQL_CLRdll.MySQLclass].HelloWorld
GO

after I ran

CREATE ASSEMBLY MyFirstUdp FROM 'C:\Users\username\Documents\Visual Studio 2005\Projects\SQL_CLRdll\SQL_CLRdll\bin\Debug\SQL_CLRdll.dll

I can list all assemblies and all functions/procedures,
but I seem to be unable to associate the assembly to the functions/procedures...

Body:
I use the following SQL:

SELECT      so.name AS [ObjectName],
            so.[type],
            SCHEMA_NAME(so.[schema_id]) AS [SchemaName],
            asmbly.name AS [AssemblyName],
            asmbly.permission_set_desc,
            am.assembly_class,
            am.assembly_method
FROM        sys.assembly_modules am
INNER JOIN  sys.assemblies asmbly
        ON  asmbly.assembly_id = am.assembly_id
        AND asmbly.is_user_defined = 1 -- if using SQL Server 2008 or newer
--      AND asmbly.name NOT LIKE 'Microsoft%' -- if using SQL Server 2005
INNER JOIN  sys.objects so
        ON  so.[object_id] = am.[object_id]
UNION ALL
SELECT      at.name AS [ObjectName],
            'UDT' AS [type],
            SCHEMA_NAME(at.[schema_id]) AS [SchemaName],
            asmbly.name AS [AssemblyName],
            asmbly.permission_set_desc,
            at.assembly_class,
            NULL AS [assembly_method]
FROM        sys.assembly_types at
INNER JOIN  sys.assemblies asmbly
        ON  asmbly.assembly_id = at.assembly_id
        AND asmbly.is_user_defined = 1 -- if using SQL Server 2008 or newer
--      AND asmbly.name NOT LIKE 'Microsoft%' -- if using SQL Server 2005
ORDER BY    [AssemblyName], [type], [ObjectName]

Please note:

User-Defined Types (UDTs) are found in: sys.assembly_types

You can only list SQLCLR references that have been used in CREATE { PROCEDURE | FUNCTION | AGGREGATE | TRIGGER | TYPE }  statements. You cannot find SQLCLR methods that have not yet been referenced by a CREATE. Meaning, you cannot say: "give me a list of methods in this assembly that I can create T-SQL objects for".

For more info on working with SQLCLR in general, please visit: SQLCLR Info


问:
javascript programming with jinja values
I have a block of HTML code

```<code><td>{{stock.C4}}</td>
<td>{{stock.C5}}</td>
<td>{{stock.C6}}</td>
<td>{{stock.C7}}</td>
<td>{{stock.C8}}</td>
</code>```

{{stock.C4}} has an output of None in the html cell.
I want (maybe javascript?) code that basically says

```<code> if {{stock.C4}} == 'None'
       element.style.backgroundColor = "red"
</code>```

code that makes the cell a color based on the html/jinja value

答:
Use document.querySelectorAll to get all the td of a specific table, the use array#forEach to check if it is empty using innerHTML, if so use classList.add to add a css class to it

var getAllTD = document.querySelectorAll("#demoTable td");
getAllTD.forEach(function(item) {
  if (item.innerHTML === '') {
    item.classList.add('empty')
  }

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.empty {
  background: green;
}</code>```

    1
    2

    4

    5

```

Body:
I have a block of HTML code

{{stock.C4}}
{{stock.C5}}
{{stock.C6}}
{{stock.C7}}
{{stock.C8}}

{{stock.C4}} has an output of None in the html cell.
I want (maybe javascript?) code that basically says

 if {{stock.C4}} == 'None'
       element.style.backgroundColor = "red"

code that makes the cell a color based on the html/jinja value

Body:
Use document.querySelectorAll to get all the td of a specific table, the use array#forEach to check if it is empty using innerHTML, if so use classList.add to add a css class to it

var getAllTD = document.querySelectorAll("#demoTable td");
getAllTD.forEach(function(item) {
  if (item.innerHTML === '') {
    item.classList.add('empty')
  }

})

.empty {
  background: green;
}

<table border="1" id="demoTable">
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td></td>
    <td>4</td>
  </tr>
  <tr>
    <td>5</td>
    <td></td>
  </tr>
</table>


问:
angular2-highcharts throwing exceptions when we port a Graph
Angular2-highcharts is throwing a wierd exception when I am trying to port my existing graph. The code for my graph is as shown below:-

http://jsfiddle.net/kkulig/dx2vj8k1/

```<code>var chart = Highcharts.chart('container', {

  chart: {
    type: 'bar',
    marginLeft: 10
  },

  plotOptions: {
    bar: {
        dataLabels: {
        enabled: true
      }
    }
  },

  xAxis: {
    left: '50%',
    categories: ['15-19', '20-21'],
    lineWidth: 0,
    tickWidth: 0,
    labels: {
      align: 'left',
      x: -18
    },
    title: {
        text: 'Age Group',
      align: 'high',
      rotation: 0,
      x: 40
    }
  },

  yAxis: [{
    left: '55%',
    width: '45%',
    labels: {
      enabled: false
    },
    title: {
      x: -160,
      text: 'Female'
    },
    gridLineWidth: 0
  }, {
    reversed: true,
    width: '45%',
    offset: 0,
    labels: {
      enabled: false
    },
    title: {
      x: 170,
      text: 'Male'
    },
    gridLineWidth: 0
  }],

  series: [{
    data: [1, 3]
  }, {
    data: [2, 5],
    yAxis: 1
  }]
});
</code>```

When I try to port this to angular2-highcharts, I get a pretty bizarre error as shown below. What am I doing Wrong?

The plnkr is here http://plnkr.co/edit/UvOmYi?p=preview

The error which I see is below:-

The output of the above Plnkr is here.

答:
This error is because of percentage issue while defining width,left,right.
angular2-highcharts is highcharts plugin for Angular is based on Typescript.

So you cannot use width: '45%', directly because it is string instead use width:window.innerWidth * .45.

http://plnkr.co/edit/Bp3O8SwWjwkLFCRkrQPa?p=preview

```<code>chart: {
    type: 'bar',
    marginLeft: 10
  },

  plotOptions: {
    bar: {
      dataLabels: {
        enabled: true
      }
    }
  },
  xAxis: {
    left: window.innerWidth * .52,
    categories: ['15-19', '20-21'],
    lineWidth: 0,
    tickWidth: 0,
    labels: {
      align: 'left',
      x: -18
    },
    title: {
      text: 'Age Group',
      align: 'high',
      x: 10
    }
  },

  yAxis: [{
    left: window.innerWidth * .55,
    width:window.innerWidth * .45,
    labels: {
      enabled: false
    },
    title: {
      x: -160,
      text: 'Female'
    },
    gridLineWidth: 0
  }, {
    reversed: true,
    width: window.innerWidth * .45,
    offset: 0,
    labels: {
      enabled: false
    },
    title: {
      x: 170,
      text: 'Male'
    },
    gridLineWidth: 0
  }],

  series: [{
    data: [1, 3]
  }, {
    data: [2, 5],
    yAxis: 1
  }]
 };
</code>```

Body:
Angular2-highcharts is throwing a wierd exception when I am trying to port my existing graph. The code for my graph is as shown below:-

http://jsfiddle.net/kkulig/dx2vj8k1/

var chart = Highcharts.chart('container', {

  chart: {
    type: 'bar',
    marginLeft: 10
  },

  plotOptions: {
    bar: {
        dataLabels: {
        enabled: true
      }
    }
  },

  xAxis: {
    left: '50%',
    categories: ['15-19', '20-21'],
    lineWidth: 0,
    tickWidth: 0,
    labels: {
      align: 'left',
      x: -18
    },
    title: {
        text: 'Age Group',
      align: 'high',
      rotation: 0,
      x: 40
    }
  },

  yAxis: [{
    left: '55%',
    width: '45%',
    labels: {
      enabled: false
    },
    title: {
      x: -160,
      text: 'Female'
    },
    gridLineWidth: 0
  }, {
    reversed: true,
    width: '45%',
    offset: 0,
    labels: {
      enabled: false
    },
    title: {
      x: 170,
      text: 'Male'
    },
    gridLineWidth: 0
  }],

  series: [{
    data: [1, 3]
  }, {
    data: [2, 5],
    yAxis: 1
  }]
});

When I try to port this to angular2-highcharts, I get a pretty bizarre error as shown below. What am I doing Wrong?

The plnkr is here http://plnkr.co/edit/UvOmYi?p=preview

The error which I see is below:-

The output of the above Plnkr is here.

Body:
This error is because of percentage issue while defining width,left,right.
angular2-highcharts is highcharts plugin for Angular is based on Typescript.

So you cannot use width: '45%', directly because it is string instead use width:window.innerWidth * .45.

http://plnkr.co/edit/Bp3O8SwWjwkLFCRkrQPa?p=preview

chart: {
    type: 'bar',
    marginLeft: 10
  },

  plotOptions: {
    bar: {
      dataLabels: {
        enabled: true
      }
    }
  },
  xAxis: {
    left: window.innerWidth * .52,
    categories: ['15-19', '20-21'],
    lineWidth: 0,
    tickWidth: 0,
    labels: {
      align: 'left',
      x: -18
    },
    title: {
      text: 'Age Group',
      align: 'high',
      x: 10
    }
  },

  yAxis: [{
    left: window.innerWidth * .55,
    width:window.innerWidth * .45,
    labels: {
      enabled: false
    },
    title: {
      x: -160,
      text: 'Female'
    },
    gridLineWidth: 0
  }, {
    reversed: true,
    width: window.innerWidth * .45,
    offset: 0,
    labels: {
      enabled: false
    },
    title: {
      x: 170,
      text: 'Male'
    },
    gridLineWidth: 0
  }],

  series: [{
    data: [1, 3]
  }, {
    data: [2, 5],
    yAxis: 1
  }]
 };


问:
ModuleVersionNotFoundException android studio
when i click on run button then i got this error

Error:org.gradle.api.artifacts.ResolveException: Could not resolve all dependencies for configuration ':app:_debugApkCopy'.

Error:org.gradle.internal.resolve.ModuleVersionNotFoundException: Could not find com.android.support:appcompat-v7:27.0.1.

please see below screen shot

and when i try to gradle sync
then i got this problem

please see below screen shot

my build.gradle

```<code>buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }

}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}
android {
    signingConfigs {
        config {
        }
    }
    repositories {
        mavenCentral()
    }
    compileSdkVersion 25
    buildToolsVersion '26.0.0'
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.hechat"
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    dexOptions {
        javaMaxHeapSize "2048M"
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'project.properties'
        exclude 'META-INF/INDEX.LIST'

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

    repositories {
        maven { url "https://dl.bintray.com/hani-momanii/maven" }
    }
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.google.code.findbugs'
    })
    compile('com.twitter.sdk.android:twitter:2.3.1@aar') { transitive = true; }
    compile('com.crashlytics.sdk.android:crashlytics:2.6.5@aar') { transitive = true; }
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.3.1'
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
    compile 'net.gotev:uploadservice:2.1'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'hani.momanii.supernova_emoji_library:supernova-emoji-library:0.0.2'
    compile 'com.google.android.gms:play-services:11.0.4'
    compile 'com.google.firebase:firebase-core:10.2.1'
    compile 'com.google.code.gson:gson:2.3'
    compile 'org.apache.httpcomponents:httpcore:4.3.2'
    compile 'org.apache.httpcomponents:httpmime:4.3.3'
    compile 'com.mcxiaoke.volley:library:1.0.17'
    compile 'com.github.clans:fab:1.6.2'
    compile 'org.jsoup:jsoup:1.8.1'
    compile 'com.parse.bolts:bolts-tasks:1.4.0'
    compile 'com.commit451:PhotoView:1.2.4'
    compile 'com.android.support:multidex:1.0.0'
    compile 'com.splitwise:tokenautocomplete:1.3.3'
    compile 'com.tubb.smrv:swipemenu-recyclerview:5.2.1'
    compile 'com.github.bumptech.glide:glide:3.5.2'
    compile 'se.emilsjolander:stickylistheaders:2.7.0'
    compile 'com.mindorks:placeholderview:0.6.4'
    compile 'org.twitter4j:twitter4j-core:4.0.2'
    compile 'jp.wasabeef:fresco-processors:2.1.0'
    compile 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.3.0'
    compile 'com.google.firebase:firebase-messaging:10.2.1'
    compile 'com.android.billingclient:billing:1.0'

    testCompile 'junit:junit:4.12'
    compile project(':cometchat_platinum-sdk')

}

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

i have not used v-27 then why i am facing v7 issue
thanks in advance

答:
Try this i have same problem i solved using  below dependencies of Facebook

Use this

```<code>compile 'com.facebook.android:facebook-android-sdk:4.26.0'
</code>```

instead of this

```<code>compile 'com.facebook.android:facebook-android-sdk:[4,5)'
</code>```

Body:
when i click on run button then i got this error

Error:org.gradle.api.artifacts.ResolveException: Could not resolve all dependencies for configuration ':app:_debugApkCopy'.

Error:org.gradle.internal.resolve.ModuleVersionNotFoundException: Could not find com.android.support:appcompat-v7:27.0.1.

please see below screen shot

and when i try to gradle sync
then i got this problem

please see below screen shot

my build.gradle

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }

}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}
android {
    signingConfigs {
        config {
        }
    }
    repositories {
        mavenCentral()
    }
    compileSdkVersion 25
    buildToolsVersion '26.0.0'
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.hechat"
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    dexOptions {
        javaMaxHeapSize "2048M"
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'project.properties'
        exclude 'META-INF/INDEX.LIST'

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

    repositories {
        maven { url "https://dl.bintray.com/hani-momanii/maven" }
    }
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.google.code.findbugs'
    })
    compile('com.twitter.sdk.android:twitter:2.3.1@aar') { transitive = true; }
    compile('com.crashlytics.sdk.android:crashlytics:2.6.5@aar') { transitive = true; }
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.3.1'
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
    compile 'net.gotev:uploadservice:2.1'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'hani.momanii.supernova_emoji_library:supernova-emoji-library:0.0.2'
    compile 'com.google.android.gms:play-services:11.0.4'
    compile 'com.google.firebase:firebase-core:10.2.1'
    compile 'com.google.code.gson:gson:2.3'
    compile 'org.apache.httpcomponents:httpcore:4.3.2'
    compile 'org.apache.httpcomponents:httpmime:4.3.3'
    compile 'com.mcxiaoke.volley:library:1.0.17'
    compile 'com.github.clans:fab:1.6.2'
    compile 'org.jsoup:jsoup:1.8.1'
    compile 'com.parse.bolts:bolts-tasks:1.4.0'
    compile 'com.commit451:PhotoView:1.2.4'
    compile 'com.android.support:multidex:1.0.0'
    compile 'com.splitwise:tokenautocomplete:1.3.3'
    compile 'com.tubb.smrv:swipemenu-recyclerview:5.2.1'
    compile 'com.github.bumptech.glide:glide:3.5.2'
    compile 'se.emilsjolander:stickylistheaders:2.7.0'
    compile 'com.mindorks:placeholderview:0.6.4'
    compile 'org.twitter4j:twitter4j-core:4.0.2'
    compile 'jp.wasabeef:fresco-processors:2.1.0'
    compile 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.3.0'
    compile 'com.google.firebase:firebase-messaging:10.2.1'
    compile 'com.android.billingclient:billing:1.0'

    testCompile 'junit:junit:4.12'
    compile project(':cometchat_platinum-sdk')

}

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

i have not used v-27 then why i am facing v7 issue
thanks in advance

Body:
Try this i have same problem i solved using  below dependencies of Facebook

Use this

compile 'com.facebook.android:facebook-android-sdk:4.26.0'

instead of this

compile 'com.facebook.android:facebook-android-sdk:[4,5)'


问:
Passing switches to Xcode 3.1 user scripts
I have a user script that would be much more useful if it could dynamically change some of its execution dependent on what the user wanted.  Passing simple switches would easily solve this problem but I don't see any way to do it.

I also tried embedding a keyword in the script name, but Xcode copies the script to a guid-looking filename before execution, so that won't work either.

So does anyone know of a way to call a user script with some sort of argument? (other that the normal %%%var%%% variables)

EDIT:

User scripts are accessible via the script menu in Xcode's menubar (between the Window and Help menus).  My question is not about "run script" build phase scripts.  My apologies for leaving that somewhat ambiguous.

答:
You can't pass parameters to user scripts — instead, user scripts operate on the context you're working in (e.g. the selected file, the selected text, etc.).

You should use the context to determine what the user really wants.

OwnerDisplayName: MyztikJenz

OwnerDisplayName: Chris Hanson


问:
Form Collection item coming up as null
I am trying to use form collection and this is what i am using to submit the form.

```<code> <%=Html.ActionLink("Update", "Calendar", ViewData["sub"], new { onclick =  "this.form.submit();" })%>
</code>```

Just for the heck of it i tried replacing it with a dropdownlist that retains its value and all of a sudden i get all my form collection.

```<code> <%=Html.DropDownList("dllMonth", new SelectList(new List<string>() { "January",
    "Feburary", "March", "April", "June", "July", "August", "September", "October", "November", "December"}, ViewData["Month"]), new { onchange = "this.form.submit();" })%>
</code>```

Can someone please explain whats going on?

答:
I changed my action link to the following and now all is working fine:</p>

```<code><a name="update" href="Calendar" onclick="this.form.submit();" type="submit">Update</a>
</code>```

Title: Form Collection item coming up as null

Body:
I am trying to use form collection and this is what i am using to submit the form.

 <%=Html.ActionLink("Update", "Calendar", ViewData["sub"], new { onclick =  "this.form.submit();" })%>

Just for the heck of it i tried replacing it with a dropdownlist that retains its value and all of a sudden i get all my form collection.

 <%=Html.DropDownList("dllMonth", new SelectList(new List<string>() { "January",
    "Feburary", "March", "April", "June", "July", "August", "September", "October", "November", "December"}, ViewData["Month"]), new { onchange = "this.form.submit();" })%>

Can someone please explain whats going on?

Body:
I changed my action link to the following and now all is working fine:

<a name="update" href="Calendar" onclick="this.form.submit();" type="submit">Update</a>


问:
Use Bing Spell Check before Microsoft Translate which is called before call to LUIS
So...
I'm trying to use the Bot Framwork with LUIS in Swedish.
Using the samples I implemented translation of the input from Swedish to English and then called the LUIS functionality.
It worked perfect until we got some very strange intent hits from LUIS.
What we found out was that a very small spelling error (in Swedish) caused the translation to create a message that triggered wrong intent.
We can solve the problem by checking the score of the received intent, but the message back to the user "I didn't understand that" isn't especially helpful.
Running the same message through Bing Spell Check  and replace the faulty text with the correct one will produce a correct behaviour (mostly).

What I would like to do is to use the result from the Spell Check to ask the user if the text he/she should be replace with the result from Bing.

Now the problem: I can't find a proper way to implement the dialog to the user. (If possible, I would like to avoid using the PromptDialog.Confirm since it is tricky to localize)

What I have now (that doesn't work) is roughly:

```<code>if (activity.Type == ActivityTypes.Message)
{
    correctedText = await sc.BingSpellCheck(activity.Text, spellValues);

    if (spellValues.Count > 0)
    {
      // Ask the client if the correction is ok
      await Conversation.SendAsync(activity, () => new CorrectSpellingDialog());
    }
    Translate.Current.ToEnglish(activity.Text, "en");
    await Conversation.SendAsync(activity, () => new MeBotLuisDialog());
}
</code>```

What I would like here is to create a CorrectSpellingDialog() that just returns true or false, nad if it is true I will call the ...MeBotLuisDialog().

Sorry for all the text but it's a long problem :-)

Any takers on this?

(The other solution I had was to create an Intent "SpellCheckError" that is trigged from the Bing Spell Check and the in the intent send a message with the corrected message back to the bot (even though I don't know I that is doable in a proper way))
// Tommy

答:
To enable Bing Spell Check API in your bot, you will first get the key from Bing service, then in the Web.config file add the BingSpellCheckApiKey and together enable IsSpellCorrectionEnabled for example:

<appSettings>

  <add key="BotId" value="YourBotId" />
  <add key="MicrosoftAppId" value="" />
  <add key="MicrosoftAppPassword" value="" />
  <add key="BingSpellCheckApiKey" value="YourBingSpellApiKey" />
  <add key="IsSpellCorrectionEnabled" value="true" />
</appSettings>
```

<p>Then you can create a component for your bot to use Bing Spell Api, for more information, you can refer to Quickstart for Bing Spell Check API with C#. Here you can a service in your app for example like this Service.</p>

<p>Then in <code>MessagesController</code>, check the spell first before sending message to dialog. and since your want to show a confirm dialog to user if the text should be replace with the result from Bing, you can send a <code>FormFlow</code> first to let user to have a choice. For example:</p>

<p>Code of <code>MessagesController</code>:</p>

<pre class="lang-cs prettyprint-override"><code>private static readonly bool IsSpellCorrectionEnabled = bool.Parse(WebConfigurationManager.AppSettings["IsSpellCorrectionEnabled"]);
private BingSpellCheckService spellService = new BingSpellCheckService();

/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
   if (activity.Type == ActivityTypes.Message)
    {
        if (IsSpellCorrectionEnabled)
        {
            try
            {
                var text = await this.spellService.GetCorrectedTextAsync(activity.Text);
                if(text != activity.Text)
                {
                    //if spelling is wrong, go to rootdialog
                    await Conversation.SendAsync(activity, () => new Dialogs.RootDialog(activity.Text, text));
                }
                else
                {
                    //if right, direct go to luisdialog

                    await Conversation.SendAsync(activity, () => new Dialogs.MyLuisDialog());

                }
            }
            catch(Exception ex)
            {
                Trace.TraceError(ex.ToString());
            }
        }
        else
        {
            await Conversation.SendAsync(activity, () => new Dialogs.MyLuisDialog());
        }

    }
    else
    {
        HandleSystemMessage(activity);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}
</code>```

Code of my RootDialog:

[Serializable]
public class RootDialog : IDialog<object>
{
    private string otext;
    private string ntext;
    public RootDialog(string oldtext, string newtext)
    {
        otext = oldtext;
        ntext = newtext;
    }

    public async Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);
    }

    public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
    {
        var message = await result;
        var form = new FormDialog<Confirmation>(new Confirmation(otext, ntext),
                Confirmation.BuildForm, FormOptions.PromptInStart, null);
        context.Call(form, this.GetResultAsync);
    }

    private async Task GetResultAsync(IDialogContext context, IAwaitable<Confirmation> result)
    {
        var state = await result;
        await context.Forward(new MyLuisDialog(), null, context.Activity, System.Threading.CancellationToken.None);
    }

}

[Serializable]
public class Confirmation
{

    public string Text { get; set; }
    private static string otext;
    private static string ntext;
    public Confirmation(string oldtext, string newtext)
    {
        otext = oldtext;
        ntext = newtext;
    }
    public static IForm<Confirmation> BuildForm()
    {
        return new FormBuilder<Confirmation>()
            .Field(new FieldReflector<Confirmation>(nameof(Text))
            .SetType(null)
            .SetDefine(async(state, field) =>
            {
                field
                .AddDescription(otext, otext)
                .AddTerms(otext, otext)
                .AddDescription(ntext,ntext)
                .AddTerms(ntext, ntext);

                return true;
            }))
            .Build();
    }
}
```

Body:
So...
I'm trying to use the Bot Framwork with LUIS in Swedish.
Using the samples I implemented translation of the input from Swedish to English and then called the LUIS functionality.
It worked perfect until we got some very strange intent hits from LUIS.
What we found out was that a very small spelling error (in Swedish) caused the translation to create a message that triggered wrong intent.
We can solve the problem by checking the score of the received intent, but the message back to the user "I didn't understand that" isn't especially helpful.
Running the same message through Bing Spell Check  and replace the faulty text with the correct one will produce a correct behaviour (mostly).

What I would like to do is to use the result from the Spell Check to ask the user if the text he/she should be replace with the result from Bing.

Now the problem: I can't find a proper way to implement the dialog to the user. (If possible, I would like to avoid using the PromptDialog.Confirm since it is tricky to localize)

What I have now (that doesn't work) is roughly:

if (activity.Type == ActivityTypes.Message)
{
    correctedText = await sc.BingSpellCheck(activity.Text, spellValues);

    if (spellValues.Count > 0)
    {
      // Ask the client if the correction is ok
      await Conversation.SendAsync(activity, () => new CorrectSpellingDialog());
    }
    Translate.Current.ToEnglish(activity.Text, "en");
    await Conversation.SendAsync(activity, () => new MeBotLuisDialog());
}

What I would like here is to create a CorrectSpellingDialog() that just returns true or false, nad if it is true I will call the ...MeBotLuisDialog().

Sorry for all the text but it's a long problem :-)

Any takers on this?

(The other solution I had was to create an Intent "SpellCheckError" that is trigged from the Bing Spell Check and the in the intent send a message with the corrected message back to the bot (even though I don't know I that is doable in a proper way))
// Tommy

Body:
To enable Bing Spell Check API in your bot, you will first get the key from Bing service, then in the Web.config file add the BingSpellCheckApiKey and together enable IsSpellCorrectionEnabled for example:

<appSettings>
  <!-- update these with your BotId, Microsoft App Id and your Microsoft App Password-->
  <add key="BotId" value="YourBotId" />
  <add key="MicrosoftAppId" value="" />
  <add key="MicrosoftAppPassword" value="" />
  <add key="BingSpellCheckApiKey" value="YourBingSpellApiKey" />
  <add key="IsSpellCorrectionEnabled" value="true" />
</appSettings>

Then you can create a component for your bot to use Bing Spell Api, for more information, you can refer to Quickstart for Bing Spell Check API with C#. Here you can a service in your app for example like this Service.

Then in MessagesController, check the spell first before sending message to dialog. and since your want to show a confirm dialog to user if the text should be replace with the result from Bing, you can send a FormFlow first to let user to have a choice. For example:

Code of MessagesController:

private static readonly bool IsSpellCorrectionEnabled = bool.Parse(WebConfigurationManager.AppSettings["IsSpellCorrectionEnabled"]);
private BingSpellCheckService spellService = new BingSpellCheckService();

/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
   if (activity.Type == ActivityTypes.Message)
    {
        if (IsSpellCorrectionEnabled)
        {
            try
            {
                var text = await this.spellService.GetCorrectedTextAsync(activity.Text);
                if(text != activity.Text)
                {
                    //if spelling is wrong, go to rootdialog
                    await Conversation.SendAsync(activity, () => new Dialogs.RootDialog(activity.Text, text));
                }
                else
                {
                    //if right, direct go to luisdialog

                    await Conversation.SendAsync(activity, () => new Dialogs.MyLuisDialog());

                }
            }
            catch(Exception ex)
            {
                Trace.TraceError(ex.ToString());
            }
        }
        else
        {
            await Conversation.SendAsync(activity, () => new Dialogs.MyLuisDialog());
        }

    }
    else
    {
        HandleSystemMessage(activity);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}

Code of my RootDialog:

[Serializable]
public class RootDialog : IDialog<object>
{
    private string otext;
    private string ntext;
    public RootDialog(string oldtext, string newtext)
    {
        otext = oldtext;
        ntext = newtext;
    }

    public async Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);
    }

    public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
    {
        var message = await result;
        var form = new FormDialog<Confirmation>(new Confirmation(otext, ntext),
                Confirmation.BuildForm, FormOptions.PromptInStart, null);
        context.Call(form, this.GetResultAsync);
    }

    private async Task GetResultAsync(IDialogContext context, IAwaitable<Confirmation> result)
    {
        var state = await result;
        await context.Forward(new MyLuisDialog(), null, context.Activity, System.Threading.CancellationToken.None);
    }

}

[Serializable]
public class Confirmation
{

    public string Text { get; set; }
    private static string otext;
    private static string ntext;
    public Confirmation(string oldtext, string newtext)
    {
        otext = oldtext;
        ntext = newtext;
    }
    public static IForm<Confirmation> BuildForm()
    {
        return new FormBuilder<Confirmation>()
            .Field(new FieldReflector<Confirmation>(nameof(Text))
            .SetType(null)
            .SetDefine(async(state, field) =>
            {
                field
                .AddDescription(otext, otext)
                .AddTerms(otext, otext)
                .AddDescription(ntext,ntext)
                .AddTerms(ntext, ntext);

                return true;
            }))
            .Build();
    }
}


问:
Navigation Bar Failure
So I have an navigation bar for my website that is pretty basic, you click on the word and it takes you to that page. Well after putting a drop down on my page the navigation menu suddenly stopped working. Can anyone see a problem here that I am missing that would allowing the navigation menu to suddenly stop working after a drop down menu occurs?

<!DOCTYPE html>

        Welcome to All About History

Home

About Me

People in History

Contact Me

```

答:
This happens because your dropdown has z-index:999. Even though it fades out it is still there on top of the navigation bar with 0 opacity. In your welcome-fadeout, make the z-index '-1' so that nav bar comes on top of the banner

<!DOCTYPE html>

        Welcome to All About History

Home

About Me

People in History

Contact Me

```

Title: Navigation Bar Failure

Body:
This happens because your dropdown has z-index:999. Even though it fades out it is still there on top of the navigation bar with 0 opacity. In your welcome-fadeout, make the z-index '-1' so that nav bar comes on top of the banner

<!DOCTYPE html>
<html>
<head>
<style>
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover:not(.active) {
    background-color: #111;
}

.active {
    background-color: #4CAF50;

    }

.dropdown-notification {
 height: 25vh;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  line-height: 40px;
  background-color: #4CAF50;
  animation: welcome-dropdown 2s ease, welcome-fadeout 2s 4s forwards;
  text-align: center;
  vertical-align: middle;
  line-height: 25vh;
  font-size: 70px;
}

@keyframes welcome-dropdown {
  from {
    transform: translateY(calc(-100vh));
  }
  to {
    transform: translateY(0);
  }
}

@keyframes welcome-fadeout {
  from {
    opacity: 1;
  }

  to {
    opacity: 0;
    z-index: -1;
  }
}
</style>
</head>
<body>

<div class="dropdown-notification text-center">
        Welcome to All About History
   </div>

 <nav>
  <ul>
     <li><a class="active" href="website.html">Home</a></li>
    <li><a href="about.html">About Me</a></li>
    <li><a href="people.html">People in History</a></li>
    <li><a href="contact.html">Contact Me</a></li>
  </ul>
</nav>

</body>
</html>


问:
Redirect cache is stuck in Chrome
I've disabled caching when the dev tools are open but it is still redirecting me to a page I accidentally set as a 301 redirect when testing some code. Now I can't get to the correct page because Chrome always assumes I'm trying to get to the original page I redirected to when I was testing.

For instance, I setup a test redirect from http://example.dev/page-1 to go to http://example.dev/page-2 but that was accidental. I need it to actually load http://example.dev/page-1 but every time it now takes me to http://example.dev/page-2 which doesn't actually exist.

I've tried clearing the application cache as well and doing a hard reload on the site but those didn't work.

What am I missing here?

答:
Chrome always cache page redirection. Try the following way to clear redirection cache.

Go to chrome://net-internals/

Clear cache with top right arrow option Clear cache

Try on your page again :)

hope this can help you

Title: Redirect cache is stuck in Chrome


问:
Get Google Analytics data using GAPI without login in

I have a news website and I have to show the "Top 5 most visited news of the day" using the data tracked with google analytics, but I haven't managed to make it work. Every code example I've found shows a pop up to login, as if he had his google account linked with the data in analytics, but obviously that's not the case.

I'm trying using this with JS, something like this

```<code><script src="https://apis.google.com/js/client:platform.js"></script>

...

<script>
    function start() {
      // 2. Initialize the JavaScript client library.
      gapi.client.load('analytics', 'v3').then(function() {
        gapi.client.init({
          'apiKey': 'SOME_API_KEY',
          'clientId': 'SOME_CLIENT_ID',
          'scope': 'https://www.googleapis.com/auth/analytics.readonly',
        }).then(function() {
            return gapi.client.analytics.data.ga.get({
              'ids': 'ga:' + "SOME_ID",
              'start-date': 'yesterday',
              'end-date': 'today',
              'metrics': 'ga:pageviews',
              'dimensions': 'ga:pagetitle',
              'max-results': '5',
              'sort': '-ga:pageviews,-ga:date'
            });
        }).then(function(response) {
          console.log(response  );
        }, function(reason) {
          console.log(reason)
          console.log('Error: ' + reason.result.error.message);
        });
      });
    };
    gapi.load('client', start);
</script>
</code>```

And I'm getting this response:

```<code>{result: {…}, body: "{↵  "error": {↵    "code": 401,↵    "message": "Re…project.",↵    "status": "UNAUTHENTICATED"↵  }↵}↵", headers: {…}, status: 401, statusText: null}
body
:
"{↵  "error": {↵    "code": 401,↵    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",↵    "status": "UNAUTHENTICATED"↵  }↵}↵"
</code>```

What am i missing?

答:
I'm not sure if you are able to use NodeJS. But if you use the google-oauth-jwt library or the googleapis library. See this link for an example tutorial for googleapis with NodeJS.

You need to use a key from the service account, so you need to create a service account. You could login with an access token, by using googleapis.auth.JWT, which needs your serviceaccount emailaddress, the private key and the scope ['https://www.googleapis.com/auth/analytics.readonly']

I'll show you some example code from a project of mine:

Googleapis library NodeJS (I'm using express and I used a promise in my routing to get the key, and google api data)

```<code>var jwtClient = new google.auth.JWT(
            '[your serviceaccount@emailaddress]',
            path.join(__dirname, '../.', '/files/KEY.json'),//path to your json key file]
            null,
            ['https://www.googleapis.com/auth/analytics.readonly'] //scope
        );

        jwtClient.authorize(function (err, tokens) {
            console.log('jwtClient.authorize() started');

            //console.log(tokens);
            if (err) {
                console.log('error in authorization:' + err);
                return;
            } else {
                console.log('authorization success!');
                console.log(tokens);
                return tokens;
            }
        });

var VIEW_ID = 'ga:[yourviewid]';
    analytics.data.ga.get({
        'auth': jwtClient,
        'ids': VIEW_ID,
        'metrics': 'ga:uniquePageviews',
        'dimensions': 'ga:pagePath',
        'start-date': 'today',
        'end-date': 'today',
        'sort': '-ga:uniquePageviews',
        'max-results': 5,

    }, function (err, response) {
        if (err) {
            console.log(err);
            return;
        }
        //console.log(JSON.stringify(response, null, 4));
        return JSON.stringify(response, null, 4);
    });
</code>```

Example with routing and Google-oauth-jwt library

```<code>var express = require('express');
var router = express.Router();
var googleAuth = require('google-oauth-jwt');

router.get('/login', function(req, res, next) {
      googleAuth.authenticate({
        email: 'yourserviceaccount@project.iam.gserviceaccount.com',
        // use the PEM file we generated from the downloaded key
        key: "-----BEGIN PRIVATE KEY-----\nMII [your big ass private key which can be obtained by using a file too.-----END PRIVATE KEY-----\n",
        // specify the scopes you wish to access
        scopes: ['https://www.googleapis.com/auth/analytics.readonly']
        }, function (err, token) {
          res.json({token: token});
      });
    });
</code>```

Body:
I have a news website and I have to show the "Top 5 most visited news of the day" using the data tracked with google analytics, but I haven't managed to make it work. Every code example I've found shows a pop up to login, as if he had his google account linked with the data in analytics, but obviously that's not the case.

I'm trying using this with JS, something like this

...

And I'm getting this response:

{result: {…}, body: "{↵  "error": {↵    "code": 401,↵    "message": "Re…project.",↵    "status": "UNAUTHENTICATED"↵  }↵}↵", headers: {…}, status: 401, statusText: null}
body
:
"{↵  "error": {↵    "code": 401,↵    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",↵    "status": "UNAUTHENTICATED"↵  }↵}↵"

What am i missing?

Body:
I'm not sure if you are able to use NodeJS. But if you use the google-oauth-jwt library or the googleapis library. See this link for an example tutorial for googleapis with NodeJS.

You need to use a key from the service account, so you need to create a service account. You could login with an access token, by using googleapis.auth.JWT, which needs your serviceaccount emailaddress, the private key and the scope ['https://www.googleapis.com/auth/analytics.readonly']

I'll show you some example code from a project of mine:

Googleapis library NodeJS (I'm using express and I used a promise in my routing to get the key, and google api data)

var jwtClient = new google.auth.JWT(
            '[your serviceaccount@emailaddress]',
            path.join(__dirname, '../.', '/files/KEY.json'),//path to your json key file]
            null,
            ['https://www.googleapis.com/auth/analytics.readonly'] //scope
        );

        jwtClient.authorize(function (err, tokens) {
            console.log('jwtClient.authorize() started');

            //console.log(tokens);
            if (err) {
                console.log('error in authorization:' + err);
                return;
            } else {
                console.log('authorization success!');
                console.log(tokens);
                return tokens;
            }
        });

var VIEW_ID = 'ga:[yourviewid]';
    analytics.data.ga.get({
        'auth': jwtClient,
        'ids': VIEW_ID,
        'metrics': 'ga:uniquePageviews',
        'dimensions': 'ga:pagePath',
        'start-date': 'today',
        'end-date': 'today',
        'sort': '-ga:uniquePageviews',
        'max-results': 5,

    }, function (err, response) {
        if (err) {
            console.log(err);
            return;
        }
        //console.log(JSON.stringify(response, null, 4));
        return JSON.stringify(response, null, 4);
    });

Example with routing and Google-oauth-jwt library

var express = require('express');
var router = express.Router();
var googleAuth = require('google-oauth-jwt');

router.get('/login', function(req, res, next) {
      googleAuth.authenticate({
        email: 'yourserviceaccount@project.iam.gserviceaccount.com',
        // use the PEM file we generated from the downloaded key
        key: "-----BEGIN PRIVATE KEY-----\nMII [your big ass private key which can be obtained by using a file too.-----END PRIVATE KEY-----\n",
        // specify the scopes you wish to access
        scopes: ['https://www.googleapis.com/auth/analytics.readonly']
        }, function (err, token) {
          res.json({token: token});
      });
    });


问:
How do I initialize and use exported ReactJS classes from other modules (with WebPack and ES6)?
I'm using WebPack and ES6, so I can't use module.exports and have to use export default. I have a library like this:

```<code>// helloworld.js
import React from 'react';

class HelloWorld extends React.Component {
        test() {
                alert("TEST FROM test()");
        }
        render() {
                alert("TEST");
                return (
                        <p>Hello, world!</p>
                );
        }
}

// THIS WORKS WHEN I REQUIRE THIS MODULE
// var thing = new HelloWorld();
// thing.test();

export default HelloWorld;
</code>```

The commented out portions work when I var helloworld = require('helloworld.js');, but I can't figure out how to initialize and use this object outside where I require this.

None of these attempts work. How do I initialize this object and use it?

```<code>// hello_world.test();
// hello_world.HelloWorld.test();
// var thing = new hello_world();
// var thing = new hello_world.HelloWorld();
</code>```

My main reason is because I need the component in a route using ReactRouter like this and none of these attempts work.

I tried this (bellow) and this tells me to check the render method...

```<code>ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world}/>
        </Switch>
</BrowserRouter>)
</code>```

This (bellow) renders a BLANK PAGE!!!!

```<code>ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world.HelloWorld}/>
        </Switch>
</BrowserRouter>)
</code>```

I'm out of ideas. This does not help. Neither does this. Could please someone lend me some pointers?

EDIT:

Solution was simply to add default at the end of require (var hello_world = require('./helloworld.js').default;). This works to use this in the route like: <Route exact path="/helloworld" component={hello_world}/>.

If you were to use this outside the scope, you would do:

```<code>var thing = new hello_world();
thing.test();
</code>```

Working solution:

```<code>var hello_world = require('./hello_world.js').default; // Must add default.

// Using it outside a route, with a class method called test().
var thing = new hello_world();
thing.test();

// Using it in a router (ReactRouter with Switch).
ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world}/>
        </Switch>
</BrowserRouter>)
, document.getElementById("root"));
</code>```

答:
You should be able to use the component in a regular jsx file like this:

```<code>var HelloWorld = require('path/to/HelloWorld.jsx');
...
<div>
    <HelloWorld></HelloWorld>
</div>
</code>```

Or in a react-router component, with the same require statement like this:

```<code>var HelloWorld = require('path/to/HelloWorld.jsx');
....
<Route exact path="/helloworld" component={HelloWorld}/>
</code>```

Body:
I'm using WebPack and ES6, so I can't use module.exports and have to use export default. I have a library like this:

// helloworld.js
import React from 'react';

class HelloWorld extends React.Component {
        test() {
                alert("TEST FROM test()");
        }
        render() {
                alert("TEST");
                return (

Hello, world!

                );
        }
}

// THIS WORKS WHEN I REQUIRE THIS MODULE
// var thing = new HelloWorld();
// thing.test();

export default HelloWorld;

The commented out portions work when I var helloworld = require('helloworld.js');, but I can't figure out how to initialize and use this object outside where I require this.

None of these attempts work. How do I initialize this object and use it?

// hello_world.test();
// hello_world.HelloWorld.test();
// var thing = new hello_world();
// var thing = new hello_world.HelloWorld();

My main reason is because I need the component in a route using ReactRouter like this and none of these attempts work.

I tried this (bellow) and this tells me to check the render method...

ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world}/>
        </Switch>
</BrowserRouter>)

This (bellow) renders a BLANK PAGE!!!!

ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world.HelloWorld}/>
        </Switch>
</BrowserRouter>)

I'm out of ideas. This does not help. Neither does this. Could please someone lend me some pointers?

EDIT:

Solution was simply to add default at the end of require (var hello_world = require('./helloworld.js').default;). This works to use this in the route like: <Route exact path="/helloworld" component={hello_world}/>.

If you were to use this outside the scope, you would do:

var thing = new hello_world();
thing.test();

Working solution:

var hello_world = require('./hello_world.js').default; // Must add default.

// Using it outside a route, with a class method called test().
var thing = new hello_world();
thing.test();

// Using it in a router (ReactRouter with Switch).
ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world}/>
        </Switch>
</BrowserRouter>)
, document.getElementById("root"));

Body:
You should be able to use the component in a regular jsx file like this:

var HelloWorld = require('path/to/HelloWorld.jsx');
...
<div>
    <HelloWorld></HelloWorld>
</div>

Or in a react-router component, with the same require statement like this:

var HelloWorld = require('path/to/HelloWorld.jsx');
....
<Route exact path="/helloworld" component={HelloWorld}/>


问:
rails partial rendering html does not run javascript
Hi I am calling a partial from controller file but the javascript inside the partial is not executing . The partial is of .html.erb format.

```<code><% content_for :javascript do %>

  <script type="text/javascript">
    var eventName = typeof(Turbolinks) !== 'undefined' ? 'page:change' : 'DOMContentLoaded';

    document.addEventListener(eventName, function() {
      console.log("hello");

      <% if flash[:notice] %>
        ShopifyApp.flashNotice("<%= escape_javascript flash[:notice].html_safe %>");
      <% end %>

      <% if flash[:error] %>
        ShopifyApp.flashError("<%= escape_javascript flash[:error].html_safe %>");
      <% end %>
    });
  </script>
<% end %>
</code>```

is the code for partial

```<code> respond_to do |format|
    if @timer.save

      flash[:notice]="updated"
      format.html{render :partial => "layouts/flash_messages", :locals => {:flash => flash}}

    else
        flash[:error]="error"
      format.html{render :partial => "layouts/flash_messages", :locals => {:flash => flash}}
    end
</code>```

is the controller code .

答:
If you want to render Javascript in rails use below method.

Controller Code looks like:

```<code>def create
  @user = User.find(params[:id])
  respond_to do |format|
    format.html {redirect_to @user }
    format.js
  end
end
</code>```

template this code going to render will look like.

filename:  create.js.erb

```<code> $("#someidname").html("<%= @user.email %>");
</code>```

Note @user is also available here. you can render other partial also like:

```<code>$("#someit").html("<%= escape_javascript(render('users/email')) %>");
</code>```

Also, make sure you are sending ajax request.

Body:
Hi I am calling a partial from controller file but the javascript inside the partial is not executing . The partial is of .html.erb format.

<% content_for :javascript do %>

<% end %>

is the code for partial

 respond_to do |format|
    if @timer.save

      flash[:notice]="updated"
      format.html{render :partial => "layouts/flash_messages", :locals => {:flash => flash}}

    else
        flash[:error]="error"
      format.html{render :partial => "layouts/flash_messages", :locals => {:flash => flash}}
    end

is the controller code .

Body:
If you want to render Javascript in rails use below method.

Controller Code looks like:

def create
  @user = User.find(params[:id])
  respond_to do |format|
    format.html {redirect_to @user }
    format.js
  end
end

template this code going to render will look like.

filename:  create.js.erb

 $("#someidname").html("<%= @user.email %>");

Note @user is also available here. you can render other partial also like:

$("#someit").html("<%= escape_javascript(render('users/email')) %>");

Also, make sure you are sending ajax request.


问:
Powershell, Mass moving files of a certain type
I want to make a script which will take a parent directory which has a number of child directories which have files in them. Using a listing I wish to move all of the files in the child directories in to the parent directory. </p>

<p>I have created the following code so far which gives a listing of all the files of the specified type in the child directories but I am unsure how to a mass move of all the child files. </p>

```<code>    Write-host "Please enter source Dir:"
$sourceDir = read-host

Write-Host "Format to look for with .  :"
$format = read-host

#Write-host "Please enter output Dir:"
#$outDir = read-host

$Dir = get-childitem -Path $sourceDir -Filter $format -recurse | format-table name

$files = $Dir | where {$_.extension -eq "$format"}
$files #| format-table name
</code>```

答:
A previous poster pointed out that the script would overwrite files of the same name. It might be possible to extend the script by a test and to avoid that possibility. Something like this:</p>

```<code>$sourceDir = read-host "Please enter source Dir"
$format = read-host "Format to look for?"
$destDir = read-host "Please enter Destination Dir"

Get-ChildItem -Path $sourceDir -Filter $format -Recurse | Copy-Item   -Destination $DestDir
$files = $DestDir | where {$_.extension -eq "$format"}

If (Test-Path $files) {
    $i = 0
    While (Test-Path $DestinationFile) {
        $i += 1
        $DestinationFile = "$files$i.$format"
        Copy-Item -Destination $DestDir  $DestinationFile
    }
}
Else {
    $DestinationFile = "$files$i.$format"
    Copy-Item -Destination $DestDir $DestinationFile
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -Force
</code>```

Body:
I want to make a script which will take a parent directory which has a number of child directories which have files in them. Using a listing I wish to move all of the files in the child directories in to the parent directory.

I have created the following code so far which gives a listing of all the files of the specified type in the child directories but I am unsure how to a mass move of all the child files.

    Write-host "Please enter source Dir:"
$sourceDir = read-host

Write-Host "Format to look for with .  :"
$format = read-host

#Write-host "Please enter output Dir:"
#$outDir = read-host

$Dir = get-childitem -Path $sourceDir -Filter $format -recurse | format-table name

$files = $Dir | where {$_.extension -eq "$format"}
$files #| format-table name

Body:
A previous poster pointed out that the script would overwrite files of the same name. It might be possible to extend the script by a test and to avoid that possibility. Something like this:

$sourceDir = read-host "Please enter source Dir"
$format = read-host "Format to look for?"
$destDir = read-host "Please enter Destination Dir"

Get-ChildItem -Path $sourceDir -Filter $format -Recurse | Copy-Item   -Destination $DestDir
$files = $DestDir | where {$_.extension -eq "$format"}

If (Test-Path $files) {
    $i = 0
    While (Test-Path $DestinationFile) {
        $i += 1
        $DestinationFile = "$files$i.$format"
        Copy-Item -Destination $DestDir  $DestinationFile
    }
}
Else {
    $DestinationFile = "$files$i.$format"
    Copy-Item -Destination $DestDir $DestinationFile
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -Force