问:
Surprising behaviour of Python date and timedelta subtraction
I am trying to do some Python date and timedelta maths and stumbled upon this.

```<code>>>> import datetime
>>> dt = datetime.date(2000, 4, 20)
>>> td = datetime.timedelta(days=1)
>>> dt - td
datetime.date(2000, 4, 19)
>>> -(td) + dt
datetime.date(2000, 4, 19)
>>> dt - td == dt + (-td)
True
</code>```

So far so good, but when the timedelta also includes some hours it gets interesting.

```<code>>>> td = datetime.timedelta(days=1, hours=1)
>>> dt - td
datetime.date(2000, 4, 19)
>>> -(td) + dt
datetime.date(2000, 4, 18)
</code>```

or in a comparison:

```<code>>>> dt - td == dt + (-td)
False
</code>```

I would have expected that a - b == a + (-b), but this doesn't seem to work for date and timedelta. As far as I was able to track that down, this happens because adding/subtracting date and timedelta only considers the days field of timedelta, which is probably correct. However negating a timedelta considers all fields and may change the days field as well.

```<code>>>> -datetime.timedelta(days=1)
datetime.timedelta(-1)
>>> -datetime.timedelta(days=1, hours=1)
datetime.timedelta(-2, 82800)
</code>```

As can be seen in the second example, days=-2 after the negation, and therefore date + timedelta will actually subtract 2 days.

Should this be considered a bug in the python datetime module? Or is this rather some 'normal' behaviour which needs to be taken into account when doing things like that?

Internally the datetime module creates a new timedelta, with just the days field of the original timedelta object passed in, when subtracting a timedelta to a date object. Which equates to following, code that seems to be quite odd.

```<code>>>> dt + datetime.timedelta(-(-(-dt).days))
datetime.date(2000, 4, 18)
</code>```

I can't really sea a reason for just using the negated days field when doing date - timedelta subtractions.

Edit:

Here is the relevant code path in python datetime module:

```<code>class date:

    ...

    def __sub__(self, other):
        """Subtract two dates, or a date and a timedelta."""
        if isinstance(other, timedelta):
           return self + timedelta(-other.days)
        ...
</code>```

If it would just pass on -other then the condition a - b == a + (-b) would hold true. (It would change current behaviour though).

```<code>class date:

    ...

    def __sub__(self, other):
        """Subtract two dates, or a date and a timedelta."""
        if isinstance(other, timedelta):
           return self - other  # timedelta.__rsub__ would take care of negating other
        ...
</code>```

答:
This is because of the way how negative timedeltas are represented.

```<code>import datetime
td = datetime.timedelta(days=1, hours=1)
print (td.days, td.seconds)
# prints 1 3600
minus_td = -td
print (minus_td.days, minus_td.seconds)
# prints -2 82800
</code>```

I hope you now better understand why days were affected.

Seconds in a timedelta are always normalized to a positive amount between 0 and 86399:

```<code>>>> print (datetime.timedelta(seconds=-10).seconds)
86390
</code>```

Body:
I am trying to do some Python date and timedelta maths and stumbled upon this.

>>> import datetime
>>> dt = datetime.date(2000, 4, 20)
>>> td = datetime.timedelta(days=1)
>>> dt - td
datetime.date(2000, 4, 19)
>>> -(td) + dt
datetime.date(2000, 4, 19)
>>> dt - td == dt + (-td)
True

So far so good, but when the timedelta also includes some hours it gets interesting.

>>> td = datetime.timedelta(days=1, hours=1)
>>> dt - td
datetime.date(2000, 4, 19)
>>> -(td) + dt
datetime.date(2000, 4, 18)

or in a comparison:

>>> dt - td == dt + (-td)
False

I would have expected that a - b == a + (-b), but this doesn't seem to work for date and timedelta. As far as I was able to track that down, this happens because adding/subtracting date and timedelta only considers the days field of timedelta, which is probably correct. However negating a timedelta considers all fields and may change the days field as well.

>>> -datetime.timedelta(days=1)
datetime.timedelta(-1)
>>> -datetime.timedelta(days=1, hours=1)
datetime.timedelta(-2, 82800)

As can be seen in the second example, days=-2 after the negation, and therefore date + timedelta will actually subtract 2 days.

Should this be considered a bug in the python datetime module? Or is this rather some 'normal' behaviour which needs to be taken into account when doing things like that?

Internally the datetime module creates a new timedelta, with just the days field of the original timedelta object passed in, when subtracting a timedelta to a date object. Which equates to following, code that seems to be quite odd.

>>> dt + datetime.timedelta(-(-(-dt).days))
datetime.date(2000, 4, 18)

I can't really sea a reason for just using the negated days field when doing date - timedelta subtractions.

Edit:

Here is the relevant code path in python datetime module:

class date:

    ...

    def __sub__(self, other):
        """Subtract two dates, or a date and a timedelta."""
        if isinstance(other, timedelta):
           return self + timedelta(-other.days)
        ...

If it would just pass on -other then the condition a - b == a + (-b) would hold true. (It would change current behaviour though).

class date:

    ...

    def __sub__(self, other):
        """Subtract two dates, or a date and a timedelta."""
        if isinstance(other, timedelta):
           return self - other  # timedelta.__rsub__ would take care of negating other
        ...

Body:
This is because of the way how negative timedeltas are represented.

import datetime
td = datetime.timedelta(days=1, hours=1)
print (td.days, td.seconds)
# prints 1 3600
minus_td = -td
print (minus_td.days, minus_td.seconds)
# prints -2 82800

I hope you now better understand why days were affected.

Seconds in a timedelta are always normalized to a positive amount between 0 and 86399:

>>> print (datetime.timedelta(seconds=-10).seconds)
86390


来源: stackexchange

问:
OpenScoring + PMML
I'm building a new rule engine using PMML.
I have read quite a bit and would like to know if anyone can give me some pros/cons for using OpenScoring (http://openscoring.io/)? Or some performance statistics?
I have both real-time and batch processes requesting models that are going to query for scores.

Thanks,

答:
The datapoint shared in https://news.ycombinator.com/item?id=13821217 suggests that OpenScoring is reasonably scalable. To quote -

Dataset size in the hundred millions of examples with hundreds of features.
  Handled thousands of requests per second, no problem.

(Somewhat tangentially to the question, but hopefully useful) - I concur with the author that PMML itself is somewhat limiting in expressive power.

ContentLicense: CC BY-SA 3.0

Title: OpenScoring + PMML


问:
sass --interactive returns FormatException: Could not find an option named "interactive"
I've get a FormatException error every time i try to invoke the sass interactive shell. Please does anyone know the reason for this and how it can be resolved. i've tried googling but all i get is syntax errors and nothing about this. please find below the error message returned.
thanks in advance for your help.</p>

```<code> my_username$ sass --interactive
/usr/local/lib/node_modules/sass/sass.dart.js:1436
if(this===init.globalState.e)throw u}}finally{this.cy=x
                             ^

FormatException: Could not find an option named "interactive".
    at b (/usr/local/lib/node_modules/sass/sass.dart.js:1916:3)
    at q (/usr/local/lib/node_modules/sass/sass.dart.js:1922:23)
    at iu.fo (/usr/local/lib/node_modules/sass/sass.dart.js:6358:14)
    at iu.aC (/usr/local/lib/node_modules/sass/sass.dart.js:6256:9)
    at /usr/local/lib/node_modules/sass/sass.dart.js:8058:42
    at uM.a (/usr/local/lib/node_modules/sass/sass.dart.js:3050:72)
    at uM.dart.uM.$2 (/usr/local/lib/node_modules/sass/sass.dart.js:3146:24)
    at tU.dart.tU.$1 (/usr/local/lib/node_modules/sass/sass.dart.js:3142:31)
    at tn.fv (/usr/local/lib/node_modules/sass/sass.dart.js:3380:41)
    at qv.$0 (/usr/local/lib/node_modules/sass/sass.dart.js:3329:16)
</code>```

答: It looks like you're using Dart Sass, which doesn't (currently) support the --interactive flag. Feel free to file a feature request, though!

Body:
I've get a FormatException error every time i try to invoke the sass interactive shell. Please does anyone know the reason for this and how it can be resolved. i've tried googling but all i get is syntax errors and nothing about this. please find below the error message returned.
thanks in advance for your help.

 my_username$ sass --interactive
/usr/local/lib/node_modules/sass/sass.dart.js:1436
if(this===init.globalState.e)throw u}}finally{this.cy=x
                             ^

FormatException: Could not find an option named "interactive".
    at b (/usr/local/lib/node_modules/sass/sass.dart.js:1916:3)
    at q (/usr/local/lib/node_modules/sass/sass.dart.js:1922:23)
    at iu.fo (/usr/local/lib/node_modules/sass/sass.dart.js:6358:14)
    at iu.aC (/usr/local/lib/node_modules/sass/sass.dart.js:6256:9)
    at /usr/local/lib/node_modules/sass/sass.dart.js:8058:42
    at uM.a (/usr/local/lib/node_modules/sass/sass.dart.js:3050:72)
    at uM.dart.uM.$2 (/usr/local/lib/node_modules/sass/sass.dart.js:3146:24)
    at tU.dart.tU.$1 (/usr/local/lib/node_modules/sass/sass.dart.js:3142:31)
    at tn.fv (/usr/local/lib/node_modules/sass/sass.dart.js:3380:41)
    at qv.$0 (/usr/local/lib/node_modules/sass/sass.dart.js:3329:16)


问:
Convert OpenCV keypoints to CGPoint
Currently, I am object tracking with OpenCV. When OpenCV returns the keypoints of where the objects are, they are out of the range of the iPhone screen. I'm thinking that there is some sort of conversion that needs to be done in order to use these points with swift.

Does anyone know the conversion that needs to be done?

Any help would be appreciated.

答:
The cvPoint values are image coordinates (if the tracking algorithm is valid). You can mark these points on the image using cvCircle and then display the image on the iPhone screen to check if they are valid.
When an image is displayed on the screen using UIImageView, the size of the displayed image might not be the same as the image resolution. In that case, you will need to scale the coordinates, if you want to position something on the image. See here for an example.</p>

Title: Convert OpenCV keypoints to CGPoint


问:
What's the issue with this 1000th prime number code?
```<code>count=5 #Nth prime number
i=10  #number to be checked
while (count!=1000):  #until its not 1000th
 if i%2==0 or i%3==0 or i%5==0 or i%7==0:  #to check non prime
  i=i+1 #next number initialized
 else: #for prime
  count=count+1 #move to next position
if count==1000: #if is 1000th position
 print i," is 1000th prime." #print prime
</code>```

I am considering 2,3,5,7 are already known as prime and starting from 10.

It gives "11 is 1000th prime" as output.
There is a logical error somewhere, I guess.

答:
143 is 11*13 so its not prime.
Your code would count it as prime because you only check if it can be divided by the first 5 prime numbers.
To resolve your doubt I just multiplied the next to primes 11 and 13.
Hope it helps.

By the way your code is also wrong because it only increments "i" when it match the condition, so when it s always checking:
    if 11%2==0 or 11%3==0 or 11%5==0 or 11%7==0:

Solution for your code (doesn't calculate the 1000th prime):

```<code>count=5 #Nth prime number
i=10  #number to be checked
while (count!=1000):  #until its not 1000th
    if i%2==0 or i%3==0 or i%5==0 or i%7==0:  #to check non prime
        pass #next number initialized
    else: #for prime
        count=count+1 #move to next position
    i=i+1
if count==1000: #if is 1000th position
    print i-1," is 1000th prime." #print prime
</code>```

Solution for your problem:

```<code>def is_prime(n):
  if n == 2 or n == 3: return True
  if n < 2 or n%2 == 0: return False
  if n < 9: return True
  if n%3 == 0: return False
  r = int(n**0.5)
  f = 5
  while f <= r:
    if n%f == 0: return False
    if n%(f+2) == 0: return False
    f +=6
  return True

count=5 #Nth prime number
i=10  #number to be checked
while (count!=8):  #until its not 1000th
    if not is_prime(i):  #to check non prime
        pass #next number initialized
    else: #for prime
        count=count+1 #move to next position
    i=i+1
if count==8: #if is 1000th position
    print i-1," is 1000th prime." #print prime
</code>```

Function is_prime(n) got from isPrime Function for Python Language

Body:
count=5 #Nth prime number
i=10  #number to be checked
while (count!=1000):  #until its not 1000th
 if i%2==0 or i%3==0 or i%5==0 or i%7==0:  #to check non prime
  i=i+1 #next number initialized
 else: #for prime
  count=count+1 #move to next position
if count==1000: #if is 1000th position
 print i," is 1000th prime." #print prime

I am considering 2,3,5,7 are already known as prime and starting from 10.

It gives "11 is 1000th prime" as output.
There is a logical error somewhere, I guess.

Body:
143 is 11*13 so its not prime.
Your code would count it as prime because you only check if it can be divided by the first 5 prime numbers.
To resolve your doubt I just multiplied the next to primes 11 and 13.
Hope it helps.

By the way your code is also wrong because it only increments "i" when it match the condition, so when it s always checking:
    if 11%2==0 or 11%3==0 or 11%5==0 or 11%7==0:

Solution for your code (doesn't calculate the 1000th prime):

count=5 #Nth prime number
i=10  #number to be checked
while (count!=1000):  #until its not 1000th
    if i%2==0 or i%3==0 or i%5==0 or i%7==0:  #to check non prime
        pass #next number initialized
    else: #for prime
        count=count+1 #move to next position
    i=i+1
if count==1000: #if is 1000th position
    print i-1," is 1000th prime." #print prime

Solution for your problem:

def is_prime(n):
  if n == 2 or n == 3: return True
  if n < 2 or n%2 == 0: return False
  if n < 9: return True
  if n%3 == 0: return False
  r = int(n**0.5)
  f = 5
  while f <= r:
    if n%f == 0: return False
    if n%(f+2) == 0: return False
    f +=6
  return True

count=5 #Nth prime number
i=10  #number to be checked
while (count!=8):  #until its not 1000th
    if not is_prime(i):  #to check non prime
        pass #next number initialized
    else: #for prime
        count=count+1 #move to next position
    i=i+1
if count==8: #if is 1000th position
    print i-1," is 1000th prime." #print prime

Function is_prime(n) got from isPrime Function for Python Language


问:
Why does intellisense and code suggestion stop working when Visual Studio is open?
I have been having issues with Intellisense in Microsoft Visual Studio 2012. I will be working in a project, editing code and whatnot (after a period of time, anywhere from 5 minutes to over an hour) and all of a sudden, no more code suggestions or intellisense. Both seem to stop working completely at the same time.

The only solution that I have tried is to reset all my settings, close out of Visual Studio completely and reopen the project again. Is there a better solution or an update that will fix this?

答:
What worked for me is by disabling and then re-enabling the Resharper

Goto

Tools -> Options-> Resharper ->General

Click

Suspend -> This disables the resharper

Then check your Intellisense is working or not.
In my case, it did and then I resumed the Resharper.

If this does not work, you might need to
Goto

Resharper -> Options-> Environment -> Intellisense -> General

And

Change Intellisense to Visual Studio


问:
How do I check if an object is "empty" or not?
The Cube class have two constructors, one which accepts three parameters that are converted into the tree attributes of the cube, and another one that doesn't require any parameter and therefore creates an "empty" cube. My question is how can a boolean method check if the cubes are valid or empty? Is there a way to do that without the need of checking each one of the attributes?</p>

```<code>class Application {

    public static void main(String[] args) {

        Cube c1 = new Cube(4, 3, 6);
        Cube c2 = new Cube();

        System.out.println(isNotEmpty(c1));
        System.out.println(isNotEmpty(c2));
    }

    public static boolean isNotEmpty(Cube cube) {
        if (/*cube attributes are NOT empty*/) {
            return true;
        } else {
            return false;
        }
    }

    public static class Cube {
        private int height;
        private int width;
        private int depth;

        public Cube() {}

        public Cube(int height, int width, int depth) {
            this.height = height;
            this.width = width;
            this.depth = depth;
        }

        public int getHeight() { return height; }
        public int getWidth() { return width; }
        public int getDepth() { return depth; }
    }
}
</code>```

答:
It seems a so tricky question. At first, we have to have any criteria: What is an empty object?. When we have some criteria, even single, we must check it.

From the reason when we are considering the Cube c3 = new Cube(0, 0, 0) like is not empty, so, here is one of ways:

```<code>public class CubeApplication {

    public static void main(String[] args) {

        Cube c1 = new Cube(4, 3, 6);
        Cube c2 = new Cube();
        Cube c3 = new Cube(0, 0, 0);

        System.out.println(c1.isEmpty());
        System.out.println(c2.isEmpty());
        System.out.println(c3.isEmpty());
    }

    static class Cube {

        private int hight;
        private int width;
        private int depth;
        private boolean isEmpty;

        public Cube() {
            this.isEmpty = false;
        }

        public Cube(int hight, int width, int depth) {
            this.hight = hight;
            this.width = width;
            this.depth = depth;
            this.isEmpty = true;
        }

        public boolean isEmpty() {
            return this.isEmpty;
        }

        public int getHight() {
            return this.hight;
        }

        public int getWidth() {
            return this.width;
        }

        public int getDepth() {
            return this.depth;
        }
    }
}
</code>```

OUTPUT:

```<code>true
false
true
</code>```

Body:
The Cube class have two constructors, one which accepts three parameters that are converted into the tree attributes of the cube, and another one that doesn't require any parameter and therefore creates an "empty" cube. My question is how can a boolean method check if the cubes are valid or empty? Is there a way to do that without the need of checking each one of the attributes?

class Application {

    public static void main(String[] args) {

        Cube c1 = new Cube(4, 3, 6);
        Cube c2 = new Cube();

        System.out.println(isNotEmpty(c1));
        System.out.println(isNotEmpty(c2));
    }

    public static boolean isNotEmpty(Cube cube) {
        if (/*cube attributes are NOT empty*/) {
            return true;
        } else {
            return false;
        }
    }

    public static class Cube {
        private int height;
        private int width;
        private int depth;

        public Cube() {}

        public Cube(int height, int width, int depth) {
            this.height = height;
            this.width = width;
            this.depth = depth;
        }

        public int getHeight() { return height; }
        public int getWidth() { return width; }
        public int getDepth() { return depth; }
    }
}

Body:
It seems a so tricky question. At first, we have to have any criteria: What is an empty object?. When we have some criteria, even single, we must check it.

From the reason when we are considering the Cube c3 = new Cube(0, 0, 0) like is not empty, so, here is one of ways:

public class CubeApplication {

    public static void main(String[] args) {

        Cube c1 = new Cube(4, 3, 6);
        Cube c2 = new Cube();
        Cube c3 = new Cube(0, 0, 0);

        System.out.println(c1.isEmpty());
        System.out.println(c2.isEmpty());
        System.out.println(c3.isEmpty());
    }

    static class Cube {

        private int hight;
        private int width;
        private int depth;
        private boolean isEmpty;

        public Cube() {
            this.isEmpty = false;
        }

        public Cube(int hight, int width, int depth) {
            this.hight = hight;
            this.width = width;
            this.depth = depth;
            this.isEmpty = true;
        }

        public boolean isEmpty() {
            return this.isEmpty;
        }

        public int getHight() {
            return this.hight;
        }

        public int getWidth() {
            return this.width;
        }

        public int getDepth() {
            return this.depth;
        }
    }
}

OUTPUT:

true
false
true


问:
Prepend comment to SASS/Compass output
Is there a convenient way to have SASS automatically prepend a comment to the beginning of each CSS output file? Specifically, when using Compasss I'd like to stick a brief warning telling designers not to edit the CSS directly and to point them to instructions on getting started with Compass. I use an output style of :compressed, which strips out comments that are in the input SCSS/SASS file.

If there isn't a convenient way to do this then I'll submit an issue/patch. I was thinking of adding an option named :output_prefix that takes a String that will be prepended to all output CSS files.

答:
compressed strips out all comments. I suggest you put this in a property:

```<code>warning { do-not: "edit this file"; }
</code>```

Regarding the proposed patch, I do not think this use case is compelling enough to warrant such a feature.

ContentLicense: CC BY-SA 2.5

Title: Prepend comment to SASS/Compass output

Body:
compressed strips out all comments. I suggest you put this in a property:

warning { do-not: "edit this file"; }

Regarding the proposed patch, I do not think this use case is compelling enough to warrant such a feature.


问:
MSB4018 The "CL" task failed unexpectedly in VS2015 Enterprise
I am using Visual Studio 2015 Enterprise and am unable to compile VC++ projects.

If I create a new Visual C++ Win32 Console Application with default settings and make no changes at all, building the project results in this error 13 times:

MSB4018: The "CL" task failed unexpectedly.

Does anyone know what can cause this error?

Full Error text:

```<code>1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018: The "CL" task failed unexpectedly.
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018: System.TypeInitializationException: The type initializer for 'Microsoft.Build.Utilities.FileTracker' threw an exception. ---> System.IO.FileNotFoundException: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.Shared.NativeMethodsShared.ThrowExceptionForErrorCode(Int32 errorCode)
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.Shared.NativeMethodsShared.GetLongFilePath(String path)
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.Utilities.FileTracker..cctor()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    --- End of inner exception stack trace ---
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.CPPTasks.CL.ComputeOutOfDateSources()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.CPPTasks.TrackedVCToolTask.SkipTaskExecution()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.Utilities.ToolTask.Execute()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.CPPTasks.TrackedVCToolTask.Execute()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()
</code>```

I get the same errors on any VC++ project I try to compile from VS. (compiling from the command line seems to work)

This question about VS 2017 seems similar, but it doesn't look like it was ever answered.

I have tried uninstalling and re-installing Visual C++ (Image of Visual Studio 2015 Features List).

Image of Project Creation

Any help would be greatly appreciated, I am quite lost on this one.

答:
MSB4018 The “CL” task failed unexpectedly in VS2015 Enterprise

According to the error log "MSB4018: The "CL" task failed unexpectedly.", it looks like something fundamental is wrong, we could try to uninstall and reinstall the Visual Studio to resolve this. If this issue still persist, please try to modify the TEMP and TMP environment variables (both user and system) and re-pointed the temp directories to other locations and set permissions to Full Control for both those folders.

You can refer to the similar issue here.

Body:
I am using Visual Studio 2015 Enterprise and am unable to compile VC++ projects.

If I create a new Visual C++ Win32 Console Application with default settings and make no changes at all, building the project results in this error 13 times:

MSB4018: The "CL" task failed unexpectedly.

Does anyone know what can cause this error?

Full Error text:

1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018: The "CL" task failed unexpectedly.
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018: System.TypeInitializationException: The type initializer for 'Microsoft.Build.Utilities.FileTracker' threw an exception. ---> System.IO.FileNotFoundException: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.Shared.NativeMethodsShared.ThrowExceptionForErrorCode(Int32 errorCode)
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.Shared.NativeMethodsShared.GetLongFilePath(String path)
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.Utilities.FileTracker..cctor()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    --- End of inner exception stack trace ---
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.CPPTasks.CL.ComputeOutOfDateSources()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.CPPTasks.TrackedVCToolTask.SkipTaskExecution()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.Utilities.ToolTask.Execute()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.CPPTasks.TrackedVCToolTask.Execute()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(253,5): error MSB4018:    at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()

I get the same errors on any VC++ project I try to compile from VS. (compiling from the command line seems to work)

This question about VS 2017 seems similar, but it doesn't look like it was ever answered.

I have tried uninstalling and re-installing Visual C++ (Image of Visual Studio 2015 Features List).

Image of Project Creation

Any help would be greatly appreciated, I am quite lost on this one.


问:
wkhtmltopdf 12.4 - QXcbConnection Could not connect to display
I'm getting an error (see below) and have looked through the many answers here but still have no idea how to get this to work:

ERROR
"The exit status code '134' says something went wrong: stderr: "QXcbConnection: Could not connect to display Aborted (core dumped) " stdout: "" command: /usr/bin/wkhtmltopdf --lowquality '/tmp/knp_snappy595ac8ce820719.82188465.html' 'TEST_874041855595ac8ce809a93.09267749.pdf'"

SERVER
I'm using a DigitalOcean Ubuntu 16.04 droplet with PHP 7.1 and Laravel 5.4 with Snappy and wkhtmltopdf version 12.4 64bit (everything works fine on my local Windows machine BTW), but I get the above error on the server. Here's my code:

CODE
$rendered_output = new Pdf('/usr/bin/wkhtmltopdf');
$rendered_output->generateFromHtml(view('pdf')),'file.pdf');

INSTALLATION
I installed wkhtmltopdf and updated the server using these commands:
sudo apt-get update
sudo apt-get install wkhtmltopdf

HELP
Has anyone got any ideas how I can fix this please (even if it means using a different DO server and some other distro)? Thank you in advance.

答:
I fixed this by doing two things:

I installed xvfb on the server: sudo apt-get install xvfb

I called xvfb: $snappy = new Pdf('/usr/bin/xvfb-run /usr/bin/wkhtmltopdf');


问:
Windows registry associate single application with multiple file types with unique icons
I am using NSIS to create an installer for an application I have developed using WPF which has about 3 different file formats it deals with and have been reading over the guidelines available from Microsoft extensively: https://msdn.microsoft.com/en-us/library/windows/desktop/cc144104

However I have found them lacking in examples for anything more complex and often when I try to find examples of how other applications are registering themselves (in the windows registry) it is not matching up with the previously mentioned guidelines at all...

But I have ended up with the following which seems to work fairly well, the application will start when associated files are opened through explorer and they are showing the default icon from the application executable:

```<code># Register the application paths
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\App Paths\GUI.exe" "" "$INSTDIR\GUI.exe"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\App Paths\GUI.exe" "Path" "$INSTDIR"

# Register the application
WriteRegStr HKCR "Applications\GUI.exe" "" "GUI"
WriteRegStr HKCR "Applications\GUI.exe" "DefaultIcon" "$INSTDIR\GUI.exe"
WriteRegStr HKCR "Applications\GUI.exe" "FriendlyAppName" "General User Interface"
WriteRegStr HKCR "Applications\GUI.exe" "UseExecutableForTaskbarGroupIcon" ""
WriteRegStr HKCR "Applications\GUI.exe\SupportedTypes" "" ""
WriteRegStr HKCR "Applications\GUI.exe\SupportedTypes\.ext1" "" ""
WriteRegStr HKCR "Applications\GUI.exe\SupportedTypes\.ext2" "" ""
WriteRegStr HKCR "Applications\GUI.exe\SupportedTypes\.ext3" "" ""

# Create the application ProgIDs
WriteRegStr HKCR "GUI.App" "" "GUI"
WriteRegStr HKCR "GUI.App" "DefaultIcon" "GUI.exe"
WriteRegStr HKCR "GUI.App\shell\open\command" "" 'GUI.exe "%1"'

# Associate application file extensions
WriteRegStr HKCR ".ext1" "" "GUI.App"
WriteRegStr HKCR ".ext1\OpenWithProgIds" "GUI.App" ""
WriteRegStr HKCR ".ext2" "" "GUI.App"
WriteRegStr HKCR ".ext2\OpenWithProgIds" "GUI.App" ""
WriteRegStr HKCR ".ext3" "" "GUI.App"
WriteRegBin HKCR ".ext3\OpenWithProgIds" "GUI.App" ""

# Calculate estimated EstimatedSize
${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2
IntFmt $0 "0x%08X" $INSTSIZE

# Write Add/Remove Programs Info
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "DisplayName" "General User Interface"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "UninstallString" "$INSTDIR\GUI.Uninstaller.exe"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "DisplayIcon" "$INSTDIR\GUI.exe"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "Publisher" "General User Interface Publisher"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "DisplayVersion" ${VERSION}
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "NoModify" 1
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "NoRepair" 1
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "EstimatedSize" $INSTSIZE
</code>```

However I have noticed that the strings that I have specified as 'friendly' display values such as "GUI" and "General User Interface" are being ignored and it is instead using the assembly name from the executable, what could be causing this to happen?

The other problem is I want to be able to show a separate icon for each file extension I have associated with the application in explorer. So I have been looking into using Resource Hacker™ to insert additional icons and resources into my applications executable from the command line, but am actually entirely unsure of how to go about associating the non-default icons embedded in the executable with individual extensions and have been unable to find any resources or examples, so a push in the right direction would be greatly appreciated.

Lastly I am unsure of how to use the 'REG_EXPAND_SZ' registry data type to reference strings and other resources embedded in an executable, in some examples the resource names are prefixed with '-' and in others they are not... So any good learning resources on this would also be greatly appreciated.

Thanks,
Alex.

答:
Windows will read from the .exe if it cannot find your friendly name and it will also cache this name for future use (HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\MuiCache and similar keys) so try to delete the cached name. Hopefully it will find your real friendly name if it has to go and look for it again.

To get different icons for each type you also need one progid per type (myapp.type1, myapp.type2 etc.) so you can set different DefaultIcon paths for each type. The syntax of this path is c:\path\app.exe[,[-]number] where ...\app.exe,2 means the third (0,1,2) icon in app.exe and ...\app.exe,-2 means the icon with resource id 2. See this blog post for more details.

Strings starting with @ are redirected strings and you can read about those on MSDN.

Some final words of advice. Not everything in your example uses the full path, you should always specify the full path to your .exe.

When all else fails, use Process Monitor to see what and where Windows is reading...

Body:
I am using NSIS to create an installer for an application I have developed using WPF which has about 3 different file formats it deals with and have been reading over the guidelines available from Microsoft extensively: https://msdn.microsoft.com/en-us/library/windows/desktop/cc144104

However I have found them lacking in examples for anything more complex and often when I try to find examples of how other applications are registering themselves (in the windows registry) it is not matching up with the previously mentioned guidelines at all...

But I have ended up with the following which seems to work fairly well, the application will start when associated files are opened through explorer and they are showing the default icon from the application executable:

# Register the application paths
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\App Paths\GUI.exe" "" "$INSTDIR\GUI.exe"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\App Paths\GUI.exe" "Path" "$INSTDIR"

# Register the application
WriteRegStr HKCR "Applications\GUI.exe" "" "GUI"
WriteRegStr HKCR "Applications\GUI.exe" "DefaultIcon" "$INSTDIR\GUI.exe"
WriteRegStr HKCR "Applications\GUI.exe" "FriendlyAppName" "General User Interface"
WriteRegStr HKCR "Applications\GUI.exe" "UseExecutableForTaskbarGroupIcon" ""
WriteRegStr HKCR "Applications\GUI.exe\SupportedTypes" "" ""
WriteRegStr HKCR "Applications\GUI.exe\SupportedTypes\.ext1" "" ""
WriteRegStr HKCR "Applications\GUI.exe\SupportedTypes\.ext2" "" ""
WriteRegStr HKCR "Applications\GUI.exe\SupportedTypes\.ext3" "" ""

# Create the application ProgIDs
WriteRegStr HKCR "GUI.App" "" "GUI"
WriteRegStr HKCR "GUI.App" "DefaultIcon" "GUI.exe"
WriteRegStr HKCR "GUI.App\shell\open\command" "" 'GUI.exe "%1"'

# Associate application file extensions
WriteRegStr HKCR ".ext1" "" "GUI.App"
WriteRegStr HKCR ".ext1\OpenWithProgIds" "GUI.App" ""
WriteRegStr HKCR ".ext2" "" "GUI.App"
WriteRegStr HKCR ".ext2\OpenWithProgIds" "GUI.App" ""
WriteRegStr HKCR ".ext3" "" "GUI.App"
WriteRegBin HKCR ".ext3\OpenWithProgIds" "GUI.App" ""

# Calculate estimated EstimatedSize
${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2
IntFmt $0 "0x%08X" $INSTSIZE

# Write Add/Remove Programs Info
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "DisplayName" "General User Interface"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "UninstallString" "$INSTDIR\GUI.Uninstaller.exe"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "DisplayIcon" "$INSTDIR\GUI.exe"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "Publisher" "General User Interface Publisher"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "DisplayVersion" ${VERSION}
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "NoModify" 1
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "NoRepair" 1
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\GUI" "EstimatedSize" $INSTSIZE

However I have noticed that the strings that I have specified as 'friendly' display values such as "GUI" and "General User Interface" are being ignored and it is instead using the assembly name from the executable, what could be causing this to happen?

The other problem is I want to be able to show a separate icon for each file extension I have associated with the application in explorer. So I have been looking into using Resource Hacker™ to insert additional icons and resources into my applications executable from the command line, but am actually entirely unsure of how to go about associating the non-default icons embedded in the executable with individual extensions and have been unable to find any resources or examples, so a push in the right direction would be greatly appreciated.

Lastly I am unsure of how to use the 'REG_EXPAND_SZ' registry data type to reference strings and other resources embedded in an executable, in some examples the resource names are prefixed with '-' and in others they are not... So any good learning resources on this would also be greatly appreciated.

Thanks,
Alex.


问:
How to set Banner ad in all activity?
I am new in android app development and I am creating an app in android studio, which has 2 activities. One  is activity_main.xml which has a button to open second activity. When I set the banner ad it shows only on bottom of activity_main.xml and I want to set same banner ad in my second activity. What should I do. Please help me.thanks!!</p>

答:
You'd need to copy the ad banner view from activity_main.xml to your second activity's layout.

Also, please include code in your questions as it makes it easier for people to help you!

Title: How to set Banner ad in all activity?


问:
Replace String with characters with substring
I tried to make security to display email data by replacing some words with symbol (*) but not as expected there might be an error in making the example script as below.

```<code>String email = "thismyemail@myhost.com";
String get_text = email.get_text(3, 6);
String hasil = email.replace(get_text,"*");
email_string = (EditText) findViewById(R.id.emailT);
email_string.setText(hasil);
</code>```

But the result is like this

```<code>thi*email@myhost.com
</code>```

Which I expect

```<code>thi***email@myhost.com
</code>```

答:
```<code>String hasil = email.replace(get_text,"***");
</code>```

But please note that if that text appears anywhere else in the string it will be replaced as well.

Also, if the email is like jf@mymailserver.com you won't be replacing a part of their user id with *.

So you can probably find a better way to select the characters, taking into account email length and also not "replacing" text but rather putting those chars at the specific position you want to.

See this related question for some ideas on how to improve this:

masking of email address in java

Body:
I tried to make security to display email data by replacing some words with symbol (*) but not as expected there might be an error in making the example script as below.

String email = "thismyemail@myhost.com";
String get_text = email.get_text(3, 6);
String hasil = email.replace(get_text,"*");
email_string = (EditText) findViewById(R.id.emailT);
email_string.setText(hasil);

But the result is like this

thi*email@myhost.com

Which I expect

thi***email@myhost.com

Body:
String hasil = email.replace(get_text,"***");

But please note that if that text appears anywhere else in the string it will be replaced as well.

Also, if the email is like jf@mymailserver.com you won't be replacing a part of their user id with *.

So you can probably find a better way to select the characters, taking into account email length and also not "replacing" text but rather putting those chars at the specific position you want to.

See this related question for some ideas on how to improve this:

masking of email address in java


问:
Rails 5 nested attributes not saving update
I have two models with nested attributes. My form can update book :title, but not nested attributes. After I submit i see paramaters is going in terminal but there is no rollback just (0.2ms)begintransaction (0.2ms)commit transaction.

I spent whole day to solve that, i tried inverse_of, optional: true, autosave: true in models. But still not able save update. Also there is no unpermitted paramater error. There is another problem.

Model:

```<code>has_many :pages
accepts_nested_attributes_for :pages
</code>```

Controller:

```<code>def update
  if @book.update_attributes(book_params)
    redirect_to @book
  else
    render 'edit'
  end
end

def book_params
  params.require(:book).permit(:title, pages_attributes: [:id, :state])
end
</code>```

My form:

```<code><%= form_for(@book) do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title, :autofocus => true, class: 'form-control' %>

  <%= f.fields_for :pages do |builder| %>
    <%= builder.select(:state, options_for_select({ "close" => 0, "open" => 1, })) %>
  <% end %>
  <%= f.submit 'Submit',  %>
<% end %>
</code>```

Example console result:

```<code>book = Book.first
book.update(title:"test", pages_attributes: [id: 124142 , book_id: 1, state: 1 ])
   (0.2ms)  begin transaction
   (0.2ms)  commit transaction
</code>```

EDIT

Server log:

```<code>Started PATCH "/book/firstbook" for 127.0.0.1 at 2017-07-05 21:57:37 +0300
Processing by booksController#update as HTML
  Parameters: {
    "utf8"=>"✓",
    "authenticity_token"=>"pElKKQq+M/5GuEG6nJ6Ac1vkEHyIknA2vPiDC9ND+50tq34nDtCRRX9k6TxaMZCInufp68m6BnO8jt4BsJ1bFg==",
    "book"=>{
      "title"=>"firstbook",
      "pages_attributes"=>{
        "0"=>{"state"=>"0", "id"=>"1"},
        "1"=>{"state"=>"0", "id"=>"2"},
        "2"=>{"state"=>"0", "id"=>"3"},
        "3"=>{"state"=>"0", "id"=>"4"},
        "4"=>{"state"=>"0", "id"=>"5"},
        "5"=>{"state"=>"0", "id"=>"6"},
        "6"=>{"state"=>"0", "id"=>"7"},
        "7"=>{"state"=>"0", "id"=>"8"},
        "8"=>{"state"=>"0", "id"=>"9"},
        "9"=>{"state"=>"0", "id"=>"10"},
      }
    },
    "commit"=>"submit", "id"=>"firstbook"
  }
  book Load (0.2ms)  SELECT  "books".* FROM "books" WHERE "books"."slug" = ? ORDER BY "books"."id" ASC LIMIT ?  [["slug", "firstbook"], ["LIMIT", 1]]
   (0.1ms)  begin transaction
   (0.1ms)  commit transaction
Redirected to http://localhost:3000/book/firstbook
Completed 302 Found in 48ms (ActiveRecord: 0.5ms)
</code>```

答:
Could you try f.fields_for :pages, @book.pages.build do |builder|?
I'm not 100% sure this will work but I had the same problem with fields for a while back and this is how I fixed it.

Body:
I have two models with nested attributes. My form can update book :title, but not nested attributes. After I submit i see paramaters is going in terminal but there is no rollback just (0.2ms)begintransaction (0.2ms)commit transaction.

I spent whole day to solve that, i tried inverse_of, optional: true, autosave: true in models. But still not able save update. Also there is no unpermitted paramater error. There is another problem.

Model:

has_many :pages
accepts_nested_attributes_for :pages

Controller:

def update
  if @book.update_attributes(book_params)
    redirect_to @book
  else
    render 'edit'
  end
end

def book_params
  params.require(:book).permit(:title, pages_attributes: [:id, :state])
end

My form:

<%= form_for(@book) do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title, :autofocus => true, class: 'form-control' %>

  <%= f.fields_for :pages do |builder| %>
    <%= builder.select(:state, options_for_select({ "close" => 0, "open" => 1, })) %>
  <% end %>
  <%= f.submit 'Submit',  %>
<% end %>

Example console result:

book = Book.first
book.update(title:"test", pages_attributes: [id: 124142 , book_id: 1, state: 1 ])
   (0.2ms)  begin transaction
   (0.2ms)  commit transaction

EDIT

Server log:

Started PATCH "/book/firstbook" for 127.0.0.1 at 2017-07-05 21:57:37 +0300
Processing by booksController#update as HTML
  Parameters: {
    "utf8"=>"✓",
    "authenticity_token"=>"pElKKQq+M/5GuEG6nJ6Ac1vkEHyIknA2vPiDC9ND+50tq34nDtCRRX9k6TxaMZCInufp68m6BnO8jt4BsJ1bFg==",
    "book"=>{
      "title"=>"firstbook",
      "pages_attributes"=>{
        "0"=>{"state"=>"0", "id"=>"1"},
        "1"=>{"state"=>"0", "id"=>"2"},
        "2"=>{"state"=>"0", "id"=>"3"},
        "3"=>{"state"=>"0", "id"=>"4"},
        "4"=>{"state"=>"0", "id"=>"5"},
        "5"=>{"state"=>"0", "id"=>"6"},
        "6"=>{"state"=>"0", "id"=>"7"},
        "7"=>{"state"=>"0", "id"=>"8"},
        "8"=>{"state"=>"0", "id"=>"9"},
        "9"=>{"state"=>"0", "id"=>"10"},
      }
    },
    "commit"=>"submit", "id"=>"firstbook"
  }
  book Load (0.2ms)  SELECT  "books".* FROM "books" WHERE "books"."slug" = ? ORDER BY "books"."id" ASC LIMIT ?  [["slug", "firstbook"], ["LIMIT", 1]]
   (0.1ms)  begin transaction
   (0.1ms)  commit transaction
Redirected to http://localhost:3000/book/firstbook
Completed 302 Found in 48ms (ActiveRecord: 0.5ms)


问:
Neural Network Always Produces Same/Similar Outputs for Any Input
I have a problem where I am trying to create a neural network for Tic-Tac-Toe. However, for some reason, training the neural network causes it to produce nearly the same output for any given input.

I did take a look at Artificial neural networks benchmark, but my network implementation is built for neurons with the same activation function for each neuron, i.e. no constant neurons.

To make sure the problem wasn't just due to my choice of training set (1218 board states and moves generated by a genetic algorithm), I tried to train the network to reproduce XOR. The logistic activation function was used. Instead of using the derivative, I multiplied the error by output*(1-output) as some sources suggested that this was equivalent to using the derivative. I can put the Haskell source on HPaste, but it's a little embarrassing to look at. The network has 3 layers: the first layer has 2 inputs and 4 outputs, the second has 4 inputs and 1 output, and the third has 1 output. Increasing to 4 neurons in the second layer didn't help, and neither did increasing to 8 outputs in the first layer.

I then calculated errors, network output, bias updates, and the weight updates by hand based on http://hebb.mit.edu/courses/9.641/2002/lectures/lecture04.pdf to make sure there wasn't an error in those parts of the code (there wasn't, but I will probably do it again just to make sure). Because I am using batch training, I did not multiply by x in equation (4) there. I am adding the weight change, though http://www.faqs.org/faqs/ai-faq/neural-nets/part2/section-2.html suggests to subtract it instead.

The problem persisted, even in this simplified network. For example, these are the results after 500 epochs of batch training and of incremental training.

```<code>Input    |Target|Output (Batch)      |Output(Incremental)
[1.0,1.0]|[0.0] |[0.5003781562785173]|[0.5009731800870864]
[1.0,0.0]|[1.0] |[0.5003740346965251]|[0.5006347214672715]
[0.0,1.0]|[1.0] |[0.5003734471544522]|[0.500589332376345]
[0.0,0.0]|[0.0] |[0.5003674110937019]|[0.500095157458231]
</code>```

Subtracting instead of adding produces the same problem, except everything is 0.99 something instead of 0.50 something. 5000 epochs produces the same result, except the batch-trained network returns exactly 0.5 for each case. (Heck, even 10,000 epochs didn't work for batch training.)

Is there anything in general that could produce this behavior?

Also, I looked at the intermediate errors for incremental training, and the although the inputs of the hidden/input layers varied, the error for the output neuron was always +/-0.12. For batch training, the errors were increasing, but extremely slowly and the errors were all extremely small (x10^-7). Different initial random weights and biases made no difference, either.

Note that this is a school project, so hints/guides would be more helpful. Although reinventing the wheel and making my own network (in a language I don't know well!) was a horrible idea, I felt it would be more appropriate for a school project (so I know what's going on...in theory, at least. There doesn't seem to be a computer science teacher at my school).

EDIT: Two layers, an input layer of 2 inputs to 8 outputs, and an output layer of 8 inputs to 1 output, produces much the same results: 0.5+/-0.2 (or so) for each training case. I'm also playing around with pyBrain, seeing if any network structure there will work.

Edit 2: I am using a learning rate of 0.1. Sorry for forgetting about that.

Edit 3: Pybrain's "trainUntilConvergence" doesn't get me a fully trained network, either, but 20000 epochs does, with 16 neurons in the hidden layer. 10000 epochs and 4 neurons, not so much, but close. So, in Haskell, with the input layer having 2 inputs & 2 outputs, hidden layer with 2 inputs and 8 outputs, and output layer with 8 inputs and 1 output...I get the same problem with 10000 epochs. And with 20000 epochs.

Edit 4: I ran the network by hand again based on the MIT PDF above, and the values match, so the code should be correct unless I am misunderstanding those equations.

Some of my source code is at http://hpaste.org/42453/neural_network__not_working; I'm working on cleaning my code somewhat and putting it in a Github (rather than a private Bitbucket) repository.

All of the relevant source code is now at https://github.com/l33tnerd/hsann.

答: It's hard to tell without seeing a code sample, but a bias bug can have that effect (e.g. forgetting to add the bias to the input), so I would take a closer look at that part of the code.</p>

Body:
I have a problem where I am trying to create a neural network for Tic-Tac-Toe. However, for some reason, training the neural network causes it to produce nearly the same output for any given input.

I did take a look at Artificial neural networks benchmark, but my network implementation is built for neurons with the same activation function for each neuron, i.e. no constant neurons.

To make sure the problem wasn't just due to my choice of training set (1218 board states and moves generated by a genetic algorithm), I tried to train the network to reproduce XOR. The logistic activation function was used. Instead of using the derivative, I multiplied the error by output*(1-output) as some sources suggested that this was equivalent to using the derivative. I can put the Haskell source on HPaste, but it's a little embarrassing to look at. The network has 3 layers: the first layer has 2 inputs and 4 outputs, the second has 4 inputs and 1 output, and the third has 1 output. Increasing to 4 neurons in the second layer didn't help, and neither did increasing to 8 outputs in the first layer.

I then calculated errors, network output, bias updates, and the weight updates by hand based on http://hebb.mit.edu/courses/9.641/2002/lectures/lecture04.pdf to make sure there wasn't an error in those parts of the code (there wasn't, but I will probably do it again just to make sure). Because I am using batch training, I did not multiply by x in equation (4) there. I am adding the weight change, though http://www.faqs.org/faqs/ai-faq/neural-nets/part2/section-2.html suggests to subtract it instead.

The problem persisted, even in this simplified network. For example, these are the results after 500 epochs of batch training and of incremental training.

Input    |Target|Output (Batch)      |Output(Incremental)
[1.0,1.0]|[0.0] |[0.5003781562785173]|[0.5009731800870864]
[1.0,0.0]|[1.0] |[0.5003740346965251]|[0.5006347214672715]
[0.0,1.0]|[1.0] |[0.5003734471544522]|[0.500589332376345]
[0.0,0.0]|[0.0] |[0.5003674110937019]|[0.500095157458231]

Subtracting instead of adding produces the same problem, except everything is 0.99 something instead of 0.50 something. 5000 epochs produces the same result, except the batch-trained network returns exactly 0.5 for each case. (Heck, even 10,000 epochs didn't work for batch training.)

Is there anything in general that could produce this behavior?

Also, I looked at the intermediate errors for incremental training, and the although the inputs of the hidden/input layers varied, the error for the output neuron was always +/-0.12. For batch training, the errors were increasing, but extremely slowly and the errors were all extremely small (x10^-7). Different initial random weights and biases made no difference, either.

Note that this is a school project, so hints/guides would be more helpful. Although reinventing the wheel and making my own network (in a language I don't know well!) was a horrible idea, I felt it would be more appropriate for a school project (so I know what's going on...in theory, at least. There doesn't seem to be a computer science teacher at my school).

EDIT: Two layers, an input layer of 2 inputs to 8 outputs, and an output layer of 8 inputs to 1 output, produces much the same results: 0.5+/-0.2 (or so) for each training case. I'm also playing around with pyBrain, seeing if any network structure there will work.

Edit 2: I am using a learning rate of 0.1. Sorry for forgetting about that.

Edit 3: Pybrain's "trainUntilConvergence" doesn't get me a fully trained network, either, but 20000 epochs does, with 16 neurons in the hidden layer. 10000 epochs and 4 neurons, not so much, but close. So, in Haskell, with the input layer having 2 inputs & 2 outputs, hidden layer with 2 inputs and 8 outputs, and output layer with 8 inputs and 1 output...I get the same problem with 10000 epochs. And with 20000 epochs.

Edit 4: I ran the network by hand again based on the MIT PDF above, and the values match, so the code should be correct unless I am misunderstanding those equations.

Some of my source code is at http://hpaste.org/42453/neural_network__not_working; I'm working on cleaning my code somewhat and putting it in a Github (rather than a private Bitbucket) repository.

All of the relevant source code is now at https://github.com/l33tnerd/hsann.


问:
Faster/Piped version of Stream.CopyTo
I was shocked to see that the default implementation of Stream.CopyTo is not piped. No piping means that no reading on the source is done whilst writing to the destination.

This means that in most cases performance is half of what it could be. (Copy Filestream from C: to another HDD)

How do I implement a fast piped CopyTo?

答:
Files have sequential read-ahead and write buffering directly from the operating system. You are unlikely to improve performance of the most basic Copy implementation in those cases.

TCP sockets similarly will buffer quite a bit of data for you, and so the basic Copy should be fine for them too so long as your protocol allows for bulk data sends.

When you open the file up as unbuffered (very rare -- typically you do this if you can perform your own caching that you know will be better than the OS), or have a poorly designed network protocol is where performing your own special buffering might give sizable improvements.

Something like this should be sufficient in most of those cases...

```<code>static async Task CopyMaybeFaster(Stream src, Stream dst)
{
    byte[] buffer = new byte[65536];
    int curoff = 0;

    Task<int> readTask = src.ReadAsync(buffer, curoff, 32768);
    Task writeTask = Task.CompletedTask;
    int len;

    while ((len = await readTask.ConfigureAwait(false)) != 0)
    {
        await writeTask.ConfigureAwait(false);
        writeTask = dst.WriteAsync(buffer, curoff, len);

        curoff ^= 32768;
        readTask = src.ReadAsync(buffer, curoff, 32768);
    }

    await writeTask.ConfigureAwait(false);
}
</code>```

Title: Faster/Piped version of Stream.CopyTo

Body:
Files have sequential read-ahead and write buffering directly from the operating system. You are unlikely to improve performance of the most basic Copy implementation in those cases.

TCP sockets similarly will buffer quite a bit of data for you, and so the basic Copy should be fine for them too so long as your protocol allows for bulk data sends.

When you open the file up as unbuffered (very rare -- typically you do this if you can perform your own caching that you know will be better than the OS), or have a poorly designed network protocol is where performing your own special buffering might give sizable improvements.

Something like this should be sufficient in most of those cases...

static async Task CopyMaybeFaster(Stream src, Stream dst)
{
    byte[] buffer = new byte[65536];
    int curoff = 0;

    Task<int> readTask = src.ReadAsync(buffer, curoff, 32768);
    Task writeTask = Task.CompletedTask;
    int len;

    while ((len = await readTask.ConfigureAwait(false)) != 0)
    {
        await writeTask.ConfigureAwait(false);
        writeTask = dst.WriteAsync(buffer, curoff, len);

        curoff ^= 32768;
        readTask = src.ReadAsync(buffer, curoff, 32768);
    }

    await writeTask.ConfigureAwait(false);
}


问:
Is it possible to listen for function calls in C# (i.e. treat C# function calls as events)?
I would like to log when functions in my app are called. Is there a way I can listen for functions called and run code on such events?

If so, where do I start looking at how to do this?

答:
What do you want to do this for?  Is it for performance profiling, or because you want to execute something when (for example) a function has been called x times?

If its for performance profiling, if you're using Visual Studio, the IDE has some built-in profiling functions.  Under the "Debug" menu, there is the "performance Profiler" (Alt+F2).  Running that on your application can give you a lot of detail about what is being called, how many time, how much CPU load etc etc.  Particularly useful if you generate the "Create Detail Report" once it has run.

It's a bit hard to interpret, but if you're interested in how much time is being spent doing various functions in your application, it can be very useful.


问:
Write actual values to bar chart using Gruff within Ruby
I am generating a bar chart with values [1,5,10,23]. Currently, I have no way of knowing those exact values when looking at the image generated by Gruff. I just know that 23 falls somewhere between the lines of 20 and 25.

Is it possible to write the exact values within the image?

答:
I think this is what you are looking for:</p>

```<code>g.show_labels_for_bar_values = true
</code>```

Body:
I think this is what you are looking for:

g.show_labels_for_bar_values = true


问:
Unable to access web application that's running in container built on docker
I have a simple python program that does the following

identitydock.py

```<code>from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello Docker!\n'

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

My Dockerfile is as follows

Dockerfile

```<code>FROM python:3.4

RUN groupadd -r uwsgi && useradd -r -g uwsgi uwsgi
RUN pip install Flask==0.10.1 uWSGI==2.0.8
WORKDIR /app
COPY app /app
COPY cmd.sh /

EXPOSE 9090 9191
USER uwsgi

CMD ["/cmd.sh"]
</code>```

my cmd.sh is as follows:

```<code>#!/bin/bash
set -e

if [ "$ENV" = 'DEV' ]; then
  echo "Running Development Server"
  exec python "identidock.py"
else
  echo "Running Production Server"
  exec uwsgi --http 0.0.0.0:9090 --wsgi-file /app/identidock.py \
             --callable app --stats 0.0.0.0:9191
fi
</code>```

A simple web page that should return 'hello docker' for some reason does not work when I run using docker.

The commands I gave to run the application:

docker build -t identidock .

docker run -d -p 5000:5000 identidock

When I do curl localhost:5000 I get the following message

curl: (7) Failed to connect to localhost port 5000: Connection refused

May I know if there is an issue with my docker configuration?

I am using the following docker version on MacOSX

Docker version 17.03.1-ce, build c6d412e

Reference source
https://github.com/using-docker/using_docker_in_dev

Edit -1

On docker ps -a , the container status shows 'UP'

on docker logs CONTAINER_ID, i get the following logs

```<code>Running Production Server
*** Starting uWSGI 2.0.8 (64bit) on [Thu Jul  6 02:04:04 2017] ***
compiled with version: 4.9.2 on 06 July 2017 02:03:16
os: Linux-4.4.74-boot2docker #1 SMP Mon Jun 26 18:01:14 UTC 2017
nodename: 323e6ff35d0d
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /app
detected binary path: /usr/local/bin/uwsgi
your processes number limit is 1048576
your memory page size is 4096 bytes
detected max file descriptor number: 1048576
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on 0.0.0.0:9090 fd 4
uwsgi socket 0 bound to TCP address 127.0.0.1:45710 (port auto-assigned) fd 3
Python version: 3.4.6 (default, Jun 21 2017, 18:32:49)  [GCC 4.9.2]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x1bd9640
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 145536 bytes (142 KB) for 1 cores
*** Operational MODE: single process ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x1bd9640 pid: 1 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 1)
spawned uWSGI worker 1 (pid: 6, cores: 1)
*** Stats server enabled on 0.0.0.0:9191 fd: 13 ***
spawned uWSGI http 1 (pid: 7)
</code>```

答: You're connecting port 5000 on the host to port 5000 on the container. But you don't have anything running on port 5000, you have something running on 9090 and 9091. so try docker run -d -p 5000:9090 identidock or docker run -d -p 5000:9091 identidock

ContentLicense: CC BY-SA 4.0

Body:
I have a simple python program that does the following

identitydock.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello Docker!\n'

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

My Dockerfile is as follows

Dockerfile

FROM python:3.4

RUN groupadd -r uwsgi && useradd -r -g uwsgi uwsgi
RUN pip install Flask==0.10.1 uWSGI==2.0.8
WORKDIR /app
COPY app /app
COPY cmd.sh /

EXPOSE 9090 9191
USER uwsgi

CMD ["/cmd.sh"]

my cmd.sh is as follows:

#!/bin/bash
set -e

if [ "$ENV" = 'DEV' ]; then
  echo "Running Development Server"
  exec python "identidock.py"
else
  echo "Running Production Server"
  exec uwsgi --http 0.0.0.0:9090 --wsgi-file /app/identidock.py \
             --callable app --stats 0.0.0.0:9191
fi

A simple web page that should return 'hello docker' for some reason does not work when I run using docker.

The commands I gave to run the application:

docker build -t identidock .

docker run -d -p 5000:5000 identidock

When I do curl localhost:5000 I get the following message

curl: (7) Failed to connect to localhost port 5000: Connection refused

May I know if there is an issue with my docker configuration?

I am using the following docker version on MacOSX

Docker version 17.03.1-ce, build c6d412e

Reference source
https://github.com/using-docker/using_docker_in_dev

Edit -1

On docker ps -a , the container status shows 'UP'

on docker logs CONTAINER_ID, i get the following logs

Running Production Server
*** Starting uWSGI 2.0.8 (64bit) on [Thu Jul  6 02:04:04 2017] ***
compiled with version: 4.9.2 on 06 July 2017 02:03:16
os: Linux-4.4.74-boot2docker #1 SMP Mon Jun 26 18:01:14 UTC 2017
nodename: 323e6ff35d0d
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working directory: /app
detected binary path: /usr/local/bin/uwsgi
your processes number limit is 1048576
your memory page size is 4096 bytes
detected max file descriptor number: 1048576
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on 0.0.0.0:9090 fd 4
uwsgi socket 0 bound to TCP address 127.0.0.1:45710 (port auto-assigned) fd 3
Python version: 3.4.6 (default, Jun 21 2017, 18:32:49)  [GCC 4.9.2]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x1bd9640
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 145536 bytes (142 KB) for 1 cores
*** Operational MODE: single process ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x1bd9640 pid: 1 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 1)
spawned uWSGI worker 1 (pid: 6, cores: 1)
*** Stats server enabled on 0.0.0.0:9191 fd: 13 ***
spawned uWSGI http 1 (pid: 7)


问:
Vertically align text next to an image?
Why won't vertical-align: middle work?  And yet, vertical-align: top does work.

span{
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <img src="https://via.placeholder.com/30" alt="small img" />
  <span>Doesn't work.</span>
</div></code>```

答:
It can be confusing, I agree. Try utilizing table features. I use this simple CSS trick to position modals at the center of the webpage. It has large browser support:

```<code><div class="table">
    <div class="cell">
        <img src="..." alt="..." />
        <span>It works now</span>
    </div>
</div>
</code>```

and CSS part:

```<code>.table { display: table; }
.cell { display: table-cell; vertical-align: middle; }
</code>```

Note that you have to style and adjust the size of image and table container to make it work as you desire. Enjoy.

OwnerDisplayName: sam

Title: Vertically align text next to an image?

Body:
Why won't vertical-align: middle work?  And yet, vertical-align: top does work.

span{
  vertical-align: middle;
}

  Doesn't work.

LastEditorDisplayName: Michael Haren

Body:
It can be confusing, I agree. Try utilizing table features. I use this simple CSS trick to position modals at the center of the webpage. It has large browser support:

<div class="table">
    <div class="cell">
        <img src="..." alt="..." />
        <span>It works now</span>
    </div>
</div>

and CSS part:

.table { display: table; }
.cell { display: table-cell; vertical-align: middle; }

Note that you have to style and adjust the size of image and table container to make it work as you desire. Enjoy.


问:
how to combine two LPCWSTRs?
I have two variables that are LPCWSTRs. I want to create a new variable that will have the values of the first and second variable.

I tried this but it didn't work.

```<code>LPCWSTR d = L"sd";
LPCWSTR f = L"f";
LPCWSTR df = d + f;
</code>```

I get this error when i try that.

```<code>1   IntelliSense: expression must have integral or enum type
</code>```

Is there a function that can combine two LPCWSTRs?

答:
It doesn't work because the C++ compiler cannot generate code to join together arrays.  The two strings in the example are arrays of type wchar_t.  To join arrays you must use higher level functions.  There are several ways of doing it:

```<code>LPWSTR df[20]; // cannot be LPCWSTR, because the C is for const.
wcsprintf(df, L"%s%s", d, f);
</code>```

or

```<code>LPWSTR df[20];
wcscpy(df, d);
wcscat(df, f);
</code>```

or use STL as previously answered.

Title: how to combine two LPCWSTRs?

Body:
I have two variables that are LPCWSTRs. I want to create a new variable that will have the values of the first and second variable.

I tried this but it didn't work.

LPCWSTR d = L"sd";
LPCWSTR f = L"f";
LPCWSTR df = d + f;

I get this error when i try that.

1   IntelliSense: expression must have integral or enum type

Is there a function that can combine two LPCWSTRs?

Body:
It doesn't work because the C++ compiler cannot generate code to join together arrays.  The two strings in the example are arrays of type wchar_t.  To join arrays you must use higher level functions.  There are several ways of doing it:

LPWSTR df[20]; // cannot be LPCWSTR, because the C is for const.
wcsprintf(df, L"%s%s", d, f);

or

LPWSTR df[20];
wcscpy(df, d);
wcscat(df, f);

or use STL as previously answered.


问:
How do you stop injection in this PHP/PDO
So I have look at so many post, web sites and video and now I am so confused!  I can't seem to get it right.
How do you stop injection in this PHP/PDO.  I have this code that works, but it allows injection.

```<code>//*THIS WORKS BUT ALLOWS INJECTION
//*

//The variable $word comes from another php file where the search is created.
public function getAllCards($word) {

    $sql = "SELECT * FROM carddbtable WHERE businessNameDB='".$word."'";

foreach ($this->conn->query($sql) as $row) {

    echo json_encode($row)."<br>"."<br>";
}

$db = null;
}
</code>```

With this new code I am trying to remove the variable  "$word"  from the   "SELECT * FROM "  statement
to stop the injection and add the  "prepare"   and the  error checking and the   "execute" statement,  but I can't get it right. How would I do this?     FYI this is a GoDaddy shared server.

```<code>//Getting the search "word" from the GetCards.php
 public function getAllCards($word) {

    //Empty var to store all returned info from db
    $returnArray = array();

    // sql statement to be executed
    $sql = "SELECT * FROM carddbtable WHERE businessNameDB=':word";

    // prepare to be executed
    $statement = $this->conn->prepare($sql);

    // error occurred
    if (!$statement) {
        throw new Exception($statement->error);
    }

    // execute statement
    $statement->execute( :word => '$word' );

//run the query
foreach ($this->conn->query($statement) as $row) {

echo json_encode($row)."<br>"."<br>";

}

    // store all appended $rows in $returnArray to be sent to app
    $returnArray[] = $row;
}
</code>```

答:
This is what i have now.  </p>

```<code>  //Getting the search "word" from the GetCards.php
 public function getAllCards($word) {

    //Empty var to store all returned info from db
    $returnArray = array();

    //  prepare to be executed sql statement to be executed if not entered word
    $statement = $this->conn->prepare("SELECT * FROM carddbtable WHERE businessNameDB=:word");

    // error occurred
//        if (!$statement) {
//           throw new Exception($statement->error);

//        }

    // execute statement
    $res = $statement->execute([ 'word' => $word ]);

//run the query
foreach ($this->conn->query($res) as $row) {

echo json_encode($row)."<br>"."<br>";

}

    // store all appended $rows in $returnArray to be sent to app
    $returnArray[] = $row;

}
</code>```

Body:
So I have look at so many post, web sites and video and now I am so confused!  I can't seem to get it right.
How do you stop injection in this PHP/PDO.  I have this code that works, but it allows injection.

//*THIS WORKS BUT ALLOWS INJECTION
//*

//The variable $word comes from another php file where the search is created.
public function getAllCards($word) {

    $sql = "SELECT * FROM carddbtable WHERE businessNameDB='".$word."'";

foreach ($this->conn->query($sql) as $row) {

    echo json_encode($row)."
"."
";
}

$db = null;
}

With this new code I am trying to remove the variable  "$word"  from the   "SELECT * FROM "  statement
to stop the injection and add the  "prepare"   and the  error checking and the   "execute" statement,  but I can't get it right. How would I do this?     FYI this is a GoDaddy shared server.

//Getting the search "word" from the GetCards.php
 public function getAllCards($word) {

    //Empty var to store all returned info from db
    $returnArray = array();

    // sql statement to be executed
    $sql = "SELECT * FROM carddbtable WHERE businessNameDB=':word";

    // prepare to be executed
    $statement = $this->conn->prepare($sql);

    // error occurred
    if (!$statement) {
        throw new Exception($statement->error);
    }

    // execute statement
    $statement->execute( :word => '$word' );

//run the query
foreach ($this->conn->query($statement) as $row) {

echo json_encode($row)."
"."
";

}

    // store all appended $rows in $returnArray to be sent to app
    $returnArray[] = $row;
}

Body:
This is what i have now.

  //Getting the search "word" from the GetCards.php
 public function getAllCards($word) {

    //Empty var to store all returned info from db
    $returnArray = array();

    //  prepare to be executed sql statement to be executed if not entered word
    $statement = $this->conn->prepare("SELECT * FROM carddbtable WHERE businessNameDB=:word");

    // error occurred
//        if (!$statement) {
//           throw new Exception($statement->error);

//        }

    // execute statement
    $res = $statement->execute([ 'word' => $word ]);

//run the query
foreach ($this->conn->query($res) as $row) {

echo json_encode($row)."<br>"."<br>";

}

    // store all appended $rows in $returnArray to be sent to app
    $returnArray[] = $row;

}


问:
Is there a command to get the average position of currently selected objects or components in Maya? (Maya 2016, Python, Mel)
Is there a Mel or Python command that returns the average position of the currently selected objects and/or components? I know that in component selection mode, selecting a set of vertices will cause the manipulator context to move to accommodate the selected vertices, but this does not seem to work in object mode.

In either case, my goal is to be able to easily obtain the average translation of the selected objects/components without having to write code specific to each sort of thing that may be selected.

答:
you could try getting the world space position of all of the objects and then averaging it yourself - maybe something like this?

```<code>import maya.cmds as mc

sel = mc.ls(sl=True, fl=True)
count = len(sel)
sums = [0,0,0]
for item in sel:
    pos = mc.xform(item, q=true, t=True)
    sums[0] += pos[0]
    sums[1] += pos[1]
    sums[2] += pos[2]
center = [sums[0]/count, sums[1]/count, sums[2]/count]
</code>```

*Note: edited based on some comments below

Body:
you could try getting the world space position of all of the objects and then averaging it yourself - maybe something like this?

import maya.cmds as mc

sel = mc.ls(sl=True, fl=True)
count = len(sel)
sums = [0,0,0]
for item in sel:
    pos = mc.xform(item, q=true, t=True)
    sums[0] += pos[0]
    sums[1] += pos[1]
    sums[2] += pos[2]
center = [sums[0]/count, sums[1]/count, sums[2]/count]

*Note: edited based on some comments below


问:
Get values of cell row beside it only otherwise have a blank cell & formula
Is there a way preferably through excel formulas but also VBA to get the cell next to it and and if there is no value return a blank?  If there is a value return that given number. Blank as in no data in it not even a =A1

In an example
Column A has a formula which gives 1, 2, 3 each row downwards.  In column B I have formula which gets the value next to it (A1, A2 etc,) but it only appears blank and the formula is still there.

I also know how to simply copy and paste special which could be deemed a workaround but I am just curious if there is a better way of doing this.

```<code>  Sub CopyCol()

        Sheets("Sheet3").Columns(10).Copy

        Sheets("Sheet3").Columns(10).PasteSpecial xlPasteValues

End Sub
</code>```

Thanks.

答:
Use this:</p>

```<code>Option Explicit

Public Sub CopyCol()
    Dim ur As Range, col1 As Variant, col2 As Variant, r As Long

    Set ur = ThisWorkbook.Sheets("Sheet3").UsedRange

    ur.Columns("B").Clear
    col2 = ur.Columns("B")
    col1 = ur.Columns("A")

    If Not IsEmpty(col1) Then
        If IsArray(col1) Then
            For r = 1 To UBound(col1)
                If Len(col1(r, 1)) > 0 Then col2(r, 1) = col1(r, 1)
            Next
        Else
            col2 = col1
        End If
        ur.Columns("B") = col2
    End If
End Sub
</code>```

Body:
Is there a way preferably through excel formulas but also VBA to get the cell next to it and and if there is no value return a blank?  If there is a value return that given number. Blank as in no data in it not even a =A1

In an example
Column A has a formula which gives 1, 2, 3 each row downwards.  In column B I have formula which gets the value next to it (A1, A2 etc,) but it only appears blank and the formula is still there.

I also know how to simply copy and paste special which could be deemed a workaround but I am just curious if there is a better way of doing this.

  Sub CopyCol()

        Sheets("Sheet3").Columns(10).Copy

        Sheets("Sheet3").Columns(10).PasteSpecial xlPasteValues

End Sub

Thanks.

Body:
Use this:

Option Explicit

Public Sub CopyCol()
    Dim ur As Range, col1 As Variant, col2 As Variant, r As Long

    Set ur = ThisWorkbook.Sheets("Sheet3").UsedRange

    ur.Columns("B").Clear
    col2 = ur.Columns("B")
    col1 = ur.Columns("A")

    If Not IsEmpty(col1) Then
        If IsArray(col1) Then
            For r = 1 To UBound(col1)
                If Len(col1(r, 1)) > 0 Then col2(r, 1) = col1(r, 1)
            Next
        Else
            col2 = col1
        End If
        ur.Columns("B") = col2
    End If
End Sub


问:
How can I write operational results to remote database from IBM ODM Rules
I know it is not a good practice, but I need to write operational decision results into a remote database at the end of execution of the ruleflow. Does IBM ODM 8.7 provides any mechanism to achieve that ? Any workaround ? Any help ?</p>

答:
Here you should have two problems using this approach:

All information available in the Warehouse is 'opened'. This means that if you have (probably will) sensitive information, these will appear as plain text in the Warehouse Console — this maybe is not a feasible solution for some companies.

You will probably have a loss of performance for the execution of the ruleset. This can delay your business responses in a critical and productive environment.


问:
Interceptor not working at method level in a Servlet
I have a simple web-app maven project with the following structure:

SimpleServlet.java is a servlet with the following code:

```<code>@Logger
public class SimpleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("hello");
    }

}
</code>```

And the Logger class is an interceptor interface with the following code:

```<code>@InterceptorBinding
@Retention(RUNTIME)
@Target({ METHOD, TYPE })
public @interface Logger {}
</code>```

And the MyLogger class is an interceptor implementation with the following code:

```<code>@Interceptor
@Logger
public class MyLogger {

    @AroundInvoke
    public Object veQuePedo(InvocationContext ctx) throws Exception {
        System.out.println("Logged");
        return ctx.proceed();
    }

}
</code>```

My web.xml:

```<code><web-app xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
          version="3.0">

  <display-name>Archetype Created Web Application</display-name>
  <servlet>
        <servlet-name>ThaServlet</servlet-name>
        <servlet-class>com.SimpleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ThaServlet</servlet-name>
        <url-pattern>/hola</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

And my beans.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
    version="1.1"
    bean-discovery-mode="all">
    <interceptors>
        <class>com.MyLogger</class>
    </interceptors>
</beans>
</code>```

The case is that I read an interceptor only works on CDI beans, which I tested and noticed is correct.

For this example we are talking about a servlet, so I come to you with the following questions:

1) If the my servlet (the one in my example) is not considered a CDI bean, why when I set the @Logger interceptor works?

2) Why the interceptor @Logger in my servlet does not work at method level and does work fine at class level?

Debugging with the annotation at method level I see the servlet is wrapped, but for some reason the @AroundInvoke method is ignored.

答:
Services provided by CDI, like interception, generally only happen on business method invocations.

Essentially, these are invocations of a method through a contextual reference (an injected bean, or the containers invocation of methods on components that are treated as beans like Servlets).

In your case, the method called from "outside" the bean to "inside" the bean is not doGet() -- it's some other inherited method. The call to doGet() comes from within the bean itself and cannot be intercepted.

That's why your interception at the class level seems to be intercepted once, although it's not on the doGet() that you later try to annotate directly.

Body:
I have a simple web-app maven project with the following structure:

SimpleServlet.java is a servlet with the following code:

@Logger
public class SimpleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("hello");
    }

}

And the Logger class is an interceptor interface with the following code:

@InterceptorBinding
@Retention(RUNTIME)
@Target({ METHOD, TYPE })
public @interface Logger {}

And the MyLogger class is an interceptor implementation with the following code:

@Interceptor
@Logger
public class MyLogger {

    @AroundInvoke
    public Object veQuePedo(InvocationContext ctx) throws Exception {
        System.out.println("Logged");
        return ctx.proceed();
    }

}

My web.xml:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
          version="3.0">

  <display-name>Archetype Created Web Application</display-name>
  <servlet>
        <servlet-name>ThaServlet</servlet-name>
        <servlet-class>com.SimpleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ThaServlet</servlet-name>
        <url-pattern>/hola</url-pattern>
    </servlet-mapping>
</web-app>

And my beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
    version="1.1"
    bean-discovery-mode="all">
    <interceptors>
        <class>com.MyLogger</class>
    </interceptors>
</beans>

The case is that I read an interceptor only works on CDI beans, which I tested and noticed is correct.

For this example we are talking about a servlet, so I come to you with the following questions:

1) If the my servlet (the one in my example) is not considered a CDI bean, why when I set the @Logger interceptor works?

2) Why the interceptor @Logger in my servlet does not work at method level and does work fine at class level?

Debugging with the annotation at method level I see the servlet is wrapped, but for some reason the @AroundInvoke method is ignored.


答:
Your code seems right. If ur expected output is like the one mentioned above, you can just add 2 more "*" to the code.

```<code>String hasil = email.replace(get_text,"***");
</code>```

I hope it helps

Title: Replace String with characters with substring

Body:
I tried to make security to display email data by replacing some words with symbol (*) but not as expected there might be an error in making the example script as below.

String email = "thismyemail@myhost.com";
String get_text = email.get_text(3, 6);
String hasil = email.replace(get_text,"*");
email_string = (EditText) findViewById(R.id.emailT);
email_string.setText(hasil);

But the result is like this

thi*email@myhost.com

Which I expect

thi***email@myhost.com

Body:
Your code seems right. If ur expected output is like the one mentioned above, you can just add 2 more "*" to the code.

String hasil = email.replace(get_text,"***");

I hope it helps


问:
Need help using getline in a file
Im having issues displaying the output. There is always and extra line being printed. I did some research and it turns out that its because my getline. Also I apologize for the format

```<code>#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct menuItemType
{
string menuItem;
double menuPrice;
};

int main()
 {
 menuItemType plainEgg;
 menuItemType baconEgg;
 menuItemType muffin;
 menuItemType frenchToast;
 menuItemType fruitBasket;
 menuItemType cereal;
 menuItemType coffee;
 menuItemType tea;

ifstream infile;
infile.open("Ch9_Ex5Data.txt");

while(infile)
{
getline(infile,plainEgg.menuItem);
infile >> plainEgg.menuPrice;

getline(infile,baconEgg.menuItem);
infile >> baconEgg.menuPrice;

getline(infile,muffin.menuItem);
infile >> muffin.menuPrice;

getline(infile,frenchToast.menuItem);
infile >> frenchToast.menuPrice;

getline(infile,fruitBasket.menuItem);
infile >> fruitBasket.menuPrice;

getline(infile,cereal.menuItem);
infile >> cereal.menuPrice;

getline(infile,coffee.menuItem);
infile >> coffee.menuPrice;

getline(infile,tea.menuItem);
infile >> tea.menuPrice;

cout << plainEgg.menuItem << plainEgg.menuPrice << endl;
cout << baconEgg.menuItem << baconEgg.menuPrice << endl;
cout << muffin.menuItem << muffin.menuPrice << endl;
cout << frenchToast.menuItem << frenchToast.menuPrice << endl;
cout << fruitBasket.menuItem << fruitBasket.menuPrice << endl;
cout << cereal.menuItem << cereal.menuPrice << endl;
cout << coffee.menuItem << coffee.menuPrice << endl;
cout << tea.menuItem << tea.menuPrice << endl;
}
infile.close();

return 0;
}
</code>```

Contents in the file

```<code>Plain Eggs
1.45
Bacon and Eggs
2.45
etc.
</code>```

I tried using

```<code>if (infile.eof())
    cout << endl;
</code>```

this is my output

```<code>Plain Egg1.45   // <-- this is the only correct output
Bacon
and Egg2.45
Muffin
0.99
French
Toast1.99
Fruit
Basket2.49
Cereal
0.69
Coffee
0.50
Tea
0.75
</code>```

Only thing that printed correctly was the very first line. (Note)I have to use structure.

答:
There are at least three major problems in the shown code. The first one is not properly checking for an end of file condition:

```<code>while(infile)
</code>```

This checks if the input stream already entered a failed state.

After reading the last line in your file, your input stream hasn't failed yet. Everything, up until point, has went exactly according to plan.

So, after the last line in the file, this condition will still evaluate to true, running the loop one more time. Of course, it will fail miserably.

And explicitly checking if (infile.eof()) will, again, if the file has already encountered an end-of-file condition.

What you probably want to do is to try to start reading the next line from the file, and if it fails, then you've reached the end of it:

```<code>while (getline(infile,plainEgg.menuItem))
{
      // The code that reads the next set of items.
</code>```

But this, alone, won't solve all of your problems.

```<code>getline(infile,plainEgg.menuItem);
infile >> plainEgg.menuPrice;
</code>```

This is mixing an unformatted input operation, std::getline(), with a formatted input operation, the >> operator.

Such combination is fragile, and has several non-obvious failure modes, as explained here, so I won't repeat that; just see this earlier question for more information.

Although there are ways to do this correctly, it's going to be easier for you to rewrite your code to use only std::getline(), or the >> operator to read everything, until you fully understand how to correctly combine unformatted and formatted input operations.

The last problem is a minor quibble. The shown code fails to properly handle incomplete input, and error checking. As shown, as long as it successfully reads the first piece in a set of data, it assumes that the remaining data will be there. You should verify that every input operation (whether you choose to use formatted or unformatted input operations) is properly checked for success.

Title: Need help using getline in a file

Body:
Im having issues displaying the output. There is always and extra line being printed. I did some research and it turns out that its because my getline. Also I apologize for the format

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct menuItemType
{
string menuItem;
double menuPrice;
};

int main()
 {
 menuItemType plainEgg;
 menuItemType baconEgg;
 menuItemType muffin;
 menuItemType frenchToast;
 menuItemType fruitBasket;
 menuItemType cereal;
 menuItemType coffee;
 menuItemType tea;

ifstream infile;
infile.open("Ch9_Ex5Data.txt");

while(infile)
{
getline(infile,plainEgg.menuItem);
infile >> plainEgg.menuPrice;

getline(infile,baconEgg.menuItem);
infile >> baconEgg.menuPrice;

getline(infile,muffin.menuItem);
infile >> muffin.menuPrice;

getline(infile,frenchToast.menuItem);
infile >> frenchToast.menuPrice;

getline(infile,fruitBasket.menuItem);
infile >> fruitBasket.menuPrice;

getline(infile,cereal.menuItem);
infile >> cereal.menuPrice;

getline(infile,coffee.menuItem);
infile >> coffee.menuPrice;

getline(infile,tea.menuItem);
infile >> tea.menuPrice;

cout << plainEgg.menuItem << plainEgg.menuPrice << endl;
cout << baconEgg.menuItem << baconEgg.menuPrice << endl;
cout << muffin.menuItem << muffin.menuPrice << endl;
cout << frenchToast.menuItem << frenchToast.menuPrice << endl;
cout << fruitBasket.menuItem << fruitBasket.menuPrice << endl;
cout << cereal.menuItem << cereal.menuPrice << endl;
cout << coffee.menuItem << coffee.menuPrice << endl;
cout << tea.menuItem << tea.menuPrice << endl;
}
infile.close();

return 0;
}

Contents in the file

Plain Eggs
1.45
Bacon and Eggs
2.45
etc.

I tried using

if (infile.eof())
    cout << endl;

this is my output

Plain Egg1.45   // <-- this is the only correct output
Bacon
and Egg2.45
Muffin
0.99
French
Toast1.99
Fruit
Basket2.49
Cereal
0.69
Coffee
0.50
Tea
0.75

Only thing that printed correctly was the very first line. (Note)I have to use structure.

Body:
There are at least three major problems in the shown code. The first one is not properly checking for an end of file condition:

while(infile)

This checks if the input stream already entered a failed state.

After reading the last line in your file, your input stream hasn't failed yet. Everything, up until point, has went exactly according to plan.

So, after the last line in the file, this condition will still evaluate to true, running the loop one more time. Of course, it will fail miserably.

And explicitly checking if (infile.eof()) will, again, if the file has already encountered an end-of-file condition.

What you probably want to do is to try to start reading the next line from the file, and if it fails, then you've reached the end of it:

while (getline(infile,plainEgg.menuItem))
{
      // The code that reads the next set of items.

But this, alone, won't solve all of your problems.

getline(infile,plainEgg.menuItem);
infile >> plainEgg.menuPrice;

This is mixing an unformatted input operation, std::getline(), with a formatted input operation, the >> operator.

Such combination is fragile, and has several non-obvious failure modes, as explained here, so I won't repeat that; just see this earlier question for more information.

Although there are ways to do this correctly, it's going to be easier for you to rewrite your code to use only std::getline(), or the >> operator to read everything, until you fully understand how to correctly combine unformatted and formatted input operations.

The last problem is a minor quibble. The shown code fails to properly handle incomplete input, and error checking. As shown, as long as it successfully reads the first piece in a set of data, it assumes that the remaining data will be there. You should verify that every input operation (whether you choose to use formatted or unformatted input operations) is properly checked for success.


问:
Limit number of connections to instances with AWS ELB
We are using AWS classic ELB for our service and our service can only serve x number of requests at a time. If the number of requests are greater than x then we do not want to route those requests to the instance and neither do we want to lose those requests. We would like to limit the number of connections to the instances registered with the ELB. Is there some ELB setting to configure max connections to instances?

Another solution I could find was to use ELB connection draining but based on the ELB doc [1] , using connection draining will mark the instance as OutofService after serving in-flight requests. Does that mean the instance will be terminated and de-registered from ELB after in-flight requests are served? We do not want to terminate and de-register the instances, we just want to limit the number of connections to the instances. Any solutions?

[1] http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/config-conn-drain.html

答:
ELB is more meant to spread traffic evenly across instances registered for it. If you have more traffic, you throw up more instances to deal with it. This is generally why a load balancer is matched with an auto scaling group. The Auto Scaling Group will look at set constraints and based on that either spins up more instances or pulls them down (ie. your traffic starts to slow down).

Connection draining is more meant for pulling traffic from bad instances so it doesn't get lost. Bad instances mean they aren't passing health checks because something on the instance is broken. ELB by itself doesn't terminate instances, that's another part of what the Auto Scaling Group is meant to do (basically terminate the bad instance and spin up a new instance to replace it). All ELB does is stop sending traffic to it.


问:
How can I retrieve rows in a text file
I started programing in language C, and I have some problems with reading text files. Let me explain.

I have one file text which is organized like this :

```<code>Tony
12.23
John
09.45
Tayris
03.99
</code>```

I would like to retrieve all notes less than ten and display them, but I can't...

Does anybody could help me?

Thanks a lot.

答:
C provides four functions that can be used to read files from disk:

fscanf()

field oriented function.

fgets()

line oriented function.

fgetc()

character oriented function

fread()

block oriented function.

See this article for more information.

Title: How can I retrieve rows in a text file

Body:
I started programing in language C, and I have some problems with reading text files. Let me explain.

I have one file text which is organized like this :

Tony
12.23
John
09.45
Tayris
03.99

I would like to retrieve all notes less than ten and display them, but I can't...

Does anybody could help me?

Thanks a lot.