问:
Understanding Perl Script for GPIB Interface
I am new to the perl and python. As a part of my job currently I am asked to convert the perl script to python. The purpose of this script is to automate the task of the magnum tester and parametric analyzer. Is any of you able to understand what the get_gpib_status function trying to do ??. Specific questions are

What does if(/Error/) mean in perl ?

What does it mean by

```<code>        chomp;
        s/\+//g;
        $value = $_;
        $foundError = 0;
</code>```

in perl?. What is the python equivalent of the get_gpib_status function ??.

Any kind of help is highly appreciated. Thanks in advance. The Script is as shown below.

```<code>BEGIN {unshift(@INC, "." , ".." ,
"\\Micron\\Nextest\\perl_modules");}

use runcli;
# Enable input from perl script as nextest cli command, Runcli is the
command
that you’ll use to communicate with the tester
use getHost;
# To latch in module/ "library into current script, here the
getHost.pm
is
loaded, used once on nextest system

#open FILE,">","iv.txt" or die $!;
# Make file ready for reading from FILE

$k=148;
# Time period T = 38ns corresponds to data value of 140
#$i=0;
while($k<156)
{
$i=3;
while($i<4)
{
#$logfile = "vpasscp8stg_SS_vppmode"."stg"."$i"."freq"."$k".".txt";
# Give the name to the logfile
#open(LOG,">$logfile") or die $!;
# Makes the file ready for reading from LOG

#******************* SUBS ****************************

if($i==3)
{

runcli("gpibinit;");
runcli("gpibsend(0x1,\":PAGE:CHAN:MODE SWEEP\")");
# PAGE, CHANnel, MODE, Set the mode to sweep

runcli("gpibsend(0x1,\":PAGE:CHAN:SMU1:VNAME 'Vout'\")");
# Source Monitor Unit, voltage name Vout
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU1:INAME 'Iout'\")");
# current name Iout
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU1:MODE V\")");
# voltage output node
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU1:FUNCTION VAR1\")");
# function Variable

runcli("gpibsend(0x1,\":PAGE:CHAN:SMU2:VNAME 'Vcc'\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU2:INAME 'Icc'\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU2:MODE V\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU2:FUNCTION CONSTANT\")");
# function constant

runcli("gpibsend(0x1,\":PAGE:CHAN:SMU3:VNAME 'Vpp'\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU3:INAME 'Ipp'\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU3:MODE V\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU3:FUNCTION CONSTANT\")");

#runcli("gpibsend(0x1,\":PAGE:CHAN:SMU3:DIS\")");

runcli("gpibsend(0x1,\":PAGE:CHAN:SMU4:DIS\")");

runcli("gpibsend(0x1,\":PAGE:CHAN:VSU1:DIS\")");
# Voltage Source Unit DISabled

runcli("gpibsend(0x1,\":PAGE:CHAN:VSU2:DIS\")");

runcli("gpibsend(0x1,\":PAGE:DISP:LIST:SELECT 'Vout'\")");
# DISPlay LIST
runcli("gpibsend(0x1,\":PAGE:DISP:LIST:SELECT 'Iout'\")");
runcli("gpibsend(0x1,\":PAGE:DISP:LIST:SELECT 'Vcc'\")");
runcli("gpibsend(0x1,\":PAGE:DISP:LIST:SELECT 'Icc'\")");

runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:MODE SINGLE\")");
# Single Stair Sweep
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:SPACING LINEAR\")");
# The sweep is incremented (decremented) by the
# stepsize until the stop value is reached.

runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:START 2.8\")");
# Setting the sweep range of Vout
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:STOP 18\")");
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:STEP 0.1\")");
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:COMPLIANCE 0.05\")");
# Compliance: meaning the stable state of voltage, on the parametric
analyzer
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:PCOMPLIANCE:STATE
0\")");
# PCOMPLIANCE: Might be the state before the stable state

runcli("gpibsend(0x1,\":PAGE:MEAS:DEL 2\")");
# Delay
runcli("gpibsend(0x1,\":PAGE:MEAS:HTIM 50\")");
# Hold Time

runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:CONS:SMU2:SOURCE 3.3\")");
# Setting the values for VCC
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:CONS:SMU2:COMP 0.1\")");
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:CONS:SMU3:SOURCE 12\")");
# Setting the values for VPP
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:CONS:SMU3:COMP 0.1\")");

runcli("gpibsend(0x1,\":PAGE:SCON:SING\")");

sleep(2);
runcli("ctst");
runcli("stst");
sleep(2);
runcli("pu;rs");
runcli("B16R_vpasscp_vpp.txt()");
runcli("regaccess(static_load,0x9,0x9,$k)");
# Using the Cregs 0x9 to modulate the frequency
runcli("adputr(0xcf,0x03)");
runcli("rs");
poll_4156c();
}

sub poll_4156c{
runcli("gpibsend(0x1,\":STAT:OPER:COND?\");");
# This command returns the present status of the Operation
# Status "CONDITION" register. Reading this register does not clear
it.
runcli("gpibreceive(0x1);");
while((get_gpib_status() > 0)&&($foundError < 1) ){
sleep(3);
runcli("gpibsend(0x1,\":STAT:OPER:COND?\")");
runcli("gpibreceive(0x1);");
}

}#end poll_4156c subroutine

sub get_gpib_status{
# get file info
$host_meas = getHost();
# Retrieve the nextest station detail, will return something like
mav2pt
- 0014
$file_meas = $host_meas."_temp.cli";
# Define the file_meas as the nextest cli temporary file, Contains
all
the text as displayed on Nextest CLI
open(STATUS, "$file_meas" ) || die("Can't open logfile: $!");
print "\nSTATUS received from GPIB:";
while(<STATUS>)
{
if(/Error/){
runcli("gpibinit;");
$foundError = 1;
}
else
{
chomp;
s/\+//g;
$value = $_;
$foundError = 0;
}
} # End of while(<INMEAS>) loop.
close(STATUS);
#print "value = $value";
return($value);
}#End of get_gpib_status subroutine.

$i=$i+1;
}
$k=$k+8;
}
</code>```

答:
Ad 1. /Error/ is a regular expression matching any string that contains "Error" as its substring; in this context (if(/Error/) it is evaluated as boolean expression, ie. it is true if match is found in $_ variable;

Ad. 2. chomp removes trailing newline character from its argument, or in lack of argument, from $_ variable; s/\+//g; replaces any + signs found in $_ with nothing (ie. removes them). As you might have already noticed, many Perl constructs operate on $_ if not specified otherwise.

get_gpib_status is defined in your script - sub get_gpib_status is the beginning of definition (in Perl, functions are defined using sub keyword, stands for "subroutine").

And finally, I offer my sincere condolences. Giving the task of rewriting a program from one language to another to someone without prior experience with either language is probably not the stupidest managerial decision I've heard of, but high on the list.

Body:
I am new to the perl and python. As a part of my job currently I am asked to convert the perl script to python. The purpose of this script is to automate the task of the magnum tester and parametric analyzer. Is any of you able to understand what the get_gpib_status function trying to do ??. Specific questions are

What does if(/Error/) mean in perl ?

What does it mean by

        chomp;
        s/\+//g;
        $value = $_;
        $foundError = 0;

in perl?. What is the python equivalent of the get_gpib_status function ??.

Any kind of help is highly appreciated. Thanks in advance. The Script is as shown below.

BEGIN {unshift(@INC, "." , ".." ,
"\\Micron\\Nextest\\perl_modules");}

use runcli;
# Enable input from perl script as nextest cli command, Runcli is the
command
that you’ll use to communicate with the tester
use getHost;
# To latch in module/ "library into current script, here the
getHost.pm
is
loaded, used once on nextest system

#open FILE,">","iv.txt" or die $!;
# Make file ready for reading from FILE

$k=148;
# Time period T = 38ns corresponds to data value of 140
#$i=0;
while($k<156)
{
$i=3;
while($i<4)
{
#$logfile = "vpasscp8stg_SS_vppmode"."stg"."$i"."freq"."$k".".txt";
# Give the name to the logfile
#open(LOG,">$logfile") or die $!;
# Makes the file ready for reading from LOG

#******************* SUBS ****************************

if($i==3)
{

runcli("gpibinit;");
runcli("gpibsend(0x1,\":PAGE:CHAN:MODE SWEEP\")");
# PAGE, CHANnel, MODE, Set the mode to sweep

runcli("gpibsend(0x1,\":PAGE:CHAN:SMU1:VNAME 'Vout'\")");
# Source Monitor Unit, voltage name Vout
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU1:INAME 'Iout'\")");
# current name Iout
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU1:MODE V\")");
# voltage output node
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU1:FUNCTION VAR1\")");
# function Variable

runcli("gpibsend(0x1,\":PAGE:CHAN:SMU2:VNAME 'Vcc'\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU2:INAME 'Icc'\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU2:MODE V\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU2:FUNCTION CONSTANT\")");
# function constant

runcli("gpibsend(0x1,\":PAGE:CHAN:SMU3:VNAME 'Vpp'\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU3:INAME 'Ipp'\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU3:MODE V\")");
runcli("gpibsend(0x1,\":PAGE:CHAN:SMU3:FUNCTION CONSTANT\")");

#runcli("gpibsend(0x1,\":PAGE:CHAN:SMU3:DIS\")");

runcli("gpibsend(0x1,\":PAGE:CHAN:SMU4:DIS\")");

runcli("gpibsend(0x1,\":PAGE:CHAN:VSU1:DIS\")");
# Voltage Source Unit DISabled

runcli("gpibsend(0x1,\":PAGE:CHAN:VSU2:DIS\")");

runcli("gpibsend(0x1,\":PAGE:DISP:LIST:SELECT 'Vout'\")");
# DISPlay LIST
runcli("gpibsend(0x1,\":PAGE:DISP:LIST:SELECT 'Iout'\")");
runcli("gpibsend(0x1,\":PAGE:DISP:LIST:SELECT 'Vcc'\")");
runcli("gpibsend(0x1,\":PAGE:DISP:LIST:SELECT 'Icc'\")");

runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:MODE SINGLE\")");
# Single Stair Sweep
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:SPACING LINEAR\")");
# The sweep is incremented (decremented) by the
# stepsize until the stop value is reached.

runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:START 2.8\")");
# Setting the sweep range of Vout
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:STOP 18\")");
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:STEP 0.1\")");
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:COMPLIANCE 0.05\")");
# Compliance: meaning the stable state of voltage, on the parametric
analyzer
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:VAR1:PCOMPLIANCE:STATE
0\")");
# PCOMPLIANCE: Might be the state before the stable state

runcli("gpibsend(0x1,\":PAGE:MEAS:DEL 2\")");
# Delay
runcli("gpibsend(0x1,\":PAGE:MEAS:HTIM 50\")");
# Hold Time

runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:CONS:SMU2:SOURCE 3.3\")");
# Setting the values for VCC
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:CONS:SMU2:COMP 0.1\")");
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:CONS:SMU3:SOURCE 12\")");
# Setting the values for VPP
runcli("gpibsend(0x1,\":PAGE:MEAS:SWEEP:CONS:SMU3:COMP 0.1\")");

runcli("gpibsend(0x1,\":PAGE:SCON:SING\")");

sleep(2);
runcli("ctst");
runcli("stst");
sleep(2);
runcli("pu;rs");
runcli("B16R_vpasscp_vpp.txt()");
runcli("regaccess(static_load,0x9,0x9,$k)");
# Using the Cregs 0x9 to modulate the frequency
runcli("adputr(0xcf,0x03)");
runcli("rs");
poll_4156c();
}

sub poll_4156c{
runcli("gpibsend(0x1,\":STAT:OPER:COND?\");");
# This command returns the present status of the Operation
# Status "CONDITION" register. Reading this register does not clear
it.
runcli("gpibreceive(0x1);");
while((get_gpib_status() > 0)&&($foundError < 1) ){
sleep(3);
runcli("gpibsend(0x1,\":STAT:OPER:COND?\")");
runcli("gpibreceive(0x1);");
}

}#end poll_4156c subroutine

sub get_gpib_status{
# get file info
$host_meas = getHost();
# Retrieve the nextest station detail, will return something like
mav2pt
- 0014
$file_meas = $host_meas."_temp.cli";
# Define the file_meas as the nextest cli temporary file, Contains
all
the text as displayed on Nextest CLI
open(STATUS, "$file_meas" ) || die("Can't open logfile: $!");
print "\nSTATUS received from GPIB:";
while(<STATUS>)
{
if(/Error/){
runcli("gpibinit;");
$foundError = 1;
}
else
{
chomp;
s/\+//g;
$value = $_;
$foundError = 0;
}
} # End of while(<INMEAS>) loop.
close(STATUS);
#print "value = $value";
return($value);
}#End of get_gpib_status subroutine.

$i=$i+1;
}
$k=$k+8;
}


来源: stackexchange

问:
C++ a class to be used only by another class
I'm building a class (class A) which needs to be able to create a number of instances of another class (class B) in the course of its operation, but class B is only used by a few member functions of class A, and never used outside of the class. How should class B best be defined? Is it practical / reasonable to make it a private member of Class A? Is this the intended purpose of nested classes, or am I parting with the spirit of the construct?

Thanks,
Wyatt

EDIT: On further consideration, I'm not really asking about best practice, as this is for a personal project. I want to include class B as a member of class A from an encapsulation standpoint - it just seems reasonable that a class which is wholly subordinate should in fact be a part of its owning class.

What I'm wondering is whether or not this is a reasonable use-case for nested classes? If not, what is the purpose of nested classes?

答:
I would move it outside of B, since otherwise it will be exposed to other classes via the header file of A (whether you like it or not).  Said differently, if you change the implementation of B, then clients of A must recompile - since B was declared inside of A.

The structure of my project should make it clear that the header file for B, should not be used by other classes.  For example, I have a folder called "exports" where I place all my header files that I intend to be shared outside the project.  Obviously B's header won't be found there.

In a different language that does not use header files, such as C#, I will casually place B inside of A, if B is fairly small - perhaps not more than 6-10 lines of declaration.

ContentLicense: CC BY-SA 2.5


问:
PhpStorm not finding methods in objects created by late static binding by parent abstract class
In my PHP application I have a base class for all database objects, which is further extended by specific model classes. It goes on like this (simplified):

```<code>abstract class Model extends Collection {

    (...)

    function __construct(string $primary_key, string $value) {
        $data = MysqlDB::instance() -> select(static::TABLE, implode(',', static::COLUMNS), "$primary_key=\"$value\"");
        if (count($data) != 1)
            throw new ModelException('Select condition uncertain');
        parent::__construct($data[0]);
    }

    public static function getById(string $id) : ?Model {
        try {
            return new static('id', $id);
        } catch (ModelException $e) {
            return NULL;
        }
    }

    (...)

}
</code>```

The point is, I use the getById function on child classes to obtain the needed objects. However, since the return type of getById method is Model, PhpStorm can't figure out what methods the objects has and highlights the ones I use as an error. Consequently, no type-hinting available.

For instance, assuming that final class User extends Model and that class User has method sendNotification, this kind of code:

```<code>User::getById($id) -> sendNotification($param1, $param2, ...)
</code>```

has sendNotification yellowed out as though it did not exist.

I know this isn't that much of an issue, but it's really irritating in terms of that I get distracted by constant redundant warnings and that I can't use type-hinting in such a usage case.

答:
Try with actual PHPDoc for your getById() where you specify dynamic type (e.g. @return static or @return $this).

That's the most common way of providing such "this class and its' children" typehint.

Another possible option is kind of the same .. but using PHP 7.1 functionality (so no PHPDoc blocks).

Try using self as return type instead of Model. I mean here:

```<code>public static function getById(string $id) : ?Model {
</code>```

use this instead:

```<code>public static function getById(string $id) : ?self {
</code>```

But for this one you should use PhpStorm 2017.2 EAP build as 2017.1.x has issues with that (see https://stackoverflow.com/a/44806801/783119 as an example).

ContentLicense: CC BY-SA 3.0

Body:
In my PHP application I have a base class for all database objects, which is further extended by specific model classes. It goes on like this (simplified):

abstract class Model extends Collection {

    (...)

    function __construct(string $primary_key, string $value) {
        $data = MysqlDB::instance() -> select(static::TABLE, implode(',', static::COLUMNS), "$primary_key=\"$value\"");
        if (count($data) != 1)
            throw new ModelException('Select condition uncertain');
        parent::__construct($data[0]);
    }

    public static function getById(string $id) : ?Model {
        try {
            return new static('id', $id);
        } catch (ModelException $e) {
            return NULL;
        }
    }

    (...)

}

The point is, I use the getById function on child classes to obtain the needed objects. However, since the return type of getById method is Model, PhpStorm can't figure out what methods the objects has and highlights the ones I use as an error. Consequently, no type-hinting available.

For instance, assuming that final class User extends Model and that class User has method sendNotification, this kind of code:

User::getById($id) -> sendNotification($param1, $param2, ...)

has sendNotification yellowed out as though it did not exist.

I know this isn't that much of an issue, but it's really irritating in terms of that I get distracted by constant redundant warnings and that I can't use type-hinting in such a usage case.

Body:
Try with actual PHPDoc for your getById() where you specify dynamic type (e.g. @return static or @return $this).

That's the most common way of providing such "this class and its' children" typehint.

Another possible option is kind of the same .. but using PHP 7.1 functionality (so no PHPDoc blocks).

Try using self as return type instead of Model. I mean here:

public static function getById(string $id) : ?Model {

use this instead:

public static function getById(string $id) : ?self {

But for this one you should use PhpStorm 2017.2 EAP build as 2017.1.x has issues with that (see https://stackoverflow.com/a/44806801/783119 as an example).


问:
Windows Forms application lots of ambiguous symbols
Creating a c++ forms application, I have started getting some ambiguous symbol errors. But I am not quite sure what from, it was compiling fine earlier but I may have changed something?

Thee error itself:

```<code>1>Application.cpp
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): error C2872: 'IDropTarget': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\oleidl.h(3508): note: could be 'IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): note: or       'System::Windows::Forms::IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): error C2872: 'IServiceProvider': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\servprov.h(98): note: could be 'IServiceProvider'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): note: or       'System::IServiceProvider'
1>main.cpp
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): error C2872: 'IDropTarget': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\oleidl.h(3508): note: could be 'IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): note: or       'System::Windows::Forms::IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): error C2872: 'IServiceProvider': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\servprov.h(98): note: could be 'IServiceProvider'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): note: or       'System::IServiceProvider'
</code>```

I found this strange because my form isn't contained with any of these files, I assume it's that due to the namespacing. I just don't know where this is actually coming from.

Here is my form for info:

```<code>#include <Windows.h>

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

public ref class CFormController : public Form
{
public:
    CFormController(void)
    {
        InitializeComponent();
    }
    ~CFormController()
    {
        delete components;
    }

    System::ComponentModel::Container ^components;

    void InitializeComponent(void)
    {
        this->components = gcnew System::ComponentModel::Container();
        this->Size = System::Drawing::Size(300, 300);
        this->Text = L"FormController";
        this->Padding = System::Windows::Forms::Padding(0);
        this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
    }
};
</code>```

The only other information about my form is in another class. Thats only used to display or hide it.

I found similar issues in that people didn't include the windows header before "using namespace..." but I added the include as you saw and it didn't make a difference whatsoever

答:
You are importing conflicting symbols into the global namespace.

The code you posted should fine if it is the first file included in the compile unit. If that is not the case (e.g. you included another header file before the header file you posted) they you could have the WinForms types already present in the global namespace when you include windows.h, and causes C2872.

You can move the using statements or windows.h include into a namespace to avoid the conflict.
e.g.

```<code>namespace Win32 {
#include "windows.h"
}
</code>```

or

```<code>namespace ProjectName {

using namespace System;
......
}
</code>```

Or if you really want to import the types into the global namespace, separate your code into two cpp files and import them one at a time.

Body:
Creating a c++ forms application, I have started getting some ambiguous symbol errors. But I am not quite sure what from, it was compiling fine earlier but I may have changed something?

Thee error itself:

1>Application.cpp
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): error C2872: 'IDropTarget': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\oleidl.h(3508): note: could be 'IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): note: or       'System::Windows::Forms::IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): error C2872: 'IServiceProvider': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\servprov.h(98): note: could be 'IServiceProvider'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): note: or       'System::IServiceProvider'
1>main.cpp
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): error C2872: 'IDropTarget': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\oleidl.h(3508): note: could be 'IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): note: or       'System::Windows::Forms::IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): error C2872: 'IServiceProvider': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\servprov.h(98): note: could be 'IServiceProvider'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): note: or       'System::IServiceProvider'

I found this strange because my form isn't contained with any of these files, I assume it's that due to the namespacing. I just don't know where this is actually coming from.

Here is my form for info:

#include <Windows.h>

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

public ref class CFormController : public Form
{
public:
    CFormController(void)
    {
        InitializeComponent();
    }
    ~CFormController()
    {
        delete components;
    }

    System::ComponentModel::Container ^components;

    void InitializeComponent(void)
    {
        this->components = gcnew System::ComponentModel::Container();
        this->Size = System::Drawing::Size(300, 300);
        this->Text = L"FormController";
        this->Padding = System::Windows::Forms::Padding(0);
        this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
    }
};

The only other information about my form is in another class. Thats only used to display or hide it.

I found similar issues in that people didn't include the windows header before "using namespace..." but I added the include as you saw and it didn't make a difference whatsoever

Body:
You are importing conflicting symbols into the global namespace.

The code you posted should fine if it is the first file included in the compile unit. If that is not the case (e.g. you included another header file before the header file you posted) they you could have the WinForms types already present in the global namespace when you include windows.h, and causes C2872.

You can move the using statements or windows.h include into a namespace to avoid the conflict.
e.g.

namespace Win32 {
#include "windows.h"
}

or

namespace ProjectName {

using namespace System;
......
}

Or if you really want to import the types into the global namespace, separate your code into two cpp files and import them one at a time.


问:
While creating web forms in Flask, I'm getting the error: jinja2.exceptions.UndefinedError: 'reviewform' is undefined
Here is the Flask code:

```<code>from flask import Flask, render_template
from wtforms import Form, TextAreaField

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'

class ReviewForm(Form):
    reviewText = TextAreaField()

@app.route('/', methods=['GET', 'POST'])
def index():
    reviewform = ReviewForm()
    return render_template("review.html", form=reviewform)

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

Here is the form template using Jinja2:

```<code><!doctype html>
<html>
<head>
    <title>Review Page</title>
</head>
<body>
    <h1>Enter your review</h1>
    <form method="POST" action="{{ url_for('index') }}">
        {{ reviewform.csrf_token }}
        {{ reviewform.reviewText }}
    </form>
</body>
</html>
</code>```

It appears that the object is properly defined and passed on the render_template(). I can't figure out why the error.

Here is the traceback:

```<code>Traceback (most recent call last):

  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1994, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\Jimmy Valentine\PycharmProjects\SentimentAnalysis\SentimentAnalysis.py", line 16, in index
    return render_template("review.html", form=reviewform)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\templating.py", line 134, in render_template
    context, ctx.app)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\templating.py", line 116, in _render
    rv = template.render(context)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\jinja2\environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\jinja2\_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Jimmy Valentine\PycharmProjects\SentimentAnalysis\templates\review.html", line 10, in top-level template code
    {{ reviewform.reviewText }}
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\jinja2\environment.py", line 430, in getattr
    return getattr(obj, attribute)

jinja2.exceptions.UndefinedError: 'reviewform' is undefined
</code>```

答:
You are calling render_template with form=reviewform, which means reviewform will be accessible in the template under the name form. To fix the issue, you can either:

change the call to render_template,

```<code>return render_template("review.html", reviewform=reviewform)
</code>```

or modify your template to use form instead of reviewform.

```<code><form method="POST" action="{{ url_for('index') }}">
    {{ form.csrf_token }}
    {{ form.reviewText }}
</form>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is the Flask code:

from flask import Flask, render_template
from wtforms import Form, TextAreaField

app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecretkey'

class ReviewForm(Form):
    reviewText = TextAreaField()

@app.route('/', methods=['GET', 'POST'])
def index():
    reviewform = ReviewForm()
    return render_template("review.html", form=reviewform)

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

Here is the form template using Jinja2:

<!doctype html>

    <title>Review Page</title>

Enter your review

    <form method="POST" action="{{ url_for('index') }}">
        {{ reviewform.csrf_token }}
        {{ reviewform.reviewText }}
    </form>

It appears that the object is properly defined and passed on the render_template(). I can't figure out why the error.

Here is the traceback:

Traceback (most recent call last):

  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1994, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\Jimmy Valentine\PycharmProjects\SentimentAnalysis\SentimentAnalysis.py", line 16, in index
    return render_template("review.html", form=reviewform)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\templating.py", line 134, in render_template
    context, ctx.app)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\templating.py", line 116, in _render
    rv = template.render(context)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\jinja2\environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\jinja2\_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\Jimmy Valentine\PycharmProjects\SentimentAnalysis\templates\review.html", line 10, in top-level template code
    {{ reviewform.reviewText }}
  File "C:\Users\Default\AppData\Local\Continuum\Anaconda3\lib\site-packages\jinja2\environment.py", line 430, in getattr
    return getattr(obj, attribute)

jinja2.exceptions.UndefinedError: 'reviewform' is undefined

Body:
You are calling render_template with form=reviewform, which means reviewform will be accessible in the template under the name form. To fix the issue, you can either:

change the call to render_template,

return render_template("review.html", reviewform=reviewform)

or modify your template to use form instead of reviewform.

<form method="POST" action="{{ url_for('index') }}">
    {{ form.csrf_token }}
    {{ form.reviewText }}
</form>


问:
Recaptcha::RecaptchaError in Articles#show No site key specified
I get:

"Recaptcha::RecaptchaError in Articles#show No site key specified."

And I do not understand where is my mistake.

Gemfile:

```<code>gem 'dotenv-rails', :require => 'dotenv/rails-now'
gem "recaptcha", require: "recaptcha/rails"
</code>```

.env

```<code>export RECAPTCHA_PUBLIC_KEY = '*******************************'
export RECAPTCHA_PRIVATE_KEY = '*******************************'
</code>```

comments_controller.rb

```<code>class CommentsController < ApplicationController

    http_basic_authenticate_with name: "admin", password: "**************", only: :destroy

  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  end

  def destroy
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to article_path(@article)
  end

  private
    def comment_params
      params.require(:comment).permit(:commenter, :body)
    end
end
</code>```

articles_controller.rb

```<code>class ArticlesController < ApplicationController

    http_basic_authenticate_with name: "admin", password: "**********", except: [:index, :show]

  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to articles_path
  end

  private
    def article_params
      params.require(:article).permit(:title, :text)
    end
end
</code>```

答:
It looks like your using this gem, which specifies that you need:

export RECAPTCHA_SITE_KEY  = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy'

export RECAPTCHA_SECRET_KEY = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'

when I follow your link, you have

export RECAPTCHA_PUBLIC_KEY = \'*******************************\'

export RECAPTCHA_PRIVATE_KEY = \'*******************************\'

Body:
I get:

"Recaptcha::RecaptchaError in Articles#show No site key specified."

And I do not understand where is my mistake.

Gemfile:

gem 'dotenv-rails', :require => 'dotenv/rails-now'
gem "recaptcha", require: "recaptcha/rails"

.env

export RECAPTCHA_PUBLIC_KEY = '*******************************'
export RECAPTCHA_PRIVATE_KEY = '*******************************'

comments_controller.rb

class CommentsController < ApplicationController

    http_basic_authenticate_with name: "admin", password: "**************", only: :destroy

  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  end

  def destroy
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to article_path(@article)
  end

  private
    def comment_params
      params.require(:comment).permit(:commenter, :body)
    end
end

articles_controller.rb

class ArticlesController < ApplicationController

    http_basic_authenticate_with name: "admin", password: "**********", except: [:index, :show]

  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to articles_path
  end

  private
    def article_params
      params.require(:article).permit(:title, :text)
    end
end


问:
Download prompt for ftp_get
I am currently implementing a system for users to download files from the ftp without the actual need of a ftp client. I have already developed a login system and have successfully managed to list out the files from the folder. However, I intend to make the download process using ftp_get with a "save as" prompt.

I have referred to http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/Q_23210157.html#mainSection but the solution stated wasn't conclusive.

I did use one of the suggestion in the previous forum topic, but I got a msg "There was a problem" after executing ftp_get.

I will really appreciate with any help given ! Thanks !

```<code>    //--------------------------- Connects to FTP host ---------------------------------------------
$conn_id = ftp_connect($_COOKIE["process-1"]) or die("Couldn't connect to FTP server");
$login_result = ftp_login($conn_id, $_COOKIE["process-2"], $_COOKIE["process-3"]);
//--------------------------- Validates FTP Logiin (username,password) -------------------------
if(!$login_result) die("FTP Login failed. Contact support @ customercare@strategyinstitute.com");
ftp_pasv($conn_id,true);

$current_dir = ftp_pwd($conn_id);
$chdir = ftp_chdir($conn_id,$_COOKIE["process-5"]);
if(!$chdir) echo "Change Directory failed. Origin = " .$current_dir. "; Destination: ".$_COOKIE["process-5"];

echo ftp_pwd($conn_id) ."<br>";

$server_file = $_GET['file'];

$fp = fopen('php://stdout', 'w+');
if (ftp_get($conn_id, $fp, $server_file, FTP_BINARY)) {
        echo "Successfully written to $local_file\n";
} else {
        echo "There was a problem\n";
}

ftp_close($conn_id);
</code>```

答:
```<code>// make the browser download anything you output
header('Content-type: file/binary');

// set the correct filename
header('Content-Disposition: attachment; filename="'.$file.'"');
</code>```

Title: Download prompt for ftp_get

Body:
I am currently implementing a system for users to download files from the ftp without the actual need of a ftp client. I have already developed a login system and have successfully managed to list out the files from the folder. However, I intend to make the download process using ftp_get with a "save as" prompt.

I have referred to http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/Q_23210157.html#mainSection but the solution stated wasn't conclusive.

I did use one of the suggestion in the previous forum topic, but I got a msg "There was a problem" after executing ftp_get.

I will really appreciate with any help given ! Thanks !

    //--------------------------- Connects to FTP host ---------------------------------------------
$conn_id = ftp_connect($_COOKIE["process-1"]) or die("Couldn't connect to FTP server");
$login_result = ftp_login($conn_id, $_COOKIE["process-2"], $_COOKIE["process-3"]);
//--------------------------- Validates FTP Logiin (username,password) -------------------------
if(!$login_result) die("FTP Login failed. Contact support @ customercare@strategyinstitute.com");
ftp_pasv($conn_id,true);

$current_dir = ftp_pwd($conn_id);
$chdir = ftp_chdir($conn_id,$_COOKIE["process-5"]);
if(!$chdir) echo "Change Directory failed. Origin = " .$current_dir. "; Destination: ".$_COOKIE["process-5"];

echo ftp_pwd($conn_id) ."
";

$server_file = $_GET['file'];

$fp = fopen('php://stdout', 'w+');
if (ftp_get($conn_id, $fp, $server_file, FTP_BINARY)) {
        echo "Successfully written to $local_file\n";
} else {
        echo "There was a problem\n";
}

ftp_close($conn_id);


问:
Higlight text in JTextField but only when tabbing
I want to create a JDialog where the text in the textfields is selected but only if the focus is gained from keyboard (TAB, CTRL+TAB). I have found several topics on this matter but had problems with implementing it.

Here is one which I was trying.

And my code:

```<code>public class Dialogg extends JDialog implements FocusListener, MouseListener {

private boolean focusFromMouse = false;

public Dialogg() {
    JTextField tf1 = new JTextField("text1");
    JTextField tf2 = new JTextField("text2");

    tf1.addMouseListener(this);
    tf2.addMouseListener(this);
    tf1.addFocusListener(this);
    tf2.addFocusListener(this);
}

@Override
public void focusGained(FocusEvent e) {
    if (!focusFromMouse) {
        JTextField tf = (JTextField) e.getComponent();
        tf.selectAll();
        focusFromMouse = true;
    }
}

@Override
public void focusLost(FocusEvent e) {
    focusFromMouse = false;
}

@Override
public void mouseClicked(MouseEvent e) {
    focusFromMouse = true;
}
</code>```

}

It does not work as intended, it does not matter what is focus source the text always highlights. When I run the code and follow it step by step it turns out that focusGained code happens before mouseClicked code so the flag is not reset when it should. Any hints?

EDIT:

As suggested by M. Prokhorov I have deleted less relevant (for the question) lines from the code.Thank you.

EDIT 2:

I am trying to wrap focus listener as suggested by camickr. It looks like this now:

```<code>tf1.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent evt){
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                        if (!focusFromMouse){
                        tf1.selectAll();
                        focusFromMouse=true;
                    }
                }
            });
        }
        public void focusLost(FocusEvent evt){
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    focusFromMouse=false;
                }
            });
        }
    });
public void mouseClicked(MouseEvent e) {
        focusFromMouse=true;
</code>```

I am printing line after each event to see the action order and still mouseClicked happens last. What am I doing wrong?

EDIT 3:

OK, I have found a solution which fulfils requirements of my simple Dialog.
I could not find a way of doing this with use of invokeLater or EventQueue. Vladislav's method works but as I understand it restricts the user to only use the keyboard.
I have used the initial approach but I have added an auxiliary variable and few conditions which allow to pass the flag "unharmed" trough Events that should not change the flag at given moment. It may not be subtle or universal but works for my app. Here is the code:

```<code>public void focusGained(FocusEvent e) {
    if(!focusFromMouse){
        if (higlight){
           JTextField tf = (JTextField) e.getComponent();
           tf.selectAll();
           focusFromMouse=false;
        }
    }
}

public void focusLost(FocusEvent e) {
    if (focusFromMouse){
        higlight=false;
        focusFromMouse=false;
    }else{
        higlight=true;
    }
}

public void mousePressed(MouseEvent e) {
    focusFromMouse=true;
}
</code>```

答:
When I run the code and follow it step by step it turns out that focusGained code happens before mouseClicked

Wrap the code in the FocusListener in a SwingUtilities.invokeLater(). The will place the code on the end of the Event Dispatch Thread (EDT), so the code will run after the variable in the MouseListener has been set.

See Concurrency in Swing for more information about the EDT.

Edit:

Just noticed the other answer. You might be able to do something simpler. Istead of listener for mouseClicked, listen for mousePressed. A mouseClicked event is only generated AFTER the mouseReleased event, so by that time the FocusListener logic has already been executed, even when added to the end of the EDT.

Edit 2:

If the above doesn't work then you might be able to use the EventQueue.peek() method to see if a MouseEvent is on the queue. This might even be easier than worrying about using the invokeLater.

Body:
I want to create a JDialog where the text in the textfields is selected but only if the focus is gained from keyboard (TAB, CTRL+TAB). I have found several topics on this matter but had problems with implementing it.

Here is one which I was trying.

And my code:

public class Dialogg extends JDialog implements FocusListener, MouseListener {

private boolean focusFromMouse = false;

public Dialogg() {
    JTextField tf1 = new JTextField("text1");
    JTextField tf2 = new JTextField("text2");

    tf1.addMouseListener(this);
    tf2.addMouseListener(this);
    tf1.addFocusListener(this);
    tf2.addFocusListener(this);
}

@Override
public void focusGained(FocusEvent e) {
    if (!focusFromMouse) {
        JTextField tf = (JTextField) e.getComponent();
        tf.selectAll();
        focusFromMouse = true;
    }
}

@Override
public void focusLost(FocusEvent e) {
    focusFromMouse = false;
}

@Override
public void mouseClicked(MouseEvent e) {
    focusFromMouse = true;
}

}

It does not work as intended, it does not matter what is focus source the text always highlights. When I run the code and follow it step by step it turns out that focusGained code happens before mouseClicked code so the flag is not reset when it should. Any hints?

EDIT:

As suggested by M. Prokhorov I have deleted less relevant (for the question) lines from the code.Thank you.

EDIT 2:

I am trying to wrap focus listener as suggested by camickr. It looks like this now:

tf1.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent evt){
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                        if (!focusFromMouse){
                        tf1.selectAll();
                        focusFromMouse=true;
                    }
                }
            });
        }
        public void focusLost(FocusEvent evt){
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    focusFromMouse=false;
                }
            });
        }
    });
public void mouseClicked(MouseEvent e) {
        focusFromMouse=true;

I am printing line after each event to see the action order and still mouseClicked happens last. What am I doing wrong?

EDIT 3:

OK, I have found a solution which fulfils requirements of my simple Dialog.
I could not find a way of doing this with use of invokeLater or EventQueue. Vladislav's method works but as I understand it restricts the user to only use the keyboard.
I have used the initial approach but I have added an auxiliary variable and few conditions which allow to pass the flag "unharmed" trough Events that should not change the flag at given moment. It may not be subtle or universal but works for my app. Here is the code:

public void focusGained(FocusEvent e) {
    if(!focusFromMouse){
        if (higlight){
           JTextField tf = (JTextField) e.getComponent();
           tf.selectAll();
           focusFromMouse=false;
        }
    }
}

public void focusLost(FocusEvent e) {
    if (focusFromMouse){
        higlight=false;
        focusFromMouse=false;
    }else{
        higlight=true;
    }
}

public void mousePressed(MouseEvent e) {
    focusFromMouse=true;
}


问:
Emacs regex: replacing a string inside a latex equation
I'd like to replace all occurrences of the letter 'n' that occur inside any LaTeX equation, with the letter 'N'. It can be assumed that the LaTeX equations in the document are of the form $...$

Will accept also solutions in perl or any other language/tool/application readily available on ubuntu or Windows.

答:
My solution is inspired by Tobias but uses isearch-filter-predicate for filtering instead of modifying the internals of query-replace-regexp. This needs at least Emacs 24.

Also, I only use case-sensitive search and replace for math, so I have set (case-fold-search nil) in the function below.

```<code>(defun latex-replace-in-math ()
"Call `query-replace-regexp' with `isearch-filter-predicate' set to filter out matches outside LaTeX math environments."
(interactive)
(let ((isearch-filter-predicate
 (lambda (BEG END)
   (save-excursion (save-match-data (goto-char BEG) (texmathp)))))
(case-fold-search nil))
(call-interactively 'query-replace-regexp)))
</code>```

Body:
My solution is inspired by Tobias but uses isearch-filter-predicate for filtering instead of modifying the internals of query-replace-regexp. This needs at least Emacs 24.

Also, I only use case-sensitive search and replace for math, so I have set (case-fold-search nil) in the function below.

(defun latex-replace-in-math ()
"Call `query-replace-regexp' with `isearch-filter-predicate' set to filter out matches outside LaTeX math environments."
(interactive)
(let ((isearch-filter-predicate
 (lambda (BEG END)
   (save-excursion (save-match-data (goto-char BEG) (texmathp)))))
(case-fold-search nil))
(call-interactively 'query-replace-regexp)))


问:
Is it possible to call ViewComponent from custom TagHelper?
I'm writing a custom TagHelper and want to render a ViewComponent inside it.
Something similar to what vc:xyz tag helper does, but in a more controlled way, so that I can determine at runtime which ViewComponent to render. </p>

<p>Is it possible? </p>

答:
In order to do that, you need to inject IViewComponentHelper into your TagHelper, contextualize it and then use it to render any ViewComponent depending on your application logic. Here is a quick illustration:

```<code>[HtmlTargetElement("widget", Attributes = WidgetNameAttributeName)]
public class WidgetTagHelper : TagHelper
{
    private const string WidgetNameAttributeName = "name";
    private readonly IViewComponentHelper _viewComponentHelper;

    public WidgetTagHelper(IViewComponentHelper viewComponentHelper)
    {
        _viewComponentHelper = viewComponentHelper;
    }

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    [HtmlAttributeName(WidgetNameAttributeName)]
    public string Name { get; set; }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        ((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext);

        var content = await _viewComponentHelper.InvokeAsync(typeof(WidgetViewComponent), new { name = Name });
        output.Content.SetHtmlContent(content);
    }
}
</code>```

Also, keep in mind that self-closing tags will NOT work:

```<code><widget name="abc" />
</code>```

Use this form instead:

```<code><widget name="abc"></widget>
</code>```

Body:
I'm writing a custom TagHelper and want to render a ViewComponent inside it.
Something similar to what vc:xyz tag helper does, but in a more controlled way, so that I can determine at runtime which ViewComponent to render.

Is it possible?

Body:
In order to do that, you need to inject IViewComponentHelper into your TagHelper, contextualize it and then use it to render any ViewComponent depending on your application logic. Here is a quick illustration:

[HtmlTargetElement("widget", Attributes = WidgetNameAttributeName)]
public class WidgetTagHelper : TagHelper
{
    private const string WidgetNameAttributeName = "name";
    private readonly IViewComponentHelper _viewComponentHelper;

    public WidgetTagHelper(IViewComponentHelper viewComponentHelper)
    {
        _viewComponentHelper = viewComponentHelper;
    }

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    [HtmlAttributeName(WidgetNameAttributeName)]
    public string Name { get; set; }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        ((IViewContextAware)_viewComponentHelper).Contextualize(ViewContext);

        var content = await _viewComponentHelper.InvokeAsync(typeof(WidgetViewComponent), new { name = Name });
        output.Content.SetHtmlContent(content);
    }
}

Also, keep in mind that self-closing tags will NOT work:

<widget name="abc" />

Use this form instead:

<widget name="abc"></widget>


问:
geom_smooth with facet_grid and different fitting functions
First of all, apologies for the example, but I couldn't find a better data set to demonstrate the problem. Hopefully, it will suffice. Say I'm trying to make a facet grid of transmission (automatic vs. manual) and number of gears from the mtcars data set that plots mpg against displacement, like this:

```<code># Load library
library(ggplot2)

# Load data
data(mtcars)

# Plot data
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth()
print(p)
</code>```

which gives,

Notice, I've added a trend line using geom_smooth and it has defaulted to use a loess curve. I can fit user-defined functions rather than a loess curve using  nls for the method and then stating a formula, which is great. But is it possible to fit different user-specified curves for each facet? For example, a linear regression to the top left panel and decaying exponential for the bottom right. Is this possible? Or am I using a hammer to drive in screws?

EDIT:
A solution for custom (i.e., user-defined) fitting functions is given here.

答:
Following the suggestions given here, a possibile solution is:

```<code># Load library
library(ggplot2)

# Load data
data(mtcars)

# Vector of smoothing methods for each plot panel
meths <- c("loess","lm","lm","lm","lm","lm","lm")

# Smoothing function with different behaviour in the different plot panels
mysmooth <- function(formula,data,...){
   meth <- eval(parse(text=meths[unique(data$PANEL)]))
   x <- match.call()
   x[[1]] <- meth
   eval.parent(x)
}

# Plot data
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method="mysmooth")
print(p)
</code>```

Body:
First of all, apologies for the example, but I couldn't find a better data set to demonstrate the problem. Hopefully, it will suffice. Say I'm trying to make a facet grid of transmission (automatic vs. manual) and number of gears from the mtcars data set that plots mpg against displacement, like this:

# Load library
library(ggplot2)

# Load data
data(mtcars)

# Plot data
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth()
print(p)

which gives,

Notice, I've added a trend line using geom_smooth and it has defaulted to use a loess curve. I can fit user-defined functions rather than a loess curve using  nls for the method and then stating a formula, which is great. But is it possible to fit different user-specified curves for each facet? For example, a linear regression to the top left panel and decaying exponential for the bottom right. Is this possible? Or am I using a hammer to drive in screws?

EDIT:
A solution for custom (i.e., user-defined) fitting functions is given here.

Body:
Following the suggestions given here, a possibile solution is:

# Load library
library(ggplot2)

# Load data
data(mtcars)

# Vector of smoothing methods for each plot panel
meths <- c("loess","lm","lm","lm","lm","lm","lm")

# Smoothing function with different behaviour in the different plot panels
mysmooth <- function(formula,data,...){
   meth <- eval(parse(text=meths[unique(data$PANEL)]))
   x <- match.call()
   x[[1]] <- meth
   eval.parent(x)
}

# Plot data
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method="mysmooth")
print(p)


问:
count of nodes selected for an xpath in chrome console
How to get count of nodes selected for an xpath in chrome console?

I was able to select a set of node with Xpath :

```<code>$x("//*[@rel='noopener noreferrer']")
</code>```

in chrome console. but unable to get the count of number of nodes selected using count function in chrome using

```<code>$x(count("//*[@rel='noopener noreferrer']"))
</code>```

while it is working fine in firefox using count function as

```<code>(//*[@rel='noopener noreferrer'])
</code>```

Please help me to get count using chrome console

答:
```<code>$x("//*[contains(@rel, 'noreferrer') and contains(@rel, 'noopener')]").length
</code>```

$x() returns an array of nodes that match the XPath selector, so we just use the native length property of the array to get the count.

The selector contains(@rel, 'noreferrer') and contains(@rel, 'noopener') ensures that your query isn't order-sensitive.

Body:
How to get count of nodes selected for an xpath in chrome console?

I was able to select a set of node with Xpath :

$x("//*[@rel='noopener noreferrer']")

in chrome console. but unable to get the count of number of nodes selected using count function in chrome using

$x(count("//*[@rel='noopener noreferrer']"))

while it is working fine in firefox using count function as

(//*[@rel='noopener noreferrer'])

Please help me to get count using chrome console

Body:
$x("//*[contains(@rel, 'noreferrer') and contains(@rel, 'noopener')]").length

$x() returns an array of nodes that match the XPath selector, so we just use the native length property of the array to get the count.

The selector contains(@rel, 'noreferrer') and contains(@rel, 'noopener') ensures that your query isn't order-sensitive.


问:
What is an example of the Liskov Substitution Principle?
I have heard that the Liskov Substitution  Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?</p>

答:
Substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S

Let's do a simple example in Java:

Bad example

```<code>public class Bird{
    public void fly(){}
}
public class Duck extends Bird{}
</code>```

The duck can fly because it is a bird, but what about this:

```<code>public class Ostrich extends Bird{}
</code>```

Ostrich is a bird, but it can't fly, Ostrich class is a subtype of class Bird, but it shouldn't be able to use the fly method, that means we are breaking the LSP principle.

Good example

```<code>public class Bird{}
public class FlyingBirds extends Bird{
    public void fly(){}
}
public class Duck extends FlyingBirds{}
public class Ostrich extends Bird{}
</code>```

OwnerDisplayName: NotMyself

LastEditorDisplayName: Turbulent Intellect

Body:
Substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S

Let's do a simple example in Java:

Bad example

public class Bird{
    public void fly(){}
}
public class Duck extends Bird{}

The duck can fly because it is a bird, but what about this:

public class Ostrich extends Bird{}

Ostrich is a bird, but it can't fly, Ostrich class is a subtype of class Bird, but it shouldn't be able to use the fly method, that means we are breaking the LSP principle.

Good example

public class Bird{}
public class FlyingBirds extends Bird{
    public void fly(){}
}
public class Duck extends FlyingBirds{}
public class Ostrich extends Bird{}


问:
Package by feature modularization in Java
I've got an application with package by layer layout written in Spring and exposing REST API, so I've got packages called controller, service, model, dao etc.

I want to refactor it, so it will be package by feature, where every top-level package will be little module with a facade class (which will be public), and package-private controller, service, repository classes. Just to make sure that everything is small and organized.

Separating them by feature is not a problem, but what should I do with entities?

I've got a structure of model like this:

For example: I've got a feature that handles adding, removing etc. of auditorAssignment objects. So in new package there will be rest controller exposing such API, service, repository (all package-private) and some public facade that another modules could use (i.e. to get assignments or add them if needed). What should I do with whole model - entities? Should it be placed somewhere outside as a core? Or maybe entities should be splitted between packages, but public (to get relationships working)?

答:
You should package by bounded context (BC) and not by feature (considering that a BC can have one or more features). Then you can use any of the integration technics between BC, for example anti-corruption layers.

What should I do with whole model - entities? Should it be placed somewhere outside as a core? Or maybe entities should be splitted between packages, but public (to get relationships working)?

In case of entities you split them by the attributes specific in every BC and they can share the same IDs so you can update the shared proporties also (as there are a lot of cases where entities in different BC have some common properties; i.e. nickname for users in the Authorization BC and Author name for the corresponding author in the Colaboration BC).

P.S. If you split them like that you are at an inch distance from microservices


问:
Change Eclipse tab to correctly indent line as Emacs does
In Emacs when I hit tab anywhere on a line, the line will indent correctly (or at least to the mode settings). When I hit tab again it will move back to the next block. When programming Python this really helps since closing a block is done by lowering the indention level.

Is there a way to configure Eclipse to do the same?

Currently, I have to erase the leading white space then hit tab.

This question is a reposting of a superuser question.

答:
In Eclipse, go to Windows -> Preference -> Java -> Formatter.

In Active Profile drop down box, select any profile, click Edit on right of it.

In Profile Dialog box opened, you can change a lot of things like Indentation, New Line, Braces, White Spaces etc.

Alternatively, if your profile is altogether different than standard one, Create a new active profile and then edit it accordingly.


问:
The name "ViewModelLocator" does not exist in the namespace
I'm just writing some training Windows project using MVVM Light Toolkit. Where the MVVM Light  reference was added to the project, the following resource was automatically added to the App.xml

```<code>  <Application x:Class="TestApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:TestApp" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" d1p1:Ignorable="d" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006">
  <Application.Resources>
    <ResourceDictionary>
      <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="using:TestApp.ViewModel" />
    </ResourceDictionary>
  </Application.Resources>
</Application>
</code>```

Unfortunately, it doesn't work, i.e. the project cannot be build/compiled because of these errors:

Blockquote
  Severity    Code    Description Project File    Line    Suppression State
  Error       Unknown type 'ViewModelLocator' in XML namespace 'using:TestApp.ViewModel'  TestApp.Windows C:\Users\Krzysztof\documents\visual studio 2015\Projects\TestApp\TestApp\TestApp.Shared\App.xaml    4

  Error       The name "ViewModelLocator" does not exist in the namespace "using:TestApp.ViewModel".  TestApp.Windows C:\Users\Krzysztof\documents\visual studio 2015\Projects\TestApp\TestApp\TestApp.Shared\App.xaml    4

Briefly, I can't add the ViewModelLocator to the App.xml resources.

I found several common solutions for this problem (e.g.: changing solution platform, cleaning, rebuilding, restarting Visual Studio etc.) , but they change nothing. Creating a new project doesn't help as well.

Is there any other way to make it work? I use Visual Studio Community 2015.

答:
Comment out the auto-added sections of your viewmodel.xaml and the app.xaml and rebuild (with presumably no errors).  Then uncomment the app.xaml - it should appear fine, if not sorry, can't help you any more.  If so, then add in your datacontext to your view.

I ran into this too but to me, it appeared more to be an issue of the app.xaml attempting to access a fully built assembly reference and the visual studio interpreter not being sufficient.

Body:
I'm just writing some training Windows project using MVVM Light Toolkit. Where the MVVM Light  reference was added to the project, the following resource was automatically added to the App.xml

  <Application x:Class="TestApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:TestApp" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" d1p1:Ignorable="d" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006">
  <Application.Resources>
    <ResourceDictionary>
      <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="using:TestApp.ViewModel" />
    </ResourceDictionary>
  </Application.Resources>
</Application>

Unfortunately, it doesn't work, i.e. the project cannot be build/compiled because of these errors:

Blockquote
  Severity    Code    Description Project File    Line    Suppression State
  Error       Unknown type 'ViewModelLocator' in XML namespace 'using:TestApp.ViewModel'  TestApp.Windows C:\Users\Krzysztof\documents\visual studio 2015\Projects\TestApp\TestApp\TestApp.Shared\App.xaml    4

  Error       The name "ViewModelLocator" does not exist in the namespace "using:TestApp.ViewModel".  TestApp.Windows C:\Users\Krzysztof\documents\visual studio 2015\Projects\TestApp\TestApp\TestApp.Shared\App.xaml    4

Briefly, I can't add the ViewModelLocator to the App.xml resources.

I found several common solutions for this problem (e.g.: changing solution platform, cleaning, rebuilding, restarting Visual Studio etc.) , but they change nothing. Creating a new project doesn't help as well.

Is there any other way to make it work? I use Visual Studio Community 2015.


问:
Pandas - Replace values in a DataFrame Based on a Boollean DataFrame
I'm using Pandas v0.20.2 and I have DataFrame, like the following:

```<code>df = pd.DataFrame(dict(a=[0,1], b=[3,4], c=[6,7]),
              index=['spam', 'ham'])
#       a  b  c
# spam  0  3  6
# ham   1  4  7
</code>```

And I have another DataFrame that is a mask:

```<code>mask = pd.DataFrame(dict(a=[True,False], b=[True,True]),
                index=['spam', 'ham'])
#           a     b
# spam   True  True
# ham   False  True
</code>```

And I want to set the values in df equal to 999 where it is True in the mask.

I thought that the following would work:

```<code>df[mask] = 999
</code>```

But it doesn't. I get the error below:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-65-503f937859ab> in <module>()
----> 1 df[mask] = 999

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
   2326             self._setitem_array(key, value)
   2327         elif isinstance(key, DataFrame):
-> 2328             self._setitem_frame(key, value)
   2329         else:
   2330             # set column

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/frame.pyc in _setitem_frame(self, key, value)
   2364         self._check_inplace_setting(value)
   2365         self._check_setitem_copy()
-> 2366         self._where(-key, value, inplace=True)
   2367
   2368     def _ensure_valid_index(self, value):

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/generic.pyc in _where(self, cond, other, inplace, axis, level, try_cast, raise_on_error)
   5096             for dt in cond.dtypes:
   5097                 if not is_bool_dtype(dt):
-> 5098                     raise ValueError(msg.format(dtype=dt))
   5099
   5100         cond = cond.astype(bool, copy=False)

ValueError: Boolean array expected for the condition, not float64
</code>```

I would appreciate any help on this.

答:
You can reindex the mask to have the same shape as df, and then use df.mask:

```<code>df.mask(mask.reindex(df.index, df.columns, fill_value=False), 999)
Out:
        a    b  c
spam  999  999  6
ham     1  999  7
</code>```

At that point, regular indexing should also work:

```<code>df[mask.reindex(df.index, df.columns, fill_value=False)] = 999
</code>```

Body:
I'm using Pandas v0.20.2 and I have DataFrame, like the following:

df = pd.DataFrame(dict(a=[0,1], b=[3,4], c=[6,7]),
              index=['spam', 'ham'])
#       a  b  c
# spam  0  3  6
# ham   1  4  7

And I have another DataFrame that is a mask:

mask = pd.DataFrame(dict(a=[True,False], b=[True,True]),
                index=['spam', 'ham'])
#           a     b
# spam   True  True
# ham   False  True

And I want to set the values in df equal to 999 where it is True in the mask.

I thought that the following would work:

df[mask] = 999

But it doesn't. I get the error below:

ValueError                                Traceback (most recent call last)
<ipython-input-65-503f937859ab> in <module>()
----> 1 df[mask] = 999

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
   2326             self._setitem_array(key, value)
   2327         elif isinstance(key, DataFrame):
-> 2328             self._setitem_frame(key, value)
   2329         else:
   2330             # set column

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/frame.pyc in _setitem_frame(self, key, value)
   2364         self._check_inplace_setting(value)
   2365         self._check_setitem_copy()
-> 2366         self._where(-key, value, inplace=True)
   2367
   2368     def _ensure_valid_index(self, value):

/home/gbra/anaconda3/envs/outer_disk/lib/python2.7/site-packages/pandas/core/generic.pyc in _where(self, cond, other, inplace, axis, level, try_cast, raise_on_error)
   5096             for dt in cond.dtypes:
   5097                 if not is_bool_dtype(dt):
-> 5098                     raise ValueError(msg.format(dtype=dt))
   5099
   5100         cond = cond.astype(bool, copy=False)

ValueError: Boolean array expected for the condition, not float64

I would appreciate any help on this.

Body:
You can reindex the mask to have the same shape as df, and then use df.mask:

df.mask(mask.reindex(df.index, df.columns, fill_value=False), 999)
Out:
        a    b  c
spam  999  999  6
ham     1  999  7

At that point, regular indexing should also work:

df[mask.reindex(df.index, df.columns, fill_value=False)] = 999


问:
How to get vee-validator's $validator when using nuxt.js
I have installed vee-validator in my nuxt.js install (using the express template).

I have added the plugin into my nuxt.config.js file like so:

```<code>plugins: [
    { src: '~plugins/vee-validate.js' }
]
</code>```

I have also added it into the build settings:

```<code>build: {
    vendor: ['vee-validate'],
    ...
</code>```

When I use the HTML tags e.g. v-validate="'required'", the validation is working as expected, and I can show/hide errors in the template.

Now I am trying to set up a form so that when it is submitted, all fields will be validated and errors will only be displayed after an attempted submission. To do this, I have set up a method like so:

```<code>  methods: {
    onLogin: (e) => {
      e.preventDefault()
      console.log('validator', this.$validator)
    }
  }
</code>```

For some reason, the this.$validator is undefined. Can someone tell me how I can access it please? I have tried adding:

```<code>inject: ['$validator']
</code>```

but this didn't seem to make any difference.

Thanks for any help.

答:
Turns out the problem was using the ES6 function style, got in the habit of using it from Angular!

Changed:

```<code>methods: {
    onLogin: (e) => {
      e.preventDefault()
      console.log('validator', this.$validator)
    }
}
</code>```

to:

```<code>methods: {
    onLogin: function (e) {
      e.preventDefault()
      console.log('validator', this.$validator)
    }
}
</code>```

and now it works fine.

Body:
I have installed vee-validator in my nuxt.js install (using the express template).

I have added the plugin into my nuxt.config.js file like so:

plugins: [
    { src: '~plugins/vee-validate.js' }
]

I have also added it into the build settings:

build: {
    vendor: ['vee-validate'],
    ...

When I use the HTML tags e.g. v-validate="'required'", the validation is working as expected, and I can show/hide errors in the template.

Now I am trying to set up a form so that when it is submitted, all fields will be validated and errors will only be displayed after an attempted submission. To do this, I have set up a method like so:

  methods: {
    onLogin: (e) => {
      e.preventDefault()
      console.log('validator', this.$validator)
    }
  }

For some reason, the this.$validator is undefined. Can someone tell me how I can access it please? I have tried adding:

inject: ['$validator']

but this didn't seem to make any difference.

Thanks for any help.

Body:
Turns out the problem was using the ES6 function style, got in the habit of using it from Angular!

Changed:

methods: {
    onLogin: (e) => {
      e.preventDefault()
      console.log('validator', this.$validator)
    }
}

to:

methods: {
    onLogin: function (e) {
      e.preventDefault()
      console.log('validator', this.$validator)
    }
}

and now it works fine.


问:
Storing data in time range before and after threshold value is met
I have a data frame that contains a column with timestamps (called "Timestamp") and a column containing air pollutant concentrations (called "value").

I have a threshold value for the air pollutant, say 11 (for example), and would like to graph concentration versus time plots for the 5 hours before the threshold is met until 24 hours after the threshold is met for all occurrences of concentrations reaching or exceeding 11.

I think I can figure out the graphing but my main issue at this point is subsetting and storing the data for the periods before and after the threshold is met. Any ideas on how I can do this?

Thanks.

答:
I apologize for the following code beeing a bit confusing. However, I think it should work like this:

```<code>require(tidyverse)
require(lubridate)

# Create example data
timestamp <- c("2017-01-01 00:00:00", "2017-01-01 01:00:00", "2017-01-01 02:00:00",
           "2017-01-01 03:00:00", "2017-01-01 04:00:00", "2017-01-01 05:00:00",
           "2017-01-01 06:00:00", "2017-01-01 07:00:00", "2017-01-01 08:00:00",
           "2017-01-01 09:00:00", "2017-01-01 10:00:00", "2017-01-01 11:00:00")

value <- c(8, 10, 12, 13, 10, 2, 3, 6, 5, 8, 6, 7)

df <- data.frame(timestamp = ymd_hms(timestamp), value = value)

# Find incidents with values over 11
df %>%
  mutate(treshold = ifelse(value >= 11, 1, 0)) %>%
  filter(treshold == 1) %>%
  .$timestamp-> incidents

# Create new data frame to store final data
final_df <- data.frame()

# Loop over incidents and filter for relevant data points
for (i in seq(length(incidents))){
  df %>%
    filter(timestamp %in% (incidents[i] + dhours(-5:24))) %>%
    mutate(id = i) %>%
    rbind(final_df, .) -> final_df
}
</code>```

You can now use the final data frame to create your plot. Therefore, you can filter for each incident using the id column.

Alternatively, you could run the following code to create a distinct plot for each incident:

```<code>ggplot(final_df, aes(x = timestamp, y = value)) + geom_line() + facet_wrap(~id)
</code>```

Body:
I apologize for the following code beeing a bit confusing. However, I think it should work like this:

require(tidyverse)
require(lubridate)

# Create example data
timestamp <- c("2017-01-01 00:00:00", "2017-01-01 01:00:00", "2017-01-01 02:00:00",
           "2017-01-01 03:00:00", "2017-01-01 04:00:00", "2017-01-01 05:00:00",
           "2017-01-01 06:00:00", "2017-01-01 07:00:00", "2017-01-01 08:00:00",
           "2017-01-01 09:00:00", "2017-01-01 10:00:00", "2017-01-01 11:00:00")

value <- c(8, 10, 12, 13, 10, 2, 3, 6, 5, 8, 6, 7)

df <- data.frame(timestamp = ymd_hms(timestamp), value = value)

# Find incidents with values over 11
df %>%
  mutate(treshold = ifelse(value >= 11, 1, 0)) %>%
  filter(treshold == 1) %>%
  .$timestamp-> incidents

# Create new data frame to store final data
final_df <- data.frame()

# Loop over incidents and filter for relevant data points
for (i in seq(length(incidents))){
  df %>%
    filter(timestamp %in% (incidents[i] + dhours(-5:24))) %>%
    mutate(id = i) %>%
    rbind(final_df, .) -> final_df
}

You can now use the final data frame to create your plot. Therefore, you can filter for each incident using the id column.

Alternatively, you could run the following code to create a distinct plot for each incident:

ggplot(final_df, aes(x = timestamp, y = value)) + geom_line() + facet_wrap(~id)


问:
Autoload namespaces based on directory structure
According to the top comment on the PHP page spl_autoload_register( ) :

Good news for PHP 5.3 users with namespaced classes:

When you create a subfolder structure matching the namespaces of the >containing classes, you will never even have to define an autoloader.

```<code><?php
    spl_autoload_extensions(".php"); // comma-separated list
    spl_autoload_register();
?>
</code>```

However, when I have the following structure:

* classes/someclass.php

* index.php

Where someclass.php contains the following:

```<code><?php
    class someclass {
        function __construct( ) {
            echo 'It works!';
        }
    }
?>
</code>```

and index.php contains:

```<code><?php
    spl_autoload_extensions(".php");
    spl_autoload_register();

    new classes\someclass;
?>
</code>```

Then I get the following error:

Fatal error: spl_autoload(): Class classes\someclass could not be
  loaded

Am I getting this wrong? How can I make this work?

From the comments

This doesn't work either for the class:

```<code><?php
    namespace classes;
    class someclass {
        function __construct( ) {
            echo 'It works!';
        }
    }
?>
</code>```

答:
Do not use the spl_autoload_extensions () function if the files to load only have the php extension.
In my case, I create a class called autoload .. something similar to this:

```<code><?php

class Autoload
{
    private static $_extensions = array(
        0 => '.inc',
        1 => '.lib.php',
        2 => '.class.php',
    );

    public function __construct()
    {
        self::set_include_path();
        spl_autoload_extensions(implode(',', self::$_extensions));
        spl_autoload_register(__CLASS__, 'load_class');
    }

    public static function set_include_paths()
    {
        set_include_path(implode(PATH_SEPARATOR, array(
            realpath('classes');
            realpath('system');
            ...
            get_include_path();,
        )));
    }

    public function load_class($class)
    {
        if (!empty($class)) {
            spl_autoload($class);
        }

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

The use of ?> At the end of the file is not necessary.

Body:
According to the top comment on the PHP page spl_autoload_register( ) :

Good news for PHP 5.3 users with namespaced classes:

When you create a subfolder structure matching the namespaces of the >containing classes, you will never even have to define an autoloader.

<?php
    spl_autoload_extensions(".php"); // comma-separated list
    spl_autoload_register();
?>

However, when I have the following structure:

* classes/someclass.php

* index.php

Where someclass.php contains the following:

<?php
    class someclass {
        function __construct( ) {
            echo 'It works!';
        }
    }
?>

and index.php contains:

<?php
    spl_autoload_extensions(".php");
    spl_autoload_register();

    new classes\someclass;
?>

Then I get the following error:

Fatal error: spl_autoload(): Class classes\someclass could not be
  loaded

Am I getting this wrong? How can I make this work?

From the comments

This doesn't work either for the class:

<?php
    namespace classes;
    class someclass {
        function __construct( ) {
            echo 'It works!';
        }
    }
?>

Body:
Do not use the spl_autoload_extensions () function if the files to load only have the php extension.
In my case, I create a class called autoload .. something similar to this:

<?php

class Autoload
{
    private static $_extensions = array(
        0 => '.inc',
        1 => '.lib.php',
        2 => '.class.php',
    );

    public function __construct()
    {
        self::set_include_path();
        spl_autoload_extensions(implode(',', self::$_extensions));
        spl_autoload_register(__CLASS__, 'load_class');
    }

    public static function set_include_paths()
    {
        set_include_path(implode(PATH_SEPARATOR, array(
            realpath('classes');
            realpath('system');
            ...
            get_include_path();,
        )));
    }

    public function load_class($class)
    {
        if (!empty($class)) {
            spl_autoload($class);
        }

        return false;
    }
}

The use of ?> At the end of the file is not necessary.


问:
Understanding std::map::find
I am trying to learn how to use std::map with functions. I am a bit confused about how std::map::find works in this regard. Here is a simple code where I use a Lambda function along with map.

```<code>auto Lambda = [](const int&a, const int& b) {
 cout << "\n Inside lambda \n";
 return a < b;
 };

std::map<int, int, decltype(Lambda)> expt(Lambda);
expt[1] = 2;
expt[10] = 12;
auto search1 = expt.find(1);
auto search10 = expt.find(10);
if(search1 != expt.end()) {
    std::cout << "Found " << search1->first << " " << search1->second << '\n';
}
else {
    std::cout << "Not found\n";
}
</code>```

Here is the output that I get:

```<code>Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Found 1 2
</code>```

I am a bit confused about how find actually works in this case. Why do I get 7 calls of the lambda function even though I just have 2 keys in my map?

答:
Let me try to tackle this:

The point here is: you provide the definition of '<' operation only in map constructor. Map needs to perofrm the '<=' operation and it apparently does it like this:

```<code>bool le(left, rigth){
  return (left<right) and not (rigth<left);
}
</code>```

so it it is sometimes enough to do just one <, and sometimes 2 are required for a single operation on map.

The first 2 comparisons are caused by the insertion operation. The map algorithm has to decide if the new element is <= the existing one. It performs 2 < comparisons in order to find out (new<old and old>new). (Notice that if you insert 10 first, and then 1, you will only get one comparison, since the first of them new<old would yield the unambigous result (true)).

The first find executes the lambda 2 times for the same reason. The first check < returns false, so it needs to do the second one, with the swapped arguments to learn if the values are equal or not.

Once again, same story...

Title: Understanding std::map::find

Body:
I am trying to learn how to use std::map with functions. I am a bit confused about how std::map::find works in this regard. Here is a simple code where I use a Lambda function along with map.

auto Lambda = [](const int&a, const int& b) {
 cout << "\n Inside lambda \n";
 return a < b;
 };

std::map<int, int, decltype(Lambda)> expt(Lambda);
expt[1] = 2;
expt[10] = 12;
auto search1 = expt.find(1);
auto search10 = expt.find(10);
if(search1 != expt.end()) {
    std::cout << "Found " << search1->first << " " << search1->second << '\n';
}
else {
    std::cout << "Not found\n";
}

Here is the output that I get:

Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Inside lambda
Found 1 2

I am a bit confused about how find actually works in this case. Why do I get 7 calls of the lambda function even though I just have 2 keys in my map?

Body:
Let me try to tackle this:

The point here is: you provide the definition of '<' operation only in map constructor. Map needs to perofrm the '<=' operation and it apparently does it like this:

bool le(left, rigth){
  return (left<right) and not (rigth<left);
}

so it it is sometimes enough to do just one <, and sometimes 2 are required for a single operation on map.

The first 2 comparisons are caused by the insertion operation. The map algorithm has to decide if the new element is <= the existing one. It performs 2 < comparisons in order to find out (new<old and old>new). (Notice that if you insert 10 first, and then 1, you will only get one comparison, since the first of them new<old would yield the unambigous result (true)).

The first find executes the lambda 2 times for the same reason. The first check < returns false, so it needs to do the second one, with the swapped arguments to learn if the values are equal or not.

Once again, same story...


问:
Making a normal "submit" button that will get me to the "div id="example"
Is it possible to make a submit button that when I click it, it will get me to the for example
 without Javascript? I already tried with different ways but as always the first page is showing all tags from other ID's page's. I already have the Javascript code but I don't want to use, I want to do all this by simple HTML tags, if possible please help.

答:
Instead of

```<code><button type="submit">Submit</button>
</code>```

why not do something like

```<code><a href="#Home">submit</a>
</code>```

Body:
Instead of

<button type="submit">Submit</button>

why not do something like

<a href="#Home">submit</a>


问:
Influxdb: How to get count of number of results in a group by query
Is there anyway that i can get the count of total number of results / points / records in a group by query result?

> SELECT COUNT("water_level") FROM "h2o_feet" WHERE "location"='coyote_creek' AND time >= '2015-08-18T00:00:00Z' AND time <= '2015-08-18T00:30:00Z' GROUP BY time(12m)

name: h2o_feet
--------------
time                   count
2015-08-18T00:00:00Z   2
2015-08-18T00:12:00Z   2
2015-08-18T00:24:00Z   2```

I expect the count as 3 in this case. Even though I can calculate the number of results using the time period and interval (12m) here, I would like to know whether it is possible to do so with a query to database.

答:
You will need to do some manual work. Run it directly,

```<code>$ influx -execute "select * from measurement_name" -database="db_name" | wc -l
</code>```

This will return 4 more than the actual values.

Here is an example,

```<code>luvpreet@DHARI-Inspiron-3542:~/www$ influx -execute "select * from yprices" -database="vehicles" | wc -l
5

luvpreet@DHARI-Inspiron-3542:~/www$ influx -execute "select * from yprices" -database="vehicles"
name: yprices
time                price
----                -----
1493626629063286219 2

luvpreet@DHARI-Inspiron-3542:~/www$
</code>```

So, I think now you know why subtract 4 from the value.

Body:
Is there anyway that i can get the count of total number of results / points / records in a group by query result?

> SELECT COUNT("water_level") FROM "h2o_feet" WHERE "location"='coyote_creek' AND time >= '2015-08-18T00:00:00Z' AND time <= '2015-08-18T00:30:00Z' GROUP BY time(12m)

name: h2o_feet
--------------
time                   count
2015-08-18T00:00:00Z   2
2015-08-18T00:12:00Z   2
2015-08-18T00:24:00Z   2

I expect the count as 3 in this case. Even though I can calculate the number of results using the time period and interval (12m) here, I would like to know whether it is possible to do so with a query to database.

Body:
You will need to do some manual work. Run it directly,

$ influx -execute "select * from measurement_name" -database="db_name" | wc -l

This will return 4 more than the actual values.

Here is an example,

luvpreet@DHARI-Inspiron-3542:~/www$ influx -execute "select * from yprices" -database="vehicles" | wc -l
5

luvpreet@DHARI-Inspiron-3542:~/www$ influx -execute "select * from yprices" -database="vehicles"
name: yprices
time                price
----                -----
1493626629063286219 2

luvpreet@DHARI-Inspiron-3542:~/www$

So, I think now you know why subtract 4 from the value.


问:
Generate HTML Table from Curl Response
My PHP code is as follows:

```<code><?php
//set Header
header('Content-Type: application/json');

//set POST variables
$url = 'https://api.example.com';
$fields = array([
    'Type' => "Free",
    'Value' => "UK1234"
]);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'APIKEY: aaaa-bbbb-cccc-dddd'));
curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields));
//save response to variable $result
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

echo $result;
</code>```

This returns the following array:

```<code>[
  {
    "data": [
      {
        "id": "ABC123",
        "Type": "Free",
        "Sector": "Software",
        "Name": "Beta A"
      },
      {
        "id": "ABC124",
        "Type": "Free",
        "Sector": "Software",
        "Name": "Beta B"
      }
    ]
  }
]
</code>```

I want to output specific objects, for instance id, Sector, Name. These would be the table headers. I tried a basic for loop but it didn't work:

```<code>for($i=0;$i<count($result);$i++) {
  echo('<tr>');
  echo('<td>' . $result[0]['data'][$i]['id'] . '</td>');
  echo('<td>' . $result[0]['data'][$i]['Sector'] . '</td>');
  echo('<td>' . $result[0]['data'][$i]['Name'] . '</td>');
  echo('</tr>');
}
</code>```

I can't figure out why. I also tried removing [0], and this is what I get:

```<code><tr><td>[</td><td>[</td><td>[</td></tr>
</code>```

The reason it shows html is due to 'Content-Type: application/json'.

Anything simpler than a for loop? This "data":[...] is giving me troubles and I have a hard time choosing the correct path to the object I want.

答:
This will do the trick:

```<code>//decode response in order to access objects
$data = json_decode($result, true);
</code>```

Also, the correct approach for the loop should be as follows:

```<code>for($i=0;$i<count($data[0]["data"]);$i++) {
  echo('<tr>');
  echo('<td>' . $data[0]['data'][$i]['id'] . '</td>');
  echo('<td>' . $data[0]['data'][$i]['Sector'] . '</td>');
  echo('<td>' . $data[0]['data'][$i]['Name'] . '</td>');
  echo('</tr>');
}
</code>```

Title: Generate HTML Table from Curl Response

Body:
My PHP code is as follows:

<?php
//set Header
header('Content-Type: application/json');

//set POST variables
$url = 'https://api.example.com';
$fields = array([
    'Type' => "Free",
    'Value' => "UK1234"
]);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: text/json', 'APIKEY: aaaa-bbbb-cccc-dddd'));
curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields));
//save response to variable $result
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

echo $result;

This returns the following array:

[
  {
    "data": [
      {
        "id": "ABC123",
        "Type": "Free",
        "Sector": "Software",
        "Name": "Beta A"
      },
      {
        "id": "ABC124",
        "Type": "Free",
        "Sector": "Software",
        "Name": "Beta B"
      }
    ]
  }
]

I want to output specific objects, for instance id, Sector, Name. These would be the table headers. I tried a basic for loop but it didn't work:

for($i=0;$i<count($result);$i++) {
  echo('
');
  echo('' . $result[0]['data'][$i]['id'] . '	');
  echo('' . $result[0]['data'][$i]['Sector'] . '	');
  echo('' . $result[0]['data'][$i]['Name'] . '	');
  echo('
');
}

I can't figure out why. I also tried removing [0], and this is what I get:

[	[	[

The reason it shows html is due to 'Content-Type: application/json'.

Anything simpler than a for loop? This "data":[...] is giving me troubles and I have a hard time choosing the correct path to the object I want.

Body:
This will do the trick:

//decode response in order to access objects
$data = json_decode($result, true);

Also, the correct approach for the loop should be as follows:

for($i=0;$i<count($data[0]["data"]);$i++) {
  echo('<tr>');
  echo('<td>' . $data[0]['data'][$i]['id'] . '</td>');
  echo('<td>' . $data[0]['data'][$i]['Sector'] . '</td>');
  echo('<td>' . $data[0]['data'][$i]['Name'] . '</td>');
  echo('</tr>');
}


问:
Xcode: Build Failed, but no error messages
Using Xcode 4.5.1. Our project has been building fine for the last three months, but suddenly, when I try to build, it says "Build failed", but does not show any errors on the triangle exclamation mark tab, nor does it give a reason when it pops up build failed.

We have not changed the bundle identifier, or any other project properties. I tried a clean, then build, but no luck.

What may be causing the problem?

Similar to this question, but none of the solutions apply.

答:
Other answers helped me find the Report Navigator. The only error displayed was:

Build operation failed without specifying any errors. Individual build
  tasks may have failed for unknown reasons.  One possible cause is if
  there are too many (possibly zombie) processes; in this case,
  rebooting may fix the problem.

I fixed this by closing the Simulator.


问:
Python Parsing Framework
If I needed facilitate the extraction of data from various (non-API) internet sources, is there a framework-type solution that would streamline the process of having developers write reusable, yet source specific parsers on a large scale?</p>

答: Pyparsing is a Python library that I've found to be very useful for parsing custom domain specific languages.</p>

Title: Python Parsing Framework