问:
Spring init-method params
I am new to spring and I wanted to ask whether or not it is possible to pass params to the init and destroy methods of a bean. </p>

<p>Thanks. </p>

答:
```<code>    protected void invokeCustomInitMethod(String beanName, Object bean, String initMethodName)
        throws Throwable {

    if (logger.isDebugEnabled()) {
        logger.debug("Invoking custom init method '" + initMethodName +
                "' on bean with beanName '" + beanName + "'");
    }
    try {
        Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null);
        if (initMethod == null) {
            throw new NoSuchMethodException("Couldn't find an init method named '" + initMethodName +
                    "' on bean with name '" + beanName + "'");
        }
        if (!Modifier.isPublic(initMethod.getModifiers())) {
            initMethod.setAccessible(true);
        }
        initMethod.invoke(bean, (Object[]) null);
    }
    catch (InvocationTargetException ex) {
        throw ex.getTargetException();
    }
}
</code>```

see spring soruce code in Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null);
the init method is find and param is null

Title: Spring init-method params

Body:
I am new to spring and I wanted to ask whether or not it is possible to pass params to the init and destroy methods of a bean.

Thanks.

Body:
    protected void invokeCustomInitMethod(String beanName, Object bean, String initMethodName)
        throws Throwable {

    if (logger.isDebugEnabled()) {
        logger.debug("Invoking custom init method '" + initMethodName +
                "' on bean with beanName '" + beanName + "'");
    }
    try {
        Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null);
        if (initMethod == null) {
            throw new NoSuchMethodException("Couldn't find an init method named '" + initMethodName +
                    "' on bean with name '" + beanName + "'");
        }
        if (!Modifier.isPublic(initMethod.getModifiers())) {
            initMethod.setAccessible(true);
        }
        initMethod.invoke(bean, (Object[]) null);
    }
    catch (InvocationTargetException ex) {
        throw ex.getTargetException();
    }
}

see spring soruce code in Method initMethod = BeanUtils.findMethod(bean.getClass(), initMethodName, null);
the init method is find and param is null


来源: stackexchange

问:
SSL Certificate + EC2
Is there a way to associate a SSL certificate with an EC2 instance without the need for an ELB?

I'm using a cloudformation template to do this, and I already have my SSL certificate. If it is necessary to associate with an ELB, then why does it have to be done this way?

答:
For anyone that is looking to setup their SSL on EC2, and they have purchased their SSL certificate outside of AWS, you can definitely have it for a single EC2 instance. </p>

<p>There is a full tutorial on how to achieve this in a medium article https://medium.com/@adnanxteam/how-to-add-ssl-certificate-to-laravel-on-ec2-aws-18104cc036d1  </p>

ContentLicense: CC BY-SA 3.0

Title: SSL Certificate + EC2

Body:
For anyone that is looking to setup their SSL on EC2, and they have purchased their SSL certificate outside of AWS, you can definitely have it for a single EC2 instance.

There is a full tutorial on how to achieve this in a medium article https://medium.com/@adnanxteam/how-to-add-ssl-certificate-to-laravel-on-ec2-aws-18104cc036d1


问:
Import only Last column of Excel through SSIS
I have an excel file which I receive daily. The number of columns in that file is not specific. My requirement is just to load the last column in my table through SSIS. How will I be able to identify last used column dynamically?</p>

答: No you can't do that. The number of columns and data types must be determined beforehand and can't be changed. Otherwise SSIS will fail. So no way to dynamically get the last column. Workaround is maybe get the last column from inside excel using some macro then use that as the source for SSIS.</p>


问:
Sending cookies with postman
I read the manual of sending request with cookie with postman:

As the packaged app runs in a sandbox separately from the browser, it
  can not access cookies set inside the browser. This restriction can
  also be overcome using the Interceptor extension. Postman routes all
  requests through the Interceptor, which then uses the browser context
  to send requests. Cookies set inside the browser are automatically
  attached to your requests. Read the original blog post on Interceptor.

Once the interceptor is enabled, you can also send cookies from
  Postman. Just set the "Cookie" header, and the cookie will be sent
  with the request. You can also get access to cookies that are
  available when the response is returned. Check out out blog post for
  more

So I downloaded the interceptor for google chrome, and it enable.

Also, I add the following to postman: Cookie JSESSIONID=daczcz36789

When I look at the network I notice that the Cookie is not sent.

What I do wrong?

答:
Chrome apps including Postman are being deprecated as mentioned here. Now the recommendation is to go for native apps which are not detached from the sandboxed environment of the browser.

Quoting from the feature page:

FEATURES EXCLUSIVE TO THE NATIVE APPS:

COOKIES: The native apps let you work with cookies directly.  Unlike
the Chrome app, no separate extension (Interceptor) is needed.

BUILT-IN PROXY: The native apps come with a built-in proxy that you

can use to capture network traffic.

RESTRICTED HEADERS: The latest
version of the native apps let you send headers like Origin and
User-Agent.  These are restricted in the Chrome app. DON'T FOLLOW

REDIRECTS OPTION: This option exists in the native apps to prevent
requests that return a 300-series response from being automatically
redirected.  Previously, users needed to use the Interceptor extension
to do this in the Chrome app.

MENU BAR: The native apps are not
restricted by the Chrome standards for the menu bar.

POSTMAN CONSOLE:
The latest version of the native apps has a built-in console, which
allows you to view the network request details for API calls.

So once you install the native Postman app from here, you don't have to go looking for additional Chrome extensions like Interceptor. Earlier, Postman Interceptor like apps were an additional requirement if we wanted to check browser cookies. All the cookies were visible in Cookies tab as shown below:

Title: Sending cookies with postman

ContentLicense: CC BY-SA 4.0


问:
How to ignore or remove null element from an array inside collection
```<code>Collection {#363 ▼
  #items: array:3 [▼
    0 => Tag {#376 ▶}
    1 => null
    2 => Tag {#374 ▶}
  ]
}
</code>```

I want to remove the second key/pair element from this collection. How can I achieve this?

答:
You can use $collection->filter(); to remove the null values.

```<code>$filtered = $collection->filter(function ($value, $key) {
    return $value != null;
});
</code>```

See documentation.

Body:
Collection {#363 ▼
  #items: array:3 [▼
    0 => Tag {#376 ▶}
    1 => null
    2 => Tag {#374 ▶}
  ]
}

I want to remove the second key/pair element from this collection. How can I achieve this?

Body:
You can use $collection->filter(); to remove the null values.

$filtered = $collection->filter(function ($value, $key) {
    return $value != null;
});

See documentation.


问:
Not In query not working
I'm trying to run this query, it's supposed to get all employees who're not drivers in wh_route, the driver is a fk for

The following queries are working and giving me back results:

```<code>select distinct driver from wh_route;
select id from pa_employee o where o.id not in (1,2,3,4,5);
</code>```

But when I try to do this:

```<code>select id from pa_employee o where o.id not in (select distinct driver from wh_route);
</code>```

It doesn't return any results.

Tables for reference:

```<code>WH_ROUTE
id    driver
1     1
2     2

PA_EMPLOYEE
id
1
2
3
</code>```

The expected behaviour is that it returns me the id 3, but it returns me nothing

答:
NOT IN is somewhat tricky if the sub-query returns null values. Try NOT EXISTS instead:

```<code>select id from pa_employee o
where o.id not exists (select * from wh_route where driver = o.id);
</code>```

Title: Not In query not working

Body:
I'm trying to run this query, it's supposed to get all employees who're not drivers in wh_route, the driver is a fk for

The following queries are working and giving me back results:

select distinct driver from wh_route;
select id from pa_employee o where o.id not in (1,2,3,4,5);

But when I try to do this:

select id from pa_employee o where o.id not in (select distinct driver from wh_route);

It doesn't return any results.

Tables for reference:

WH_ROUTE
id    driver
1     1
2     2

PA_EMPLOYEE
id
1
2
3

The expected behaviour is that it returns me the id 3, but it returns me nothing

Body:
NOT IN is somewhat tricky if the sub-query returns null values. Try NOT EXISTS instead:

select id from pa_employee o
where o.id not exists (select * from wh_route where driver = o.id);


问:
How to break a loop for getting an integer array in c++
How can I break a loop when I define an integer array with a number and I want to finish the loop by pressing the ENTER.
I test '\n' and '\r' and '\0' and char(13) and NULL but didn't work !
for example ( in this code i try to stop the loop with ascii code of ENTER) :

```<code>#include <iostream>
using namespace std;
int main()
{
    int n[100];
    for (int i = 0; i < 100 && n[i]!=char(13); i++)
    {
        cin >> n[i];
    }
    return 0;
}
</code>```

答: You can change the code n[i]!=char(13) to n[i-1]!=char(13), because when you check the value of what your enter, the variable i has been changed to i++, so the value of n[i] is undefined,and you will always get true.

Body:
How can I break a loop when I define an integer array with a number and I want to finish the loop by pressing the ENTER.
I test '\n' and '\r' and '\0' and char(13) and NULL but didn't work !
for example ( in this code i try to stop the loop with ascii code of ENTER) :

#include <iostream>
using namespace std;
int main()
{
    int n[100];
    for (int i = 0; i < 100 && n[i]!=char(13); i++)
    {
        cin >> n[i];
    }
    return 0;
}


问:
split the parent element if the keyword found in xml file using perl

Question Updated

I have a keyword tag <split/> in the xml file. Base on this I need to split the elements to be closed which has been opened and Also I need to open DUMMY OPENING TAGS which we are adding the closing tags on the keyword elements.

For eg. Input:

```<code><section>
   <para> The para sample lines...
      <list>
     <list-item><para> ..... .... </para></list-item>
     <list-item><para> ..... .... </para></list-item>
     <list-item><para> ..... <split/> .... </para></list-item>
      </list>
     The para sample lines.. </para>
</section>
</code>```

Expected Output:

```<code><section>
   <para> The para sample lines...
      <list>
     <list-item><para> ..... .... </para></list-item>
     <list-item><para> ..... .... </para></list-item>
     <list-item><para> ..... </para></list-item>
      </list>
   </para>
</section>
*<split/>*
<section> <!--dummy tag-->
   <para><!--dummy tag-->
      <list><!--dummy tag-->
     <list-item><para><!--dummy tag--> <split/> .... </para></list-item>
      </list>
      The para sample lines.. </para>
</section>
</code>```

Note: Asterisks for just identification purpose only (need to delete the tag)

I am very new in using Module based on the Markup Languages. Could someone help me to get the idea. (I am also trying...)

答:
Here's an example of how you could do this using XML::Twig:

```<code>#!/usr/bin/env perl
use strict;
use warnings;

use XML::Twig;

my $first_doc = XML::Twig -> parse ( \*DATA );

my $second_doc = XML::Twig -> new;
$second_doc -> set_root ( $first_doc -> root -> copy ); #create a copy.

while ( my $after_split = $first_doc -> get_xpath('//split',0)->next_sibling ) {
   $after_split -> delete;
}

$first_doc -> get_xpath('//split',0) -> delete; # delete split tag.

while ( my $before_split = $second_doc -> get_xpath('//split',0)->prev_sibling ) {
   $before_split -> delete;
}

$second_doc -> get_xpath('//split',0) -> delete; # delete split tag.

$first_doc -> set_pretty_print ('indented_a');
$first_doc -> print;

print "\n--- second doc ---\n";
$second_doc -> set_pretty_print ('indented_a');
$second_doc -> print;

__DATA__
<section>
   <para>
      <list>
      <list-item><para> sample content for first doc <split/> second doc sample content </para></list-item>

      </list>
   </para>
</section>
</code>```

This gives you as output:

```<code><section>
  <para>
    <list>
      <list-item>
        <para> sample content for first doc </para>
      </list-item>
    </list>
  </para>
</section>

--- second doc ---
<section>
  <para>
    <list>
      <list-item>
        <para> second doc sample content </para>
      </list-item>
    </list>
  </para>
</section>
</code>```

You will probably want to look at parsefile and sprint from XML::Twig to handle reading your own file, and generating output.

Note - this does a 'full split' of the document into essentially two separate documents - but this technique should work withing a subtree, because the core of it is locating your split element, and deleting everything before or after it as necessary.

Body:
Question Updated

I have a keyword tag <split/> in the xml file. Base on this I need to split the elements to be closed which has been opened and Also I need to open DUMMY OPENING TAGS which we are adding the closing tags on the keyword elements.

For eg. Input:

   <para> The para sample lines...
      <list>
     <list-item><para> ..... .... </para></list-item>
     <list-item><para> ..... .... </para></list-item>
     <list-item><para> ..... <split/> .... </para></list-item>
      </list>
     The para sample lines.. </para>

Expected Output:

   <para> The para sample lines...
      <list>
     <list-item><para> ..... .... </para></list-item>
     <list-item><para> ..... .... </para></list-item>
     <list-item><para> ..... </para></list-item>
      </list>
   </para>

*<split/>*

   <para>
      <list>
     <list-item><para> <split/> .... </para></list-item>
      </list>
      The para sample lines.. </para>

Note: Asterisks for just identification purpose only (need to delete the tag)

I am very new in using Module based on the Markup Languages. Could someone help me to get the idea. (I am also trying...)

Body:
Here's an example of how you could do this using XML::Twig:

#!/usr/bin/env perl
use strict;
use warnings;

use XML::Twig;

my $first_doc = XML::Twig -> parse ( \*DATA );

my $second_doc = XML::Twig -> new;
$second_doc -> set_root ( $first_doc -> root -> copy ); #create a copy.

while ( my $after_split = $first_doc -> get_xpath('//split',0)->next_sibling ) {
   $after_split -> delete;
}

$first_doc -> get_xpath('//split',0) -> delete; # delete split tag.

while ( my $before_split = $second_doc -> get_xpath('//split',0)->prev_sibling ) {
   $before_split -> delete;
}

$second_doc -> get_xpath('//split',0) -> delete; # delete split tag.

$first_doc -> set_pretty_print ('indented_a');
$first_doc -> print;

print "\n--- second doc ---\n";
$second_doc -> set_pretty_print ('indented_a');
$second_doc -> print;

__DATA__
<section>
   <para>
      <list>
      <list-item><para> sample content for first doc <split/> second doc sample content </para></list-item>

      </list>
   </para>
</section>

This gives you as output:

<section>
  <para>
    <list>
      <list-item>
        <para> sample content for first doc </para>
      </list-item>
    </list>
  </para>
</section>

--- second doc ---
<section>
  <para>
    <list>
      <list-item>
        <para> second doc sample content </para>
      </list-item>
    </list>
  </para>
</section>

You will probably want to look at parsefile and sprint from XML::Twig to handle reading your own file, and generating output.

Note - this does a 'full split' of the document into essentially two separate documents - but this technique should work withing a subtree, because the core of it is locating your split element, and deleting everything before or after it as necessary.


问:
Why am I getting "this.state is null" in Reactjs?
I am brand new to Reacjs, I visited several question with a similar title but none helped me.

Why this code doesn't change my state?

```<code> componentWillMount()
 {
     /** I am using superagent to fetch some data but it doesn't matter */

     var url = "http://www.omdbapi.com/?s=star&apikey=mykey";
     Request.get(url).then((response) => {

     this.setState({ messages: response.body.Search});

    });
  }
</code>```

My render method

```<code>    render() {

         return (

                 <div>
  <ListaMensagens  messages={this.state.messages}  /> this.state is null here.
                </div>
            ...
</code>```

How can I change my state with the retrieved data and pass it to a child component?

答:
In general you can use setState in componentWillMount without getting into trouble, BUT...

in your case you are setting the state after the response of the request which is causing problems.

Three solutions for your problem:

1: Use the constructor to initialize the state.

```<code>constructor(props){
    super(props);

    this.state = {
        messages: []
    };
}
</code>```

2: Fire setState in componentWillMount without waiting for any Promise

```<code>componentWillMount() {
    this.setState({
        messages: []
    });
    request(...);
}
</code>```

3: In the render function check if the state is set properly

```<code>render(){
    <div>
        { this.state && this.state.messages && <ListMensagens ... /> }
    </div>
}
</code>```

Body:
I am brand new to Reacjs, I visited several question with a similar title but none helped me.

Why this code doesn't change my state?

 componentWillMount()
 {
     /** I am using superagent to fetch some data but it doesn't matter */

     var url = "http://www.omdbapi.com/?s=star&apikey=mykey";
     Request.get(url).then((response) => {

     this.setState({ messages: response.body.Search});

    });
  }

My render method

    render() {

         return (

  <ListaMensagens  messages={this.state.messages}  /> this.state is null here.

            ...

How can I change my state with the retrieved data and pass it to a child component?

Body:
In general you can use setState in componentWillMount without getting into trouble, BUT...

in your case you are setting the state after the response of the request which is causing problems.

Three solutions for your problem:

1: Use the constructor to initialize the state.

constructor(props){
    super(props);

    this.state = {
        messages: []
    };
}

2: Fire setState in componentWillMount without waiting for any Promise

componentWillMount() {
    this.setState({
        messages: []
    });
    request(...);
}

3: In the render function check if the state is set properly

render(){
    <div>
        { this.state && this.state.messages && <ListMensagens ... /> }
    </div>
}


问:
moment.format returning 3 days off
I have the following code in my Angular app:

```<code>ctrl.getDate = function() {
  console.log(ctrl.day.date); => 2017-12-06T05:00:00.000Z
  return moment(ctrl.day.date).format('MMMM do YYYY'); => December 3rd
    2017
  };
</code>```

What is going on here?  The date passed is clearly 2017-12-06 but for some reason the '.format' method is changing it to a day 3 days earlier.

答:
Capitalisation matters:

```<code>return moment(ctrl.day.date).format('MMMM Do YYYY');
</code>```

Changing do to Do

Title: moment.format returning 3 days off

Body:
I have the following code in my Angular app:

ctrl.getDate = function() {
  console.log(ctrl.day.date); => 2017-12-06T05:00:00.000Z
  return moment(ctrl.day.date).format('MMMM do YYYY'); => December 3rd
    2017
  };

What is going on here?  The date passed is clearly 2017-12-06 but for some reason the '.format' method is changing it to a day 3 days earlier.

Body:
Capitalisation matters:

return moment(ctrl.day.date).format('MMMM Do YYYY');

Changing do to Do


问:
How to implement inversifyJS basic example intro html page
I can't find example with html page or any live example for browsers (html page).

I need basic example just what to import lib and make one class.

I found on http://inversify.io  :

InversifyJS compiles to clean, simple JavaScript code which runs on
  any browser, in Node.js, or in any JavaScript engine that supports
  ECMAScript 5 (or newer).

答: To use InversifyJS in a web browser you are going to need Webpack. You need to bundle your app just like when working with any other frontend library these days. We don't have an official example but I found this blog https://blog.kloud.com.au/2017/03/22/dependency-injection-in-vuejs-app-with-typescript/ and the code is available on GitHub https://github.com/devkimchi/Vue.js-with-ASP.NET-Core-Sample/tree/master/src/VueJsTsIocSample</p>


问:
Future Any does not conform with Future E
I am having a problem in Scala when trying to return a result from a method.

I am using Play 2.6 and ReactiveMongo.

Error in the images bellow:

Could somebody give some clues?

答:
Future.map method is accepting a function to map the Future's result, so for your code, it's mapping result's Future result, equal to:

```<code>  result.map(writeResult: WriteResult => {
    case Success => entity
    case Failure(f) => f.printStackTrace()
  })
</code>```

As the above code, you are trying to return WriteResult and Unit,so the map result type is Any, and return Future[Any] type. so the type mismatch compile error thrown.

Actually you need is: result.map(writeResult: WriteResult => entity). and you can invoke create method like:

```<code>  val res = create(entity)
  res.onComplete {
    case Success(e) => println(e)
    case Failure(f) => f.printStackTrace()
  }
</code>```

Body:
Future.map method is accepting a function to map the Future's result, so for your code, it's mapping result's Future result, equal to:

  result.map(writeResult: WriteResult => {
    case Success => entity
    case Failure(f) => f.printStackTrace()
  })

As the above code, you are trying to return WriteResult and Unit,so the map result type is Any, and return Future[Any] type. so the type mismatch compile error thrown.

Actually you need is: result.map(writeResult: WriteResult => entity). and you can invoke create method like:

  val res = create(entity)
  res.onComplete {
    case Success(e) => println(e)
    case Failure(f) => f.printStackTrace()
  }


答:
Just figured out: in the wh_route table there was a null value for driver, so the working query became </p>

```<code>select id
  from pa_employee o
  where o.id not in (
    select distinct driver
      from wh_route
      where id is not null);
</code>```

Title: Not In query not working

Body:
Just figured out: in the wh_route table there was a null value for driver, so the working query became

select id
  from pa_employee o
  where o.id not in (
    select distinct driver
      from wh_route
      where id is not null);


问:
Setting backgroundColor of custom NSView
What is the process of drawing to NSView using storyboards for osx? I have added a NSView to the NSViewController. Then, I added a few constraints and an outlet.

Next, I added some code to change the color:
import Cocoa

```<code>class ViewController: NSViewController {

    @IBOutlet var box: NSView!

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

    override func viewWillAppear() {
        box.layer?.backgroundColor = NSColor.blueColor().CGColor
        //box.layer?.setNeedsDisplay()
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}
</code>```

I would like to do custom drawing and changing colors of the NSView. I have
performed sophisticated drawing on iOS in the past, but am totally stuck here.
Does anyone see what I'm doing wrong?

答: Since macOS 10.13 (High Sierra) NSView responds to selector backgroundColor although it is not documented!</p>

Body:
What is the process of drawing to NSView using storyboards for osx? I have added a NSView to the NSViewController. Then, I added a few constraints and an outlet.

Next, I added some code to change the color:
import Cocoa

class ViewController: NSViewController {

    @IBOutlet var box: NSView!

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

    override func viewWillAppear() {
        box.layer?.backgroundColor = NSColor.blueColor().CGColor
        //box.layer?.setNeedsDisplay()
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}

I would like to do custom drawing and changing colors of the NSView. I have
performed sophisticated drawing on iOS in the past, but am totally stuck here.
Does anyone see what I'm doing wrong?


问:
php string in a string with double and single quotes as 1 string

Hello, I am trying to make a array in php that looks like this:

```<code>$array= array("test"2"", "'test"2"'");
</code>```

Of course this doesn't work because of the two strings, but is there a way in php to get is to ignore all quotes in such a string so it sees it as a valid string? The problem being that I need the quotes in my string and it are double quotes and single quotes.

EDIT:
Thanks for the quick response! I was wondering if there is a way of doing this with code? I have a huge string to do this with?

```<code>$array= array("test\"2\"", "'test\"2\"'");
</code>```

答:
If you write text in double quotes, you have to escape it inside text using \.

```<code>$array = array("test\"2\"", "'test\"2\"'");
</code>```

If you write text in single quotes, you have to escape single quotes same way

```<code>$array = array('test"2"', '\'test"2"\'');
</code>```

Body:
Hello, I am trying to make a array in php that looks like this:

$array= array("test"2"", "'test"2"'");

Of course this doesn't work because of the two strings, but is there a way in php to get is to ignore all quotes in such a string so it sees it as a valid string? The problem being that I need the quotes in my string and it are double quotes and single quotes.

EDIT:
Thanks for the quick response! I was wondering if there is a way of doing this with code? I have a huge string to do this with?

$array= array("test\"2\"", "'test\"2\"'");

Body:
If you write text in double quotes, you have to escape it inside text using \.

$array = array("test\"2\"", "'test\"2\"'");

If you write text in single quotes, you have to escape single quotes same way

$array = array('test"2"', '\'test"2"\'');


问:
How to print the outcome of this code in HTML with proc print command
How can I make the outcome of this code to print into html using proc print? This is because I have to integrate the code inside an existing code that uses only proc print. Thanks in advance.

```<code>filename cmd pipe "dir G:\ | findstr /c:""bytes free""";

data _null_;
   infile cmd;
   input;
   free_space_gb = input(scan(_infile_,3,' '), comma20.) * 2**-30;
   put "There is currently " free_space_gb 8.2 "GB of free space on the G
   drive";
call symput('free_space_gb',free_space_gb); /*Create macro variable*/
run;

%macro print_alert_html;
  %if &free_space_gb < 1 %then %do;
   ods listing close;
   ods html file = "%sysfunc(pathname(work))\report.html";
    ods html text = "Alert: only &free_space_gb GB of space left on the G
drive!";
   ods html close;
   ods listing;
 %end;
%mend;
</code>```

答:
If you need to use Proc PRINT then the Gb information needs to be kept in a data set.  You might want to use Proc REPORT  when outputting a status message because it has a NOHEADER option. </p>

<p>The REPORT where clause will cause output only when the Gb is < 1.  </p>

```<code>filename cmd pipe "dir G:\ | findstr /c:""bytes free""";

data message;
   infile cmd;
   input;

   free_space_gb = input(scan(_infile_,3,' '), comma20.) * 2**-30;

   message = "There is currently " || strip(put(free_space_gb, 8.2)) ||  "GB of free space on the G drive";
run;

%macro print_alert_html;
   ods listing close;
   ods html file = "%sysfunc(pathname(work))\report.html";

   title;
   footnote;
   options nocenter nodate nonumber;
   proc report data=message noheader;
      column message;
      where free_space_gb < 1.00;
   run;

   ods html close;
   ods listing;
%mend;

%print_alert_html;
</code>```

Body:
How can I make the outcome of this code to print into html using proc print? This is because I have to integrate the code inside an existing code that uses only proc print. Thanks in advance.

filename cmd pipe "dir G:\ | findstr /c:""bytes free""";

data _null_;
   infile cmd;
   input;
   free_space_gb = input(scan(_infile_,3,' '), comma20.) * 2**-30;
   put "There is currently " free_space_gb 8.2 "GB of free space on the G
   drive";
call symput('free_space_gb',free_space_gb); /*Create macro variable*/
run;

%macro print_alert_html;
  %if &free_space_gb < 1 %then %do;
   ods listing close;
   ods html file = "%sysfunc(pathname(work))\report.html";
    ods html text = "Alert: only &free_space_gb GB of space left on the G
drive!";
   ods html close;
   ods listing;
 %end;
%mend;

Body:
If you need to use Proc PRINT then the Gb information needs to be kept in a data set.  You might want to use Proc REPORT  when outputting a status message because it has a NOHEADER option.

The REPORT where clause will cause output only when the Gb is < 1.

filename cmd pipe "dir G:\ | findstr /c:""bytes free""";

data message;
   infile cmd;
   input;

   free_space_gb = input(scan(_infile_,3,' '), comma20.) * 2**-30;

   message = "There is currently " || strip(put(free_space_gb, 8.2)) ||  "GB of free space on the G drive";
run;

%macro print_alert_html;
   ods listing close;
   ods html file = "%sysfunc(pathname(work))\report.html";

   title;
   footnote;
   options nocenter nodate nonumber;
   proc report data=message noheader;
      column message;
      where free_space_gb < 1.00;
   run;

   ods html close;
   ods listing;
%mend;

%print_alert_html;


问:
Discovering Protractor / jasmine tests in Test explorer of Visual studio?
I have an application written in angular and i have developed my app with angular-cli.
I have unit tests written using jasmine and E2E tests in protractor.

Is there a way i can discover my tests in Test explorer of Visual studio?

Is there a way i can associate the unit tests and protractor tests with test cases / work item in visual studio?

This is needed for generating test reports and to trace back the unit tests and E2E tests to the backlog items/ requirements in VSTS.

Additional info:
I have added my protractor tests in nodejs project.
The unit test are part of the angular application created with angular-cli.

I am using Visual studio 2017. Please let me know if more information is needed.

Any help would be appreciated.

Thanks in advance!

答:
Visual Studio is just IDE tool. You can use any tool You want to make your coding experience better.

Depends in which language is written Your code, but for the node.js and angular you will need good JavaScript IDE.

The best tool that I have used for JavaScript is WebStorm of JetBrains, if you want free You should use Atom or Eclipse.


问:
Tkinter: Pyimage is not working in a Function
I was trying to code a small window in a program that is giving you feedback about your statistics in the game. The output is working fine, but the image i tried to edit is not working. I tried to define the image global, i tried to take the direct path, i tried to change the suffix of the picture i want to edit (right now it's a .gif -file) but nothing is working. Whats wrong? What is my mistake?</p>

```<code>import tkinter
def blackhole():
    Black=tkinter.Tk()
    Black.title("BlackHole")
    schrift=tkinter.Label(Black,text="BlackHole: Game got reseted!")
    schrift.pack()
    Medal=tkinter.Label(Black,text="Congretulation! You earn the Bronze Medal!")
    Medal.pack()
    knopf=tkinter.Button(Black,text="Ok",command=submit)
    knopf.pack()
    canvas = tkinter.Canvas(Black, width=250, height=250)
    canvas.pack()
    tk_img = tkinter.PhotoImage(file = '/Users/Hannes/Desktop/Klickbot/b.gif')
    canvas.create_image(150, 150, image=tk_img)
</code>```

答:
To include images with Tkinter you should use Pillow (PIL).

https://python-pillow.org/

Run pip install Pillow from the terminal to install.

Sample usage:

```<code>from PIL import ImageTk, Image
img = ImageTk.PhotoImage(Image.open("logo.png"))
panel = Label(root, image=self.img)
panel.pack(side="top", fill="both", expand="yes")
</code>```

Body:
I was trying to code a small window in a program that is giving you feedback about your statistics in the game. The output is working fine, but the image i tried to edit is not working. I tried to define the image global, i tried to take the direct path, i tried to change the suffix of the picture i want to edit (right now it's a .gif -file) but nothing is working. Whats wrong? What is my mistake?

import tkinter
def blackhole():
    Black=tkinter.Tk()
    Black.title("BlackHole")
    schrift=tkinter.Label(Black,text="BlackHole: Game got reseted!")
    schrift.pack()
    Medal=tkinter.Label(Black,text="Congretulation! You earn the Bronze Medal!")
    Medal.pack()
    knopf=tkinter.Button(Black,text="Ok",command=submit)
    knopf.pack()
    canvas = tkinter.Canvas(Black, width=250, height=250)
    canvas.pack()
    tk_img = tkinter.PhotoImage(file = '/Users/Hannes/Desktop/Klickbot/b.gif')
    canvas.create_image(150, 150, image=tk_img)

Body:
To include images with Tkinter you should use Pillow (PIL).

https://python-pillow.org/

Run pip install Pillow from the terminal to install.

Sample usage:

from PIL import ImageTk, Image
img = ImageTk.PhotoImage(Image.open("logo.png"))
panel = Label(root, image=self.img)
panel.pack(side="top", fill="both", expand="yes")


问:
CreateTimerQueueTimer callback and race condition
I'm using timer queues in my application, and pass a pointer to one of my own C++ Timer objects as the 'parameter' to the callback (in CreateTimerQueueTimer). I then call a virtual method on the object in the callback.

The destructor of the Timer object will make sure to cancel the timer using DeleteTimerQueueTimer().

```<code>static void callback( PVOID param, BOOLEAN timerOrWaitFired )
{
    Timer* timer = reinterpret_cast< Timer* >( param );
    timer->TimedOut();
}

class Timer
{
public:
   Timer();

   virtual ~Timer()
   {
       ::DeleteTimerQueueTimer( handle );
   }

   void Start( double period )
   {
      ::CreateTimerQueueTimer( &handle, ..., &callback, this, ... );
   }

   virtual void TimedOut() = 0;

   ...
};
</code>```

However, there is a subtle race condition that if the callback has already been called, but the timer object is destroyed before the call to TimedOut(), the app crashes because the callback calls the virtual method on a non-existent object. Or even worse, while it's being deleted.

I do have mutexes in place to control multi-threaded calls, but I still get the problem.

Is using an object pointer as the callback parameter really a good idea? With no guarantees of synchronisation between the threads, it just smells bad to me.

Is there a better solution? What do other people do?

One thing that occurs is to keep a set of pointers to every single Timer instance (add in constructor, remove in destructor). But I don't think this would work because if Timer is derived from, we'd only remove the pointer from the set in the base class destructor; the damage is already done if we've started destroying the derived object.

Cheers.

答:
The concept of using the object pointer as callback function parameter is not bad by itself. However, you obviously need to start the destruction after the last callback has exited.

So, I wouldn't make Timer abstract and derive from it at all. I would use another abstract class TimerImpl and make the Timer class use a TimerImpl instance:

```<code>class Timer
{
  TimerInstance* impl;
  void TimeOut() { impl->TimeOut(); }
public:
  ~Timer() {
    ... make sure the timer has ended and wont fire again after this line...
    delete impl;
  }
}

struct TimerImpl
{
  virtual void TimeOut()=0;
  virtual ~TimerImpl();
}
</code>```

This way, you can ensure the destruction won't begin till after you say.

The second thing is, you have to wait for the last timer event to burn out. According to MSDN doc, you can do it by calling

```<code>DeleteTimerQueueTimer(TimerQueue, Timer, INVALID_HANDLE_VALUE)
</code>```

OwnerDisplayName: Steve Folly

ContentLicense: CC BY-SA 2.5

Body:
I'm using timer queues in my application, and pass a pointer to one of my own C++ Timer objects as the 'parameter' to the callback (in CreateTimerQueueTimer). I then call a virtual method on the object in the callback.

The destructor of the Timer object will make sure to cancel the timer using DeleteTimerQueueTimer().

static void callback( PVOID param, BOOLEAN timerOrWaitFired )
{
    Timer* timer = reinterpret_cast< Timer* >( param );
    timer->TimedOut();
}

class Timer
{
public:
   Timer();

   virtual ~Timer()
   {
       ::DeleteTimerQueueTimer( handle );
   }

   void Start( double period )
   {
      ::CreateTimerQueueTimer( &handle, ..., &callback, this, ... );
   }

   virtual void TimedOut() = 0;

   ...
};

However, there is a subtle race condition that if the callback has already been called, but the timer object is destroyed before the call to TimedOut(), the app crashes because the callback calls the virtual method on a non-existent object. Or even worse, while it's being deleted.

I do have mutexes in place to control multi-threaded calls, but I still get the problem.

Is using an object pointer as the callback parameter really a good idea? With no guarantees of synchronisation between the threads, it just smells bad to me.

Is there a better solution? What do other people do?

One thing that occurs is to keep a set of pointers to every single Timer instance (add in constructor, remove in destructor). But I don't think this would work because if Timer is derived from, we'd only remove the pointer from the set in the base class destructor; the damage is already done if we've started destroying the derived object.

Cheers.

Body:
The concept of using the object pointer as callback function parameter is not bad by itself. However, you obviously need to start the destruction after the last callback has exited.

So, I wouldn't make Timer abstract and derive from it at all. I would use another abstract class TimerImpl and make the Timer class use a TimerImpl instance:

class Timer
{
  TimerInstance* impl;
  void TimeOut() { impl->TimeOut(); }
public:
  ~Timer() {
    ... make sure the timer has ended and wont fire again after this line...
    delete impl;
  }
}

struct TimerImpl
{
  virtual void TimeOut()=0;
  virtual ~TimerImpl();
}

This way, you can ensure the destruction won't begin till after you say.

The second thing is, you have to wait for the last timer event to burn out. According to MSDN doc, you can do it by calling

DeleteTimerQueueTimer(TimerQueue, Timer, INVALID_HANDLE_VALUE)

OwnerDisplayName: jpalecek


问:
create transaction to stored procedures calls under c#
I am using stored procedures in sql server.
I have several stored procedures calls written in c#. I want to wrap them inside transaction:

```<code>//Begin Transaction here
sp1Call();
sp2Call();
sp3Call();
//Commit here
//Rollback if failed
</code>```

is there any way to do it?

Update:
I am using the enterprise library. example to sp1Call():

```<code>public static void sp1Call(string itemName)
    {
        DbCommand command = db.GetStoredProcCommand("dbo.sp1_insertItem");
        db.AddInParameter(command, "@item_name", DbType.String, itemName);
        db.ExecuteNonQuery(command);
    }
</code>```

答: You'll want to check out SqlTransaction.

Body:
I am using stored procedures in sql server.
I have several stored procedures calls written in c#. I want to wrap them inside transaction:

//Begin Transaction here
sp1Call();
sp2Call();
sp3Call();
//Commit here
//Rollback if failed

is there any way to do it?

Update:
I am using the enterprise library. example to sp1Call():

public static void sp1Call(string itemName)
    {
        DbCommand command = db.GetStoredProcCommand("dbo.sp1_insertItem");
        db.AddInParameter(command, "@item_name", DbType.String, itemName);
        db.ExecuteNonQuery(command);
    }


问:
Is there a limit to the size of a regex match in Rascal?
In trying to match all multiline comments in a Java source file I run into a StackOverflow() error. It happens when the matched comment is pretty large. I've managed to more or less pinpoint the limit to 2500 characters, but this might be specific to my environment.

I'm using the following expression to match the comments:

```<code>/<comment:((\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/))+>/mi
</code>```

Is there some limit to the size of the match I should be aware of, or is there a flaw in my regex?

My stacktrace is:

```<code>|project://Sevo1/src/Volume.rsc|(985,32,<53,12>,<53,44>): StackOverflow()
    at countLines(|project://Sevo1/src/Volume.rsc|(985,33,<53,12>,<53,45>))
    at $root$(|prompt:///|(0,73,<1,0>,<1,73>))
</code>```

答:
Your regex is not optimal as it contains a *-quantified capturing group that contains alternatives matching at the same locations inside the string.  You may see that [^*] matches any char but * (i.e. it matches line breaks), and then you have [\r\n] that also matches line breaks. Note that the chunks of text you match are mostly 1-char long (except for * chunks matched with (\*+([^*\/]|[\r\n]))), and the regex engine just does not seem to cope with that task well here.

Nested quantifiers are only good when you match longer chunks at one go. Re-write the pattern as

```<code>/<comment:\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\/>/
</code>```

and it will be more efficient. See the regex demo.

Details

\/\* - a /* substring

[^*]*\*+ - 0+ characters other than * followed with one or more literal *

(?:[^\/*][^*]*\*+)* - 0+ sequences of:

[^\/*][^*]*\*+ - not a / or * (matched with [^/*]) followed with 0+ non-asterisk characters ([^*]*) followed with one or more asterisks (\*+)

\/ - closing /

Body:
In trying to match all multiline comments in a Java source file I run into a StackOverflow() error. It happens when the matched comment is pretty large. I've managed to more or less pinpoint the limit to 2500 characters, but this might be specific to my environment.

I'm using the following expression to match the comments:

/<comment:((\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/))+>/mi

Is there some limit to the size of the match I should be aware of, or is there a flaw in my regex?

My stacktrace is:

|project://Sevo1/src/Volume.rsc|(985,32,<53,12>,<53,44>): StackOverflow()
    at countLines(|project://Sevo1/src/Volume.rsc|(985,33,<53,12>,<53,45>))
    at $root$(|prompt:///|(0,73,<1,0>,<1,73>))

Body:
Your regex is not optimal as it contains a *-quantified capturing group that contains alternatives matching at the same locations inside the string.  You may see that [^*] matches any char but * (i.e. it matches line breaks), and then you have [\r\n] that also matches line breaks. Note that the chunks of text you match are mostly 1-char long (except for * chunks matched with (\*+([^*\/]|[\r\n]))), and the regex engine just does not seem to cope with that task well here.

Nested quantifiers are only good when you match longer chunks at one go. Re-write the pattern as

/<comment:\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\/>/

and it will be more efficient. See the regex demo.

Details

\/\* - a /* substring

[^*]*\*+ - 0+ characters other than * followed with one or more literal *

(?:[^\/*][^*]*\*+)* - 0+ sequences of:

[^\/*][^*]*\*+ - not a / or * (matched with [^/*]) followed with 0+ non-asterisk characters ([^*]*) followed with one or more asterisks (\*+)

\/ - closing /


问:
Facebook won't send notifications from messages sent by a user that was transferred from a bot to the facebook page inbox by the Handover Protocol
I will name my firstborn after whoever answers my question!

My bot uses the Handover Protocol to transfer users from the bot (primary receiver) to the page's inbox (secondary receiver) after they tap on a 'chat with human' button, the problem is that I'm not getting any facebook notifications when the user starts messaging a human (page inbox).

Right now I'm having the bot email me anytime it transfers a user to a human but this fix obviously doesn't scale, ideally I would want facebook to send me notifications on my phone just like it does by default to pages that receive messages and don't have any bots installed.

I know I can see the messages sent to a human by using the 'standby' webhook but those are developer-side server logs, what I want are normal facebook notifications sent to the page owner and the people in the page's Roles so they reply to those messages instead of me (the developer) being the only one being notified through emails I have to send myself.

答:
1.You have to go to Your Page--> Settings--> Notifications--> Select this option
 from Messages- "Get a notification each time your Page receives a message".
2.Download "Facebook Pages Manager" App to get all your page related notification
  on your phone.</p>


问:
Warning: mysqli_real_connect(): (HY000/2002): No such file or directory in /private/tmp/wordpress/wp-includes/wp-db.php on line 1452
I'm trying to run PHPUnit to unittest a WordPress plugin, but the error in the title keeps showing up.

I used WP-CLI to setup the unittests, but also WP-CLI throws a similar error when I try to run it.

I use MAMP to run the database.

I have setup WP-CLI and PHPUnit as phars, that are aliased in ~/.bash-profile, and ran with the default "php" supplied by OS X.
Changing this, and running WP-CLI and PHPUnit with the latest PHP version supplied by MAMP fixed WP-CLI(It was running and connecting to the database just fine) but PHPUnit was still throwing the same error.

I have tried editing the wp-config.php file, and setting the host to ":/path/to/mamp/mysql.socket", "localhost:/path/to/mamp/mysql.socket" and "127.0.0.1", none of which helped.

I'm totally stuck, and don't know what to try next.

答:
Just go to your your phpMyAdmin, click on your database and copy the ip where is running the service and replace on your wp-config.php file:

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** MySQL hostname */
define('DB_HOST', 'ip_where_is_running_mysqlserver');

Replace Localhost to ip of running MySQL Server


问:
PHP SQLSRV - Query Not Working with ROW_NUMBER
My PHP version is 5.6.24, I'm using XAMPP, and I'm using this plugin : php_sqlsrv_56_ts.dll.
My PHP project was working fine until just now, it showed some error when retrieving data.

This is the query that I tried to execute :

```<code>SELECT  ROW_NUMBER() OVER ( ORDER BY IsFlagLive DESC, NamaProyek ASC ) No ,
Id , NamaProyek , NamaPT , IPSite
FROM    dbo.MasterKolam
WHERE   RowStatus = 0
ORDER BY IsFlagLive DESC , NamaProyek ASC
</code>```

I executed the query in SSMS, it worked fine.
I didn't change anything to the code or the query. I tried to remove the ROW_NUMBER part

```<code>ROW_NUMBER() OVER ( ORDER BY IsFlagLive DESC, NamaProyek ASC ) No ,
</code>```

It worked, but then I realized that many functions didn't work as well, so the issue is not only the ROW_NUMBER().

Is it something about T-SQL ? If yes, why my SQLSRV suddenly doesn't support it ? Is there any configuration for it ? Cheers.

(update) This is the script in PHP :

```<code>$str = "SELECT ROW_NUMBER() OVER(ORDER BY IsFlagLive DESC, NamaProyek ASC) No, SELECT Id, NamaProyek,NamaPT,NamaDatabase,IdKuitansi,IsFlagLive,Logo,alamat,TlpNfax,SenderEmail,SenderPassword,IsPKP, ToBeApprove, ToBeApproveManager, IPSite FROM dbo.MasterKolam WHERE RowStatus = 0 ORDER BY IsFlagLive Desc, NamaProyek ASC";
$res = sqlsrv_query($KONEKSIMaster,$str,$params,$options);
$num = sqlsrv_num_rows($res);
</code>```

答: It is all good now, guys. Apparently it is related to the disk space. I freed up some space (from ~2GB to ~9GB) and it works fine. Cheers !</p>

Body:
My PHP version is 5.6.24, I'm using XAMPP, and I'm using this plugin : php_sqlsrv_56_ts.dll.
My PHP project was working fine until just now, it showed some error when retrieving data.

This is the query that I tried to execute :

SELECT  ROW_NUMBER() OVER ( ORDER BY IsFlagLive DESC, NamaProyek ASC ) No ,
Id , NamaProyek , NamaPT , IPSite
FROM    dbo.MasterKolam
WHERE   RowStatus = 0
ORDER BY IsFlagLive DESC , NamaProyek ASC

I executed the query in SSMS, it worked fine.
I didn't change anything to the code or the query. I tried to remove the ROW_NUMBER part

ROW_NUMBER() OVER ( ORDER BY IsFlagLive DESC, NamaProyek ASC ) No ,

It worked, but then I realized that many functions didn't work as well, so the issue is not only the ROW_NUMBER().

Is it something about T-SQL ? If yes, why my SQLSRV suddenly doesn't support it ? Is there any configuration for it ? Cheers.

(update) This is the script in PHP :

$str = "SELECT ROW_NUMBER() OVER(ORDER BY IsFlagLive DESC, NamaProyek ASC) No, SELECT Id, NamaProyek,NamaPT,NamaDatabase,IdKuitansi,IsFlagLive,Logo,alamat,TlpNfax,SenderEmail,SenderPassword,IsPKP, ToBeApprove, ToBeApproveManager, IPSite FROM dbo.MasterKolam WHERE RowStatus = 0 ORDER BY IsFlagLive Desc, NamaProyek ASC";
$res = sqlsrv_query($KONEKSIMaster,$str,$params,$options);
$num = sqlsrv_num_rows($res);


问:
Java - removing first character of a string
In Java, I have a String:

```<code>Jamaica
</code>```

I would like to remove the first character of the string and then return amaica

How would I do this?

答:
My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.</p>

```<code> public static String removeLeadingChar(String str, char ch) {
    int idx = 0;
    while ((idx < str.length()) && (str.charAt(idx) == ch))
        idx++;
    return str.substring(idx);
}
</code>```

Body:
In Java, I have a String:

Jamaica

I would like to remove the first character of the string and then return amaica

How would I do this?

Body:
My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.

 public static String removeLeadingChar(String str, char ch) {
    int idx = 0;
    while ((idx < str.length()) && (str.charAt(idx) == ch))
        idx++;
    return str.substring(idx);
}


问:
Postgres COPY TO not working for intended destination directory
I have written a function that prepares data based on user-input from the web and copies the results down as a csv to a specified directory, from where the package (each request will contain information from 3 different tables/csv files) will be made available for the user to download.

The function itself works if the output directory is in the pg_data directory /var/lib/pgsql/data/adc_downloads, the permissions are:

```<code>drwxr-xr-x  2 postgres postgres  4096 Dec  5 15:18 adc_downloads
</code>```

But ideally I want the output directory to be here: /var/www/vhosts/[vhostname]/httpdocs/adc_downloads. After getting it to work in pg_data, I used chown -R --reference=/var/lib/pgsql/data/adc_downloads /var/www/vhosts/[vhostname]/httpdocs/adc_downloads and chmod with the same parameters to mimic the permissions which appears to have worked:

```<code>drwxr-xr-x  2 postgres postgres  4096 Dec  5 14:19 adc_downloads
</code>```

but I'm still getting a Permission denied error when trying to run the function with the intended output directory.

Something else then must be overriding the permissions I've (tried to?) set, any ideas what this might be? Given the function itself works in one directory but not another I don't think it's an SELinux issue, though I may of course be wrong.

Version Info: Postgres 8.4 CentOS 6.5 built with Plesk.

答: got this working (thanks to @joop's recommendation) in the intended location /var/www/vhosts/[vhostname]/httpdocs/adc_downloads by adding execute permission for the other users (including the postgres user) for the [vhostname] and httpdocs directories

Body:
I have written a function that prepares data based on user-input from the web and copies the results down as a csv to a specified directory, from where the package (each request will contain information from 3 different tables/csv files) will be made available for the user to download.

The function itself works if the output directory is in the pg_data directory /var/lib/pgsql/data/adc_downloads, the permissions are:

drwxr-xr-x  2 postgres postgres  4096 Dec  5 15:18 adc_downloads

But ideally I want the output directory to be here: /var/www/vhosts/[vhostname]/httpdocs/adc_downloads. After getting it to work in pg_data, I used chown -R --reference=/var/lib/pgsql/data/adc_downloads /var/www/vhosts/[vhostname]/httpdocs/adc_downloads and chmod with the same parameters to mimic the permissions which appears to have worked:

drwxr-xr-x  2 postgres postgres  4096 Dec  5 14:19 adc_downloads

but I'm still getting a Permission denied error when trying to run the function with the intended output directory.

Something else then must be overriding the permissions I've (tried to?) set, any ideas what this might be? Given the function itself works in one directory but not another I don't think it's an SELinux issue, though I may of course be wrong.

Version Info: Postgres 8.4 CentOS 6.5 built with Plesk.


问:
How will _Exit behave in a C++ program?
C99 offers the _Exit function, which exits "immediately", although it does may close file descriptors. Unix/POSIX extends this behavior by mandating the closing of all fd's without flushing (and offers the synonym _exit).

Will these functions call destructors for static objects when called from a C++ program? Does the C++ standard make any guarantees about _Exit?

(Inspired by this question; I suddenly wondered what happens in the typical fork-exec-_exit idiom in C++.)

答:
I did a quick test with gcc on Mac OS and my destructors didn't get called.

```<code>struct A
{
    ~A()
    {
        puts("A::~A");
    }
};

A globalA;

int main()
{
    A localA;
    _exit(0); // or _Exit(0)
    return 0;
}
</code>```

exit(0) on the other hand calls globalA's destructor.

Title: How will _Exit behave in a C++ program?

Body:
I did a quick test with gcc on Mac OS and my destructors didn't get called.

struct A
{
    ~A()
    {
        puts("A::~A");
    }
};

A globalA;

int main()
{
    A localA;
    _exit(0); // or _Exit(0)
    return 0;
}

exit(0) on the other hand calls globalA's destructor.


问:
Python: List of dictionaries: How to - nice printout using sys.stdout
I have the following list of dictionaries:

```<code>[{'Sequence': 'TGACCCTGCTTGGCGATCCCGGCGTTTC', 'Start': '52037', 'Strand': '+', 'End': '52064'}, {'Sequence': 'TGATCGCGCAACTGCAGCGGGAGTTAC', 'Start': '188334', 'Strand': '+', 'End': '188360'}, {'Sequence': 'TGATCCGGCACTCGTTGGAGTTCGTATC', 'Start': '245882', 'Strand': '+', 'End': '245909'}, {'Sequence': 'TGACCTTGGTCAGATCGATGACCGTAAT', 'Start': '318422', 'Strand': '+', 'End': '318449'}, {'Sequence': 'TGACCCGCGTATTTTGGAGCAGAAGTATC', 'Start': '343421', 'Strand': '+', 'End': '343449'}, {'Sequence': 'TGATCCGGCACTCGTTGGAGTTCGTATC', 'Start': '359576', 'Strand': '+', 'End': '359603'}, {'Sequence': 'TGATCGGCAATTCCTATGGCAAGTATC', 'Start': '457457', 'Strand': '+', 'End': '457483'}, {'Sequence': 'TGATCGAGGCGCCAGTTGTGCCCGTATT', 'Start': '627296', 'Strand': '+', 'End': '627323'}, {'Sequence': 'TGATCCAAGTGAACCCCCGCCCAGTAAA', 'Start': '637265', 'Strand': '+', 'End': '637292'}, {'Sequence': 'TGACCGGAAGACCGCCGTCGAGCGTATC', 'Start': '829035', 'Strand': '+', 'End': '829062'}, {'Sequence': 'TGATCGCGGCACCGACACCGGTCGTAAT', 'Start': '864440', 'Strand': '+', 'End': '864467'}, {'Sequence': 'TGATCGTTTCCGTGCTCGGAGCGTATC', 'Start': '934160', 'Strand': '+', 'End': '934186'}, {'Sequence': 'TGACCTGGCTCGAGGCCTGAGGAGTAAA', 'Start': '1162006', 'Strand': '+', 'End': '1162033'}, {'Sequence': 'TGACCCGCCGCAACATCCCCTTCGTAAA', 'Start': '1294515', 'Strand': '+', 'End': '1294542'}]
</code>```

I would like to acquire the following output (redirecting prints via sys.stdout):

```<code>Start:1234  End:5678  Strand:+  Sequence:ABCDEFG
...
</code>```

So far, my idea involves looping through the list and using the get-method to get the value of the key and then do a manual printout, basically like this:

```<code>for item in dictList:
    print("Start"+item.get('Start'))
    print("End"+item.get('End'))
    ...
</code>```

I am not sure how to deal with the newlines though. I read about sys.stdout flush to avoid
newlines, but since I do not want to avoid all newlines, I am not sure if this would suit my aim.

Is there a smarter/shorter way to do this?

Update

Thanks to Aleksey, I thought of changing my print statement to:

```<code>for item in dictList:
    print("Start"+str(item.get('Start'))+"  "+"End"+str(item.get('End'))+"  "+"Strand"+str(item.get('Strand'))+"  "+"Sequence: "+str(item.get('Sequence')))
</code>```

Update2

so far, I am sticking to this:

```<code>print(ecf+"  "+replicon+"  -  "+"Validated results: Total number of hits: "+str(len(finalList)))
print("")

for item in finalList:
    print("Start: "+str(item.get('Start'))+"  "+"End: "+str(item.get('End'))+"  "+"Strand: "+str(item.get('Strand'))+"  "+"Sequence: "+str(item.get('Sequence')))
</code>```

which prints:

```<code>ECF02  pSymA  -  Validated results: Total number of hits: 284

Start: 2876  End: 2903  Strand: +  Sequence: GAACTACAGGAAGTTCATGGTCTCCTTC
Start: 2876  End: 2900  Strand: +  Sequence: GAACTACAGGAAGTTCATGGTCTCC
Start: 9214  End: 9238  Strand: +  Sequence: GAACGTCGGGCGCAAGAGCCGCTTT
...
</code>```

please note: dictList was replaced by finalList. Due to parts of my script running before those prints

答:
Taken from my update, inspired by Aleksey Solovey</p>

```<code>print(ecf+"  "+replicon+"  -  "+"Validated results: Total number of hits: "+str(len(finalList)))
print("")

for item in finalList:
    print("Start: "+str(item.get('Start'))+"  "+"End: "+str(item.get('End'))+"  "+"Strand: "+str(item.get('Strand'))+"  "+"Sequence: "+str(item.get('Sequence')))
</code>```

Body:
I have the following list of dictionaries:

[{'Sequence': 'TGACCCTGCTTGGCGATCCCGGCGTTTC', 'Start': '52037', 'Strand': '+', 'End': '52064'}, {'Sequence': 'TGATCGCGCAACTGCAGCGGGAGTTAC', 'Start': '188334', 'Strand': '+', 'End': '188360'}, {'Sequence': 'TGATCCGGCACTCGTTGGAGTTCGTATC', 'Start': '245882', 'Strand': '+', 'End': '245909'}, {'Sequence': 'TGACCTTGGTCAGATCGATGACCGTAAT', 'Start': '318422', 'Strand': '+', 'End': '318449'}, {'Sequence': 'TGACCCGCGTATTTTGGAGCAGAAGTATC', 'Start': '343421', 'Strand': '+', 'End': '343449'}, {'Sequence': 'TGATCCGGCACTCGTTGGAGTTCGTATC', 'Start': '359576', 'Strand': '+', 'End': '359603'}, {'Sequence': 'TGATCGGCAATTCCTATGGCAAGTATC', 'Start': '457457', 'Strand': '+', 'End': '457483'}, {'Sequence': 'TGATCGAGGCGCCAGTTGTGCCCGTATT', 'Start': '627296', 'Strand': '+', 'End': '627323'}, {'Sequence': 'TGATCCAAGTGAACCCCCGCCCAGTAAA', 'Start': '637265', 'Strand': '+', 'End': '637292'}, {'Sequence': 'TGACCGGAAGACCGCCGTCGAGCGTATC', 'Start': '829035', 'Strand': '+', 'End': '829062'}, {'Sequence': 'TGATCGCGGCACCGACACCGGTCGTAAT', 'Start': '864440', 'Strand': '+', 'End': '864467'}, {'Sequence': 'TGATCGTTTCCGTGCTCGGAGCGTATC', 'Start': '934160', 'Strand': '+', 'End': '934186'}, {'Sequence': 'TGACCTGGCTCGAGGCCTGAGGAGTAAA', 'Start': '1162006', 'Strand': '+', 'End': '1162033'}, {'Sequence': 'TGACCCGCCGCAACATCCCCTTCGTAAA', 'Start': '1294515', 'Strand': '+', 'End': '1294542'}]

I would like to acquire the following output (redirecting prints via sys.stdout):

Start:1234  End:5678  Strand:+  Sequence:ABCDEFG
...

So far, my idea involves looping through the list and using the get-method to get the value of the key and then do a manual printout, basically like this:

for item in dictList:
    print("Start"+item.get('Start'))
    print("End"+item.get('End'))
    ...

I am not sure how to deal with the newlines though. I read about sys.stdout flush to avoid
newlines, but since I do not want to avoid all newlines, I am not sure if this would suit my aim.

Is there a smarter/shorter way to do this?

Update

Thanks to Aleksey, I thought of changing my print statement to:

for item in dictList:
    print("Start"+str(item.get('Start'))+"  "+"End"+str(item.get('End'))+"  "+"Strand"+str(item.get('Strand'))+"  "+"Sequence: "+str(item.get('Sequence')))

Update2

so far, I am sticking to this:

print(ecf+"  "+replicon+"  -  "+"Validated results: Total number of hits: "+str(len(finalList)))
print("")

for item in finalList:
    print("Start: "+str(item.get('Start'))+"  "+"End: "+str(item.get('End'))+"  "+"Strand: "+str(item.get('Strand'))+"  "+"Sequence: "+str(item.get('Sequence')))

which prints:

ECF02  pSymA  -  Validated results: Total number of hits: 284

Start: 2876  End: 2903  Strand: +  Sequence: GAACTACAGGAAGTTCATGGTCTCCTTC
Start: 2876  End: 2900  Strand: +  Sequence: GAACTACAGGAAGTTCATGGTCTCC
Start: 9214  End: 9238  Strand: +  Sequence: GAACGTCGGGCGCAAGAGCCGCTTT
...

please note: dictList was replaced by finalList. Due to parts of my script running before those prints

Body:
Taken from my update, inspired by Aleksey Solovey

print(ecf+"  "+replicon+"  -  "+"Validated results: Total number of hits: "+str(len(finalList)))
print("")

for item in finalList:
    print("Start: "+str(item.get('Start'))+"  "+"End: "+str(item.get('End'))+"  "+"Strand: "+str(item.get('Strand'))+"  "+"Sequence: "+str(item.get('Sequence')))


问:
Issue with google geocode API : Getting "partial_match" in response
I am using google Geocode API to get the lat long of particular address.

when I am searching for "364 S Side Square, Carlinville, IL 62626, USA" in google search or google maps it gives the accurate pin point on google search result or maps result.

but same time when i am searching the same address using Geocode API using below request call, it gives "partial_match" : true

http://maps.googleapis.com/maps/api/geocode/json?address=364 S Side Square, Carlinville, IL 62626, USA&sensor=false

any one knows why it gives "partial_match" : true in response ?

what changes i have to do in the API request so that i won't get "partial_match" ?

答:
To understand the nature of the partial match flag for the '364 S Side Square, Carlinville, IL 62626, USA' let's have a look at this address in geocoder tool:

https://google-developers.appspot.com/maps/documentation/utils/geocoder/#q%3D364%2520S%2520Side%2520Square%252C%2520Carlinville%252C%2520IL%252062626%252C%2520USA

Indeed, the search string and formatted address in the result are exactly the same, however, we have to pay attention to other values like location_type and place_id

As you can see the location type is RANGE_INTERPOLATED and the place ID has a long value Ei0zNjQgUyBTaWRlIFNxdWFyZSwgQ2FybGludmlsbGUsIElMIDYyNjI2LCBVU0E. This means Google doesn't have an exact address feature in their database and tries to interpolate where this address might be located. In case if address exists in the Google database, you will see a location type ROOFTOP and a shorter place ID (something similar to ChIJrTLr-GyuEmsRBfy61i59si0).

Resuming aforementioned, the partial match flag in your example indicates that exact street address feature doesn't exist in the Google database.

This also can be confirmed by the following sentence in the documentation:

Partial matches most often occur for street addresses that do not exist within the locality you pass in the request.

https://developers.google.com/maps/documentation/geocoding/intro#GeocodingResponses

You also have an option to report a missing address to Google following the help center:

https://support.google.com/maps/answer/6320846

I hope my answer addresses your doubt!


问:
Objective C/XCode - Image in ImageView not recognised by Xcode
I am developing a simple calculator to sum the prices of 3 images in a view. These images are stored inside imageviews. The image inside each imageview can be changed using button 1-6 etc etc. The price is displayed on a label at the bottom.

I am using an if statement(s) that says if the image inside xyz imageview is @"zyx", set price as yzx.

I know the calculator works because the calculator always takes the "else" value (even if the price I set for the else value changes)

```<code>if(
   self.topimage.image == [UIImage imageNamed:@"image.png"]){

    self.TopImageView.Price = 200;
}
else if(
        self.topimage.image == [UIImage imageNamed:@"slacks.png"]){

    self.TopImageView.Price = 400;
}
else {
    self.TopImageView.Price = 9;

}
</code>```

Xcode can't recognise when the image inside the imageview equals an image of whatever name / doesn't update the price.

I tried as well pulling the image straight from the array rather than naming it:

```<code> if(
       self.topimage.image == [UIImage imageNamed:[self.imagesArray objectAtIndex: 1]]){

    self.TopImageView.Price = 200;
}
</code>```

and still the price on the label doesn't change. I'm assuming this is because the price of the imageview doesn't change.

the price on the label is given by:

```<code>_totalprice = (self.TopImageView.Price + self.MiddleImageView.Price + self.BottomImageView.Price);

    self.Pricelabel.text = [NSString stringWithFormat:@"£%.0f", _totalprice];
</code>```

all properties are defined and the program runs with no errors. The calculator itself works and correctly sums the 'else' values from my if clauses. All images are under "supporting files" in xcode and I know there can't be an issue with pulling them because they display on the app when pulling them from an array.

Here, for an example, is all the code I have under one button:

```<code>- (IBAction)Button2:(UIButton *)sender {

    self.clothesindex = self.clothesindex - 1;

    if (self.clothesindex == (-1)) {
        self.clothesindex = 2;
    }
    self.topimage.image = [UIImage imageNamed:[self.imagesArray objectAtIndex: self.clothesindex ]];

    if(
       self.topimage.image == [UIImage imageNamed:@"image.png"]){

        self.TopImageView.Price = 200;
    }
    else if(
            self.topimage.image == [UIImage imageNamed:@"slacks.png"]){

        self.TopImageView.Price = 400;
    }
    else {
        self.TopImageView.Price = 9;

    }

    _totalprice = (self.TopImageView.Price + self.MiddleImageView.Price + self.BottomImageView.Price);

    self.Pricelabel.text = [NSString stringWithFormat:@"£%.0f", _totalprice];
}
</code>```

where "top image" is the imageview, "TopImageView" is a class, and "Price" a property of that class.

Any help would be greatly appreciated.

答:
To compare images you can use this method,</p>

```<code>- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2
{
    NSData *data1 = UIImagePNGRepresentation(image1);
    NSData *data2 = UIImagePNGRepresentation(image2);

    return [data1 isEqual:data2];
}
</code>```

Body:
I am developing a simple calculator to sum the prices of 3 images in a view. These images are stored inside imageviews. The image inside each imageview can be changed using button 1-6 etc etc. The price is displayed on a label at the bottom.

I am using an if statement(s) that says if the image inside xyz imageview is @"zyx", set price as yzx.

I know the calculator works because the calculator always takes the "else" value (even if the price I set for the else value changes)

if(
   self.topimage.image == [UIImage imageNamed:@"image.png"]){

    self.TopImageView.Price = 200;
}
else if(
        self.topimage.image == [UIImage imageNamed:@"slacks.png"]){

    self.TopImageView.Price = 400;
}
else {
    self.TopImageView.Price = 9;

}

Xcode can't recognise when the image inside the imageview equals an image of whatever name / doesn't update the price.

I tried as well pulling the image straight from the array rather than naming it:

 if(
       self.topimage.image == [UIImage imageNamed:[self.imagesArray objectAtIndex: 1]]){

    self.TopImageView.Price = 200;
}

and still the price on the label doesn't change. I'm assuming this is because the price of the imageview doesn't change.

the price on the label is given by:

_totalprice = (self.TopImageView.Price + self.MiddleImageView.Price + self.BottomImageView.Price);

    self.Pricelabel.text = [NSString stringWithFormat:@"£%.0f", _totalprice];

all properties are defined and the program runs with no errors. The calculator itself works and correctly sums the 'else' values from my if clauses. All images are under "supporting files" in xcode and I know there can't be an issue with pulling them because they display on the app when pulling them from an array.

Here, for an example, is all the code I have under one button:

- (IBAction)Button2:(UIButton *)sender {

    self.clothesindex = self.clothesindex - 1;

    if (self.clothesindex == (-1)) {
        self.clothesindex = 2;
    }
    self.topimage.image = [UIImage imageNamed:[self.imagesArray objectAtIndex: self.clothesindex ]];

    if(
       self.topimage.image == [UIImage imageNamed:@"image.png"]){

        self.TopImageView.Price = 200;
    }
    else if(
            self.topimage.image == [UIImage imageNamed:@"slacks.png"]){

        self.TopImageView.Price = 400;
    }
    else {
        self.TopImageView.Price = 9;

    }

    _totalprice = (self.TopImageView.Price + self.MiddleImageView.Price + self.BottomImageView.Price);

    self.Pricelabel.text = [NSString stringWithFormat:@"£%.0f", _totalprice];
}

where "top image" is the imageview, "TopImageView" is a class, and "Price" a property of that class.

Any help would be greatly appreciated.

Body:
To compare images you can use this method,

- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2
{
    NSData *data1 = UIImagePNGRepresentation(image1);
    NSData *data2 = UIImagePNGRepresentation(image2);

    return [data1 isEqual:data2];
}


问:
VbScript to launch URL in default browser from batch file argument
I have a batch script MyBatch.bat, it successfully calls MyVbScript.vbs by the statement:

```<code>cscript //nologo %~dp0\MyVbScript.vbs %NewPort%
</code>```

Where NewPort is a environment variable value.

MyVbScript.vbs is getting called successfully (tested) and value of NewPort is passed to VBS successfully (tested) from batch script.

But I am NOT able to generate the URL for launching in default browser. I want to generate the URL like http://localhost:7006/MyWebApplication where 7006 is value of NewPort variable.

MyVbScript.vbs contains:

```<code>Option Explicit
Dim wsh
Dim port
Dim myNum

Set wsh=WScript.CreateObject("WScript.Shell")
port = WScript.Arguments(0)

'MsgBox port//For testing
wsh.Run " "http://localhost:"&port&"/MyWebApplication" "

'End of VB script
</code>```

How to generate the URL and launch it in default browser. I don't want to specify Chrome or Mozilla and IE because user may not have a particular browser.

答:
The following worked:

```<code>wsh.Run "http://localhost:"&port&"/MyWebApplication"
</code>```

Any seasoned programmer can suggest other code too if I have written more LOC unnecessarily.

Body:
I have a batch script MyBatch.bat, it successfully calls MyVbScript.vbs by the statement:

cscript //nologo %~dp0\MyVbScript.vbs %NewPort%

Where NewPort is a environment variable value.

MyVbScript.vbs is getting called successfully (tested) and value of NewPort is passed to VBS successfully (tested) from batch script.

But I am NOT able to generate the URL for launching in default browser. I want to generate the URL like http://localhost:7006/MyWebApplication where 7006 is value of NewPort variable.

MyVbScript.vbs contains:

Option Explicit
Dim wsh
Dim port
Dim myNum

Set wsh=WScript.CreateObject("WScript.Shell")
port = WScript.Arguments(0)

'MsgBox port//For testing
wsh.Run " "http://localhost:"&port&"/MyWebApplication" "

'End of VB script

How to generate the URL and launch it in default browser. I don't want to specify Chrome or Mozilla and IE because user may not have a particular browser.

Body:
The following worked:

wsh.Run "http://localhost:"&port&"/MyWebApplication"

Any seasoned programmer can suggest other code too if I have written more LOC unnecessarily.


问:
Redirect from one scene to another Unity 3D script
I have 2 scenes and I want to redirect from one to another on the button click. I used AssetBundle for that.
Here is the code for exporting of assets:

```<code>public class ExportAssetBundles
{
    [MenuItem("Assets/Build AssetBundle")]
    static void ExportResource()
    {
        string folderName = "AssetBundles";
        string filePath = Path.Combine(Application.streamingAssetsPath, folderName);

        BuildPipeline.BuildAssetBundles(filePath, BuildAssetBundleOptions.None, BuildTarget.NoTarget);
    }
}
</code>```

And here is the code for loading:

```<code>public class RedirectToMenu : MonoBehaviour {
    void Start () {
        Button btn = GetComponent<Button>);
        btn.onClick.AddListener(OnClick);
    }

    public void OnClick(){
        Debug.Log("You have clicked the button!");
        LoadAsset("MenuFinal");
    }

    IEnumerator LoadAsset(string assetBundleName)//, string objectNameToLoad)
    {
        string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundles");
        filePath = System.IO.Path.Combine(filePath, assetBundleName);

        var assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(filePath);
        yield return assetBundleCreateRequest;

        AssetBundle asseBundle = assetBundleCreateRequest.assetBundle;
    }
}
</code>```

So when I run my scene in Unity I get such error in console:

```<code>ArgumentException: The output path "D:/userdata/Documents/Scene1/Assets/StreamingAssets\AssetBundles" doesn't exist(at ExportAssetBundles.ExportResource () (at Assets/ExportAssetBundles.cs:16)
</code>```

I have put my scenes into Assets folder:

Also, I have added them to Build settings:

So how can I fix this error and make the redirection work? Is that a code problem or some file locations problem?

答:
The path you ask for is

```<code>"D:/userdata/Documents/Scene1/Assets/StreamingAssets\AssetBundles"
</code>```

but your real path is

```<code>"D:/userdata/Documents/Scene1/Assets/StreamingAssets\AssetBundle" <- no 's'
</code>```

Body:
I have 2 scenes and I want to redirect from one to another on the button click. I used AssetBundle for that.
Here is the code for exporting of assets:

public class ExportAssetBundles
{
    [MenuItem("Assets/Build AssetBundle")]
    static void ExportResource()
    {
        string folderName = "AssetBundles";
        string filePath = Path.Combine(Application.streamingAssetsPath, folderName);

        BuildPipeline.BuildAssetBundles(filePath, BuildAssetBundleOptions.None, BuildTarget.NoTarget);
    }
}

And here is the code for loading:

public class RedirectToMenu : MonoBehaviour {
    void Start () {
        Button btn = GetComponent<Button>);
        btn.onClick.AddListener(OnClick);
    }

    public void OnClick(){
        Debug.Log("You have clicked the button!");
        LoadAsset("MenuFinal");
    }

    IEnumerator LoadAsset(string assetBundleName)//, string objectNameToLoad)
    {
        string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "AssetBundles");
        filePath = System.IO.Path.Combine(filePath, assetBundleName);

        var assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(filePath);
        yield return assetBundleCreateRequest;

        AssetBundle asseBundle = assetBundleCreateRequest.assetBundle;
    }
}

So when I run my scene in Unity I get such error in console:

ArgumentException: The output path "D:/userdata/Documents/Scene1/Assets/StreamingAssets\AssetBundles" doesn't exist(at ExportAssetBundles.ExportResource () (at Assets/ExportAssetBundles.cs:16)

I have put my scenes into Assets folder:

Also, I have added them to Build settings:

So how can I fix this error and make the redirection work? Is that a code problem or some file locations problem?

Body:
The path you ask for is

"D:/userdata/Documents/Scene1/Assets/StreamingAssets\AssetBundles"

but your real path is

"D:/userdata/Documents/Scene1/Assets/StreamingAssets\AssetBundle" <- no 's'


问:
Rails / Devise (Devise token auth) Redirect upon unlocking account
I'm currently trying to find a way to change my redirection url upon unlocking an account. Currently when an account is locked the user is getting a email to unlock is account but then the te user get redirect on a default url. Since my rails project is an api it would be nice to redirect to my front-end</p>

```<code>Started GET "/api/auth/unlock?unlock_token=YvR4nNssxhB9h8hvDAse" for
127.0.0.1 at 2017-12-04 15:28:08 -0500
Processing by Devise::UnlocksController#show as JSON
Parameters: {"unlock_token"=>"YvR4nNssxhB9h8hvDAse"}
User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE
"users"."unlock_token" = $1 ORDER BY "users"."id" ASC LIMIT $2
[["unlock_token",
"6f3c4d7aa5254e143f89cd7f187e22ce56b11e6abe1f5eb252e34d86ac101908"],
["LIMIT", 1]]
(0.1ms)  BEGIN
SQL (0.7ms)  UPDATE "users" SET "locked_at" = $1, "failed_attempts" = $2,
"unlock_token" = $3, "updated_at" = $4 WHERE "users"."id" = $5
[["locked_at", nil], ["failed_attempts", 0], ["unlock_token", nil],
["updated_at", "2017-12-04 20:28:08.783744"], ["id", 1]]
(3.4ms)  COMMIT
Redirected to http://localhost:3000/api/auth/sign_in
Completed 302 Found in 17ms (ActiveRecord: 5.0ms)

Started GET "/api/auth/sign_in" for 127.0.0.1 at 2017-12-04 15:28:08
-0500
Processing by DeviseTokenAuth::SessionsController#new as JSON
[active_model_serializers] Rendered ActiveModel::Serializer::Null with
Hash (0.14ms)
Completed 405 Method Not Allowed in 2ms (Views: 0.9ms | ActiveRecord:
0.0ms)

Started GET "/api/auth/sign_in" for 127.0.0.1 at 2017-12-04 15:31:26
-0500
Processing by DeviseTokenAuth::SessionsController#new as JSON
[active_model_serializers] Rendered ActiveModel::Serializer::Null with
Hash (0.11ms)
Completed 405 Method Not Allowed in 1ms (Views: 0.7ms | ActiveRecord:
0.0ms)
</code>```

答:
To do any customization with Devise, one must override the default controllers by creating a new controller and inheriting from it in your case that would be Devise::UnlocksController

For example:
CustomUnlocksController < Devise::UnlocksController

https://github.com/plataformatec/devise/blob/master/app/controllers/devise/unlocks_controller.rb

Override after_unlock_path_for to the path which you are going to redirect after.

Body:
I'm currently trying to find a way to change my redirection url upon unlocking an account. Currently when an account is locked the user is getting a email to unlock is account but then the te user get redirect on a default url. Since my rails project is an api it would be nice to redirect to my front-end

Started GET "/api/auth/unlock?unlock_token=YvR4nNssxhB9h8hvDAse" for
127.0.0.1 at 2017-12-04 15:28:08 -0500
Processing by Devise::UnlocksController#show as JSON
Parameters: {"unlock_token"=>"YvR4nNssxhB9h8hvDAse"}
User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE
"users"."unlock_token" = $1 ORDER BY "users"."id" ASC LIMIT $2
[["unlock_token",
"6f3c4d7aa5254e143f89cd7f187e22ce56b11e6abe1f5eb252e34d86ac101908"],
["LIMIT", 1]]
(0.1ms)  BEGIN
SQL (0.7ms)  UPDATE "users" SET "locked_at" = $1, "failed_attempts" = $2,
"unlock_token" = $3, "updated_at" = $4 WHERE "users"."id" = $5
[["locked_at", nil], ["failed_attempts", 0], ["unlock_token", nil],
["updated_at", "2017-12-04 20:28:08.783744"], ["id", 1]]
(3.4ms)  COMMIT
Redirected to http://localhost:3000/api/auth/sign_in
Completed 302 Found in 17ms (ActiveRecord: 5.0ms)

Started GET "/api/auth/sign_in" for 127.0.0.1 at 2017-12-04 15:28:08
-0500
Processing by DeviseTokenAuth::SessionsController#new as JSON
[active_model_serializers] Rendered ActiveModel::Serializer::Null with
Hash (0.14ms)
Completed 405 Method Not Allowed in 2ms (Views: 0.9ms | ActiveRecord:
0.0ms)

Started GET "/api/auth/sign_in" for 127.0.0.1 at 2017-12-04 15:31:26
-0500
Processing by DeviseTokenAuth::SessionsController#new as JSON
[active_model_serializers] Rendered ActiveModel::Serializer::Null with
Hash (0.11ms)
Completed 405 Method Not Allowed in 1ms (Views: 0.7ms | ActiveRecord:
0.0ms)


问:
Removal of an iFrame after internal submit has been clicked
Hope people can help - been using 'Stack Over Flow' for reference for many years now, but this is the first time I'm stuck on some coding. Below is the iFrame, what I would like to happen is when the submit button on the form has been clicked is for it to disappear, but instead the iFrame is still there and within the iFrame it goes to 'How can we help you today?'

Also, when the iFrame disappears a line of text should appear.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="overflow: hidden;position: relative;height: 970px; width:150%;" onclick="removeIFrame();">
<iframe id="myIframe" src="https://sheersense.freshdesk.com/support/tickets/new" scrolling="no" width="100%" height="1125px" frameborder="0" style="position: absolute; top:-150px"></iframe>

<div id="text_display" style="">Thank you for your ticket, a member of the Sheersense team will be in touch with you shortly.</div>
</div></code>```

Many thanks for the help!

答:
You can find the possible answer in this post-
https://stackoverflow.com/a/3690896/8438534

As mentioned in that answer, if the click is in the iframe area, the iframe context handles the click event, it does not bubble up to the iframe parent. So the div will never register the click event at all if it happened in the iframe area.

Body:
Hope people can help - been using 'Stack Over Flow' for reference for many years now, but this is the first time I'm stuck on some coding. Below is the iFrame, what I would like to happen is when the submit button on the form has been clicked is for it to disappear, but instead the iFrame is still there and within the iFrame it goes to 'How can we help you today?'

Also, when the iFrame disappears a line of text should appear.

Thank you for your ticket, a member of the Sheersense team will be in touch with you shortly.

Many thanks for the help!


问:
Learn Python the Hard Way Exercise 17 Extra Question(S)
I'm doing Zed Shaw's fantastic Learn Python The Hard Way, but an extra question has me stumped: Line 9--10 could be written in one line, how? I've tried some different thoughts, but to no avail. I could move on, but what would the fun in that be?

```<code>from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

# we could do these two on one line too, how?
input = open(from_file)
indata = input.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

output = open(to_file, 'w')
output.write(indata)

print "Alright, all done."
</code>```

Zed also writes that he could do the whole script in one line. I'm not exactly sure what he means by that.

Feel free to help me however you want: by giving the answer or merely hinting---and perhaps including a collapsed or hidden answer to the question.

答:
try the following code:</p>

```<code>import shutil, sys; shutil.copy(sys.argv[0], sys.argv[2])
</code>```

Body:
I'm doing Zed Shaw's fantastic Learn Python The Hard Way, but an extra question has me stumped: Line 9--10 could be written in one line, how? I've tried some different thoughts, but to no avail. I could move on, but what would the fun in that be?

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

# we could do these two on one line too, how?
input = open(from_file)
indata = input.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

output = open(to_file, 'w')
output.write(indata)

print "Alright, all done."

Zed also writes that he could do the whole script in one line. I'm not exactly sure what he means by that.

Feel free to help me however you want: by giving the answer or merely hinting---and perhaps including a collapsed or hidden answer to the question.

Body:
try the following code:

import shutil, sys; shutil.copy(sys.argv[0], sys.argv[2])