问:
Access members of unkown template type of derived template class through pointer to base class C++
I need to have a map holding different value types. I achieved that using a derived template class Derived of type T derived from B  and declaring my map using a pointer to the base class Base like so:

```<code>class Base {
    public:
    ~Base(){}
};

template <class T>
class Derived: public Base {
     public:
     Derived(T value) {
          this->value = value;
     }
     T value;
 };

 std::map<std::string, std::shared_ptr<Base>> my_map;

 using KeyValuePair = std::pair<std::string, std::shared_ptr<Base>>;

 my_map.insert(KeyValuePair("foo1",std::make_shared<Derived<int>>(10)));
 my_map.insert(KeyValuePair("foo2",std::make_shared<Derived<double>>(20.0)));
 my_map.insert(KeyValuePair("foo3",std::make_shared<Derived<std::string>>("bla")));
</code>```

I now for example want to print the value of a map entry

```<code> for (auto const& x : my_map)
{
    std::cout << *x.get() << std::endl;
}
</code>```

However, I now have the problem that I cannot access the the members in the Derived class by casting x to Derived, because I don't know the type of the template parameter. So the following is not possible:

```<code>std::shared_ptr<Derived<?>> derived = std::dynamic_cast<Derived<?>>(x);
</code>```

I thought about having a virtual function in the Base class which returns the member, but I don't know the return type, so not an option.

I also don't want to specify several virtual functions for several return types, as the whole point of the code is to avoid copying code and having a "generic map"

However, I don't see another solution besides using some fancy boost magic by returning a streamable boost::any like the following, as this removes any information about the type.

```<code> using streamable_any = boost::type_erasure::any<boost::mpl::vector<
 boost::type_erasure::copy_constructible<>,
 boost::type_erasure::destructible<>,
 boost::type_erasure::ostreamable<>>>;
</code>```

What are the possibilities I have to achieve what I want? I suspect that I need to consider a design change.

答:
Getting:

```<code>template<class...Ts>
struct types {};

template<class types, template<class...>class>
struct apply_to {};
template<class types, template<class...>class Z>
using apply_to_t=typename apply_to<types, Z>::type;
template<class...Ts, template<class...>class Z>
struct apply_to<types<Ts...>, Z>{ using type=Z<Ts...>; };

template<class types>
using variant_of=apply_to_t<types, boost::variant>;

using supported_types = types<int, double, std::string>;

class Base {
  virtual variant_of_t<supported_types> get() const = 0;
protected:
  ~Base() {}
};

template<class T>
class Derived final: public Base {
  T t;
public:
  virtual variant_of_t<supported_types> get() const override {
    return t;
  }
  virtual ~Derived() {}
};
</code>```

Setting can be a bit trickier.

```<code>template<class...Ts>
using sink = boost::variant< std::function<void(Ts)>... >;

template<class types>
using setters = apply_to_t<types, sink>;

class Base {
  virtual variant_of_t<supported_types> get() const = 0;
  virtual void set( std::function<void(setters<supported_types>)> ) = 0;
protected:
  ~Base() {}
};

template<class T>
class Derived final: public Base {
  T t;
public:
  virtual void set( std::function<void(setters<supported_types>)> s ) override {
    s( std::function<void(T)>( [&](T&& in) { t = std::forward<T>(in); } ) );
  }
  virtual variant_of_t<supported_types> get() const override {
    return t;
  }
  virtual ~Derived() {}
};
</code>```

which is a bit more insane.

This gives you type-safe get and set.  When you call set, you must pass in a lambda that can accept any type setter, and do the right thing.  When you call get, it returns a variant over the possibilities of the contained data, which you have to deal with.

Printing would look like:

```<code>for (auto const& x : my_map)
{
   if (!x) continue;
   boost::apply_visitor([&](auto&& x){
     std::cout << x << std::endl;
   }, x->get());
}
</code>```

Suppose you want to set a value.

```<code>template<class...Fs>
struct override_t;
template<class F0, class F1, class...Fs>
struct override_t<F0, F1, Fs...>: F0, override_t<F1, Fs...> {
  using RBase=override_t<F1, Fs...>;
  using F0::operator();
  using RBase::operator();
  override_t( F0 f0, F1 f1, Fs... fs ):
    F0(std::move(f0)),
    RBase(std::move(f1), std::move(fs)...)
  {}
};
template<class F0>
struct override_t<F0>: F0 {
  using F0::operator();
  override_t( F0 f0 ):
    F0(std::move(f0))
  {}
};
template<>
struct override_t<> {};
template<class...Fs>
override_t<Fs...> override( Fs... fs ) { return {std::move(fs)...}; }

x->set(
  [&]( auto setters ) {
    boost::apply_visitor(
      override(
        [&]( std::function<void(int)> set ) {
          set(7);
        },
        [&]( auto&& ) {
           assert(false); // wrong type
        }
      ),
      setters
    );
  }
);
</code>```

as type-safe setting of a value with unknown type is rather difficult to get right.

Body:
I need to have a map holding different value types. I achieved that using a derived template class Derived of type T derived from B  and declaring my map using a pointer to the base class Base like so:

class Base {
    public:
    ~Base(){}
};

template <class T>
class Derived: public Base {
     public:
     Derived(T value) {
          this->value = value;
     }
     T value;
 };

 std::map<std::string, std::shared_ptr<Base>> my_map;

 using KeyValuePair = std::pair<std::string, std::shared_ptr<Base>>;

 my_map.insert(KeyValuePair("foo1",std::make_shared<Derived<int>>(10)));
 my_map.insert(KeyValuePair("foo2",std::make_shared<Derived<double>>(20.0)));
 my_map.insert(KeyValuePair("foo3",std::make_shared<Derived<std::string>>("bla")));

I now for example want to print the value of a map entry

 for (auto const& x : my_map)
{
    std::cout << *x.get() << std::endl;
}

However, I now have the problem that I cannot access the the members in the Derived class by casting x to Derived, because I don't know the type of the template parameter. So the following is not possible:

std::shared_ptr<Derived<?>> derived = std::dynamic_cast<Derived<?>>(x);

I thought about having a virtual function in the Base class which returns the member, but I don't know the return type, so not an option.

I also don't want to specify several virtual functions for several return types, as the whole point of the code is to avoid copying code and having a "generic map"

However, I don't see another solution besides using some fancy boost magic by returning a streamable boost::any like the following, as this removes any information about the type.

 using streamable_any = boost::type_erasure::any<boost::mpl::vector<
 boost::type_erasure::copy_constructible<>,
 boost::type_erasure::destructible<>,
 boost::type_erasure::ostreamable<>>>;

What are the possibilities I have to achieve what I want? I suspect that I need to consider a design change.

Body:
Getting:

template<class...Ts>
struct types {};

template<class types, template<class...>class>
struct apply_to {};
template<class types, template<class...>class Z>
using apply_to_t=typename apply_to<types, Z>::type;
template<class...Ts, template<class...>class Z>
struct apply_to<types<Ts...>, Z>{ using type=Z<Ts...>; };

template<class types>
using variant_of=apply_to_t<types, boost::variant>;

using supported_types = types<int, double, std::string>;

class Base {
  virtual variant_of_t<supported_types> get() const = 0;
protected:
  ~Base() {}
};

template<class T>
class Derived final: public Base {
  T t;
public:
  virtual variant_of_t<supported_types> get() const override {
    return t;
  }
  virtual ~Derived() {}
};

Setting can be a bit trickier.

template<class...Ts>
using sink = boost::variant< std::function<void(Ts)>... >;

template<class types>
using setters = apply_to_t<types, sink>;

class Base {
  virtual variant_of_t<supported_types> get() const = 0;
  virtual void set( std::function<void(setters<supported_types>)> ) = 0;
protected:
  ~Base() {}
};

template<class T>
class Derived final: public Base {
  T t;
public:
  virtual void set( std::function<void(setters<supported_types>)> s ) override {
    s( std::function<void(T)>( [&](T&& in) { t = std::forward<T>(in); } ) );
  }
  virtual variant_of_t<supported_types> get() const override {
    return t;
  }
  virtual ~Derived() {}
};

which is a bit more insane.

This gives you type-safe get and set.  When you call set, you must pass in a lambda that can accept any type setter, and do the right thing.  When you call get, it returns a variant over the possibilities of the contained data, which you have to deal with.

Printing would look like:

for (auto const& x : my_map)
{
   if (!x) continue;
   boost::apply_visitor([&](auto&& x){
     std::cout << x << std::endl;
   }, x->get());
}

Suppose you want to set a value.

template<class...Fs>
struct override_t;
template<class F0, class F1, class...Fs>
struct override_t<F0, F1, Fs...>: F0, override_t<F1, Fs...> {
  using RBase=override_t<F1, Fs...>;
  using F0::operator();
  using RBase::operator();
  override_t( F0 f0, F1 f1, Fs... fs ):
    F0(std::move(f0)),
    RBase(std::move(f1), std::move(fs)...)
  {}
};
template<class F0>
struct override_t<F0>: F0 {
  using F0::operator();
  override_t( F0 f0 ):
    F0(std::move(f0))
  {}
};
template<>
struct override_t<> {};
template<class...Fs>
override_t<Fs...> override( Fs... fs ) { return {std::move(fs)...}; }

x->set(
  [&]( auto setters ) {
    boost::apply_visitor(
      override(
        [&]( std::function<void(int)> set ) {
          set(7);
        },
        [&]( auto&& ) {
           assert(false); // wrong type
        }
      ),
      setters
    );
  }
);

as type-safe setting of a value with unknown type is rather difficult to get right.


来源: stackexchange

问:
intellij System.getProperty ("user.dir"), how to get consistent result , whether ide, run script/app, or test?
Had a bit of a nightmare getting consistent result from my code when reading "user.dir" property depending on how the code was launched.

I have a gradle project, some code & scripts in src/main/groovy and tests in source/test/groovy, and running code from command line, or in the IDE (run script directly) and running some tests

i'd built myself a new gradle project and was trying to open a file resources in src/main/resources.

when i ran my unit tests, the user.dir = 'project root' (which is what i was expecting). when i built a script and right clicked in the IDE, then the user.dir property returned the current script directory path in source main!

so a lookup in a test returned a different test.

I also tried setting this in build.gradle

```<code>//setup proj.dir as project root
System.setProperty( "proj.dir", project.projectDir.toString() )
</code>```

and build a gradle task to print this - and it shows the project directory as result.

There doesn't appear to a global 'fix or config' in intellij to always get consistent return when reading the property "user.dir" to be project root. unless i missed something?

in the IDE if i look at the run/debug configurations - under defaults the entry for groovy says the working directory is the project root (as id expected).  however when i looked under the groovy node and my script there ('testPCE'), then the working directory was set as the scripts current location.

once i found out that i can edit the IDE run/debug configurations i reset the working directory to be the project root, and now get a consistent result.  But seem to have to check this on each script if i need to.

so my questions is what can i do/configure/set so that i get an env variable which always returns the project root, whether from command line launch, in gradle, by running by right click of script from IDE, or from tests in the IDE/ or from commnd line

There must, be a 'robust' way to ensure that all lookups on some env variable will return the same answer  regardless of how your code is executed.

know i know whats happening, i can adjust my ide to  set where i want working directory to be - but have to keep checking.  I want something reliable that will always work, whether its IDE, command line, inside tomcat web container etc to get the 'project root' and build paths reliably from this one stable point, that will work consistently

Does anyone know how to do this?

答:
perhaps not ideal bu this is working.  I'm trying to load a config file from the resources area that's in the classpath, but my code is a static block in class.

in this case i had to get the classLoader for the Class object and getResource on that (which includes checking across the classpath (i didnt want a spring dependency for this project if i could avoid it).

So the the code that seems to work - without having to resolve "user.dir" property is shown below

```<code>//configure standard converters
static {
    // class class loader will include resources so file will be found
    def configFile =  "config/BinderConfig.groovy"
    def resource = new File (configFile).canonicalPath
    resource = Gbinder.getClassLoader().getResource(configFile)
    def binderConfig = new ConfigSlurper().parse (resource)

    binderConfig.global.converters.each {
    typeConverters << it
    }

    typeConverters
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Had a bit of a nightmare getting consistent result from my code when reading "user.dir" property depending on how the code was launched.

I have a gradle project, some code & scripts in src/main/groovy and tests in source/test/groovy, and running code from command line, or in the IDE (run script directly) and running some tests

i'd built myself a new gradle project and was trying to open a file resources in src/main/resources.

when i ran my unit tests, the user.dir = 'project root' (which is what i was expecting). when i built a script and right clicked in the IDE, then the user.dir property returned the current script directory path in source main!

so a lookup in a test returned a different test.

I also tried setting this in build.gradle

//setup proj.dir as project root
System.setProperty( "proj.dir", project.projectDir.toString() )

and build a gradle task to print this - and it shows the project directory as result.

There doesn't appear to a global 'fix or config' in intellij to always get consistent return when reading the property "user.dir" to be project root. unless i missed something?

in the IDE if i look at the run/debug configurations - under defaults the entry for groovy says the working directory is the project root (as id expected).  however when i looked under the groovy node and my script there ('testPCE'), then the working directory was set as the scripts current location.

once i found out that i can edit the IDE run/debug configurations i reset the working directory to be the project root, and now get a consistent result.  But seem to have to check this on each script if i need to.

so my questions is what can i do/configure/set so that i get an env variable which always returns the project root, whether from command line launch, in gradle, by running by right click of script from IDE, or from tests in the IDE/ or from commnd line

There must, be a 'robust' way to ensure that all lookups on some env variable will return the same answer  regardless of how your code is executed.

know i know whats happening, i can adjust my ide to  set where i want working directory to be - but have to keep checking.  I want something reliable that will always work, whether its IDE, command line, inside tomcat web container etc to get the 'project root' and build paths reliably from this one stable point, that will work consistently

Does anyone know how to do this?

Body:
perhaps not ideal bu this is working.  I'm trying to load a config file from the resources area that's in the classpath, but my code is a static block in class.

in this case i had to get the classLoader for the Class object and getResource on that (which includes checking across the classpath (i didnt want a spring dependency for this project if i could avoid it).

So the the code that seems to work - without having to resolve "user.dir" property is shown below

//configure standard converters
static {
    // class class loader will include resources so file will be found
    def configFile =  "config/BinderConfig.groovy"
    def resource = new File (configFile).canonicalPath
    resource = Gbinder.getClassLoader().getResource(configFile)
    def binderConfig = new ConfigSlurper().parse (resource)

    binderConfig.global.converters.each {
    typeConverters << it
    }

    typeConverters
 }


问:
opening URLConnection with a particular web resource
I am not able to open a URLConnection with a particular web resource . I am getting

" java.net.ConnectException: Connection timed out:"  .  Is it because of that domain is blocking the direct URL connection ? If so how they are blocking this ?  below is the code snippet i wrote .

Code snippet:

import java.io.;
import java.net.;

public class TestFileRead{

```<code>public static void main(String args[]){

    try{

        String serviceUrl = "http://xyz.com/examples.zip";
        HttpURLConnection serviceConnection = (HttpURLConnection) new URL(serviceUrl).openConnection();
        System.out.println(serviceConnection);
        serviceConnection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)");

        DataInputStream din=new DataInputStream(serviceConnection.getInputStream());
        FileOutputStream fout=new FileOutputStream("downloaded");
        DataOutputStream dout=new DataOutputStream(fout);
        int bytes;
        while(din.available()>0){
            bytes=din.readByte();
            dout.write(bytes);
        }
    }catch(Exception ex){
        ex.printStackTrace();
    }

}
</code>```

}

答:
You are probably using the proxy setup in your browser to access the Yahoo home page which explains why it works in your browser and not in your code. You require a proxy configuration for your Java application.

The simplest way would be to set the system property http.proxyHost and http.proxyPort when running the code (in Eclipse or when running from command line just add -Dhttp.proxyHost=your.host.com -Dhttp.proxyPort=80) and you should be good to go. Pick up the proxy settings from your browser configuration/settings.

EDIT: This link does a decent job of explaining the possible solutions when dealing with proxies in Java.

ContentLicense: CC BY-SA 2.5

Body:
I am not able to open a URLConnection with a particular web resource . I am getting

" java.net.ConnectException: Connection timed out:"  .  Is it because of that domain is blocking the direct URL connection ? If so how they are blocking this ?  below is the code snippet i wrote .

Code snippet:

import java.io.;
import java.net.;

public class TestFileRead{

public static void main(String args[]){

    try{

        String serviceUrl = "http://xyz.com/examples.zip";
        HttpURLConnection serviceConnection = (HttpURLConnection) new URL(serviceUrl).openConnection();
        System.out.println(serviceConnection);
        serviceConnection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)");

        DataInputStream din=new DataInputStream(serviceConnection.getInputStream());
        FileOutputStream fout=new FileOutputStream("downloaded");
        DataOutputStream dout=new DataOutputStream(fout);
        int bytes;
        while(din.available()>0){
            bytes=din.readByte();
            dout.write(bytes);
        }
    }catch(Exception ex){
        ex.printStackTrace();
    }

}

}


问:
Place 2D Bitmap on ARCore anchor Android openGL ES 2.0
How do you place 2D bitmap on ARCore anchor location that always faces the user (camera)?
I want to place a marker where the user taps.

Do you have to multiply model, view, projection matrices to achieve this?

Currently I tried to use the andy_shadow.obj to display the bitmap since it's a flat 3D object. But I'm having trouble making it face the user(rotating) and placing it where the user taps.

```<code>Matrix.rotateM(mModelMatrix, 0, 90.0f, 1.0f, 0.0f, 0.0f);
</code>```

This rotates the object to face the camera but when you turn 45 degrees to left/right and place a new one, it will look flat since it is 90degrees from where the frame started.

Maybe placing a 2D object on screen UI in openGL is possible?

答:
There are 2 questions you're asking.  First, how do you rotate an object to always look at the camera.

I was able to do this by using the rotation of the frame vs. the rotation of the anchor. in HelloArActivity.onDrawFrame() change

```<code>planeAttachment.getPose().toMatrix(mAnchorMatrix, 0);
</code>```

to be

```<code>float translation[] = new float[3];
float rotation[] = new float[4];
planeAttachment.getPose().getTranslation(translation,0);
frame.getPose().getRotationQuaternion(rotation,0);

Pose rotatedPose = new Pose(translation,rotation);
rotatedPose.toMatrix(mAnchorMatrix,0);
</code>```

This will make "Andy" always look at you as you move around.

The second part of drawing a 2D image requires a little more code. At a high level:

Create a rectangle using vertices around (0,0,0)

Use a UVMap to map the texture on to the quad.

Use a vertex shader that multiplies the position by the MVP matrix

A working example is at QuadRenderer.java.  In the sample, uses it just as the ObjectRenderer class is used.

Body:
How do you place 2D bitmap on ARCore anchor location that always faces the user (camera)?
I want to place a marker where the user taps.

Do you have to multiply model, view, projection matrices to achieve this?

Currently I tried to use the andy_shadow.obj to display the bitmap since it's a flat 3D object. But I'm having trouble making it face the user(rotating) and placing it where the user taps.

Matrix.rotateM(mModelMatrix, 0, 90.0f, 1.0f, 0.0f, 0.0f);

This rotates the object to face the camera but when you turn 45 degrees to left/right and place a new one, it will look flat since it is 90degrees from where the frame started.

Maybe placing a 2D object on screen UI in openGL is possible?

Body:
There are 2 questions you're asking.  First, how do you rotate an object to always look at the camera.

I was able to do this by using the rotation of the frame vs. the rotation of the anchor. in HelloArActivity.onDrawFrame() change

planeAttachment.getPose().toMatrix(mAnchorMatrix, 0);

to be

float translation[] = new float[3];
float rotation[] = new float[4];
planeAttachment.getPose().getTranslation(translation,0);
frame.getPose().getRotationQuaternion(rotation,0);

Pose rotatedPose = new Pose(translation,rotation);
rotatedPose.toMatrix(mAnchorMatrix,0);

This will make "Andy" always look at you as you move around.

The second part of drawing a 2D image requires a little more code. At a high level:

Create a rectangle using vertices around (0,0,0)

Use a UVMap to map the texture on to the quad.

Use a vertex shader that multiplies the position by the MVP matrix

A working example is at QuadRenderer.java.  In the sample, uses it just as the ObjectRenderer class is used.


问:
Regex Mismatch if Character Anywhere in Pattern
Using regex with python 2.7.

I want to match patterns inside a string unless a certain character exists anywhere in the pattern. Say something simple like

```<code>>>>import re
>>>string = "hello this is a number 1234 and goodbye"
>>>re.sub("(\d{4})", "[my number]")
</code>```

Which would return

```<code>hello this is a number [my number] and goodbye
</code>```

However, I want to get a mismatch if the number 3 appears anywhere inside the pattern, not the whole string. How do I do this?

So this doesn't match.

```<code>>>>"hello this is a number 1234 and goodbye"
hello this is a number 1234 and goodbye
</code>```

but these do

```<code>>>>"hello this is a number 31245 and goodbye"
>>>"hello 3 this is a number 1245 and goodbye"
hello this is a number 3[my number] and goodbye
hello 3 this is a number [my number] and goodbye
</code>```

答:
You can use a negative lookahead:

```<code>re.sub(r'(?!\d*3)\d{4}', "[my number]", str)
</code>```

RegEx Demo

(?!\d*3) will assert a mismatch if there is a 3 ahead after 0+ digits.

Body:
Using regex with python 2.7.

I want to match patterns inside a string unless a certain character exists anywhere in the pattern. Say something simple like

>>>import re
>>>string = "hello this is a number 1234 and goodbye"
>>>re.sub("(\d{4})", "[my number]")

Which would return

hello this is a number [my number] and goodbye

However, I want to get a mismatch if the number 3 appears anywhere inside the pattern, not the whole string. How do I do this?

So this doesn't match.

>>>"hello this is a number 1234 and goodbye"
hello this is a number 1234 and goodbye

but these do

>>>"hello this is a number 31245 and goodbye"
>>>"hello 3 this is a number 1245 and goodbye"
hello this is a number 3[my number] and goodbye
hello 3 this is a number [my number] and goodbye

Body:
You can use a negative lookahead:

re.sub(r'(?!\d*3)\d{4}', "[my number]", str)

RegEx Demo

(?!\d*3) will assert a mismatch if there is a 3 ahead after 0+ digits.


问:
Counting rows with NaN
I have the following DataFrame:

```<code>dur  wage1  wage2  wage3  cola  hours     pension  stby_pay  shift_diff
6   3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
8   1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
9   1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
13  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
17  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
31  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
43  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN
44  1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
47  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
</code>```

What I have to do is count the rows that are exactly the same, including the NaN values.

The problem is the following, I use groupby, but it is a function that ignores the NaN values, that is, it does not have them in mind when doing the counting, that is the reason why I am not returning a correct output counting the number of exact repetitions between those rows.

My code is the following one:

```<code>def detect_duplicates(data):
    x = DataFrame(columns=data.columns.tolist() + ["num_reps"])

    aux = data[data.duplicated(keep=False)]
    x = data[data.duplicated(keep=False)].drop_duplicates()
    #This line should count my repeated rows
    s = aux.groupby(data.columns.tolist(),as_index=False).transform('size')

    return x
</code>```

If I print "x" var, I get this result, it shows all the repeated rows:

```<code>dur  wage1  wage2  wage3  cola  hours     pension  stby_pay  shift_diff
6   3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
8   1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
9   1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
13  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
17  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
31  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
43  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN
44  1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
47  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
51  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
53  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN
</code>```

Now I have to count those rows from my x result that are exactly the same.

This should be my correct output:

```<code> dur    wage1   wage2   wage3   cola    hours   pension stby_pay    shift_diff  num_reps
6   3.0 2.0 3.0 NaN tcf NaN empl_contr  NaN NaN                4
8   1.0 2.8 NaN NaN none    38.0    empl_contr  2.0 3.0        2
9   1.0 5.7 NaN NaN none    40.0    empl_contr  NaN 4.0        3
43  2.0 2.5 3.0 NaN NaN 40.0    none    NaN NaN                2
</code>```

Here is my problem and it's that groupby ignores NaN values, and that's why other similar posts about this problem can't help me.

Thanks

答:
I just solved it.

The problem as I said was groupby that doesn't not accept Nan Values.

So what I have done to solve it, is to change all Nan Values with fillna(0) function so it changes all NaN to 0 and now I can do the comparation properly.

Here is my new function working properly:

```<code>def detect_duplicates(data):
    x = DataFrame(columns=data.columns.tolist() + ["num_reps"])

    aux = data[data.duplicated(keep=False)]
    x = data[data.duplicated(keep=False)].drop_duplicates()
    s =  aux.fillna(0).groupby(data.columns.tolist()).size().reset_index().rename(columns={0:'count'})
    x['num_reps'] = s['count'].tolist()[::-1]

    return x
</code>```

Title: Counting rows with NaN

Body:
I have the following DataFrame:

dur  wage1  wage2  wage3  cola  hours     pension  stby_pay  shift_diff
6   3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
8   1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
9   1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
13  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
17  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
31  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
43  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN
44  1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
47  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN

What I have to do is count the rows that are exactly the same, including the NaN values.

The problem is the following, I use groupby, but it is a function that ignores the NaN values, that is, it does not have them in mind when doing the counting, that is the reason why I am not returning a correct output counting the number of exact repetitions between those rows.

My code is the following one:

def detect_duplicates(data):
    x = DataFrame(columns=data.columns.tolist() + ["num_reps"])

    aux = data[data.duplicated(keep=False)]
    x = data[data.duplicated(keep=False)].drop_duplicates()
    #This line should count my repeated rows
    s = aux.groupby(data.columns.tolist(),as_index=False).transform('size')

    return x

If I print "x" var, I get this result, it shows all the repeated rows:

dur  wage1  wage2  wage3  cola  hours     pension  stby_pay  shift_diff
6   3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
8   1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
9   1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
13  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
17  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
31  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
43  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN
44  1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
47  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
51  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
53  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN

Now I have to count those rows from my x result that are exactly the same.

This should be my correct output:

 dur    wage1   wage2   wage3   cola    hours   pension stby_pay    shift_diff  num_reps
6   3.0 2.0 3.0 NaN tcf NaN empl_contr  NaN NaN                4
8   1.0 2.8 NaN NaN none    38.0    empl_contr  2.0 3.0        2
9   1.0 5.7 NaN NaN none    40.0    empl_contr  NaN 4.0        3
43  2.0 2.5 3.0 NaN NaN 40.0    none    NaN NaN                2

Here is my problem and it's that groupby ignores NaN values, and that's why other similar posts about this problem can't help me.

Thanks

Body:
I just solved it.

The problem as I said was groupby that doesn't not accept Nan Values.

So what I have done to solve it, is to change all Nan Values with fillna(0) function so it changes all NaN to 0 and now I can do the comparation properly.

Here is my new function working properly:

def detect_duplicates(data):
    x = DataFrame(columns=data.columns.tolist() + ["num_reps"])

    aux = data[data.duplicated(keep=False)]
    x = data[data.duplicated(keep=False)].drop_duplicates()
    s =  aux.fillna(0).groupby(data.columns.tolist()).size().reset_index().rename(columns={0:'count'})
    x['num_reps'] = s['count'].tolist()[::-1]

    return x


问:
Finding number of dlopen calls of an ELF binary in C
I would like to analyze an ELF binary file and figure out how many calls to dlopen() it makes in C, are there any libraries that can do this? Or how would I go about finding the count?</p>

答: solutions depend on the operating system and boil down to hotpatching the target process. you want to look at systemtap userspace tracing on linux ( https://sourceware.org/systemtap/SystemTap_Beginners_Guide/userspace-probing.html ) or dtrace on bsd-related systems (like osx). No clue about windows, but they presumably have an equivalent.</p>


问:
Laravel 5.5 change unauthenticated login redirect url
In Laravel < 5.5 I could change this file app/Exceptions/Handler to change the unauthenticated user redirect url:

```<code>protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('login'));
}
</code>```

But in Laravel 5.5 this has been moved to this location vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php so how can I change it now? I don't want to change stuff in the vendor directory encase it gets overridden by composer updates.

```<code>protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
                ? response()->json(['message' => 'Unauthenticated.'], 401)
                : redirect()->guest(route('login'));
}
</code>```

答:
1.Go to vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php file.

2.Search the method name is unauthenticated.

3.And change the redirect url from
 redirect()->guest(route('login')) to redirect()->guest(route('api/login')) //whatever you want.

You could return the response as a JSON if it is API services.

Body:
In Laravel < 5.5 I could change this file app/Exceptions/Handler to change the unauthenticated user redirect url:

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('login'));
}

But in Laravel 5.5 this has been moved to this location vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php so how can I change it now? I don't want to change stuff in the vendor directory encase it gets overridden by composer updates.

protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
                ? response()->json(['message' => 'Unauthenticated.'], 401)
                : redirect()->guest(route('login'));
}


问:
Why is [0] === [0] false
If debugging shows that a variable is 0, then I think that I should be able to catch it with either ==='0' or ===0 but that didn't work. I had to use only == instead, then it worked:

```<code>var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns == '0' || non_sortable_columns == 0) {
    offset = 1;
}
</code>```

I first tried this but it didn't work:

```<code>var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns === '0' || non_sortable_columns === 0) {
    offset = 1;
}
</code>```

The value was [0] and [0] === [0] is false. How can it be false?

答:
1. [0] === [0] is false because each [0] is actually a declaration that creates an array with the number 0 as its first index.

Arrays are objects and in JavaScript,  2 objects are == or === only and only if they point at the same location in memory. This means:

var a = [];
var b = a;
console.log(a == b); // "true". They both point at the same location in memory.

a = [];
b = [];
console.log(a == b); // "false". They don't point at the same location in memory.```

2. [0] == "0" evaluates to true, because:

In JavaScript, due to the nature of the == operator, when you compare an object with a primitive, the object will be coerced to a primitive, and then that primitive will be coerced to the specific type of primitive you are trying to compare it with.

"0" is a string, so [0] will have to be coerced to a string. How ? First, JavaScript will invoke its valueOf method to see if it returns a primitive, the array version of valueOf will just return that array, so valueOf doesn't yield a primitive; now JavaScript will try the object's (aka array's) toString method, an array's toString method will return a string that is the result of a comma-separated concatenation of its elements (each element will be coerced to a string as well, but that is irrelevant here), this would have been more visible if your array contained more than one element (e.g if it were [0,1], toString would return "0,1"), but your array only has 1 element, so the result of its stringification is "0" (if toString didn't return a string but another primitive, that primitive would be used in a ToString abstract operation; if neither valueOf nor toString returned a primitive, a TypeError would be thrown).

Now, our end comparison, with all the coercions and stuff, has changed to "0" == "0", which is true.

3. [0] == 0, mostly the same as #2, except after JavaScript has the string "0", it will coerce it to a number, the result of coercing the string "0" to a number is the number 0. So we have 0 == 0 which is true.

4. [0] === 0 and [0] === "0", these 2 are very simple, no coercions will happen because you are using ===.
In the first one, the reference (aka location pointed at in memory) held by [0] will be compared to the number 0, this will obviously evaluate to false;
In the second one, again, the reference held by [0] will be compared with the string "0", this again, is false.

So, as you can see, good ser, all your misery comes from ==, this operator, along with !=, are called "the evil counterparts of === and !==" by Douglas Crockford, for the same reasons which are causing your confusions.

Feel free to request any elaborations you might want and ask any questions you might have.

Additionally, see this article about object coercion, this MDN article about Array#toString, and this StackOverflow question which outlines the differences between == and ===.

Title: Why is [0] === [0] false

Body:
If debugging shows that a variable is 0, then I think that I should be able to catch it with either ==='0' or ===0 but that didn't work. I had to use only == instead, then it worked:

var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns == '0' || non_sortable_columns == 0) {
    offset = 1;
}

I first tried this but it didn't work:

var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns === '0' || non_sortable_columns === 0) {
    offset = 1;
}

The value was [0] and [0] === [0] is false. How can it be false?

Body:
1. [0] === [0] is false because each [0] is actually a declaration that creates an array with the number 0 as its first index.

Arrays are objects and in JavaScript,  2 objects are == or === only and only if they point at the same location in memory. This means:

var a = [];
var b = a;
console.log(a == b); // "true". They both point at the same location in memory.

a = [];
b = [];
console.log(a == b); // "false". They don't point at the same location in memory.

2. [0] == "0" evaluates to true, because:

In JavaScript, due to the nature of the == operator, when you compare an object with a primitive, the object will be coerced to a primitive, and then that primitive will be coerced to the specific type of primitive you are trying to compare it with.

"0" is a string, so [0] will have to be coerced to a string. How ? First, JavaScript will invoke its valueOf method to see if it returns a primitive, the array version of valueOf will just return that array, so valueOf doesn't yield a primitive; now JavaScript will try the object's (aka array's) toString method, an array's toString method will return a string that is the result of a comma-separated concatenation of its elements (each element will be coerced to a string as well, but that is irrelevant here), this would have been more visible if your array contained more than one element (e.g if it were [0,1], toString would return "0,1"), but your array only has 1 element, so the result of its stringification is "0" (if toString didn't return a string but another primitive, that primitive would be used in a ToString abstract operation; if neither valueOf nor toString returned a primitive, a TypeError would be thrown).

Now, our end comparison, with all the coercions and stuff, has changed to "0" == "0", which is true.

3. [0] == 0, mostly the same as #2, except after JavaScript has the string "0", it will coerce it to a number, the result of coercing the string "0" to a number is the number 0. So we have 0 == 0 which is true.

4. [0] === 0 and [0] === "0", these 2 are very simple, no coercions will happen because you are using ===.
In the first one, the reference (aka location pointed at in memory) held by [0] will be compared to the number 0, this will obviously evaluate to false;
In the second one, again, the reference held by [0] will be compared with the string "0", this again, is false.

So, as you can see, good ser, all your misery comes from ==, this operator, along with !=, are called "the evil counterparts of === and !==" by Douglas Crockford, for the same reasons which are causing your confusions.

Feel free to request any elaborations you might want and ask any questions you might have.

Additionally, see this article about object coercion, this MDN article about Array#toString, and this StackOverflow question which outlines the differences between == and ===.


问:
How to work with Git branches and Rails migrations
I am working on a rails app with quite a few git branches and many of them include db migrations. We try to be careful but occasionally some piece of code in master asks for a column that got removed/renamed in another branch.

What would be a nice solution to "couple" git branches with DB states?

What would these "states" actually be?

We can't just duplicate a database if it's a few GBs in size.

And what should happen with merges?

Would the solution translate to noSQL databases as well?

We currently use MySQL, mongodb and redis

EDIT: Looks like I forgot to mention a very important point, I am only interested in the development environment but with large databases (a few GBs in size).

答:
When you add a new migration in any branch, run rake db:migrate and commit both the migration and db/schema.rb

If you do this, in development, you'll be able to switch to another branch that has a different set of migrations and simply run rake db:schema:load.

Note that this will recreate the entire database, and existing data will be lost.

You'll probably only want to run production off of one branch which you're very careful with, so these steps don't apply there (just run rake db:migrate as usual there).  But in development, it should be no big deal to recreate the database from the schema, which is what rake db:schema:load will do.


问:
Java Printing a Binary Tree using Level-Order in a Specific Format
Okay, I have read through all the other related questions and cannot find one that helps with java.  I get the general idea from deciphering what i can in other languages; but i am yet to figure it out.

Problem: I would like to level sort (which i have working using recursion) and print it out in the general shape of a tree.

So say i have this:

```<code>    1
   / \
  2   3
 /   / \
4   5   6
</code>```

My code prints out the level order like this:

```<code>1 2 3 4 5 6
</code>```

I want to print it out like this:

```<code>1
2 3
4 5 6
</code>```

Now before you give me a moral speech about doing my work... I have already finished my AP Comp Sci project and got curious about this when my teacher mentioned the Breadth First Search thing.

I don't know if it will help, but here is my code so far:

```<code>/**
  * Calls the levelOrder helper method and prints out in levelOrder.
  */
 public void levelOrder()
 {
  q = new QueueList();
  treeHeight = height();
  levelOrder(myRoot, q, myLevel);
 }

 /**
  * Helper method that uses recursion to print out the tree in
  * levelOrder
  */
 private void levelOrder(TreeNode root, QueueList q, int curLev)
 {
  System.out.print(curLev);
  if(root == null)
  {
   return;
  }

  if(q.isEmpty())
  {
   System.out.println(root.getValue());
  }
  else
  {
   System.out.print((String)q.dequeue()+", ");
  }

  if(root.getLeft() != null)
  {
   q.enqueue(root.getLeft().getValue());
   System.out.println();
  }
  if(root.getRight() != null)
  {
   q.enqueue(root.getRight().getValue());
   System.out.println();
   curLev++;
  }

  levelOrder(root.getLeft(),q, curLev);
  levelOrder(root.getRight(),q, curLev);
 }
</code>```

From what i can figure out, i will need to use the total height of the tree, and use a level counter... Only problem is my level counter keeps counting when my levelOrder uses recursion to go back through the tree.

Sorry if this is to much, but some tips would be nice. :)

答:
```<code>        Queue<Node> queue = new LinkedList<>();
        queue.add(root);

        Node leftMost = null;
        while (!queue.isEmpty()) {
            Node node = queue.poll();

            if (leftMost == node) {
                System.out.println();
                leftMost = null;
            }

            System.out.print(node.getData() + " ");

            Node left = node.getLeft();
            if (left != null) {
                queue.add(left);
                if (leftMost == null) {
                    leftMost = left;
                }
            }

            Node right = node.getRight();
            if (right != null) {
                queue.add(right);

                if (leftMost == null) {
                    leftMost = right;
                }
            }
        }
</code>```

Body:
Okay, I have read through all the other related questions and cannot find one that helps with java.  I get the general idea from deciphering what i can in other languages; but i am yet to figure it out.

Problem: I would like to level sort (which i have working using recursion) and print it out in the general shape of a tree.

So say i have this:

    1
   / \
  2   3
 /   / \
4   5   6

My code prints out the level order like this:

1 2 3 4 5 6

I want to print it out like this:

1
2 3
4 5 6

Now before you give me a moral speech about doing my work... I have already finished my AP Comp Sci project and got curious about this when my teacher mentioned the Breadth First Search thing.

I don't know if it will help, but here is my code so far:

/**
  * Calls the levelOrder helper method and prints out in levelOrder.
  */
 public void levelOrder()
 {
  q = new QueueList();
  treeHeight = height();
  levelOrder(myRoot, q, myLevel);
 }

 /**
  * Helper method that uses recursion to print out the tree in
  * levelOrder
  */
 private void levelOrder(TreeNode root, QueueList q, int curLev)
 {
  System.out.print(curLev);
  if(root == null)
  {
   return;
  }

  if(q.isEmpty())
  {
   System.out.println(root.getValue());
  }
  else
  {
   System.out.print((String)q.dequeue()+", ");
  }

  if(root.getLeft() != null)
  {
   q.enqueue(root.getLeft().getValue());
   System.out.println();
  }
  if(root.getRight() != null)
  {
   q.enqueue(root.getRight().getValue());
   System.out.println();
   curLev++;
  }

  levelOrder(root.getLeft(),q, curLev);
  levelOrder(root.getRight(),q, curLev);
 }

From what i can figure out, i will need to use the total height of the tree, and use a level counter... Only problem is my level counter keeps counting when my levelOrder uses recursion to go back through the tree.

Sorry if this is to much, but some tips would be nice. :)


问:
How do I make the buttons stay in their position after they have been clicked and opened a submenu
I have 3 buttons that when clicked they open a submenu, but whenever one is clicked, the other ones move in the page, how can i keep them inline whenever one was clicked?
I've tried changing the positions but then they all become change to be on top of each other, any help will be really appreciated so thank you in advance!

Here is my code:

HTML

```<code><button class="menu-trigger btn-1">1</button>
<ul class="menu">
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>
<button class="menu-trigger btn-1">2</button>
<ul class="menu">
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>
<button class="menu-trigger btn-1">3</button>
<ul class="menu">
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>
</code>```

CSS

```<code>.menu-trigger{
    padding: 10px 25px;
    font-family: 'Roboto', sans-serif;
    font-weight: 500;
    background: transparent;
    outline: none;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    display: inline-block;
    color: lightgray;
}

.menu{
    display: none;
}

.menu.open{
    display:block;
}

.btn-1 {
    border: 2px solid yellow;
}

.btn-1:hover {
  background: #000;
  color: #fff;
}
</code>```

JS

```<code> $(function () {
      $(".menu-trigger").click(function () {
        $(this).next(".menu").toggleClass("open"); // Selects only the next one!
        $(this).html($(this).next(".menu").hasClass("open") ? menu-trigger : menu-trigger);
        return false;
      });
    });
</code>```

答:
Try changing:

CSS:

```<code>  .menu{
    position: absolute;
    top: 100px;
    float:left;
    display: none;
   }

.btn-1 {
   float: left;
   border: 2px solid yellow;
 }
</code>```

and in your code:

```<code>$(function () {
  $(".menu-trigger").click(function () {
      $(".menu").hide();
    $(this).next(".menu").toggleClass("open"); // Selects only the next one!
    $(this).next(".menu").show();
    $(this).html($(this).next(".menu").hasClass("open") ? menu-trigger : menu-trigger);
  });
});
</code>```

Body:
I have 3 buttons that when clicked they open a submenu, but whenever one is clicked, the other ones move in the page, how can i keep them inline whenever one was clicked?
I've tried changing the positions but then they all become change to be on top of each other, any help will be really appreciated so thank you in advance!

Here is my code:

HTML

<button class="menu-trigger btn-1">1</button>

test

test

test

<button class="menu-trigger btn-1">2</button>

test

test

test

<button class="menu-trigger btn-1">3</button>

test

test

test

CSS

.menu-trigger{
    padding: 10px 25px;
    font-family: 'Roboto', sans-serif;
    font-weight: 500;
    background: transparent;
    outline: none;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    display: inline-block;
    color: lightgray;
}

.menu{
    display: none;
}

.menu.open{
    display:block;
}

.btn-1 {
    border: 2px solid yellow;
}

.btn-1:hover {
  background: #000;
  color: #fff;
}

JS

 $(function () {
      $(".menu-trigger").click(function () {
        $(this).next(".menu").toggleClass("open"); // Selects only the next one!
        $(this).html($(this).next(".menu").hasClass("open") ? menu-trigger : menu-trigger);
        return false;
      });
    });

Body:
Try changing:

CSS:

  .menu{
    position: absolute;
    top: 100px;
    float:left;
    display: none;
   }

.btn-1 {
   float: left;
   border: 2px solid yellow;
 }

and in your code:

$(function () {
  $(".menu-trigger").click(function () {
      $(".menu").hide();
    $(this).next(".menu").toggleClass("open"); // Selects only the next one!
    $(this).next(".menu").show();
    $(this).html($(this).next(".menu").hasClass("open") ? menu-trigger : menu-trigger);
  });
});


问:
Batch file to run WinSCP runs in command line but not in VBA
If I copy the contents of the bat file and enter directly onto the command line in cmd.exe, the WinSCP SFTP script transfers the file from local directory to SFTP site.  When I run it from this VBA code, I do not get any log files created.  The winscp.bat and winscp.txt files are created. The ErrorCode that is returned is a "1".

Any help would be appreciated.

```<code>Public Sub SFTPUpload()
'Execute the upload commands

'Create the commands file
 Dim ObjFSO As Object
 Dim ObjFile As Object
 Dim ObjShell As Object
 Dim ErrorCode As Integer
 Dim sTempDir As String
 Dim sBat As String
 Dim sType As String
 Dim sUser As String
 Dim sPass As String
 Dim sServer As String
 Dim sHostKey As String
 Dim file As String 'Using your variable name here.
 Dim sLocal As String
 Dim sRemote As String
 Dim sWinSCP As String

 ''''''''''''''''''''''''''''''''''''''''''''
 'Set SFTP Options
 ''''''''''''''''''''''''''''''''''''''''''''
 sTempDir = DataPath & "Log\" 'Log/batch files will be stored here.
 sType = "sftp://"
 sUser = "User"
 sPass = "Name"
 file = DataPath & FileName
 sServer = "sftp.dfsco.int"
 sHostKey = "ssh-rsa 1024 9d:d9:e9:69:db:cf:9c:71:8d:cb:da:a5:cf:a7:41:a7"
 sLocal = file
 sWinSCP = "C:\Program Files (x86)\WinSCP\WinSCP.com"
 If SFTP_USE_TEST_SITE Then
         sRemote = "/Allianz/DFS/CSR/Test/OneToMany/"
     Else
         sRemote = "/Allianz/DFS/CSR/Prod/OneToMany/"
    End If
'''''''''''''''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''''''''''''''
'Create batch file and command script
'''''''''''''''''''''''''''''''''''''''''''''
On Error Resume Next
'Delete existing files
Kill sTempDir & "winscp.txt"
Kill sTempDir & "winscp.bat"
Kill sTempDir & "winscplog.xml"
Kill sTempDir & "winscplog.txt"
On Error GoTo 0

Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Set ObjFile = ObjFSO.CreateTextFile(sTempDir & "winscp.txt", True)
ObjFile.writeline "open " & sType & sUser & ":" & sPass & "@" & sServer &
   "/" & IIf(sHostKey <> vbNullString, " -hostkey=" & Chr(34) & sHostKey &
   Chr(34), vbNullString)
ObjFile.writeline "put " & sLocal & " " & sRemote
ObjFile.writeline "close"
ObjFile.writeline "exit"
ObjFile.Close
Set ObjFile = Nothing
Set ObjFile = ObjFSO.CreateTextFile(sTempDir & "\winscp.bat", True)
ObjFile.writeline sWinSCP & " /script=" & sTempDir & "winscp.txt /log=" &
   sTempDir & "winscplog.txt /xmllog=" & sTempDir & "winscplog.xml /ini=nul
   /loglevel=2"
ObjFile.Close
Set ObjFile = Nothing
Set ObjFSO = Nothing
'''''''''''''''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''''''''''''''
'Execute batch file and process output log
'''''''''''''''''''''''''''''''''''''''''''''
 Set ObjShell = VBA.CreateObject("WScript.Shell")
 sBat = sTempDir & "winscp.bat"
 ErrorCode = ObjShell.Run(sBat, 1, True)
 Set ObjShell = Nothing
 If CheckOutput(sTempDir) <> "All FTP operations completed successfully."
     Then  'MsgBox CheckOutput(sTempDir)
 If ErrorCode > 0 Then
       MsgBox "Excel encountered an error when attempting to run the FTP
       program. Error code: " & ErrorCode
 Else
       MsgBox "One2Many file has been sent to ADMS."
 End If
 '''''''''''''''''''''''''''''''''''''''''''''

Exit_Upload:
    On Error Resume Next
    'Clean up (leave log files)
    Kill sTempDir & "winscp.txt" 'Remove scripting commands (note: this file
       will contain the password)
    Kill sTempDir & "winscp.bat" 'Remove batch file
    'Clear all objects
    Set ObjFSO = Nothing
    Set ObjFile = Nothing
    Set ObjShell = Nothing
    Exit Sub

End Sub

Private Function CheckOutput(sLogDir As String) As String

Dim ObjFSO As Object
Dim ObjFile As Object
Dim StrLog As String

'Open log file
Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Set ObjFile = ObjFSO.OpenTextFile(sLogDir & "winscplog.xml")
StrLog = ObjFile.readall
ObjFile.Close
Set ObjFile = Nothing
Set ObjFSO = Nothing

'Check log file for issues
If InStr(1, StrLog, "<message>Authentication failed.</message>") > 0 Then
     CheckOutput = "The supplied password was rejected by the server. Please
     try again."
 ElseIf InStr(1, StrLog, "<failure>") Then
     If InStr(1, StrLog, "<message>Can't get attributes of file") > 0 Then
         CheckOutput = "The requested file does not exist on the FTP server
 or local folder."
     Else
         CheckOutput = "One or more attempted FTP operations has failed."
     End If
ElseIf InStr(1, StrLog, " <result success=" & Chr(34) & "false" & Chr(34)) > 0
 Then
     CheckOutput = "One or more attempted FTP operations has failed."
 ElseIf InStr(1, StrLog, " <result success=" & Chr(34) & "true" & Chr(34)) = 0
 Then
     CheckOutput = "No FTP operations were performed. This may indicate that
     no files matching the file mask were found."
 End If

 'Enter success message or append log file details.
 If CheckOutput = vbNullString Then
     CheckOutput = "All FTP operations completed successfully."
 Else
     CheckOutput = CheckOutput & vbLf & vbLf & "Please see the below files
     for additional information. Note that passwords are not logged for
    security reasons." & _
    vbLf & "Condensed log: " & sLogDir & "winscplog.xml" & vbLf & "Complete
log: " & sLogDir & "winscplog.txt"
End If

Exit_CheckOutput:
On Error Resume Next
Set ObjFile = Nothing
Set ObjFSO = Nothing
Exit Function

End Function

Sub UpdateStatus(ByVal StepNum As String, ByVal Desc As String)
Dim MyStr As String

MyStr = Now & ": " & StepNum & " - " & Desc
frmEDLBilling.txtStatus = frmEDLBilling.txtStatus & MyStr & vbCrLf
oWS_Log.Cells(Log_Row, 1) = MyStr
Log_Row = Log_Row + 1
DoEvents
End Sub
</code>```

Output for Winscp.bat & winscp.txt is as follows:

```<code>Winscp.bat contains the following:
"C:\Program Files (x86)\WinSCP\WinSCP.com" /script="D:Data\Test\Log\winscp.txt" /log="D:\Data\Test\Log\winscplog.txt" /xmllog="D:\Data\Test\Log\winscplog.xml" /ini=nul

Winscp.txt contains the following:
open sftp://userID:pwd@sftp.dfsco.int/ - hostkey="actual hostkey"
put D:\Data\Test\AZL_ONE2MANY_PDF_MASTER.txt /Allianz/Test/OneToMany/
close
exit
</code>```

答: AND the answer is:  the double quotes around Program files (x86), added them before and after the file paths for /script and /log AND, the last issue I had was that somehow I changed "Program Files (x86)" to "Program Files (x86}". The code is finally working.  Thanks for the tips on how to ask a question and also for pointing me in the right direction on double quotes.  </p>

Body:
If I copy the contents of the bat file and enter directly onto the command line in cmd.exe, the WinSCP SFTP script transfers the file from local directory to SFTP site.  When I run it from this VBA code, I do not get any log files created.  The winscp.bat and winscp.txt files are created. The ErrorCode that is returned is a "1".

Any help would be appreciated.

Public Sub SFTPUpload()
'Execute the upload commands

'Create the commands file
 Dim ObjFSO As Object
 Dim ObjFile As Object
 Dim ObjShell As Object
 Dim ErrorCode As Integer
 Dim sTempDir As String
 Dim sBat As String
 Dim sType As String
 Dim sUser As String
 Dim sPass As String
 Dim sServer As String
 Dim sHostKey As String
 Dim file As String 'Using your variable name here.
 Dim sLocal As String
 Dim sRemote As String
 Dim sWinSCP As String

 ''''''''''''''''''''''''''''''''''''''''''''
 'Set SFTP Options
 ''''''''''''''''''''''''''''''''''''''''''''
 sTempDir = DataPath & "Log\" 'Log/batch files will be stored here.
 sType = "sftp://"
 sUser = "User"
 sPass = "Name"
 file = DataPath & FileName
 sServer = "sftp.dfsco.int"
 sHostKey = "ssh-rsa 1024 9d:d9:e9:69:db:cf:9c:71:8d:cb:da:a5:cf:a7:41:a7"
 sLocal = file
 sWinSCP = "C:\Program Files (x86)\WinSCP\WinSCP.com"
 If SFTP_USE_TEST_SITE Then
         sRemote = "/Allianz/DFS/CSR/Test/OneToMany/"
     Else
         sRemote = "/Allianz/DFS/CSR/Prod/OneToMany/"
    End If
'''''''''''''''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''''''''''''''
'Create batch file and command script
'''''''''''''''''''''''''''''''''''''''''''''
On Error Resume Next
'Delete existing files
Kill sTempDir & "winscp.txt"
Kill sTempDir & "winscp.bat"
Kill sTempDir & "winscplog.xml"
Kill sTempDir & "winscplog.txt"
On Error GoTo 0

Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Set ObjFile = ObjFSO.CreateTextFile(sTempDir & "winscp.txt", True)
ObjFile.writeline "open " & sType & sUser & ":" & sPass & "@" & sServer &
   "/" & IIf(sHostKey <> vbNullString, " -hostkey=" & Chr(34) & sHostKey &
   Chr(34), vbNullString)
ObjFile.writeline "put " & sLocal & " " & sRemote
ObjFile.writeline "close"
ObjFile.writeline "exit"
ObjFile.Close
Set ObjFile = Nothing
Set ObjFile = ObjFSO.CreateTextFile(sTempDir & "\winscp.bat", True)
ObjFile.writeline sWinSCP & " /script=" & sTempDir & "winscp.txt /log=" &
   sTempDir & "winscplog.txt /xmllog=" & sTempDir & "winscplog.xml /ini=nul
   /loglevel=2"
ObjFile.Close
Set ObjFile = Nothing
Set ObjFSO = Nothing
'''''''''''''''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''''''''''''''
'Execute batch file and process output log
'''''''''''''''''''''''''''''''''''''''''''''
 Set ObjShell = VBA.CreateObject("WScript.Shell")
 sBat = sTempDir & "winscp.bat"
 ErrorCode = ObjShell.Run(sBat, 1, True)
 Set ObjShell = Nothing
 If CheckOutput(sTempDir) <> "All FTP operations completed successfully."
     Then  'MsgBox CheckOutput(sTempDir)
 If ErrorCode > 0 Then
       MsgBox "Excel encountered an error when attempting to run the FTP
       program. Error code: " & ErrorCode
 Else
       MsgBox "One2Many file has been sent to ADMS."
 End If
 '''''''''''''''''''''''''''''''''''''''''''''

Exit_Upload:
    On Error Resume Next
    'Clean up (leave log files)
    Kill sTempDir & "winscp.txt" 'Remove scripting commands (note: this file
       will contain the password)
    Kill sTempDir & "winscp.bat" 'Remove batch file
    'Clear all objects
    Set ObjFSO = Nothing
    Set ObjFile = Nothing
    Set ObjShell = Nothing
    Exit Sub

End Sub

Private Function CheckOutput(sLogDir As String) As String

Dim ObjFSO As Object
Dim ObjFile As Object
Dim StrLog As String

'Open log file
Set ObjFSO = CreateObject("Scripting.FileSystemObject")
Set ObjFile = ObjFSO.OpenTextFile(sLogDir & "winscplog.xml")
StrLog = ObjFile.readall
ObjFile.Close
Set ObjFile = Nothing
Set ObjFSO = Nothing

'Check log file for issues
If InStr(1, StrLog, "<message>Authentication failed.</message>") > 0 Then
     CheckOutput = "The supplied password was rejected by the server. Please
     try again."
 ElseIf InStr(1, StrLog, "<failure>") Then
     If InStr(1, StrLog, "<message>Can't get attributes of file") > 0 Then
         CheckOutput = "The requested file does not exist on the FTP server
 or local folder."
     Else
         CheckOutput = "One or more attempted FTP operations has failed."
     End If
ElseIf InStr(1, StrLog, " <result success=" & Chr(34) & "false" & Chr(34)) > 0
 Then
     CheckOutput = "One or more attempted FTP operations has failed."
 ElseIf InStr(1, StrLog, " <result success=" & Chr(34) & "true" & Chr(34)) = 0
 Then
     CheckOutput = "No FTP operations were performed. This may indicate that
     no files matching the file mask were found."
 End If

 'Enter success message or append log file details.
 If CheckOutput = vbNullString Then
     CheckOutput = "All FTP operations completed successfully."
 Else
     CheckOutput = CheckOutput & vbLf & vbLf & "Please see the below files
     for additional information. Note that passwords are not logged for
    security reasons." & _
    vbLf & "Condensed log: " & sLogDir & "winscplog.xml" & vbLf & "Complete
log: " & sLogDir & "winscplog.txt"
End If

Exit_CheckOutput:
On Error Resume Next
Set ObjFile = Nothing
Set ObjFSO = Nothing
Exit Function

End Function

Sub UpdateStatus(ByVal StepNum As String, ByVal Desc As String)
Dim MyStr As String

MyStr = Now & ": " & StepNum & " - " & Desc
frmEDLBilling.txtStatus = frmEDLBilling.txtStatus & MyStr & vbCrLf
oWS_Log.Cells(Log_Row, 1) = MyStr
Log_Row = Log_Row + 1
DoEvents
End Sub

Output for Winscp.bat & winscp.txt is as follows:

Winscp.bat contains the following:
"C:\Program Files (x86)\WinSCP\WinSCP.com" /script="D:Data\Test\Log\winscp.txt" /log="D:\Data\Test\Log\winscplog.txt" /xmllog="D:\Data\Test\Log\winscplog.xml" /ini=nul

Winscp.txt contains the following:
open sftp://userID:pwd@sftp.dfsco.int/ - hostkey="actual hostkey"
put D:\Data\Test\AZL_ONE2MANY_PDF_MASTER.txt /Allianz/Test/OneToMany/
close
exit


问:
There is any limit on how many critical section i can create?
i have a Class that can be accessed on multiple thread.

To make sure i don't have simultaneous access i will use a CCriticalSection

I was wondering if i can just create a CCriticalSectionfor any copy of the object (i think i can have about 100-1000 this object in the program) or it will be best to create a static member CCriticalSection and use this for all the object?

答:
Surely there is a limit, but 1000 is perfectly fine.
But in your case I believe static member is better.

Creating extra objects is the last thing you should do from the performance prospective.


问:
For loop only runs once, despite array having a length of 9
I'm running a while loop inside of a for loop. The array has a length of 9, and I have double checked the length in the program. The for loop should run for each element in the array, but instead only runs for the first element and ends. The while loop on the other hand also uses the length of the array, and runs as expected. The various 'puts' statements show this when you run the code. Why isn't the for loop running 9 times?</p>

```<code>def stock_picker(stock_prices)
  differences = Array.new
  stock_prices.each do |price|
    day = 0
    puts "The for loop is starting"

    while day < stock_prices.length
      puts "The while loop is working"
      puts price
      if price < stock_prices[day]
        puts "The if statement is working"
        difference = stock_prices[day] - price
        puts difference
        differences.push(difference)
        puts differences
      end
      day += 1
    end

    puts "The for loop is ending"

  end
  puts differences
end
</code>```

答:
If you're looking for the best possible trade you can use the combination method to find and test possible buy/sell pairs and use max_by to get the best possible profit:

```<code>def best_theoretical_trade(prices)
  prices.combination(2).max_by do |buy,sell|
    sell - buy
  end
end

best_theoretical_trade([17, 3, 6, 9, 15, 8, 6, 1, 10])
# => [3, 15]
</code>```

Where here buying at 3 and selling at 15 is the optimal strategy.

Body:
I'm running a while loop inside of a for loop. The array has a length of 9, and I have double checked the length in the program. The for loop should run for each element in the array, but instead only runs for the first element and ends. The while loop on the other hand also uses the length of the array, and runs as expected. The various 'puts' statements show this when you run the code. Why isn't the for loop running 9 times?

def stock_picker(stock_prices)
  differences = Array.new
  stock_prices.each do |price|
    day = 0
    puts "The for loop is starting"

    while day < stock_prices.length
      puts "The while loop is working"
      puts price
      if price < stock_prices[day]
        puts "The if statement is working"
        difference = stock_prices[day] - price
        puts difference
        differences.push(difference)
        puts differences
      end
      day += 1
    end

    puts "The for loop is ending"

  end
  puts differences
end

Body:
If you're looking for the best possible trade you can use the combination method to find and test possible buy/sell pairs and use max_by to get the best possible profit:

def best_theoretical_trade(prices)
  prices.combination(2).max_by do |buy,sell|
    sell - buy
  end
end

best_theoretical_trade([17, 3, 6, 9, 15, 8, 6, 1, 10])
# => [3, 15]

Where here buying at 3 and selling at 15 is the optimal strategy.


问:
Form Controls difference in using .shapes and using .buttons in code?
I have put several buttons in this macro and everything works great and looks great but I had a question about the code. As you can see down below, in this snippet of code, while using With Activesheet, the code then uses .Shapes AND .BUTTONS. It looks like .Shapes has more to do with sizing the button after it has been placed? and .BUTTONS has more to do with what it looks like and what it does?

I am just wondering what the difference in these are because at one point I use .BUTTONS to add the buttons, and then I use .shapes to change the size of the buttons. But then I use .Shapes to tell it what to do OnAction when clicked instead of .BUTTONS. What exactly is the difference in these properties? (or whatever it is called I am not sure) It just seems like they kind of intertwine and I am not too sure which to use and when.

```<code>With Activesheet
    .BUTTONS.Add(53.25, 36.75, 190.5, 41.25).Select
    .Shapes("Button 6").IncrementLeft 222.75
    .Shapes("Button 6").IncrementTop 147
    .BUTTONS("Button 6").Text = "Mexmo MFG"

    .BUTTONS("Button 10").Text = "10"
    .BUTTONS("Button 10").name = "Button 10"
    .BUTTONS("Button 11").Text = "11"
    .BUTTONS("Button 11").name = "Button 11"
    .BUTTONS("Button 12").Text = "12"
    .BUTTONS("Button 12").name = "Button 12"

    .Shapes("Atlanta MFG").OnAction = "Atlanta"
    .Shapes("Denver MFG").OnAction = "Denver"
    .Shapes("Jackson MFG").OnAction = "Jackson"
    .Shapes("Louisville MFG").OnAction = "Louisville"
End With
</code>```

答:
Some properties are only available and could be tweaked using Shape object only. That is why your code has Buttons and Shapes collections.

Most of the objects that inherit from Shapes usually exposes ShapeRange property that returns the Shape object. You can simply use that and access all the related properties.

Example:

```<code>Sub test()
    With ActiveSheet
    .Buttons.Add(53.25, 36.75, 190.5, 41.25).Select
    .Shapes("Button 6").IncrementLeft 222.75

    '/ This works same as Shapes("Button 6")
    .Buttons("Button 6").ShapeRange.IncrementTop 147

    .Shapes("Button 6").IncrementTop 147
    End With
End Sub
</code>```

Body:
I have put several buttons in this macro and everything works great and looks great but I had a question about the code. As you can see down below, in this snippet of code, while using With Activesheet, the code then uses .Shapes AND .BUTTONS. It looks like .Shapes has more to do with sizing the button after it has been placed? and .BUTTONS has more to do with what it looks like and what it does?

I am just wondering what the difference in these are because at one point I use .BUTTONS to add the buttons, and then I use .shapes to change the size of the buttons. But then I use .Shapes to tell it what to do OnAction when clicked instead of .BUTTONS. What exactly is the difference in these properties? (or whatever it is called I am not sure) It just seems like they kind of intertwine and I am not too sure which to use and when.

With Activesheet
    .BUTTONS.Add(53.25, 36.75, 190.5, 41.25).Select
    .Shapes("Button 6").IncrementLeft 222.75
    .Shapes("Button 6").IncrementTop 147
    .BUTTONS("Button 6").Text = "Mexmo MFG"

    .BUTTONS("Button 10").Text = "10"
    .BUTTONS("Button 10").name = "Button 10"
    .BUTTONS("Button 11").Text = "11"
    .BUTTONS("Button 11").name = "Button 11"
    .BUTTONS("Button 12").Text = "12"
    .BUTTONS("Button 12").name = "Button 12"

    .Shapes("Atlanta MFG").OnAction = "Atlanta"
    .Shapes("Denver MFG").OnAction = "Denver"
    .Shapes("Jackson MFG").OnAction = "Jackson"
    .Shapes("Louisville MFG").OnAction = "Louisville"
End With

Body:
Some properties are only available and could be tweaked using Shape object only. That is why your code has Buttons and Shapes collections.

Most of the objects that inherit from Shapes usually exposes ShapeRange property that returns the Shape object. You can simply use that and access all the related properties.

Example:

Sub test()
    With ActiveSheet
    .Buttons.Add(53.25, 36.75, 190.5, 41.25).Select
    .Shapes("Button 6").IncrementLeft 222.75

    '/ This works same as Shapes("Button 6")
    .Buttons("Button 6").ShapeRange.IncrementTop 147

    .Shapes("Button 6").IncrementTop 147
    End With
End Sub


问:
Animate classes as they come into view
I'm trying to fadeIn my div blocks one-at-a-time as the block scrolls into view, they would then fadeOut when almost out of view.

So far I have achieved this using JQuery Waypoints, However all the blocks fadeIn and out at once, this is because I'm targeting the class.

See my code:

```<code>// scrolling down
$portfolioRow.waypoint(function(direction) {
    if (direction === 'down') {
        $($portfolioRow).find(".portfolio-block-text").removeClass('no-opacity');
    }
}, { offset: '50%' });

// scrolling up
$portfolioRow.waypoint(function(direction) {
    if (direction === 'up') {
        $($portfolioRow).find(".portfolio-block-text").addClass('no-opacity');
    }
}, { offset: '90%' });
</code>```

答:
Inside the Waypoints handler you should be able to access the individual waypoint element using this.element.

Try changing:

```<code>$($portfolioRow).find( etc.
</code>```

to:

```<code>$(this.element).find( etc.
</code>```

Here is a Fiddle: https://jsfiddle.net/me7ye126/

My fiddle uses vanilla JS Waypoints syntax (I couldn't get Waypoints jQuery syntax to work in JSFiddle for some reason), but $(this.element) should work either way.

Title: Animate classes as they come into view

Body:
I'm trying to fadeIn my div blocks one-at-a-time as the block scrolls into view, they would then fadeOut when almost out of view.

So far I have achieved this using JQuery Waypoints, However all the blocks fadeIn and out at once, this is because I'm targeting the class.

See my code:

// scrolling down
$portfolioRow.waypoint(function(direction) {
    if (direction === 'down') {
        $($portfolioRow).find(".portfolio-block-text").removeClass('no-opacity');
    }
}, { offset: '50%' });

// scrolling up
$portfolioRow.waypoint(function(direction) {
    if (direction === 'up') {
        $($portfolioRow).find(".portfolio-block-text").addClass('no-opacity');
    }
}, { offset: '90%' });

Body:
Inside the Waypoints handler you should be able to access the individual waypoint element using this.element.

Try changing:

$($portfolioRow).find( etc.

to:

$(this.element).find( etc.

Here is a Fiddle: https://jsfiddle.net/me7ye126/

My fiddle uses vanilla JS Waypoints syntax (I couldn't get Waypoints jQuery syntax to work in JSFiddle for some reason), but $(this.element) should work either way.


问:
Reading a `BLOB` via JDBC takes too long
When I read an image from database, it appears in the JLabel immediately, but it takes too much time to complete streaming the BLOB from the DB.

```<code>public byte[] selectImage(int Id) throws SQLException {
    ResultSet res=null;
    int c=0;

    try {
        Class.forName(driver);
        con = DriverManager.getConnection(connectionURL);
    } catch (SQLException ex) {
        Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println(con.getAutoCommit());

    statement = con.createStatement() ;
    res = statement.executeQuery("SELECT PHOTO FROM CUSTOMER where ID="+Id) ;

    while(res.next() && (res!=null)) {
        Blob bodyOut = res.getBlob("PHOTO");
        int length = (int) bodyOut.length();
        System.out.println("   Body Size = "+length);
        imageBytes = bodyOut.getBytes(1, length);
        bodyOut.free();
    }

    return imageBytes;
}
</code>```

答:
Consider storing the image outside of the database. Only store enough info in the DB to let you find the file (either on the filesystem, or from an HTTP server, or however you're storing it now that it's not in the DB). Binary data isn't really the use case that an RDBMS is optimized to handle.

Also, your code has some serious problems:

The biggest problem is probably the security flaw you get by failing to use bind variables, a.k.a. a PreparedStatement in Java. This is SQL injection 101.

you're using raw JDBC. Raw JDBC is tedious and easy to mess up. For instance, you aren't closing your ResultSet or your Connection, not to mention the statement variable, which should definitely be local. And when you do start closing them, you should do it in a finally block to make sure it always happens, even if there is an error.

If you happen to get more than one result from your query—I'm guessing you shouldn't, but just in case—you will only know if you happen to look at STDOUT, and you'll just get the last image. Your while loop is probably better expressed as an if to indicate that you only expect and/or care about the first result. If you care if there is more than one results, you should probably use an if instead of a while, then add a subsequent if (rs.next()) throw new MyAppropriatelyNamedException; so you know that there is something unexpected going on.

The null check for res is worthless. By the time you execute the check, the rs.next() statement will have already thrown a NullPointerException. You should probably just delete the check.

Why are you using the logging framework, only to turn around and use System.out.println to output some debugging info?

Body:
When I read an image from database, it appears in the JLabel immediately, but it takes too much time to complete streaming the BLOB from the DB.

public byte[] selectImage(int Id) throws SQLException {
    ResultSet res=null;
    int c=0;

    try {
        Class.forName(driver);
        con = DriverManager.getConnection(connectionURL);
    } catch (SQLException ex) {
        Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println(con.getAutoCommit());

    statement = con.createStatement() ;
    res = statement.executeQuery("SELECT PHOTO FROM CUSTOMER where ID="+Id) ;

    while(res.next() && (res!=null)) {
        Blob bodyOut = res.getBlob("PHOTO");
        int length = (int) bodyOut.length();
        System.out.println("   Body Size = "+length);
        imageBytes = bodyOut.getBytes(1, length);
        bodyOut.free();
    }

    return imageBytes;
}


问:
Swift how to tell when a variable changed in a shared instance
I have a variable in a singleton pattern that is used/referenced through out the app.

I have a mainVC that has a custom view in it that sets a variable.  I want the view controller that is presented in the navigation controller to be notified when this variable changes.

For example:

in my mainVC it has an embedded navigation controller, which I push View1.  On the mainVC toolbar, there is a textfield that the user can enter values.  When this values changes, I would like to have View1 to know it has changed.  View1 can be any view that is currently presented.

答:
I wanted to add to @matt 's comment, KVO is one way to go about your solution, and from your question I think it would be the best way.  You can use the "normal" KVO which is what I implement when using it that @matt linked to.

BUT, I did find a new way that KVO can be set up that I didn't know before so I wanted to share it:

```<code>var testString: String = "Hello World" {
    //After setting
    didSet {
      // Code you want to execute after a new value is set
    }

    //Prior to setting
    willSet {
      // Code you want to execute right before setting a new value
    }
}
</code>```

I seen this while reading this article: KVO and Lazy Stored Properties

Body:
I wanted to add to @matt 's comment, KVO is one way to go about your solution, and from your question I think it would be the best way.  You can use the "normal" KVO which is what I implement when using it that @matt linked to.

BUT, I did find a new way that KVO can be set up that I didn't know before so I wanted to share it:

var testString: String = "Hello World" {
    //After setting
    didSet {
      // Code you want to execute after a new value is set
    }

    //Prior to setting
    willSet {
      // Code you want to execute right before setting a new value
    }
}

I seen this while reading this article: KVO and Lazy Stored Properties


问:
Compute data from an array with VueJS
I want to compute data from my json with vueJS

The data are like this

json from my api

```<code>[
    {
        "id": 4,
        "votes": 0
    },
    {
        "id": 3,
        "votes": 1
    },
]
</code>```

To fetch and render this data I am using this vueJS file

app.js

```<code>const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  mounted() {
    axios.get("http://example.com/votes.json")
    .then(response => {this.results = response.data})
  },
});
</code>```

Now I want to create a vue variable to display the total of votes in my index.html

index.html

```<code><div v-for="result in results">
    <p>Votes {{ result.votes }}.</p>
    <p>Id : {{ result.id }}</p>
</div>
<div>
    <p>Total of votes : {{ resultsVotes }}</p>
</div>
</code>```

答:
If the question is how to compute resultVotes, computed value is recommended:

```<code>const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  computed: {
    resultVotes () {
      return this.results.reduce((sum, val) => sum + val.votes, 0);
    }
  },
  mounted() {
    axios.get("http://example.com/votes.json")
    .then(response => {this.results = response.data})
  },
});
</code>```

Title: Compute data from an array with VueJS

Body:
I want to compute data from my json with vueJS

The data are like this

json from my api

[
    {
        "id": 4,
        "votes": 0
    },
    {
        "id": 3,
        "votes": 1
    },
]

To fetch and render this data I am using this vueJS file

app.js

const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  mounted() {
    axios.get("http://example.com/votes.json")
    .then(response => {this.results = response.data})
  },
});

Now I want to create a vue variable to display the total of votes in my index.html

index.html

Votes {{ result.votes }}.

Id : {{ result.id }}

Total of votes : {{ resultsVotes }}

Body:
If the question is how to compute resultVotes, computed value is recommended:

const vm = new Vue({
  el: '#app',
  data: {
    results: []
  },
  computed: {
    resultVotes () {
      return this.results.reduce((sum, val) => sum + val.votes, 0);
    }
  },
  mounted() {
    axios.get("http://example.com/votes.json")
    .then(response => {this.results = response.data})
  },
});


问:
Undefined symbol error: the target library has been set in rpath but it still cannot be found
```<code>calving@norfolk:~/sandbox/stage/third_party/houdini16.5/lib$ ldd libgusd.so | grep boost
    libboost_python.so.1.55.0 => /home/calveng/sandbox/stage/third_party/houdini16.5/lib/./../../../lib/libboost_python.so.1.55.0 (0x00007f735cb9c000)
    libboost_regex.so.1.55.0 => /home/calveng/sandbox/stage/third_party/houdini16.5/lib/./../../../lib/./libboost_regex.so.1.55.0 (0x00007f735af6a000)
calving@norfolk:~/sandbox/stage/third_party/houdini16.5/lib$ readelf -s --wide libgusd.so | grep _ZN5boost6system16generic_categoryEv
    1064: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND _ZN5boost6system16generic_categoryEv
    6632: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND _ZN5boost6system16generic_categoryEv
</code>```

Once I try to link this "libgusd.so" library, it will throw an error: "undefined symbol: _ZN5boost6system16generic_categoryEv"

But the point is the path which including boost has already been set by an embedded rpath, and some other boost file can be linked properly.

Does anybody ran into similar condition before? Any prompt would be really helpful.

TIPS: There isn't a LD_LIBRARY_PATH in my environment, so no overwritten.

答:
Well, it solved by:

patchelf --add-needed libboost_system.so.1.55.0 libgusd.so

I guess I still a little confusing about the difference between linked-libraries and their paths... I thought all of the dynamic libraries will be linked automatically once the program needs them.

Body:
calving@norfolk:~/sandbox/stage/third_party/houdini16.5/lib$ ldd libgusd.so | grep boost
    libboost_python.so.1.55.0 => /home/calveng/sandbox/stage/third_party/houdini16.5/lib/./../../../lib/libboost_python.so.1.55.0 (0x00007f735cb9c000)
    libboost_regex.so.1.55.0 => /home/calveng/sandbox/stage/third_party/houdini16.5/lib/./../../../lib/./libboost_regex.so.1.55.0 (0x00007f735af6a000)
calving@norfolk:~/sandbox/stage/third_party/houdini16.5/lib$ readelf -s --wide libgusd.so | grep _ZN5boost6system16generic_categoryEv
    1064: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND _ZN5boost6system16generic_categoryEv
    6632: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND _ZN5boost6system16generic_categoryEv

Once I try to link this "libgusd.so" library, it will throw an error: "undefined symbol: _ZN5boost6system16generic_categoryEv"

But the point is the path which including boost has already been set by an embedded rpath, and some other boost file can be linked properly.

Does anybody ran into similar condition before? Any prompt would be really helpful.

TIPS: There isn't a LD_LIBRARY_PATH in my environment, so no overwritten.


问:
How to open specific contact chat screen in various popular chat/social-networks apps?

Background

I've found that there is a way to open a specific contact conversation screen on WhatsApp, here .

Not only that, but I've found that an app called "Drupe" does the same, and maybe even more :

https://lh3.googleusercontent.com/EQrs1jplMlP8SkOTdpqT4NzmgzGa5Wz2qageG1Pkjc6rKg0HBb-rwlOVW07_G7bAWgo=h900

The problem

I can't find any official API of opening it this way, so I'm not sure how safe it is.

I've found SDKs, but not intents instructions.

The questions

I'd like to know more about what's available for various social-networks and chatting apps :

WhatsApp

Facebook Messenger

Viber

Line

Telegram

Hangouts

Possible features may be:

open the conversation of a contact, when input is his phone number

have a new text that will be ready to be sent in the new screen

for Facebook, maybe also be able to open using the Facebook-ID of the person (meaning this is the input), instead of a phone number.

Are such features available for each of those social networks and chatting apps?

答:
Other posts here have good information. I wanted to add for LINE because the information is lacking in many places.</p>

```<code>String userId = findUserId();
String sendText = "line://ti/p/~" + userId;
Intent intent = null;
try {
    intent = Intent.parseUri(sendText, Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException e) {
    e.printStackTrace();
}
startActivity(intent);
</code>```

Body:
Other posts here have good information. I wanted to add for LINE because the information is lacking in many places.

String userId = findUserId();
String sendText = "line://ti/p/~" + userId;
Intent intent = null;
try {
    intent = Intent.parseUri(sendText, Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException e) {
    e.printStackTrace();
}
startActivity(intent);


问:
Stream to String in Jdom
How to preserve white space in jdom?

i get the below error:

org.jdom.JDOMException: Error on line 1: Content is not allowed in prolog

This is my code, kindly tell the solution for this code...

```<code>import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

import java.io.*;
import java.lang.*;

public class JDOM_XML_TEST {
    Document m_doc = null;
    public Element elmEHResponse = null;
    String sEHResponseXml = "";
    String sOperationType = "Edit";
    static String s_return = "";
    StringBuffer strbuffer = null;
    String sParamsXml_1 = "<VWPortal>" + "<EHResponse Type='" + "  test    CustomObject" + "' ProgLangId='" + "1" + "'>" + "<Signature>public void Item1_ButtonClick_RESP1(Context ObjContextParam, string sPortlet, string sPortletInstanceId, CILPrtlDataset objCILPrtlDataset)</Signature></EHResponse><ResultType>Result</ResultType></VWPortal>";
    //String sParamsXml ="public String   Display_Test(){"     "String s ='Welcome';"    "return s;      }";

    public static void main(String[] args) {
        JDOM_XML_TEST xml_test = new JDOM_XML_TEST();
        s_return = xml_test.getXml();
        //System.out.println("Value is:::"+s_return);
    }

    public String getXml() {
        try {
            if (!sOperationType.equalsIgnoreCase("Delete")) {
                SAXBuilder builder = new SAXBuilder(false);
                //Commended for CustomObject
                //doc = builder.build(new ByteArrayInputStream(sParamsXml.getBytes("UTF-8")));

                //For CustomObject Alignment
                strbuffer = new StringBuffer();
                strbuffer.append("public String   Display_Test(){ \n");
                strbuffer.append("\t\t\tString s ='Welcome'; \n");
                strbuffer.append("\t\t\t return s;  \n");
                strbuffer.append("}");

                sEHResponseXml = strbuffer.toString();
                System.out.println("Value of sEHResponseXml:::" + sEHResponseXml);

                builder.setIgnoringElementContentWhitespace(true);
                m_doc = builder.build(new ByteArrayInputStream(sEHResponseXml.getBytes("UTF-8")));
                elmEHResponse = m_doc.getRootElement();

                System.out.println("Value of elmEHResponse in before:::" + elmEHResponse);
                XMLOutputter Out = new XMLOutputter();
                sEHResponseXml = Out.outputString(elmEHResponse);

                System.out.println("Value of elmEHResponse in after:::" + sEHResponseXml);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

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

答: This error is not related to preserving whitespace in your XML but some extra bytes before the start of your xml content. Use NotePad++ (or BBEdit etc) and check if there any extra characters at the start of your xml doc. Also post your XML here.</p>

Title: Stream to String in Jdom

Body:
How to preserve white space in jdom?

i get the below error:

org.jdom.JDOMException: Error on line 1: Content is not allowed in prolog

This is my code, kindly tell the solution for this code...

import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

import java.io.*;
import java.lang.*;

public class JDOM_XML_TEST {
    Document m_doc = null;
    public Element elmEHResponse = null;
    String sEHResponseXml = "";
    String sOperationType = "Edit";
    static String s_return = "";
    StringBuffer strbuffer = null;
    String sParamsXml_1 = "<VWPortal>" + "<EHResponse Type='" + "  test    CustomObject" + "' ProgLangId='" + "1" + "'>" + "<Signature>public void Item1_ButtonClick_RESP1(Context ObjContextParam, string sPortlet, string sPortletInstanceId, CILPrtlDataset objCILPrtlDataset)</Signature></EHResponse><ResultType>Result</ResultType></VWPortal>";
    //String sParamsXml ="public String   Display_Test(){"     "String s ='Welcome';"    "return s;      }";

    public static void main(String[] args) {
        JDOM_XML_TEST xml_test = new JDOM_XML_TEST();
        s_return = xml_test.getXml();
        //System.out.println("Value is:::"+s_return);
    }

    public String getXml() {
        try {
            if (!sOperationType.equalsIgnoreCase("Delete")) {
                SAXBuilder builder = new SAXBuilder(false);
                //Commended for CustomObject
                //doc = builder.build(new ByteArrayInputStream(sParamsXml.getBytes("UTF-8")));

                //For CustomObject Alignment
                strbuffer = new StringBuffer();
                strbuffer.append("public String   Display_Test(){ \n");
                strbuffer.append("\t\t\tString s ='Welcome'; \n");
                strbuffer.append("\t\t\t return s;  \n");
                strbuffer.append("}");

                sEHResponseXml = strbuffer.toString();
                System.out.println("Value of sEHResponseXml:::" + sEHResponseXml);

                builder.setIgnoringElementContentWhitespace(true);
                m_doc = builder.build(new ByteArrayInputStream(sEHResponseXml.getBytes("UTF-8")));
                elmEHResponse = m_doc.getRootElement();

                System.out.println("Value of elmEHResponse in before:::" + elmEHResponse);
                XMLOutputter Out = new XMLOutputter();
                sEHResponseXml = Out.outputString(elmEHResponse);

                System.out.println("Value of elmEHResponse in after:::" + sEHResponseXml);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sEHResponseXml;
    }
}


答:
I would create a didSet value observer on that variable. Then when any ViewController willappear, set the delegate to self. And track the changes of that variable on the ViewController.

Each ViewController should do:

```<code>class ViewController: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        Singleton.shared.delegate = self
    }
}

extension ViewController: SingletonDelegate {
    func variableDidChange(newVariableValue value: Int) {
    //here u get value if changed
    }
}
</code>```

And the Singleton with your variable and protocol

```<code>protocol SingletonDelegate: class {
    func variableDidChange(newVariableValue value: Int)
}

class Singleton {

    var variable:Int = 0 {
       didSet {
          delegate?.variableDidChange(newVariableValue: variable)
       }
    }

    private init() {}
    weak var delegate: SingletonDelegate?

    static let shared = Singleton()
}
</code>```

PD: notice this way only the top ViewController in the navigation will handle the newValue event.

Title: Swift how to tell when a variable changed in a shared instance

Body:
I have a variable in a singleton pattern that is used/referenced through out the app.

I have a mainVC that has a custom view in it that sets a variable.  I want the view controller that is presented in the navigation controller to be notified when this variable changes.

For example:

in my mainVC it has an embedded navigation controller, which I push View1.  On the mainVC toolbar, there is a textfield that the user can enter values.  When this values changes, I would like to have View1 to know it has changed.  View1 can be any view that is currently presented.

Body:
I would create a didSet value observer on that variable. Then when any ViewController willappear, set the delegate to self. And track the changes of that variable on the ViewController.

Each ViewController should do:

class ViewController: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        Singleton.shared.delegate = self
    }
}

extension ViewController: SingletonDelegate {
    func variableDidChange(newVariableValue value: Int) {
    //here u get value if changed
    }
}

And the Singleton with your variable and protocol

protocol SingletonDelegate: class {
    func variableDidChange(newVariableValue value: Int)
}

class Singleton {

    var variable:Int = 0 {
       didSet {
          delegate?.variableDidChange(newVariableValue: variable)
       }
    }

    private init() {}
    weak var delegate: SingletonDelegate?

    static let shared = Singleton()
}

PD: notice this way only the top ViewController in the navigation will handle the newValue event.

ContentLicense: CC BY-SA 4.0


问:
QThreadPool maxThreadCount different in Application and DLL
When using QThreadPool::globalInstance() in an application I can set the maximum number of threads to a number (say 50 for this example)

```<code>QThreadPool::globalInstance()->setMaxThreadCount(50);
</code>```

Which later we can query within that same application and 50 will be returned. However, if QThreadPool::maxThreadCount() is queried from within a DLL called by that same application, it returns that the maximum thread count is only 12. I can then increase the maxThreadCount in the library to be any number I would like, separate from the applications maxThreadCount number.

So is the QThreadPool::globalInstance only global to the independent application and libraries somehow? Why wouldn't a Qt DLL and application that share the same process not have the same global QThreadPool?

答:
Looking at the implementation of QThreadPool https://code.woboq.org/qt5/qtbase/src/corelib/global/qglobalstatic.h.html#158
we can see that :

```<code>QThreadPool *QThreadPool::globalInstance()
    {
        return theInstance();
    }
</code>```

which is defined here https://code.woboq.org/qt5/qtbase/src/corelib/thread/qthreadpool.cpp.html#50

```<code> Q_GLOBAL_STATIC(QThreadPool, theInstance)
</code>```

From here, if for some obscure reason your dll and your exec are not linked with the exact same Qt core dll, you would get the problem

Body:
When using QThreadPool::globalInstance() in an application I can set the maximum number of threads to a number (say 50 for this example)

QThreadPool::globalInstance()->setMaxThreadCount(50);

Which later we can query within that same application and 50 will be returned. However, if QThreadPool::maxThreadCount() is queried from within a DLL called by that same application, it returns that the maximum thread count is only 12. I can then increase the maxThreadCount in the library to be any number I would like, separate from the applications maxThreadCount number.

So is the QThreadPool::globalInstance only global to the independent application and libraries somehow? Why wouldn't a Qt DLL and application that share the same process not have the same global QThreadPool?

Body:
Looking at the implementation of QThreadPool https://code.woboq.org/qt5/qtbase/src/corelib/global/qglobalstatic.h.html#158
we can see that :

QThreadPool *QThreadPool::globalInstance()
    {
        return theInstance();
    }

which is defined here https://code.woboq.org/qt5/qtbase/src/corelib/thread/qthreadpool.cpp.html#50

 Q_GLOBAL_STATIC(QThreadPool, theInstance)

From here, if for some obscure reason your dll and your exec are not linked with the exact same Qt core dll, you would get the problem