问:
Import excel table sheet in word by aspose.word for C# .Net
I have a excel file and i want to import a sheet from it to my .DOCX file created by aspose.word .I tried InsertOleObject but that did not show any table and just show a object shape that linked to excel file.

答:
Unfortunately, there is no direct way to convert Excel document to Word. However, it is possible with the collaboration of Aspose.Cells and Aspose.Pdf. First convert Excel document to PDF using Aspose.Cells and later convert the PDF document to Word document using Aspose.Pdf. Please check following sample code for the purpose.

```<code>//Use Aspose.Cells to convert XLS to Word document
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook("Book1.xls");
// To convert first sheet only you need to hide other worksheets
workbook.Worksheets[1].IsVisible = false;
// Save the XLS document into PDF document
workbook.Save("output.pdf", Aspose.Cells.SaveFormat.Pdf);
//Use Aspose.Pdf to convert PDF to Word document
// Open the source PDF document
Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document("output.pdf");
// Save the PDF file into Word document
pdfDocument.Save("PDFToDOCX_out.docx", Aspose.Pdf.SaveFormat.DocX);
</code>```

I work with Aspose as developer evangelist.

Body:
Unfortunately, there is no direct way to convert Excel document to Word. However, it is possible with the collaboration of Aspose.Cells and Aspose.Pdf. First convert Excel document to PDF using Aspose.Cells and later convert the PDF document to Word document using Aspose.Pdf. Please check following sample code for the purpose.

//Use Aspose.Cells to convert XLS to Word document
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook("Book1.xls");
// To convert first sheet only you need to hide other worksheets
workbook.Worksheets[1].IsVisible = false;
// Save the XLS document into PDF document
workbook.Save("output.pdf", Aspose.Cells.SaveFormat.Pdf);
//Use Aspose.Pdf to convert PDF to Word document
// Open the source PDF document
Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document("output.pdf");
// Save the PDF file into Word document
pdfDocument.Save("PDFToDOCX_out.docx", Aspose.Pdf.SaveFormat.DocX);

I work with Aspose as developer evangelist.


来源: stackexchange

问:
Add date format into date regex
I am getting date format like this /Date(1495111091673)/.
I have created one custom filter to change date format.

```<code>app.filter('jsonDate', function () {
    return function (date) {
        return new Date(date.match(/\d+/)[0] * 1);
    }
})
</code>```

This filter returns date like this.

```<code>Thu May 18 2017 18:08:11 GMT+0530 (India Standard Time)
</code>```

But I want it as standard format like dd/MM/yyyy so I have edited my filter code like this:

```<code>app.filter('jsonDate', function () {
    return function (date) {
        return new Date(date.match(/\d+/)[0] * 1, 'dd MMMM @ HH:mm:ss');
    }
})
</code>```

Is it correct?

答:
This filter returns date like this

  Thu May 18 2017 18:08:11 GMT+0530 (India Standard Time)

No it doesn't, that's just how your console (or whatever) is choosing to display the Date instance (via Date.prototype.toString()).

I'd just use AngularJS's date filter ~ https://docs.angularjs.org/api/ng/filter/date.

For example (where dateFormat is your "/Date(1495111091673)/" formatted string)

```<code>{{dateFormat | jsonDate | date : 'shortDate'}}
</code>```

Or in JS

```<code>let parsed = $filter('jsonDate')(dateFormat)
let dateString = $filter('date')(parsed, 'shortDate')
</code>```

or via DI

```<code>.controller('controllerName', ['dateFilter', 'jsonDateFilter',
function(dateFilter, jsonDateFilter) {
  let dateString = dateFilter(jsonDateFilter(dateFormat), 'shortDate')
}])
</code>```

ContentLicense: CC BY-SA 3.0

Title: Add date format into date regex

Body:
I am getting date format like this /Date(1495111091673)/.
I have created one custom filter to change date format.

app.filter('jsonDate', function () {
    return function (date) {
        return new Date(date.match(/\d+/)[0] * 1);
    }
})

This filter returns date like this.

Thu May 18 2017 18:08:11 GMT+0530 (India Standard Time)

But I want it as standard format like dd/MM/yyyy so I have edited my filter code like this:

app.filter('jsonDate', function () {
    return function (date) {
        return new Date(date.match(/\d+/)[0] * 1, 'dd MMMM @ HH:mm:ss');
    }
})

Is it correct?

Body:
This filter returns date like this

  Thu May 18 2017 18:08:11 GMT+0530 (India Standard Time)

No it doesn't, that's just how your console (or whatever) is choosing to display the Date instance (via Date.prototype.toString()).

I'd just use AngularJS's date filter ~ https://docs.angularjs.org/api/ng/filter/date.

For example (where dateFormat is your "/Date(1495111091673)/" formatted string)

{{dateFormat | jsonDate | date : 'shortDate'}}

Or in JS

let parsed = $filter('jsonDate')(dateFormat)
let dateString = $filter('date')(parsed, 'shortDate')

or via DI

.controller('controllerName', ['dateFilter', 'jsonDateFilter',
function(dateFilter, jsonDateFilter) {
  let dateString = dateFilter(jsonDateFilter(dateFormat), 'shortDate')
}])


问:
running a command line containing Pipes and displaying result to STDOUT
How would one call a shell command from Python which contains a pipe and capture the output?

Suppose the command was something like:

```<code>cat file.log | tail -1
</code>```

The Perl equivalent of what I am trying to do would be something like:

```<code>my $string = `cat file.log | tail -1`;
</code>```

答:
This is a fork from @chown with some improvements:

an alias for import subprocess, makes easier when setting parameters

if you just want the output, you don't need to set stderr or stdin when calling Popen

for better formatting, it's recommended to decode the output

shell=True is necessary, in order to call an interpreter for the command line

```<code>#!/usr/bin/python3

import subprocess as sp

p = sp.Popen("cat app.log | grep guido", shell=True, stdout=sp.PIPE)

output = p.stdout.read()
print(output.decode('utf-8'))
</code>```

```<code>$ cat app.log
2017-10-14 22:34:12, User Removed [albert.wesker]
2017-10-26 18:14:02, User Removed [alexei.ivanovich]
2017-10-28 12:14:56, User Created [ivan.leon]
2017-11-14 09:22:07, User Created [guido.rossum]

$ python3 subproc.py
2017-11-14 09:22:07, User Created [guido.rossum]
</code>```

Body:
How would one call a shell command from Python which contains a pipe and capture the output?

Suppose the command was something like:

cat file.log | tail -1

The Perl equivalent of what I am trying to do would be something like:

my $string = `cat file.log | tail -1`;

Body:
This is a fork from @chown with some improvements:

an alias for import subprocess, makes easier when setting parameters

if you just want the output, you don't need to set stderr or stdin when calling Popen

for better formatting, it's recommended to decode the output

shell=True is necessary, in order to call an interpreter for the command line

#!/usr/bin/python3

import subprocess as sp

p = sp.Popen("cat app.log | grep guido", shell=True, stdout=sp.PIPE)

output = p.stdout.read()
print(output.decode('utf-8'))

$ cat app.log
2017-10-14 22:34:12, User Removed [albert.wesker]
2017-10-26 18:14:02, User Removed [alexei.ivanovich]
2017-10-28 12:14:56, User Created [ivan.leon]
2017-11-14 09:22:07, User Created [guido.rossum]

$ python3 subproc.py
2017-11-14 09:22:07, User Created [guido.rossum]


问:
Python script - file operations
I am trying to fetch the free disk space details of each drive using Python Scripts and storing the values in a variable 'p'.

```<code>p=(disk_usage('C:/'))
    f=open('C:\\Python27\\solr.log','a')
    f.write("Solr "+p)
</code>```

I would like to place the results from variable 'p' into a log file. If I print the variable 'p', I am able to get the results successfully. But when I try to open a log file and write into it, it is throwing the below error.

```<code>"Traceback (most recent call last):
  File "C:\Python27\sample.py", line 51, in <module>
    f.write("Result: "+p)
TypeError: must be str, not UsageTuple"
</code>```

Could anyone please help me on this.

答: I got the answer. Just changed the 'p' variable to string and then I tried to write into file. I am able to get the results in my log file.</p>

Title: Python script - file operations

Body:
I am trying to fetch the free disk space details of each drive using Python Scripts and storing the values in a variable 'p'.

p=(disk_usage('C:/'))
    f=open('C:\\Python27\\solr.log','a')
    f.write("Solr "+p)

I would like to place the results from variable 'p' into a log file. If I print the variable 'p', I am able to get the results successfully. But when I try to open a log file and write into it, it is throwing the below error.

"Traceback (most recent call last):
  File "C:\Python27\sample.py", line 51, in <module>
    f.write("Result: "+p)
TypeError: must be str, not UsageTuple"

Could anyone please help me on this.


问:
Obj-C - Dismiss keyboard by tapping anywhere on screen from UITextView?
When my user taps on my UITextView (NOT uitextfield...), an animation occurs. However after the UITextView begins editing, no other UITapGesture seems to be recognized (e.g. if I add a tapGesture to my UIView to dismiss this animation, it doesn't execute at all). I've been trying to fix this for what feels like forever. Help is appreciated, I'm stumped.

ViewController.m

```<code> - (void)viewDidLoad
        {
            [super viewDidLoad];

         self.replyField.delegate = self;

        [self.replyField setUserInteractionEnabled:YES];

        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewTapped)];
        [self.view addGestureRecognizer:gestureRecognizer];

        }

    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {

        return YES;

    }

    -(void)textViewTapped {
        NSLog(@"DISMISS PLEASE!");
        [self animateTextView:NO];

    }

       - (void)textViewDidBeginEditing:(UITextView *)textView
    {

        [self animateTextView: YES];
        self.replyField.gestureRecognizers = nil;

    }

    - (void)textViewDidEndEditing:(UITextView *)textView
    {
        [self animateTextView:NO];

    }

    - (void) animateTextView:(BOOL) up
    {
        const int movementDistance = 206;
        const float movementDuration = 0.3f;
        int movement= movement = (up ? -movementDistance : movementDistance);
        NSLog(@"%d",movement);

        [UIView beginAnimations: @"anim" context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);
        [UIView commitAnimations];

    }

    - (void)textViewDidChange:(UITextView *)textView
    {

    }
</code>```

答:
Not clearly understand what you want BTW let me explain.

First of all if you want to hide your keyboard you can do it by single line code.

Objective C

```<code>[self.view endEditing:YES];
</code>```

Swift

```<code> view.endEditing(true)
</code>```

Now in your code, you added tap gesture on self.view it means if you touch main view anywhere then your gesture method will be call. If you want that my keyboard will be hide when I touch on main view then in tap gesture's method you should write above code ([self.view endEditing:YES];) But make sure keyboard will be open if you tap on your textView.

But If you want keyboard should not open when I click on UITextView then there are many ways but follow below

Objective C

```<code>UIView* dummyInputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
myTextView.inputView = dummyInputView;
</code>```

Swift

```<code>let dummyInputView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
myTextView.inputView = dummyInputView
</code>```

Here keyboard will not be open but cursor will be blinking if you want to hide cursor then you can do by below code

Objective C

```<code> myTextView.tintColor = [UIColor clearColor];
</code>```

Swift

```<code> myTextView.tintColor = UIColor.clear
</code>```

If you have any issue then do comment.

Body:
When my user taps on my UITextView (NOT uitextfield...), an animation occurs. However after the UITextView begins editing, no other UITapGesture seems to be recognized (e.g. if I add a tapGesture to my UIView to dismiss this animation, it doesn't execute at all). I've been trying to fix this for what feels like forever. Help is appreciated, I'm stumped.

ViewController.m

 - (void)viewDidLoad
        {
            [super viewDidLoad];

         self.replyField.delegate = self;

        [self.replyField setUserInteractionEnabled:YES];

        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewTapped)];
        [self.view addGestureRecognizer:gestureRecognizer];

        }

    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {

        return YES;

    }

    -(void)textViewTapped {
        NSLog(@"DISMISS PLEASE!");
        [self animateTextView:NO];

    }

       - (void)textViewDidBeginEditing:(UITextView *)textView
    {

        [self animateTextView: YES];
        self.replyField.gestureRecognizers = nil;

    }

    - (void)textViewDidEndEditing:(UITextView *)textView
    {
        [self animateTextView:NO];

    }

    - (void) animateTextView:(BOOL) up
    {
        const int movementDistance = 206;
        const float movementDuration = 0.3f;
        int movement= movement = (up ? -movementDistance : movementDistance);
        NSLog(@"%d",movement);

        [UIView beginAnimations: @"anim" context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        self.view.frame = CGRectOffset(self.inputView.frame, 0, movement);
        [UIView commitAnimations];

    }

    - (void)textViewDidChange:(UITextView *)textView
    {

    }

Body:
Not clearly understand what you want BTW let me explain.

First of all if you want to hide your keyboard you can do it by single line code.

Objective C

[self.view endEditing:YES];

Swift

 view.endEditing(true)

Now in your code, you added tap gesture on self.view it means if you touch main view anywhere then your gesture method will be call. If you want that my keyboard will be hide when I touch on main view then in tap gesture's method you should write above code ([self.view endEditing:YES];) But make sure keyboard will be open if you tap on your textView.

But If you want keyboard should not open when I click on UITextView then there are many ways but follow below

Objective C

UIView* dummyInputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
myTextView.inputView = dummyInputView;

Swift

let dummyInputView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
myTextView.inputView = dummyInputView

Here keyboard will not be open but cursor will be blinking if you want to hide cursor then you can do by below code

Objective C

 myTextView.tintColor = [UIColor clearColor];

Swift

 myTextView.tintColor = UIColor.clear

If you have any issue then do comment.


问:
Apple Music genre selection screen
Does anybody have an idea how the genre selection bubbles in Apple music were made? The movement seems to be done with UiKit Dynamics. I definitely see collision behaviors but can't seem to reproduce the fluidity of the drag movement and the gravity towards the center of the view. I tried using UIPushBehavior and UiSnapBehavior, but no luck.

答:
i have developed it using box2d and libGdx on android,, so using libGdx u can use my code logic for iOS also...
have a look at my project, hope it helps,
https://github.com/mohitKejriwal/Bubble-UI-Android</p>

Title: Apple Music genre selection screen


问:
java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven
I'm trying to create a spring mvc application.
This is my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.acme</groupId>
    <artifactId>test</artifactId>
    <name>springmvc</name>
    <packaging>jar</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <org.springframework-version>3.1.1.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
    </properties>

    <repositories>
        <repository>
            <id>spring-milestone</id>
            <url>http://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestone</id>
            <url>http://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>

        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>

        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>

        <!-- Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>0.5.0.M6</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
            <version>0.5.0.M6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>0.5.0.M6</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <!-- com.ilppa.cocktail.Application -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.ilppa.cocktail.Application</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

when I run mvn clean install the .jar is generated but when I launch it java -jar target/test-1.0.0-BUILD-SNAPSHOT.jar

I have an error

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
    at com.acme.test.Application.main(Application.java:12)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 1 more
</code>```

I don't understand, I have no errors in eclipse, I think the .jar is in maven depences

答:
The answer to the above question is "none of the above". When you download new STS it won't support the old Spring Boot parent version. Just update parent version with latest comes with STS it will work.

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
</code>```

If you have problem getting the latest, just create a new Spring Starter Project.
Go to File->New->Spring Start Project and create a demo project you will get the latest parent version, change your version with that all will work. I do this every time I change STS.

Body:
I'm trying to create a spring mvc application.
This is my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.acme</groupId>
    <artifactId>test</artifactId>
    <name>springmvc</name>
    <packaging>jar</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <org.springframework-version>3.1.1.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
    </properties>

    <repositories>
        <repository>
            <id>spring-milestone</id>
            <url>http://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-milestone</id>
            <url>http://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>

                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>0.5.0.M6</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
            <version>0.5.0.M6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>0.5.0.M6</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.ilppa.cocktail.Application</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

when I run mvn clean install the .jar is generated but when I launch it java -jar target/test-1.0.0-BUILD-SNAPSHOT.jar

I have an error

Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/boot/SpringApplication
    at com.acme.test.Application.main(Application.java:12)
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 1 more

I don't understand, I have no errors in eclipse, I think the .jar is in maven depences

Body:
The answer to the above question is "none of the above". When you download new STS it won't support the old Spring Boot parent version. Just update parent version with latest comes with STS it will work.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

If you have problem getting the latest, just create a new Spring Starter Project.
Go to File->New->Spring Start Project and create a demo project you will get the latest parent version, change your version with that all will work. I do this every time I change STS.

ContentLicense: CC BY-SA 4.0


问:
Capybara - How to click button that is enabled by javascript while it was initialed as disabled?
I have a form with only one input box and a submit button in which the submit button is disabled until the user fill in something in the text box.

Unluckily, when I check the screenshot 'form.png', the submit button is still disabled even I already fill in a value.

spec:

```<code>scenario 'valid', js: true do
  fill_in 'Name', with: 'Hello World'
  page.save_screenshot('form.png')
end
</code>```

coffee/js:

```<code>$('#name').keyup ->
  if $('#name').val() != ''
    $('#submit').removeClass('disabled').removeAttr('disabled')
  else
    $('#submit').addClass('disabled').attr('disabled', 'disabled')
</code>```

haml/html:

```<code>= f.input :name, label: 'Name'

= f.submit 'Save', class: 'btn btn-primary form-btn', id: 'submit', disabled: true
</code>```

答:
Poltergeist definitely produces the keydown/keyup events when filling in input text fields, so it sounds like your JS isn't running. Make sure you don't have any JS code that depends on features greater than ES5, since PhantomJS doesn't support that, or errors.  In test mode all your JS assets get concatenated which means an error in any one file can prevent code in other files from being evaluated. Once you have that cleaned up you should just be able to do</p>

```<code>click_button 'Save'
</code>```

Body:
I have a form with only one input box and a submit button in which the submit button is disabled until the user fill in something in the text box.

Unluckily, when I check the screenshot 'form.png', the submit button is still disabled even I already fill in a value.

spec:

scenario 'valid', js: true do
  fill_in 'Name', with: 'Hello World'
  page.save_screenshot('form.png')
end

coffee/js:

$('#name').keyup ->
  if $('#name').val() != ''
    $('#submit').removeClass('disabled').removeAttr('disabled')
  else
    $('#submit').addClass('disabled').attr('disabled', 'disabled')

haml/html:

= f.input :name, label: 'Name'

= f.submit 'Save', class: 'btn btn-primary form-btn', id: 'submit', disabled: true

Body:
Poltergeist definitely produces the keydown/keyup events when filling in input text fields, so it sounds like your JS isn't running. Make sure you don't have any JS code that depends on features greater than ES5, since PhantomJS doesn't support that, or errors.  In test mode all your JS assets get concatenated which means an error in any one file can prevent code in other files from being evaluated. Once you have that cleaned up you should just be able to do

click_button 'Save'


问:
Azure Streaming Analytics Jobs scaling SU
I'm running into an issue I can't fix:

I created a Azure Streaming Analytics Jobs, that sometime run into this error:

```<code>Resource usage is over the capacity for one or more of the query steps.
Event processing may be delayed or stop making progress. This may be a
result of large window in your query, large events in your input, large out
of order tolerance window, or a combination of the above. Please try to
partition your query, or break down your query to more steps, and add
Streaming Unit resources from the Scale tab to avoid such condition., :
</code>```

So I decided to scale up the SU. I stopped the job, I open the scale pane and the input box keep grey. I can't change the SU value, no error message.

What can I do?

Many thanks!

答:
In order to change the SU scale you need admin/owner role on the Azure Stream Analytics job.
Sorry for the inconvenience, we are changing the user experience in order  to make this more explicit.
Let me know if it works for you after you get the admin role.
Thanks.,
JS</p>

Body:
I'm running into an issue I can't fix:

I created a Azure Streaming Analytics Jobs, that sometime run into this error:

Resource usage is over the capacity for one or more of the query steps.
Event processing may be delayed or stop making progress. This may be a
result of large window in your query, large events in your input, large out
of order tolerance window, or a combination of the above. Please try to
partition your query, or break down your query to more steps, and add
Streaming Unit resources from the Scale tab to avoid such condition., :

So I decided to scale up the SU. I stopped the job, I open the scale pane and the input box keep grey. I can't change the SU value, no error message.

What can I do?

Many thanks!


问:
Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type:
I am trying to expose REST service, but while hitting it from POSTMAN i am getting below :

WARNING: Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.util.ArrayList

Where as i have also included below jar files which are required :

```<code><dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.1</version>
    </dependency>
</code>```

Here is my REST controller Code :

```<code>@RestController
@RequestMapping("/MayankAPI")
public class TestRestAPI {
@RequestMapping(value="/sayHello" , method = RequestMethod.POST)
public TestPojo postData(@RequestBody String payload) {
  System.out.println("Hello post"+payload);
  TestPojo payload1=new TestPojo();
  payload1.setStudentName("Jack");
  return payload1;
}
@RequestMapping(value="/sayHello" , method = RequestMethod.GET)
public List<TestPojo> getData(String payload) {
  System.out.println("Hello get"+payload);
  List<TestPojo> payload1=new ArrayList<TestPojo>();
  TestPojo tp = new TestPojo();
  tp.setStudentName("Jack");
  payload1.add(tp);
  return payload1;
}
</code>```

Here is my bean which i am trying to return :

```<code>public class TestPojo {

  private String studentName;
  private String studentId;

  public String getStudentName() {
    return studentName;
  }

  public void setStudentName(String studentName) {
    this.studentName = studentName;
  }

  public String getStudentId() {
    return studentId;
  }

  public void setStudentId(String studentId) {
    this.studentId = studentId;
  }
}
</code>```

Please help me where i am doing wrong.

答:
This is happening because MappingJackson2HttpMessageConverter is not registered in my App config file as below.</p>

```<code>@Configuration
@ComponentScan("basePackages = com.test")
public class MiBenefitConfiguration extends WebMvcConfigurationSupport{

  @Bean
  public ObjectMapper getObjectMapper() {
    return new ObjectMapper();
  }

  @Bean
  public MappingJackson2HttpMessageConverter messageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(getObjectMapper());
    return converter;
  }

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(messageConverter());
    addDefaultHttpMessageConverters(converters);
  }
}
</code>```

Body:
I am trying to expose REST service, but while hitting it from POSTMAN i am getting below :

WARNING: Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.util.ArrayList

Where as i have also included below jar files which are required :

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.1</version>
    </dependency>

Here is my REST controller Code :

@RestController
@RequestMapping("/MayankAPI")
public class TestRestAPI {
@RequestMapping(value="/sayHello" , method = RequestMethod.POST)
public TestPojo postData(@RequestBody String payload) {
  System.out.println("Hello post"+payload);
  TestPojo payload1=new TestPojo();
  payload1.setStudentName("Jack");
  return payload1;
}
@RequestMapping(value="/sayHello" , method = RequestMethod.GET)
public List<TestPojo> getData(String payload) {
  System.out.println("Hello get"+payload);
  List<TestPojo> payload1=new ArrayList<TestPojo>();
  TestPojo tp = new TestPojo();
  tp.setStudentName("Jack");
  payload1.add(tp);
  return payload1;
}

Here is my bean which i am trying to return :

public class TestPojo {

  private String studentName;
  private String studentId;

  public String getStudentName() {
    return studentName;
  }

  public void setStudentName(String studentName) {
    this.studentName = studentName;
  }

  public String getStudentId() {
    return studentId;
  }

  public void setStudentId(String studentId) {
    this.studentId = studentId;
  }
}

Please help me where i am doing wrong.

Body:
This is happening because MappingJackson2HttpMessageConverter is not registered in my App config file as below.

@Configuration
@ComponentScan("basePackages = com.test")
public class MiBenefitConfiguration extends WebMvcConfigurationSupport{

  @Bean
  public ObjectMapper getObjectMapper() {
    return new ObjectMapper();
  }

  @Bean
  public MappingJackson2HttpMessageConverter messageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(getObjectMapper());
    return converter;
  }

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(messageConverter());
    addDefaultHttpMessageConverters(converters);
  }
}


问:
what is the good way to render html contents in angular4?
I have a string of html contents. How to render it in html page without using document.write() in angular 4?

my string looks like:

```<code>`<mark>4.95</mark><mark>Nunavut</mark><mark>Office Furnishings</mark><mark>0.37
 7</mark><mark>"Angle-D Binders with Locking Rings</mark><mark> Label Holders"</mark><mark>Carl Jackson</mark><mark>613</mark><mark>-54.04</mark><mark>7.3</mark><mark>7.72</mark><mark>Nunavut</mark><mark>Binders and Binder Accessories</mark><mark>0.38
 8</mark><mark>"SAFCO Mobile Desk Side File</mark><mark> Wire Frame"</mark><mark>Carl Jackson</mark><mark>613</mark><mark>127.70</mark><mark>42.76</mark><mark>6.22</mark>Nunavut<mark>Storage & Organization</mark><mark>
 9</mark><mark>"SAFCO Commercial Wire Shelving</mark><mark> Black"</mark><mark>Monica Federle</mark><mark>643</mark><mark>-695.26</mark><mark>138.14</mark><mark>35</mark><mark>Nunavut</mark><mark>Storage & Organization</mark><mark>
 10</mark><mark>Xerox 198</mark><mark>Dorothy Badders</mark><mark>678</mark><mark>-226.36</mark><mark>4.98</mark><mark>8.33</mark>
`
</code>```

答:
Save your string like:

```<code>htmlString:String = `<mark> ..... </mark>`;
</code>```

And you can use innerHTML in a div like this:

```<code><div [innerHTML]="htmlString"></div>
</code>```

Source

Body:
I have a string of html contents. How to render it in html page without using document.write() in angular 4?

my string looks like:

`4.95NunavutOffice Furnishings0.37
 7"Angle-D Binders with Locking Rings Label Holders"Carl Jackson613-54.047.37.72NunavutBinders and Binder Accessories0.38
 8"SAFCO Mobile Desk Side File Wire Frame"Carl Jackson613127.7042.766.22NunavutStorage & Organization
 9"SAFCO Commercial Wire Shelving Black"Monica Federle643-695.26138.1435NunavutStorage & Organization
 10Xerox 198Dorothy Badders678-226.364.988.33
`

Body:
Save your string like:

htmlString:String = `<mark> ..... </mark>`;

And you can use innerHTML in a div like this:

<div [innerHTML]="htmlString"></div>

Source


问:
How to get everything before and up to a certain substring within a string?
How would I return a string up to a certain character?

```<code>def get_header(s):
    '''(str) -> str
    Return the start of the given string upto and including
    </head>.'''
    return (s.split('</head>')[0])
</code>```

this is what i did but, I don't know how i would get everything before the "  "<"/heads">"" and including it.

for example:

```<code>s ="hello python world </head> , i'm a beginner "
get_header(s)
</code>```

this would return

"hello python world "<"/head">"   #without the quotient marks around the <
```

答:
more_itertools is a third-party library that implements a split_after tool.  Install via:

```<code>> pip install more_itertools
</code>```

Given

```<code>import more_itertools as mit

s = "hello python world </head> , i'm a beginner "
</code>```

Code

```<code>pred = lambda x: x == "</head>"
" ".join(next(mit.split_after(s.split(), pred)))
# 'hello python world </head>'
</code>```

The string is split by spaces into "words".  The full string is split after any words that suit the predicate.  The first result is joined together.

Body:
How would I return a string up to a certain character?

def get_header(s):
    '''(str) -> str
    Return the start of the given string upto and including
    .'''
    return (s.split('')[0])

this is what i did but, I don't know how i would get everything before the "  "<"/heads">"" and including it.

for example:

s ="hello python world  , i'm a beginner "
get_header(s)

this would return

"hello python world "<"/head">"   #without the quotient marks around the <

Body:
more_itertools is a third-party library that implements a split_after tool.  Install via:

> pip install more_itertools

Given

import more_itertools as mit

s = "hello python world </head> , i'm a beginner "

Code

pred = lambda x: x == "</head>"
" ".join(next(mit.split_after(s.split(), pred)))
# 'hello python world </head>'

The string is split by spaces into "words".  The full string is split after any words that suit the predicate.  The first result is joined together.


问:
using !! symbol before the scope variable in ng-show what would represent this ( !! )symbol
what is the real meaning of using (!)before the scope variable in angularjs.
ng-show="!!file". What would indicate if I use this symbol in angularjs ng-directives</p>

答:
From: https://developer.mozilla.org/en-US/docs/Glossary/Truthy

In JavaScript, a truthy value is a value that is considered  true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

The ! is just a "not", but it has the effect of changing any truthy value into a false boolean and any falsy value into a true boolean. When you bang-bang a variable, you are basically converting it into a <s>true</s> real boolean value based on it's truthy/falsy behavior. This is generally a good practice but isn't entirely necessary.


问:
Can't open file for writing when vim recover file with swp file
I want to recover the /home/lufei/market/resources/views/user.blade.php, here is the place of swp file.

```<code>> lufei@localhost:~/market$ ls resources/views/.user.blade.php.swp
> resources/views/.user.blade.php.swp
</code>```

I use vim -r resources/views/.user.blade.php.swp to recover the file, I get this,

E306: Cannot open resources/views/.user.blade.php.swp Press ENTER or
  type command to continue

When I use sudo vim -r resources/views/.user.blade.php.swp I can open the file, but when I use :wq in the vim I get

"/root/market/resources/views/user.blade.php"

  "/root/market/resources/views/user.blade.php" E212: Can't open file
  for writing Press ENTER or type command to continue

From the info above I think vim want to save the file to the root directory. From the vi - getting an error E212: Can't open file for writing, I guess if I create path /root/market/resources/views/ may work. But I want to directly save the file to the right place /home/lufei/market/resources/views/user.blade.php. So I use su && cd /home/lufei/market then vim -r resources/views/.user.blade.php.swp. But when I :wq in vim , I also get

```<code>"~/market/resources/views/user.blade.php"
"~/market/resources/views/user.blade.php" E212: Can't open file for writing
Press ENTER or type command to continue
</code>```

From above trying, no matter I use normal user or the root user, when I recover the file, vim  will try to save the file to the wrong place which path is not exist.

Can I directly recover the file to the right place, without create a temp path and then copy the recoveried file back to the right path.

答:
This may be caused by the edit session crush like the items 2 in command sudo vim market/resources/views/user.blade.php. It make the swp file make the wong original file path.    Note I really not have the /root/market/resources/views/user.blade.php file even the /root/market/ path. This is the first I create the file user.blade.php and without save it, and then shutdown the computer.

```<code>E325: ATTENTION
Found a swap file by the name "resources/views/.user.blade.php.swp"
          owned by: root   dated: Thu Nov  9 17:33:23 2017
         file name: ~root/market/resources/views/user.blade.php
          modified: YES
         user name: root   host name: localhost
        process ID: 128985
While opening file "resources/views/user.blade.php"

(1) Another program may be editing the same file.  If this is the case,
    be careful not to end up with two different instances of the same
    file when making changes.  Quit, or continue with caution.
(2) An edit session for this file crashed.
    If this is the case, use ":recover" or "vim -r resources/views/user.blade.php"
    to recover the changes (see ":help recovery").
    If you did this already, delete the swap file "resources/views/.user.blade.php.swp"
    to avoid this message.

Swap file "resources/views/.user.blade.php.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:
</code>```

Solution:

sudo vim market/resources/views/user.blade.php, if vim show above info, just press R and then save the file. If it not show above info, use :rec(over), then save the file.

use vim open any file env create a new file, with sudo vim aaa.txt, then use :rec(over) user.blade.php then save it. This will save the file to user.blade.php not the aaa.txt. Make sure the aaa.txt and .user.blade.php in same directory.

Body:
I want to recover the /home/lufei/market/resources/views/user.blade.php, here is the place of swp file.

> lufei@localhost:~/market$ ls resources/views/.user.blade.php.swp
> resources/views/.user.blade.php.swp

I use vim -r resources/views/.user.blade.php.swp to recover the file, I get this,

E306: Cannot open resources/views/.user.blade.php.swp Press ENTER or
  type command to continue

When I use sudo vim -r resources/views/.user.blade.php.swp I can open the file, but when I use :wq in the vim I get

"/root/market/resources/views/user.blade.php"

  "/root/market/resources/views/user.blade.php" E212: Can't open file
  for writing Press ENTER or type command to continue

From the info above I think vim want to save the file to the root directory. From the vi - getting an error E212: Can't open file for writing, I guess if I create path /root/market/resources/views/ may work. But I want to directly save the file to the right place /home/lufei/market/resources/views/user.blade.php. So I use su && cd /home/lufei/market then vim -r resources/views/.user.blade.php.swp. But when I :wq in vim , I also get

"~/market/resources/views/user.blade.php"
"~/market/resources/views/user.blade.php" E212: Can't open file for writing
Press ENTER or type command to continue

From above trying, no matter I use normal user or the root user, when I recover the file, vim  will try to save the file to the wrong place which path is not exist.

Can I directly recover the file to the right place, without create a temp path and then copy the recoveried file back to the right path.

Body:
This may be caused by the edit session crush like the items 2 in command sudo vim market/resources/views/user.blade.php. It make the swp file make the wong original file path.    Note I really not have the /root/market/resources/views/user.blade.php file even the /root/market/ path. This is the first I create the file user.blade.php and without save it, and then shutdown the computer.

E325: ATTENTION
Found a swap file by the name "resources/views/.user.blade.php.swp"
          owned by: root   dated: Thu Nov  9 17:33:23 2017
         file name: ~root/market/resources/views/user.blade.php
          modified: YES
         user name: root   host name: localhost
        process ID: 128985
While opening file "resources/views/user.blade.php"

(1) Another program may be editing the same file.  If this is the case,
    be careful not to end up with two different instances of the same
    file when making changes.  Quit, or continue with caution.
(2) An edit session for this file crashed.
    If this is the case, use ":recover" or "vim -r resources/views/user.blade.php"
    to recover the changes (see ":help recovery").
    If you did this already, delete the swap file "resources/views/.user.blade.php.swp"
    to avoid this message.

Swap file "resources/views/.user.blade.php.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:

Solution:

sudo vim market/resources/views/user.blade.php, if vim show above info, just press R and then save the file. If it not show above info, use :rec(over), then save the file.

use vim open any file env create a new file, with sudo vim aaa.txt, then use :rec(over) user.blade.php then save it. This will save the file to user.blade.php not the aaa.txt. Make sure the aaa.txt and .user.blade.php in same directory.


问:
Check if a given key already exists in a dictionary and increment it
How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there's already one there, or set it to 1 otherwise:

```<code>my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1
</code>```

答:
Agreed with cgoldberg. How I do it is:

```<code>try:
    dict[key] += 1
except KeyError:
    dict[key] = 1
</code>```

So either do it as above, or use a default dict as others have suggested. Don't use if statements. That's not Pythonic.

OwnerDisplayName: Ben

Body:
How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there's already one there, or set it to 1 otherwise:

my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1

Body:
Agreed with cgoldberg. How I do it is:

try:
    dict[key] += 1
except KeyError:
    dict[key] = 1

So either do it as above, or use a default dict as others have suggested. Don't use if statements. That's not Pythonic.

OwnerDisplayName: ryeguy

ContentLicense: CC BY-SA 2.5


问:
How to sum digits of an integer in java?
I am having a hard time figuring out the solution to this problem. I am trying to develop a program in Java that takes a number, such as 321, and finds the sum of digits, in this case 3 + 2 + 1 = 6. I need all the digits of any three digit number to add them together, and store that value using the % remainder symbol. This has been confusing me and I would appreciate anyones ideas.</p>

答:
In Java 8,

```<code>public int sum(int number) {
  return (number + "").chars()
                      .map(digit -> digit % 48)
                      .sum();
}
</code>```

Converts the number to a string and then each character is mapped to it's digit value by subtracting ascii value of '0' (48) and added to the final sum.

Body:
In Java 8,

public int sum(int number) {
  return (number + "").chars()
                      .map(digit -> digit % 48)
                      .sum();
}

Converts the number to a string and then each character is mapped to it's digit value by subtracting ascii value of '0' (48) and added to the final sum.


问:
How to read depth data at a CGPoint from AVDepthData buffer
I am attempting to find the depth data at a certain point in the captured image and return the distance in meters.

I have enabled depth data and am capturing the data alongside the image. I get the point from the X,Y coordinates of the center of the image (and when pressed) and convert it to the buffers index using

```<code>Int((width - touchPoint.x) * (height - touchPoint.y))
</code>```

with WIDTH and HEIGHT being the dimensions of the captured image. I am not sure if this is the correct method to achieve this though.

I handle the depth data as such:

```<code>func handlePhotoDepthCalculation(point : Int) {

    guard let depth = self.photo else {
        return
    }

    //
    // Convert Disparity to Depth
    //
    let depthData = (depth.depthData as AVDepthData!).converting(toDepthDataType: kCVPixelFormatType_DepthFloat32)
    let depthDataMap = depthData.depthDataMap //AVDepthData -> CVPixelBuffer

    //
    // Set Accuracy feedback
    //
    let accuracy = depthData.depthDataAccuracy
    switch (accuracy) {
    case .absolute:
        /*
        NOTE - Values within the depth map are absolutely
        accurate within the physical world.
        */
        self.accuracyLbl.text = "Absolute"
        break
    case .relative:
        /*
        NOTE - Values within the depth data map are usable for
        foreground/background separation, but are not absolutely
        accurate in the physical world. iPhone always produces this.
        */
        self.accuracyLbl.text = "Relative"
    }

    //
    // We convert the data
    //
    CVPixelBufferLockBaseAddress(depthDataMap, CVPixelBufferLockFlags(rawValue: 0))
    let depthPointer = unsafeBitCast(CVPixelBufferGetBaseAddress(depthDataMap), to: UnsafeMutablePointer<Float32>.self)

    //
    // Get depth value for image center
    //
    let distanceAtXYPoint = depthPointer[point]

    //
    // Set UI
    //
    self.distanceLbl.text = "\(distanceAtXYPoint) m" //Returns distance in meters?
    self.filteredLbl.text = "\(depthData.isDepthDataFiltered)"
}
</code>```

I am not convinced I am getting the correct position. From my research as well it looks like accuracy is only returned in .relative or .absolute and not a float/integer?

答:
Values indicating the general accuracy of a depth data map.

The accuracy of a depth data map is highly dependent on the camera calibration data used to generate it. If the camera's focal length cannot be precisely determined at the time of capture, scaling error in the z (depth) plane will be introduced. If the camera's optical center can't be precisely determined at capture time, principal point error will be introduced, leading to an offset error in the disparity estimate.
These values report the accuracy of a map's values with respect to its reported units.

case relative

Values within the depth data map are usable for foreground/background separation, but are not absolutely accurate in the physical world.

case absolute

Values within the depth map are absolutely accurate within the physical world.

You have get CGPoint from AVDepthData buffer like hight and width like follow code.

```<code>// Useful data
 let width = CVPixelBufferGetWidth(depthDataMap)
 let height = CVPixelBufferGetHeight(depthDataMap)
</code>```

Body:
I am attempting to find the depth data at a certain point in the captured image and return the distance in meters.

I have enabled depth data and am capturing the data alongside the image. I get the point from the X,Y coordinates of the center of the image (and when pressed) and convert it to the buffers index using

Int((width - touchPoint.x) * (height - touchPoint.y))

with WIDTH and HEIGHT being the dimensions of the captured image. I am not sure if this is the correct method to achieve this though.

I handle the depth data as such:

func handlePhotoDepthCalculation(point : Int) {

    guard let depth = self.photo else {
        return
    }

    //
    // Convert Disparity to Depth
    //
    let depthData = (depth.depthData as AVDepthData!).converting(toDepthDataType: kCVPixelFormatType_DepthFloat32)
    let depthDataMap = depthData.depthDataMap //AVDepthData -> CVPixelBuffer

    //
    // Set Accuracy feedback
    //
    let accuracy = depthData.depthDataAccuracy
    switch (accuracy) {
    case .absolute:
        /*
        NOTE - Values within the depth map are absolutely
        accurate within the physical world.
        */
        self.accuracyLbl.text = "Absolute"
        break
    case .relative:
        /*
        NOTE - Values within the depth data map are usable for
        foreground/background separation, but are not absolutely
        accurate in the physical world. iPhone always produces this.
        */
        self.accuracyLbl.text = "Relative"
    }

    //
    // We convert the data
    //
    CVPixelBufferLockBaseAddress(depthDataMap, CVPixelBufferLockFlags(rawValue: 0))
    let depthPointer = unsafeBitCast(CVPixelBufferGetBaseAddress(depthDataMap), to: UnsafeMutablePointer<Float32>.self)

    //
    // Get depth value for image center
    //
    let distanceAtXYPoint = depthPointer[point]

    //
    // Set UI
    //
    self.distanceLbl.text = "\(distanceAtXYPoint) m" //Returns distance in meters?
    self.filteredLbl.text = "\(depthData.isDepthDataFiltered)"
}

I am not convinced I am getting the correct position. From my research as well it looks like accuracy is only returned in .relative or .absolute and not a float/integer?

Body:
Values indicating the general accuracy of a depth data map.

The accuracy of a depth data map is highly dependent on the camera calibration data used to generate it. If the camera's focal length cannot be precisely determined at the time of capture, scaling error in the z (depth) plane will be introduced. If the camera's optical center can't be precisely determined at capture time, principal point error will be introduced, leading to an offset error in the disparity estimate.
These values report the accuracy of a map's values with respect to its reported units.

case relative

Values within the depth data map are usable for foreground/background separation, but are not absolutely accurate in the physical world.

case absolute

Values within the depth map are absolutely accurate within the physical world.

You have get CGPoint from AVDepthData buffer like hight and width like follow code.

// Useful data
 let width = CVPixelBufferGetWidth(depthDataMap)
 let height = CVPixelBufferGetHeight(depthDataMap)


问:
How to add an element to arrayList when calling the method at the same time?
I am doing a recursive program and I want to call a method 2 times in a row, which looks like this:

```<code>print(ArrayList<Integer> current + arr[0], Arrays.copyOfRange(arr, 1, arr.length) );
print(ArrayList<Integer> current, Arrays.copyOfRange(arr, 1, arr.length));
</code>```

But it is impossible to add a value to the ArrayList like that. However, I can't use current.add() outside either, because it will mess up my second call.
So is there a way to add a value to the arrayList while calling the method, or do I have to think of another way to write my code?

答:
You may overload your print method like the following:

```<code>public void print(ArrayList<Integer> current, int i, int[] arr ) {
    //print whatever you want
    //then add using current.add(i)
    current.add(i)
}
</code>```

then call your overloaded print() method in the first time like this:

```<code>print(current, arr[0], arr);
</code>```

Body:
I am doing a recursive program and I want to call a method 2 times in a row, which looks like this:

print(ArrayList<Integer> current + arr[0], Arrays.copyOfRange(arr, 1, arr.length) );
print(ArrayList<Integer> current, Arrays.copyOfRange(arr, 1, arr.length));

But it is impossible to add a value to the ArrayList like that. However, I can't use current.add() outside either, because it will mess up my second call.
So is there a way to add a value to the arrayList while calling the method, or do I have to think of another way to write my code?

Body:
You may overload your print method like the following:

public void print(ArrayList<Integer> current, int i, int[] arr ) {
    //print whatever you want
    //then add using current.add(i)
    current.add(i)
}

then call your overloaded print() method in the first time like this:

print(current, arr[0], arr);


问:
How to get value of input field in typescript file Angular 4
```<code> <div id="lists">
            <table id='mytable' cellspacing='0' cellpadding='0'>
                <tr  class="row" [ngClass]="{'selected': i === selectedIndex}"  *ngFor= 'let item of list; let i = index' [attr.data-index]='i'  [ngStyle]="{'background-color': i%2 == '0' ? 'gray' : ''}">
                    <td class='default-field'>
                        <p class='para' *ngIf="selectedIndex!=i  ">{{i+1}}. {{item}}</p>
                    </td>
                    <td class="edit-field" *ngIf="selectedIndex==i   " >
                        <input type="text" class="myCl" [value]="val" >
                    </td>
                    <td class='btns'>

                    <input type='button' value='edit' class='edit-btn'  (click)='hidePara(item,i)' *ngIf="selectedIndex!=i">

                    <input type='button' value='save' class='save-btn' *ngIf="selectedIndex==i" (click)='hidePara1(item,i)'>
                    <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>
                    </td>
                </tr>
            </table>

        </div>
</code>```

Above is my html code, i want to retrieve the value of input field when user click on save button, the hidePara1(item,i) function will execute, i want to get value of input field in hidepara1, how this can be possible.

```<code> hidePara1(item,ii)
 {
  this.selectedIndex=-1;
  this.showHideP = !this.showHideP;  //for hiding paragraph
  this.tbox = !this.tbox;  //showing text box
  this.edt=!this.edt;  //hide edt button
  this.sbtn = !this.sbtn;  //display save button

 }
</code>```

答:
You can use following code:</p>

```<code> <td class="edit-field" *ngIf="selectedIndex==i" >
      <input type="text" class="myCl" [(ngModel)]="val" >
 </td>
</code>```

Body:
{{i+1}}. {{item}}

                        <input type="text" class="myCl" [value]="val" >

                    <input type='button' value='edit' class='edit-btn'  (click)='hidePara(item,i)' *ngIf="selectedIndex!=i">

                    <input type='button' value='save' class='save-btn' *ngIf="selectedIndex==i" (click)='hidePara1(item,i)'>
                    <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>

Above is my html code, i want to retrieve the value of input field when user click on save button, the hidePara1(item,i) function will execute, i want to get value of input field in hidepara1, how this can be possible.

 hidePara1(item,ii)
 {
  this.selectedIndex=-1;
  this.showHideP = !this.showHideP;  //for hiding paragraph
  this.tbox = !this.tbox;  //showing text box
  this.edt=!this.edt;  //hide edt button
  this.sbtn = !this.sbtn;  //display save button

 }

Body:
You can use following code:

 <td class="edit-field" *ngIf="selectedIndex==i" >
      <input type="text" class="myCl" [(ngModel)]="val" >
 </td>


问:
I'm currently working on a project using the angular 2 . I am getting Access-Control-Allow-Origin issue
when i am hitting third party services from my java script code I am getting below error in the browser :

Failed to load http://api.mysite.com: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://client.mysite.com' is therefore not allowed access.

Please suggest me how to fix this issue.

答:
CORS is basically applied by the browsers for security purpose:

If you are using chrome for development you can install this extension:

https://chrome.google.com/webstore/detail/moesif-origin-cors-change/digfbfaphojjndkpccljibejjbppifbc


问:
UIAlertView is not in window hierarchy
It says:

Attempt to present <UIAlertController: 0x106155a00> on <SignInViewController: 0x105f490a0> whose view is not in the window hierarchy!

```<code>@IBAction func signIn(_ sender: Any) {
    if let emailField = email.text, let passField = password.text {
        Auth.auth().signIn(withEmail: emailField, password: passField, completion: { (user, error) in
            if error != nil {
                guard let error = AuthErrorCode(rawValue: (error?._code)!) else {
                    return
                }
                self.fireErrorHandle(code: error)
            }else{
                if let userID = user?.uid {
                    KeychainWrapper.standard.set((userID), forKey: "uid")
                    self.performSegue(withIdentifier: "toFeed", sender: nil)
                }
            }
        })
    }
}

func fireErrorHandle(code: AuthErrorCode) {
    switch code {
    case .invalidCustomToken:
        //print("Indicates a validation error with the custom token")
        showAlert(title: "Error", message: "Validation error with the custom token.")
    case .customTokenMismatch:
        //print("Indicates the service account and the API key belong to different projects")
        showAlert(title: "Error", message: "Id Mismatch.")
    case .invalidCredential:
        //print("Indicates the IDP token or requestUri is invalid")
        showAlert(title: "Error", message: "RequestUri is invalid.")
    case .userDisabled:
        //print("Indicates the user's account is disabled on the server")
        showAlert(title: "Error", message: "Account is disabled.")
    case .operationNotAllowed:
        //print("Indicates the administrator disabled sign in with the specified identity provider")
        showAlert(title: "Error", message: "Administrator disabled sign in.")
    case .emailAlreadyInUse:
        //print("Indicates the email used to attempt a sign up is already in use.")
        showAlert(title: "Error", message: "Email already in use.")
    case .invalidEmail:
        //print("Indicates the email is invalid")
        showAlert(title: "Error", message: "Email is invalid.")
    case .wrongPassword:
        //print("Indicates the user attempted sign in with a wrong password")
        showAlert(title: "Error", message: "Wrong password.")
    case .tooManyRequests:
        //print("Indicates that too many requests were made to a server method")
        showAlert(title: "Error", message: "To many requests were made please try again late.")
    case .userNotFound:
       //print("Indicates the user account was not found")
        showAlert(title: "Error", message: "Account was not found.")
    case .accountExistsWithDifferentCredential:
        //print("Indicates account linking is required")
        showAlert(title: "Error", message: "account linking is required.")
    case .requiresRecentLogin:
        //print("Indicates the user has attemped to change email or password more than 5 minutes after signing in")
        showAlert(title: "Error", message: "Attemped to change email or password more than 5 minutes after signing in.")
    case .providerAlreadyLinked:
        //print("Indicates an attempt to link a provider to which the account is already linked")
        showAlert(title: "Error", message: "Link a provider to which the account is already linked.")
    case .noSuchProvider:
        //print("Indicates an attempt to unlink a provider that is not linked")
        showAlert(title: "Error", message: "Attempt to unlink a provider that is not linked.")
    case .invalidUserToken:
        //print("Indicates user's saved auth credential is invalid, the user needs to sign in again")
        showAlert(title: "Error", message: "Please sign in again.")
    case .networkError:
        //print("Indicates a network error occurred (such as a timeout, interrupted connection, or unreachable host). These types of errors are often recoverable with a retry. The @cNSUnderlyingError field in the @c NSError.userInfo dictionary will contain the error encountered")
        showAlert(title: "Error", message: "You have been timesout due to network error. Please try again.")
    case .userTokenExpired:
        //print("Indicates the saved token has expired, for example, the user may have changed account password on another device. The user needs to sign in again on the device that made this request")
        showAlert(title: "Error", message: "May have changed account password on another device.")
    case .invalidAPIKey:
        //print("Indicates an invalid API key was supplied in the request")
        showAlert(title: "Error", message: "error")
    case .userMismatch:
        //print("Indicates that an attempt was made to reauthenticate with a user which is not the current user")
        showAlert(title: "Error", message: "Error logging in.")
    case .credentialAlreadyInUse:
        //print("Indicates an attempt to link with a credential that has already been linked with a different Firebase account")
        showAlert(title: "Error", message: "Credential that has already been linked with a different account.")
    case .weakPassword:
        //print("Indicates an attempt to set a password that is considered too weak")
        showAlert(title: "Error", message: "Password to weak.")
    case .appNotAuthorized:
        //print("Indicates the App is not authorized to use Firebase Authentication with the provided API Key")
        showAlert(title: "Error", message: "Not authorized")
    case .keychainError:
        //print("Indicates an error occurred while attempting to access the keychain")
        showAlert(title: "Error", message: "An error has occured please try again")
    default:
        //print("Indicates an internal error occurred")
        showAlert(title: "Error", message: "Internal error, please try again.")
    }
}

func showAlert(title: String, message: String) {
    let alert = UIAlertController(title: title, message:message, preferredStyle: .alert)
    let action = UIAlertAction(title: "OK", style: .default, handler: nil)
    alert.addAction(action)
    self.present(alert, animated: true, completion: nil)

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if Auth.auth().currentUser != nil {
        Timer.scheduledTimer(withTimeInterval: 0, repeats: false, block: { (timer) in
            self.performSegue(withIdentifier: "toFeed", sender: nil)
        })
    }

    if KeychainWrapper.standard.object(forKey: "uid") != nil {
        self.performSegue(withIdentifier: "toFeed", sender: nil)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.hideKeyboardWhenTappedAround()
    signInbutton.isEnabled = false
}
</code>```

I tried many different solutions and couldn't figure out what to do, I tried adding it to viewdidappear but I don't know how to add the AuthErrorCode to it. When I press the sign in button it performs the segue to another View Controller without any error handling.

答:
You can try this :

```<code>private func presentViewController(alert: UIAlertController, animated flag: Bool, completion: (() -> Void)?) -> Void {
     UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: flag, completion: completion)
  }
</code>```

Other things that you should look is whether you have properly set rootViewController or not as that might be reason for this error.

Title: UIAlertView is not in window hierarchy

Body:
It says:

Attempt to present <UIAlertController: 0x106155a00> on <SignInViewController: 0x105f490a0> whose view is not in the window hierarchy!

@IBAction func signIn(_ sender: Any) {
    if let emailField = email.text, let passField = password.text {
        Auth.auth().signIn(withEmail: emailField, password: passField, completion: { (user, error) in
            if error != nil {
                guard let error = AuthErrorCode(rawValue: (error?._code)!) else {
                    return
                }
                self.fireErrorHandle(code: error)
            }else{
                if let userID = user?.uid {
                    KeychainWrapper.standard.set((userID), forKey: "uid")
                    self.performSegue(withIdentifier: "toFeed", sender: nil)
                }
            }
        })
    }
}

func fireErrorHandle(code: AuthErrorCode) {
    switch code {
    case .invalidCustomToken:
        //print("Indicates a validation error with the custom token")
        showAlert(title: "Error", message: "Validation error with the custom token.")
    case .customTokenMismatch:
        //print("Indicates the service account and the API key belong to different projects")
        showAlert(title: "Error", message: "Id Mismatch.")
    case .invalidCredential:
        //print("Indicates the IDP token or requestUri is invalid")
        showAlert(title: "Error", message: "RequestUri is invalid.")
    case .userDisabled:
        //print("Indicates the user's account is disabled on the server")
        showAlert(title: "Error", message: "Account is disabled.")
    case .operationNotAllowed:
        //print("Indicates the administrator disabled sign in with the specified identity provider")
        showAlert(title: "Error", message: "Administrator disabled sign in.")
    case .emailAlreadyInUse:
        //print("Indicates the email used to attempt a sign up is already in use.")
        showAlert(title: "Error", message: "Email already in use.")
    case .invalidEmail:
        //print("Indicates the email is invalid")
        showAlert(title: "Error", message: "Email is invalid.")
    case .wrongPassword:
        //print("Indicates the user attempted sign in with a wrong password")
        showAlert(title: "Error", message: "Wrong password.")
    case .tooManyRequests:
        //print("Indicates that too many requests were made to a server method")
        showAlert(title: "Error", message: "To many requests were made please try again late.")
    case .userNotFound:
       //print("Indicates the user account was not found")
        showAlert(title: "Error", message: "Account was not found.")
    case .accountExistsWithDifferentCredential:
        //print("Indicates account linking is required")
        showAlert(title: "Error", message: "account linking is required.")
    case .requiresRecentLogin:
        //print("Indicates the user has attemped to change email or password more than 5 minutes after signing in")
        showAlert(title: "Error", message: "Attemped to change email or password more than 5 minutes after signing in.")
    case .providerAlreadyLinked:
        //print("Indicates an attempt to link a provider to which the account is already linked")
        showAlert(title: "Error", message: "Link a provider to which the account is already linked.")
    case .noSuchProvider:
        //print("Indicates an attempt to unlink a provider that is not linked")
        showAlert(title: "Error", message: "Attempt to unlink a provider that is not linked.")
    case .invalidUserToken:
        //print("Indicates user's saved auth credential is invalid, the user needs to sign in again")
        showAlert(title: "Error", message: "Please sign in again.")
    case .networkError:
        //print("Indicates a network error occurred (such as a timeout, interrupted connection, or unreachable host). These types of errors are often recoverable with a retry. The @cNSUnderlyingError field in the @c NSError.userInfo dictionary will contain the error encountered")
        showAlert(title: "Error", message: "You have been timesout due to network error. Please try again.")
    case .userTokenExpired:
        //print("Indicates the saved token has expired, for example, the user may have changed account password on another device. The user needs to sign in again on the device that made this request")
        showAlert(title: "Error", message: "May have changed account password on another device.")
    case .invalidAPIKey:
        //print("Indicates an invalid API key was supplied in the request")
        showAlert(title: "Error", message: "error")
    case .userMismatch:
        //print("Indicates that an attempt was made to reauthenticate with a user which is not the current user")
        showAlert(title: "Error", message: "Error logging in.")
    case .credentialAlreadyInUse:
        //print("Indicates an attempt to link with a credential that has already been linked with a different Firebase account")
        showAlert(title: "Error", message: "Credential that has already been linked with a different account.")
    case .weakPassword:
        //print("Indicates an attempt to set a password that is considered too weak")
        showAlert(title: "Error", message: "Password to weak.")
    case .appNotAuthorized:
        //print("Indicates the App is not authorized to use Firebase Authentication with the provided API Key")
        showAlert(title: "Error", message: "Not authorized")
    case .keychainError:
        //print("Indicates an error occurred while attempting to access the keychain")
        showAlert(title: "Error", message: "An error has occured please try again")
    default:
        //print("Indicates an internal error occurred")
        showAlert(title: "Error", message: "Internal error, please try again.")
    }
}

func showAlert(title: String, message: String) {
    let alert = UIAlertController(title: title, message:message, preferredStyle: .alert)
    let action = UIAlertAction(title: "OK", style: .default, handler: nil)
    alert.addAction(action)
    self.present(alert, animated: true, completion: nil)

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if Auth.auth().currentUser != nil {
        Timer.scheduledTimer(withTimeInterval: 0, repeats: false, block: { (timer) in
            self.performSegue(withIdentifier: "toFeed", sender: nil)
        })
    }

    if KeychainWrapper.standard.object(forKey: "uid") != nil {
        self.performSegue(withIdentifier: "toFeed", sender: nil)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.hideKeyboardWhenTappedAround()
    signInbutton.isEnabled = false
}

I tried many different solutions and couldn't figure out what to do, I tried adding it to viewdidappear but I don't know how to add the AuthErrorCode to it. When I press the sign in button it performs the segue to another View Controller without any error handling.

Body:
You can try this :

private func presentViewController(alert: UIAlertController, animated flag: Bool, completion: (() -> Void)?) -> Void {
     UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: flag, completion: completion)
  }

Other things that you should look is whether you have properly set rootViewController or not as that might be reason for this error.


问:
UITableViewCell : UIImageView in ContentView overlaps images in iPhone SDK.
In my iPhone app,  I am using a tableView and have added the imageView as ContentView in my tableViewcell.

At the click of button I am changing the tableView Contents. So every time I click a button it should show the corresponding image in tableViewCell.

Problem:

Suppose I am loading images 1.png, 2.png and 3.png in tableView on click of button A, B and C respectively.

Now let us consider that initially I clicked button A and 1.png appears. Now when I click the button B then 2.png appears but 1.png also remains in background. So basically it overlaps the tableViewCell with a new image.

Troubleshooting I already have done:

1) I tried releasing imageView and setting imageView.image = nil;

2) I tried reloading the table and empty out table before each button click.

3) Even I tried putting the whole code in if(cell==nil) clause of cellForRowAtIndexPath method

答:
If you use three different imageViews then try to imgView1.hidden=FALSE;imgView.hidden=TRUE;imgView3.hidden=TRUE on button1 click event.
same way for buttton2 and button3.</p>


问:
Laravel storage directory access issue
I have a problem: my data files are not available from /storage directory (Laravel's default storage directory) on real server, them return 404 missing file error. On my local server they are available and return no error. I tried recursive chmod on storage directory but that didn't fix it. Could it be accessing rights issue?

UPD:

Strange things gonna stranger: I can see files in /storage/users/ directory by url, and all files from /storage/users/November2017 are missed for me. But, here's interesting moment: when I upload file to /storage/users/ I cannot see it by url too. File was uploaded but browser returns me 404 error when I try to access it.

Files in /storage/users have been created by Voyager admin panel (default files).

答: Just run php artisan storage:link from the command line to make a link in the public folder to your storage directory.

Title: Laravel storage directory access issue


问:
Open source project has `No Scheme` in Xcode
I have uploaded an open source project called SuperCrack! to Github.  I made it with Xcode 8.3.3.  It's quite a large project with lots of pods.  I asked a friend to download and build it but he complains that there is No Scheme:

He tried the solutions here but said they didn't help.

If anybody could tell me where I went wrong and fix this problem I'd be grateful.

答: I had the same problem when trying to run this app turns out I just had to run 'pod install' </p>


问:
loop different rows from dataframe A and apply them to the same individual rows in dataframe B
As I am working on a Q-Matrix question and needing to calculate hamming distance, I am having problem of different rows (as vectors) from dataframe A to the same row in dataframe B.

Specifically, df2 is a 6x3 dataframe and df1 is a 3x3 dataframe.

```<code>    df1 <- data.frame(Q1= c(1,0,1), Q2= c(0,0,0), Q3= c(1,1,0))
    df2 <- data.frame(A =c(1,1,0,1,1,0), B =c(0,0,0,1,1,0), C =c(0,1,0,1,1,1))
</code>```

I need to apply all 6 rows from  df2 as vectors into every row in df1 sequentially in order calculate the hamming distance of all 6 vector - 1 vector pair (it should output 3 hamming distance values only). For instance, for the 1st row in df1 which is (1,0,1) should be paired with all 6 rows in df2 including (1,0,0),(1,0,1),(0,0,0),(1,1,1),(1,1,1),(0,0,1)and produce 1 hamming distance value. Following the same logic, this similar process should give 3 hamming distance values.

I have tried a few times with double for() loop but with no success. In fact, I don't even know how we print out a row from a dataframe as a vector that could do other calculation with other vector. Can anyone please help?

答:
This should work:</p>

```<code>for(i in 1:nrow(df1)){
  print(sum(apply(df2,1,function(x) x!=df1[i,])))
  }

[1] 6
[1] 8
[1] 8
</code>```

Body:
As I am working on a Q-Matrix question and needing to calculate hamming distance, I am having problem of different rows (as vectors) from dataframe A to the same row in dataframe B.

Specifically, df2 is a 6x3 dataframe and df1 is a 3x3 dataframe.

    df1 <- data.frame(Q1= c(1,0,1), Q2= c(0,0,0), Q3= c(1,1,0))
    df2 <- data.frame(A =c(1,1,0,1,1,0), B =c(0,0,0,1,1,0), C =c(0,1,0,1,1,1))

I need to apply all 6 rows from  df2 as vectors into every row in df1 sequentially in order calculate the hamming distance of all 6 vector - 1 vector pair (it should output 3 hamming distance values only). For instance, for the 1st row in df1 which is (1,0,1) should be paired with all 6 rows in df2 including (1,0,0),(1,0,1),(0,0,0),(1,1,1),(1,1,1),(0,0,1)and produce 1 hamming distance value. Following the same logic, this similar process should give 3 hamming distance values.

I have tried a few times with double for() loop but with no success. In fact, I don't even know how we print out a row from a dataframe as a vector that could do other calculation with other vector. Can anyone please help?

Body:
This should work:

for(i in 1:nrow(df1)){
  print(sum(apply(df2,1,function(x) x!=df1[i,])))
  }

[1] 6
[1] 8
[1] 8


答: Download the "Allow-control-allow-origin" Extension from the chrome browser and then enable it.</p>

Title: I'm currently working on a project using the angular 2 . I am getting Access-Control-Allow-Origin issue

Body:
when i am hitting third party services from my java script code I am getting below error in the browser :

Failed to load http://api.mysite.com: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://client.mysite.com' is therefore not allowed access.

Please suggest me how to fix this issue.


问:
Multiple RadUpload Control in One Page
I have an aspx page that uses master page. In the papx page, I load a user control containing 2 RadUpload controls (Rad1 and Rad2). User can choose to upload the file either using the first RadUpload or the second RadUpload and there is certain validation applied for each RadUpload.

The weird thing happened is that when I upload file using Rad2 (second RadUpload), the RadUpload.UploadedFiles for the first RadUpload is there (count = 1). Instead of the file being uploaded by Rad2, it is detected as if it is uploaded from Rad1, so my validation failed.

Does someone encounter this problem before? This is a very weird thing and I've spent almost 1 and a half day fixing this without knowing what happened to the control

答:
I have three radupload/progress controls on a webpage and they work perfectly.

My suggestion would be to place them explicitly in the page itself instead of within a user control.

I did not try to replicate your issue as I am in the middle of development myself but I just wanted to share something with you that worked the first time.

Title: Multiple RadUpload Control in One Page


问:
How to convert Json Array (nested) in multiple rows
I have a Json array that looks like this screenshot:

Now I want to convert this array into a table format like this:

Currently I'm working with tExtractJSONFields. But I only find a way to target one of the nested array at the same time.

My expression:

```<code>"['book'][0].['category']"
    "['book'][0].['author']"
        ......
</code>```

So I got the Ouput for the first row. But I don't want to do the same for 50, 100 etc. rows.

Does anybody know a way to solve that?

答:
In tExtractJsonFields, select edit Schema and give all the possible column you have in output schema. Select "Read by" as "Xpath".

Now in "Loop Xpath Query" write  "/book"

In the "Mapping" section, you will see all the output column under "Column" as you have given in Schema. Under Xpath Query put the respective column like :

if column is Author than Xpath Query would be "Author"

column is Price than Xpath Query would be "Price" and so on.

hope this help..

Body:
I have a Json array that looks like this screenshot:

Now I want to convert this array into a table format like this:

Currently I'm working with tExtractJSONFields. But I only find a way to target one of the nested array at the same time.

My expression:

"['book'][0].['category']"
    "['book'][0].['author']"
        ......

So I got the Ouput for the first row. But I don't want to do the same for 50, 100 etc. rows.

Does anybody know a way to solve that?