问:
Get img currentSrc using Vue
Basically, I have an img element that looks like this:

```<code><img
     ref="primaryImg"
     id="primary-img"
     class="profile-img"
     sizes="(max-width: 1920px) 80vw,
     (max-width: 1440px) 70vw,
     (max-width: 1280px) 60vw,
     (max-width: 1020px) 50vw,
     (max-width: 900px) 40vw,
     (max-width: 800px) 30vw,
     (max-width: 600px) 20vw,
     (max-width: 400px) 10vw,
     80vw"
     :srcset="profile.photos.primary._srcset"
     alt="">
</code>```

srcset contains different urls to be used depending on the user's device viewport.

In order to access the element's properties, I used Vue's this.$refs.

On mounted(), I tried to console.dir(this.$refs.primaryImg).

```<code>mounted() {
    console.dir(this.$refs.primaryImg);
},
</code>```

It did show the currentSrc on the browser's console

However, when I tried to do this

console.dir(this.$refs.primaryImg.currentSrc);

It returns an empty string. I assume this has to be a lifecycle issue, the img src might not be initialized at this point of time. How do I get the currentSrc?

答:
Vamsi's answer is correct on the img not being loaded yet.
To make your currentSrc dynamic, I suggest you capture changes in screensize and update accordingly

First, add currentSrc to your data.

```<code>data () {
  return {
    currentSrc: ''
  }
},
</code>```

Then update it on first img load

```<code><img
     ref="primaryImg"
     id="primary-img"
     class="profile-img"
     sizes="(max-width: 1920px) 80vw,
     (max-width: 1440px) 70vw,
     (max-width: 1280px) 60vw,
     (max-width: 1020px) 50vw,
     (max-width: 900px) 40vw,
     (max-width: 800px) 30vw,
     (max-width: 600px) 20vw,
     (max-width: 400px) 10vw,
     80vw"
     :srcset="profile.photos.primary._srcset"
     alt=""
     @load="e => currentSrc = e.target.currentSrc"
     >
</code>```

And to capture changes on screen size change

```<code>mounted () {
  this.$nextTick(function() {
    window.addEventListener('resize', this.updateCurrentSrc);
  })
},
methods: {
  updateCurrentSrc () {
    this.currentSrc = this.$refs.primaryImg.currentSrc
  }
}
</code>```

And to use currentSrc

```<code><img :src="currentSrc" v-if="currentSrc">
</code>```

Title: Get img currentSrc using Vue

Body:
Basically, I have an img element that looks like this:

srcset contains different urls to be used depending on the user's device viewport.

In order to access the element's properties, I used Vue's this.$refs.

On mounted(), I tried to console.dir(this.$refs.primaryImg).

mounted() {
    console.dir(this.$refs.primaryImg);
},

It did show the currentSrc on the browser's console

However, when I tried to do this

console.dir(this.$refs.primaryImg.currentSrc);

It returns an empty string. I assume this has to be a lifecycle issue, the img src might not be initialized at this point of time. How do I get the currentSrc?

Body:
Vamsi's answer is correct on the img not being loaded yet.
To make your currentSrc dynamic, I suggest you capture changes in screensize and update accordingly

First, add currentSrc to your data.

data () {
  return {
    currentSrc: ''
  }
},

Then update it on first img load

<img
     ref="primaryImg"
     id="primary-img"
     class="profile-img"
     sizes="(max-width: 1920px) 80vw,
     (max-width: 1440px) 70vw,
     (max-width: 1280px) 60vw,
     (max-width: 1020px) 50vw,
     (max-width: 900px) 40vw,
     (max-width: 800px) 30vw,
     (max-width: 600px) 20vw,
     (max-width: 400px) 10vw,
     80vw"
     :srcset="profile.photos.primary._srcset"
     alt=""
     @load="e => currentSrc = e.target.currentSrc"
     >

And to capture changes on screen size change

mounted () {
  this.$nextTick(function() {
    window.addEventListener('resize', this.updateCurrentSrc);
  })
},
methods: {
  updateCurrentSrc () {
    this.currentSrc = this.$refs.primaryImg.currentSrc
  }
}

And to use currentSrc

<img :src="currentSrc" v-if="currentSrc">


来源: stackexchange

问:
Unable to compile MPI program with OpenMP with OpenMPI
I am trying to compare solvers with one of them being parallelized in OpenMP; Solvers are all running in parallel under OpenMPI using Fixed Form Fortran 77; mpif77 does not let me link the object files with the -fopenmp switch; Make does not create the executable. I tried to compile the OpenMP source files separately with gfortran and then tried to link them with mpif77 - does not work; When I do not use the switch it throws the common error:

```<code>Undefined symbols for architecture x86_64:
  "_GOMP_parallel", referenced from:
      _parmatdiff_ in matdiff.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make: *** [solvercomp] Error
</code>```

1

My question is does OpenMPI support OpenMP and if yes, how do I ensure that 'make' links object files created to functions in OpenMP libraries?

Here is a copy of my makefile:

```<code>SOURCES = solvcomp.f matdiff.f seqjacobi.f seqconjgrad.f parsor.f
FCC = mpif77
MPIRUN = mpirun
OBJECTS = $(SOURCES:.f=.o)
TARGET = soln
FFLAGS = -o
CFLAGS = -c
NP = 4

all: $(TARGET) clean

$(TARGET): $(OBJECTS)
        $(FCC) $(FFLAGS) $(TARGET) $(OBJECTS)

$(OBJECTS): $(SOURCES)
        $(FCC) $(CFLAGS) $(SOURCES)

clean:
    rm -rf *.o *.dSYM
</code>```

答:
OpenMPI compiler mpicc|mpic++|mpif70|... is basically a program that calls a backend compiler with the appropriate flags that you need in order to include the necessary headers and link with the runtime library.

If you add the flag -showme, you will be able to see which compiler are you using. Although OpenMP is a standard, the compilers may have use different flags to indicate that your program must interpret OMP constructs and link with OpenMP runtime library. You can add -showme:link to your link command in order to see what options are being passed to the backend fortran compiler.

MPI and OpenMP are two parallel programming models commonly used together, so there shouldn't be any problem for you to do so in your programs.

https://www.open-mpi.org/doc/v2.0/man1/mpicc.1.php

ContentLicense: CC BY-SA 3.0

Body:
I am trying to compare solvers with one of them being parallelized in OpenMP; Solvers are all running in parallel under OpenMPI using Fixed Form Fortran 77; mpif77 does not let me link the object files with the -fopenmp switch; Make does not create the executable. I tried to compile the OpenMP source files separately with gfortran and then tried to link them with mpif77 - does not work; When I do not use the switch it throws the common error:

Undefined symbols for architecture x86_64:
  "_GOMP_parallel", referenced from:
      _parmatdiff_ in matdiff.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make: *** [solvercomp] Error

1

My question is does OpenMPI support OpenMP and if yes, how do I ensure that 'make' links object files created to functions in OpenMP libraries?

Here is a copy of my makefile:

SOURCES = solvcomp.f matdiff.f seqjacobi.f seqconjgrad.f parsor.f
FCC = mpif77
MPIRUN = mpirun
OBJECTS = $(SOURCES:.f=.o)
TARGET = soln
FFLAGS = -o
CFLAGS = -c
NP = 4

all: $(TARGET) clean

$(TARGET): $(OBJECTS)
        $(FCC) $(FFLAGS) $(TARGET) $(OBJECTS)

$(OBJECTS): $(SOURCES)
        $(FCC) $(CFLAGS) $(SOURCES)

clean:
    rm -rf *.o *.dSYM


问:
aspnetboilerplate template project creation build errors
I have created project from aspnetboilerplate templates ASP.NET MVC 5.x, Multipage application with ef.

I have unzipped the downloaded file

I have started Visual Studio as an administrator

aspnetboilerplate site says we can use Visual Studio 2013 or later and
My Visual studio version is:
Microsoft Visual Studio Professional 2015
Version 14.0.25431.01 Update 3
Microsoft .NET Framework
Version 4.7.02046

When I try to open and build the project, the project has build errors which I have tried to resolve by from Boilerplate project creation error but still its unable to resolve.

Build errors details are:

error CS0012: The type 'Object' is defined in an assembly that is
not referenced. You must add a reference to assembly 'netstandard,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.

error CS0006: Metadata file 'D:\AAA\Projects\SourceCode\Practices\MVC\HelloWorld\3.1.3\src\HelloWorld.Application\bin\Debug\HelloWorld.Application.dll' could not be found

error CS0006: Metadata file 'D:\AAA\Projects\SourceCode\Practices\MVC\HelloWorld\3.1.3\src\HelloWorld.Core\bin\Debug\HelloWorld.Core.dll' could not be found

error CS0006: Metadata file 'D:\AAA\Projects\SourceCode\Practices\MVC\HelloWorld\3.1.3\src\HelloWorld.EntityFramework\bin\Debug\HelloWorld.EntityFramework.dll' could not be found

error CS0006: Metadata file 'D:\AAA\Projects\SourceCode\Practices\MVC\HelloWorld\3.1.3\src\HelloWorld.WebApi\bin\Debug\HelloWorld.WebApi.dll' could not be found

I have tried all options searching for solution still its not resolving.
Any suggestions/help is appreciated.

答:
aspnetboilerplate site says we can use Visual Studio 2013 or later

Unfortunately, that is an outdated instruction.

The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.

ABP v3.0.0 is based on .NET Standard 2.0.

This concerns you regardless if you are on MVC 5.x, .NET Framework 4.x or .NET Core 2.x.

You should use VS2017 15.3.3+.

Using VS2017 15.3.3+, the projects will build, resolving errors 2 to 5.

ContentLicense: CC BY-SA 4.0


问:
How to display an image on a MKOverlayView?
UPDATE:

Images who are projected on the MKMapView using a MKOverlayView use the Mercator projection, while the image that I use as input data uses a WGS84 projection. Is there a way to convert the input image, to the right projection WGS84 -> Mercator, without tiling the image up and can it done on the fly?

Normally you could convert a image to right projection using the program gdal2tiles.
The input data however changes every fifteen minutes, so the image has to be converted every fifteen minutes. So the conversion has to be done on the fly. I also want the tiling to be done by Mapkit and not by myself using gdal2tiles or the GDAL framework.

UPDATE END

I'm currently working on a project which displays a rainfall radar over some part of the world. The radar image is provided by EUMETSAT, they offer a KML file which can be loaded into Google Earth or Google Maps. If I load the KML file in Google Maps it displays perfectly, but if I draw the image using a MKOverlayView on a MKMapView, the image is slightly of.

For example, on the left side, Google Maps and on the right side the same image is displayed at a MKMapView.

The surface that the image covers can be viewed on Google Maps, the satellite that is used for the image is the "Meteosat 0 Degree" satellite.

The surface that both images cover is of the same size, this is the LatLonBox from the KML file, it specifies where the top, bottom, right, and left sides of a bounding box for the ground overlay are aligned.

```<code>  <LatLonBox id="GE_MET0D_VP-MPE-latlonbox">
        <north>57.4922</north>
        <south>-57.4922</south>
        <east>57.4922</east>
        <west>-57.4922</west>
        <rotation>0</rotation>
  </LatLonBox>
</code>```

I create a new custom MKOverlay object called RadarOverlay with these parameters,

```<code>[[RadarOverlay alloc] initWithImageData:[[self.currentRadarData objectAtIndex:0] valueForKey:@"Image"] withLowerLeftCoordinate:CLLocationCoordinate2DMake(-57.4922, -57.4922) withUpperRightCoordinate:CLLocationCoordinate2DMake(57.4922, 57.4922)];
</code>```

The implementation of the custom MKOverlay object; RadarOverlay

```<code>- (id) initWithImageData:(NSData*) imageData withLowerLeftCoordinate:(CLLocationCoordinate2D)lowerLeftCoordinate withUpperRightCoordinate:(CLLocationCoordinate2D)upperRightCoordinate
{
     self.radarData = imageData;

     MKMapPoint lowerLeft = MKMapPointForCoordinate(lowerLeftCoordinate);
     MKMapPoint upperRight = MKMapPointForCoordinate(upperRightCoordinate);

     mapRect = MKMapRectMake(lowerLeft.x, upperRight.y, upperRight.x - lowerLeft.x, lowerLeft.y - upperRight.y);

     return self;
}

- (CLLocationCoordinate2D)coordinate
{
     return MKCoordinateForMapPoint(MKMapPointMake(MKMapRectGetMidX(mapRect), MKMapRectGetMidY(mapRect)));
}

- (MKMapRect)boundingMapRect
{
     return mapRect;
}
</code>```

The implementation of the custom MKOverlayView, RadarOverlayView

```<code>- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
{
    RadarOverlay* radarOverlay = (RadarOverlay*) self.overlay;

    UIImage *image          = [[UIImage alloc] initWithData:radarOverlay.radarData];

    CGImageRef imageReference = image.CGImage;

    MKMapRect theMapRect    = [self.overlay boundingMapRect];
   CGRect theRect           = [self rectForMapRect:theMapRect];
    CGRect clipRect     = [self rectForMapRect:mapRect];

    NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
    CGContextSetAlpha(context, [preferences floatForKey:@"RadarTransparency"]);

    CGContextAddRect(context, clipRect);
    CGContextClip(context);

    CGContextDrawImage(context, theRect, imageReference);

    [image release];
}
</code>```

When I download the image, I flip the image so it can be easily drawn in the MKOverlayView

```<code>size_t width    = (CGImageGetWidth(imageReference) / self.scaleFactor);
size_t height   = (CGImageGetHeight(imageReference) / self.scaleFactor);

// Calculate colorspace for the specified image
CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageReference);

// Allocate and clear memory for the data of the image
unsigned char *imageData = (unsigned char*) malloc(height * width * 4);
memset(imageData, 0, height * width * 4);

// Define the rect for the image
CGRect imageRect;
if(image.imageOrientation==UIImageOrientationUp || image.imageOrientation==UIImageOrientationDown)
    imageRect = CGRectMake(0, 0, width, height);
else
    imageRect = CGRectMake(0, 0, height, width);

// Create the imagecontext by defining the colorspace and the address of the location to store the data
CGContextRef imageContext = CGBitmapContextCreate(imageData, width, height, 8, width * 4, imageColorSpace, kCGImageAlphaPremultipliedLast);

CGContextSaveGState(imageContext);

// Scale the image to the opposite orientation so it can be easylier drawn with CGContectDrawImage
CGContextTranslateCTM(imageContext, 0, height);
CGContextScaleCTM(imageContext, 1.0, -1.0);

if(image.imageOrientation==UIImageOrientationLeft)
{
    CGContextRotateCTM(imageContext, M_PI / 2);
    CGContextTranslateCTM(imageContext, 0, -width);
}
else if(image.imageOrientation==UIImageOrientationRight)
{
    CGContextRotateCTM(imageContext, - M_PI / 2);
    CGContextTranslateCTM(imageContext, -height, 0);
}
else if(image.imageOrientation==UIImageOrientationDown)
{
    CGContextTranslateCTM(imageContext, width, height);
    CGContextRotateCTM(imageContext, M_PI);
}

// Draw the image in the context
CGContextDrawImage(imageContext, imageRect, imageReference);
CGContextRestoreGState(imageContext);
</code>```

After I flipped the image, I manipulate it and then store it in memory as a NSData object.

It looks like the image got stretched, but it looks allright at the center of the image, which is at the equator.

答:
WGS-84 data is using UTM projection, MKMapView is using mercator. You are using different methods to map a 3D object to a 2D surface, hence it is not giving the same results.

You'll need to go down in GDAL and move the incomming image to a different projection. Let me know if you figured it out, because it ain't an easy

ContentLicense: CC BY-SA 2.5

Body:
UPDATE:

Images who are projected on the MKMapView using a MKOverlayView use the Mercator projection, while the image that I use as input data uses a WGS84 projection. Is there a way to convert the input image, to the right projection WGS84 -> Mercator, without tiling the image up and can it done on the fly?

Normally you could convert a image to right projection using the program gdal2tiles.
The input data however changes every fifteen minutes, so the image has to be converted every fifteen minutes. So the conversion has to be done on the fly. I also want the tiling to be done by Mapkit and not by myself using gdal2tiles or the GDAL framework.

UPDATE END

I'm currently working on a project which displays a rainfall radar over some part of the world. The radar image is provided by EUMETSAT, they offer a KML file which can be loaded into Google Earth or Google Maps. If I load the KML file in Google Maps it displays perfectly, but if I draw the image using a MKOverlayView on a MKMapView, the image is slightly of.

For example, on the left side, Google Maps and on the right side the same image is displayed at a MKMapView.

The surface that the image covers can be viewed on Google Maps, the satellite that is used for the image is the "Meteosat 0 Degree" satellite.

The surface that both images cover is of the same size, this is the LatLonBox from the KML file, it specifies where the top, bottom, right, and left sides of a bounding box for the ground overlay are aligned.

  <LatLonBox id="GE_MET0D_VP-MPE-latlonbox">
        <north>57.4922</north>
        <south>-57.4922</south>
        <east>57.4922</east>
        <west>-57.4922</west>
        <rotation>0</rotation>
  </LatLonBox>

I create a new custom MKOverlay object called RadarOverlay with these parameters,

[[RadarOverlay alloc] initWithImageData:[[self.currentRadarData objectAtIndex:0] valueForKey:@"Image"] withLowerLeftCoordinate:CLLocationCoordinate2DMake(-57.4922, -57.4922) withUpperRightCoordinate:CLLocationCoordinate2DMake(57.4922, 57.4922)];

The implementation of the custom MKOverlay object; RadarOverlay

- (id) initWithImageData:(NSData*) imageData withLowerLeftCoordinate:(CLLocationCoordinate2D)lowerLeftCoordinate withUpperRightCoordinate:(CLLocationCoordinate2D)upperRightCoordinate
{
     self.radarData = imageData;

     MKMapPoint lowerLeft = MKMapPointForCoordinate(lowerLeftCoordinate);
     MKMapPoint upperRight = MKMapPointForCoordinate(upperRightCoordinate);

     mapRect = MKMapRectMake(lowerLeft.x, upperRight.y, upperRight.x - lowerLeft.x, lowerLeft.y - upperRight.y);

     return self;
}

- (CLLocationCoordinate2D)coordinate
{
     return MKCoordinateForMapPoint(MKMapPointMake(MKMapRectGetMidX(mapRect), MKMapRectGetMidY(mapRect)));
}

- (MKMapRect)boundingMapRect
{
     return mapRect;
}

The implementation of the custom MKOverlayView, RadarOverlayView

- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
{
    RadarOverlay* radarOverlay = (RadarOverlay*) self.overlay;

    UIImage *image          = [[UIImage alloc] initWithData:radarOverlay.radarData];

    CGImageRef imageReference = image.CGImage;

    MKMapRect theMapRect    = [self.overlay boundingMapRect];
   CGRect theRect           = [self rectForMapRect:theMapRect];
    CGRect clipRect     = [self rectForMapRect:mapRect];

    NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
    CGContextSetAlpha(context, [preferences floatForKey:@"RadarTransparency"]);

    CGContextAddRect(context, clipRect);
    CGContextClip(context);

    CGContextDrawImage(context, theRect, imageReference);

    [image release];
}

When I download the image, I flip the image so it can be easily drawn in the MKOverlayView

size_t width    = (CGImageGetWidth(imageReference) / self.scaleFactor);
size_t height   = (CGImageGetHeight(imageReference) / self.scaleFactor);

// Calculate colorspace for the specified image
CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageReference);

// Allocate and clear memory for the data of the image
unsigned char *imageData = (unsigned char*) malloc(height * width * 4);
memset(imageData, 0, height * width * 4);

// Define the rect for the image
CGRect imageRect;
if(image.imageOrientation==UIImageOrientationUp || image.imageOrientation==UIImageOrientationDown)
    imageRect = CGRectMake(0, 0, width, height);
else
    imageRect = CGRectMake(0, 0, height, width);

// Create the imagecontext by defining the colorspace and the address of the location to store the data
CGContextRef imageContext = CGBitmapContextCreate(imageData, width, height, 8, width * 4, imageColorSpace, kCGImageAlphaPremultipliedLast);

CGContextSaveGState(imageContext);

// Scale the image to the opposite orientation so it can be easylier drawn with CGContectDrawImage
CGContextTranslateCTM(imageContext, 0, height);
CGContextScaleCTM(imageContext, 1.0, -1.0);

if(image.imageOrientation==UIImageOrientationLeft)
{
    CGContextRotateCTM(imageContext, M_PI / 2);
    CGContextTranslateCTM(imageContext, 0, -width);
}
else if(image.imageOrientation==UIImageOrientationRight)
{
    CGContextRotateCTM(imageContext, - M_PI / 2);
    CGContextTranslateCTM(imageContext, -height, 0);
}
else if(image.imageOrientation==UIImageOrientationDown)
{
    CGContextTranslateCTM(imageContext, width, height);
    CGContextRotateCTM(imageContext, M_PI);
}

// Draw the image in the context
CGContextDrawImage(imageContext, imageRect, imageReference);
CGContextRestoreGState(imageContext);

After I flipped the image, I manipulate it and then store it in memory as a NSData object.

It looks like the image got stretched, but it looks allright at the center of the image, which is at the equator.


问:
What is the default for the "required" property in RAML 1.0?
I'm defining entities in RAML 1.0, and I feel that it's wasteful that the required attribute must be defined for each item if we want to make sure that it's (non-)optional. Is there a default value for this, and if so, which?

答:
According to the RAML 1.0 specs, the required attribute in RAML 1.0 entities defaults to "true", so it's only necessary to specify required: false for optional attributes.

Moreover, we can append a ? to the attribute name (e.g: age?), to signify that it's optional (required: false), unless the required attribute is defined, in which case the question mark will be part of the actual attribute name.


问:
How to load caffe model in c++ for predicition
I have been using Caffe on Python so far and now I am trying to use C++ to familiarize myself.

What I have done is I tried to explore the caffe FC layers by computing features and loading thru HDF5 layer. I have trained the model and it works very well with python using the following code:

```<code>caffe.set_device(0)
caffe.set_mode_gpu()
net = caffe.Net(proto_file, caffe_model, caffe.TEST)
feats, labels = get_features('test/test.txt')   #AlexNet features
for feature, label in zip(feats, labels):
    net.blobs['data'].data[...] = feature
    output = net.forward()
    output_prob = output['loss'][0]
    print output_prob.argmax(), ", ", label
</code>```

Using this python code I can check and it works very well.

I am trying to write the code in c++ to do the same prediction. This line

```<code>net.blobs['data'].data[...] = feature
</code>```

is bit tricky and I cannot do the same in c++: How can I load features into the data layer in c++:

my c++ code so far is:

```<code>    caffe::Caffe::SetDevice(0);
    caffe::Caffe::set_mode(caffe::Caffe::GPU);
    boost::shared_ptr<caffe::Net<float> > net_;
    net_.reset(new caffe::Net<float>(model_file, caffe::TEST));
    net_->CopyTrainedLayersFrom(trained_file);

    std::cout << "LOADED CAFFE MODEL\n";
    LOG(INFO) << "Blob size: "<< net_->input_blobs().size();
</code>```

This caffe example is useful but it loads image and then separates the channels. In my case I have 4096-D feature vector from AlexNet which I want to load directly as in Python code.

答:
Get the blob index according to its name:

```<code>const std::vector<std::string>& blob_names_ = net_->blob_names();
auto it = std::find(blob_names_.begin(), blob_names_.end(), "data");
int index = -1;
if (it == blob_names_.end())
{
    // no "data" blob, do error handling
}
else
{
    index = std::distance(blob_names_.begin(), it);
}
</code>```

(Of course you can also get the index by iterating over blob_names_ and compare each item).

Change the blob data:

```<code>float* feature = your_func_to_get_feature(); // custom this
caffe::Blob<float>*>& blob_to_set_ = net_->blobs()[index];
blob_to_set_->set_cpu_data(feature);
</code>```

Continue from this point as usual.

Body:
I have been using Caffe on Python so far and now I am trying to use C++ to familiarize myself.

What I have done is I tried to explore the caffe FC layers by computing features and loading thru HDF5 layer. I have trained the model and it works very well with python using the following code:

caffe.set_device(0)
caffe.set_mode_gpu()
net = caffe.Net(proto_file, caffe_model, caffe.TEST)
feats, labels = get_features('test/test.txt')   #AlexNet features
for feature, label in zip(feats, labels):
    net.blobs['data'].data[...] = feature
    output = net.forward()
    output_prob = output['loss'][0]
    print output_prob.argmax(), ", ", label

Using this python code I can check and it works very well.

I am trying to write the code in c++ to do the same prediction. This line

net.blobs['data'].data[...] = feature

is bit tricky and I cannot do the same in c++: How can I load features into the data layer in c++:

my c++ code so far is:

    caffe::Caffe::SetDevice(0);
    caffe::Caffe::set_mode(caffe::Caffe::GPU);
    boost::shared_ptr<caffe::Net<float> > net_;
    net_.reset(new caffe::Net<float>(model_file, caffe::TEST));
    net_->CopyTrainedLayersFrom(trained_file);

    std::cout << "LOADED CAFFE MODEL\n";
    LOG(INFO) << "Blob size: "<< net_->input_blobs().size();

This caffe example is useful but it loads image and then separates the channels. In my case I have 4096-D feature vector from AlexNet which I want to load directly as in Python code.

Body:
Get the blob index according to its name:

const std::vector<std::string>& blob_names_ = net_->blob_names();
auto it = std::find(blob_names_.begin(), blob_names_.end(), "data");
int index = -1;
if (it == blob_names_.end())
{
    // no "data" blob, do error handling
}
else
{
    index = std::distance(blob_names_.begin(), it);
}

(Of course you can also get the index by iterating over blob_names_ and compare each item).

Change the blob data:

float* feature = your_func_to_get_feature(); // custom this
caffe::Blob<float>*>& blob_to_set_ = net_->blobs()[index];
blob_to_set_->set_cpu_data(feature);

Continue from this point as usual.


问:
How can I get my grunt mocha test result in a html file?
Using

```<code>mochaTest: {
   test: {
    options: {
      reporter: 'html-cov',
      captureFile: 'coverage.html'
    },
    src: ['tests/*.js']
  }
}
</code>```

in my gruntfile is gives me

"html-cov" reporter not found

warning.
How can I get my test result in a html file and view it ?

Thx..

Also I'm using grunt.loadNpmTasks('grunt-selenium-standalone') task.

答:
Please check the following link:

https://github.com/pghalliday/grunt-mocha-test

Here you get the complete example, may it'll help you..

You can use Mochawesome. It is a custom reporter for use with the Javascript testing framework, mocha. It generates a nice HTML/CSS report that helps visualize your test suites.

First, you need to install the plugin:

```<code>npm install --save-dev mochawesome
</code>```

Then you change your grunt-mocha-test reporter:

```<code>mochaTest: {
    test: {
        options: {
            reporter: 'mochawesome', //You need to change this !
            colors: true,
            summery: true,
            captureFile: 'results.html',
            quiet: false,
            clearRequireCache: true
        },
        src: ['test/*spec.js'],
        excludes: ['plugins']
    },
    'travis-cov': {
        options: {
            reporter: 'travis-cov'
        }
    }
},
</code>```

Body:
Using

mochaTest: {
   test: {
    options: {
      reporter: 'html-cov',
      captureFile: 'coverage.html'
    },
    src: ['tests/*.js']
  }
}

in my gruntfile is gives me

"html-cov" reporter not found

warning.
How can I get my test result in a html file and view it ?

Thx..

Also I'm using grunt.loadNpmTasks('grunt-selenium-standalone') task.

Body:
Please check the following link:

https://github.com/pghalliday/grunt-mocha-test

Here you get the complete example, may it'll help you..

You can use Mochawesome. It is a custom reporter for use with the Javascript testing framework, mocha. It generates a nice HTML/CSS report that helps visualize your test suites.

First, you need to install the plugin:

npm install --save-dev mochawesome

Then you change your grunt-mocha-test reporter:

mochaTest: {
    test: {
        options: {
            reporter: 'mochawesome', //You need to change this !
            colors: true,
            summery: true,
            captureFile: 'results.html',
            quiet: false,
            clearRequireCache: true
        },
        src: ['test/*spec.js'],
        excludes: ['plugins']
    },
    'travis-cov': {
        options: {
            reporter: 'travis-cov'
        }
    }
},


问:
mobile landscape view Image position: absolute
```<code><head>
<meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0">
</head>

<img src="viewer.png" style="width:200; height:150; position:absolute; bottom:0; right:0;z-index:-4000;">
</code>```

Please Help : In mobile Portrait view  position is correct. but in mobile landscape view  in middle rightside..
(I placed  to view bottom of all contents.. no scrollbars in portrait view)
How to fix it?

答:
you can try this way

.imgcenter{
position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 40%;
  height: 50%;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://unsplash.it/200/80" alt="" class="imgcenter"></code>```

Body:
<meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0">

Please Help : In mobile Portrait view  position is correct. but in mobile landscape view  in middle rightside..
(I placed  to view bottom of all contents.. no scrollbars in portrait view)
How to fix it?

Body:
you can try this way

.imgcenter{
position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 40%;
  height: 50%;
  text-align: center;
}

<img src="https://unsplash.it/200/80" alt="" class="imgcenter">


问:
iPad/iOS modalView jumps left on dismiss
I added a modalView to my App, everything working fine, but on closing the modal, the whole modalView jumps about 1-2 centimeters to left while it disappears.

I did not find any reason for it yet, so here is the code regarding modal:

AppController:

```<code>- (void) showNameModal:(Player *)player
{
    namesModal = [[PlayerModalView alloc] init];
    namesModal.delegate = self;
    namesModal.player = player;

    UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:namesModal];

    navCon.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentModalViewController:navCon animated:YES];

    [navCon release];
    [namesModal release];
 }

 - (void)didDismissModalView
 {
    [self dismissModalViewControllerAnimated:YES];
 }
</code>```

ModalView:

```<code> - (void)dismissView:(id)sender
 {
    [delegate didDismissModalView];
 }
</code>```

called via navigation buttons as well ass via keyboard by

```<code>  [self dismissView:nil];
</code>```

As you can see, there is nothing special in it, could be taken from a manual actually.
What happens in detail:

Modal appears in center of screen, slides in from the bottom. centered all time.
i can handle some actions in the modalView, it stays centered.

now, dismissing the view makes it jumping to the left, than slides out.

Since it's a forced landscape-right app (currently), I was only able to notify the left-jump.

Any ideas how to get this jumping away?

Thanks

答:
This solution seems to work well: Modal View Controller with keyboard on landscape iPad changes location when dismissed

To simplify resigning the first responder (if finding it is difficult), you can just call

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

Body:
I added a modalView to my App, everything working fine, but on closing the modal, the whole modalView jumps about 1-2 centimeters to left while it disappears.

I did not find any reason for it yet, so here is the code regarding modal:

AppController:

- (void) showNameModal:(Player *)player
{
    namesModal = [[PlayerModalView alloc] init];
    namesModal.delegate = self;
    namesModal.player = player;

    UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:namesModal];

    navCon.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentModalViewController:navCon animated:YES];

    [navCon release];
    [namesModal release];
 }

 - (void)didDismissModalView
 {
    [self dismissModalViewControllerAnimated:YES];
 }

ModalView:

 - (void)dismissView:(id)sender
 {
    [delegate didDismissModalView];
 }

called via navigation buttons as well ass via keyboard by

  [self dismissView:nil];

As you can see, there is nothing special in it, could be taken from a manual actually.
What happens in detail:

Modal appears in center of screen, slides in from the bottom. centered all time.
i can handle some actions in the modalView, it stays centered.

now, dismissing the view makes it jumping to the left, than slides out.

Since it's a forced landscape-right app (currently), I was only able to notify the left-jump.

Any ideas how to get this jumping away?

Thanks

Body:
This solution seems to work well: Modal View Controller with keyboard on landscape iPad changes location when dismissed

To simplify resigning the first responder (if finding it is difficult), you can just call

[self.view endEditing:YES];
[self dismissModalViewControllerAnimated:YES];


问:
Prolog - How do i separate a tuple to be part of my pre-existing list?
I am trying to take the following:

```<code>[a,b,(c,d)]
</code>```

and turn it to

```<code>[a,b,c,d]
</code>```

I am obtaining [a], [b], and [(c,d)] separately from different findalls and appending them together to obtain the [a,b,(c,d)] list.

答:
```<code>?- write_canonical([1,2,(3,4)]).
[1,2,','(3,4)]
</code>```

You can see that parenthesis (when contain comma(s)) have a peculiar property: they behave as a structure. Another example

```<code>?- arg(2,(x,y),A).
A = y.
</code>```

For your problem, I would write

```<code>?- [user].
|: elem((X,_),X).
|: elem((_,T),X):-elem(T,X).
|: elem(X,X) :- atomic(X).
|: ^D% user://1 compiled 0.02 sec, 3 clauses
true.
</code>```

and now

```<code>?- L=[1,2,(3,4)], findall(Y,(member(X,L),elem(X,Y)),F).
L = [1, 2,  (3, 4)],
F = [1, 2, 3, 4].

?- L=[1,2,(3,4),(5),(6,7,8)], findall(Y,(member(X,L),elem(X,Y)),F).
L = [1, 2,  (3, 4), 5,  (6, 7, 8)],
F = [1, 2, 3, 4, 5, 6, 7, 8].
</code>```

Note this will work only a level depth. To enable arbitrary nesting, should be enough to change the first clause of elem/2:

```<code>elem((X,_),Y) :- elem(X,Y).
</code>```

Body:
I am trying to take the following:

[a,b,(c,d)]

and turn it to

[a,b,c,d]

I am obtaining [a], [b], and [(c,d)] separately from different findalls and appending them together to obtain the [a,b,(c,d)] list.

Body:
?- write_canonical([1,2,(3,4)]).
[1,2,','(3,4)]

You can see that parenthesis (when contain comma(s)) have a peculiar property: they behave as a structure. Another example

?- arg(2,(x,y),A).
A = y.

For your problem, I would write

?- [user].
|: elem((X,_),X).
|: elem((_,T),X):-elem(T,X).
|: elem(X,X) :- atomic(X).
|: ^D% user://1 compiled 0.02 sec, 3 clauses
true.

and now

?- L=[1,2,(3,4)], findall(Y,(member(X,L),elem(X,Y)),F).
L = [1, 2,  (3, 4)],
F = [1, 2, 3, 4].

?- L=[1,2,(3,4),(5),(6,7,8)], findall(Y,(member(X,L),elem(X,Y)),F).
L = [1, 2,  (3, 4), 5,  (6, 7, 8)],
F = [1, 2, 3, 4, 5, 6, 7, 8].

Note this will work only a level depth. To enable arbitrary nesting, should be enough to change the first clause of elem/2:

elem((X,_),Y) :- elem(X,Y).


问:
Is there any binocular AR SDK for Android?
I have one of these VR headsets that you insert your phone into and you can use VR apps. The headset also has a feature for AR, meaning I can take out a part of it and the phone`s camera can record what I am looking at and overlap AR elements on the image. The problem is none of the AR tutorials I read show how to do the split screen style VR apps usually have.</p>

答:
Its called Cardboard SDK but appears that Vuforia integrated it in its core:

https://library.vuforia.com/articles/Solution/Integrating-Cardboard-to-the-ARVR-Sample

If using other AR libraries (EasyAR maybe) Cardboard SDK might still be usefull.


问:
Finding duplicates from multiple list in python
I want to find duplicates( not to remove these duplicates but extract those repeating values) from multiple lists which are in a single list for example : a have list called Chunks which has 13 lists inside it.

my data is as follows

```<code>[[@TestRun
    And user set text "#Surname" on textbox name "surname"
    And user validate message on screen "Switch to paperless"
    And user click on "Manage accounts" label
    And user click link with label "View all online services"
    And user waits for 10 seconds
    Then page is successfully launched
    And user click link with label "Go paperless for complete convenience"
    Then page is successfully launched
    And user validate message on screen "#EmailAddress"
    And user clicks on the button "Confirm"
    Then page is successfully launched
    And user validate message on screen "#MessageValidate"
    Then page is successfully launched
    And user click on "menu open user preferences" label
    And user clicks on the link "Statement and letter preferences"
    Then page is successfully launched
    And user validate "Switch to paperless" button is disabled
    And user validate message on screen "Online only"
    When user click on "Log out" label
    Then page is successfully launched]

[@TestRun
    And user click on link "Mobile site"
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
    And user click on link "#Account"
    Then page is successfully launched
    And user verify message on screen "#Account"
    And user verify message on screen "Manage statements"
    And user verify message on screen "Step 1 of 3"
    Then page is successfully launched
    And user verify message on screen "Current format type"
    And user verify message on screen "Online"
    When user selects the radio button "Paper" ]

[@TestRun
 And user set text "#Surname" on textbox name "surname"
Then user wait for page load
And user click on button "Continue to Online Banking"
Then user wait for page load
    And user click on "menu open user preferences" label
    And user clicks on the link "Statement and letter preferences"
    Then page is successfully launched
    And page is successfully launched
    And user waits for 10 seconds ]
[ @TestRun
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
    And user waits for 10 seconds
    And user click checkbox "Telephone"
    And user click checkbox "Post"
    And user clicks on the button "Save"
    Then page is successfully launched ]]
</code>```

I have extracted every testcases in one list i.e lines betwwen two @testrun as one list

```<code> import itertools as it
import more_itertools as mit
import pandas as pd
## got seperated all test case in seprate list i.e 13 test cases in 13 lists
with open('cust_pref.txt', "r") as f1:
    lines_1 = f1.readlines()

    pred_1 = lambda x: x.startswith("@TestRun")
    inv_pred_1 = lambda x: not pred_1(x)

    lines_1 = it.dropwhile(inv_pred_1, lines_1)
    chunks_1 = list(mit.split_before(lines_1, pred_1))
##print the list of testcases
print(chunks_1)
</code>```

Now I need to find out how to find common in all this lists and how can I know from which list which are common

I tried out following

```<code>def get_duplicated_element(array):
    global result, checked_elements
    checked_elements = []
    result = -1
    def array_recursive_check(array):
        global result, checked_elements
        if result != -1: return
        for i in array:
            if type(i) == list:
                if i in checked_elements:
                    result = i
                    return
                checked_elements.append(i)
                array_recursive_check(i)
    array_recursive_check(array)
    return result

get_duplicated_element(chunks_1) ## this gives the answer as -1 , which is not expected
</code>```

Expected output is: finding common values /lines(in my cases) and if possible which steps comes in which list number in python

Desired output is :

```<code>{
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
}
</code>```

AS these steps are repeated in every list  so these sholud be the output

I have used following to get duplicates

```<code>def find_dupe(lists, target):
    seen = set()
    for lst in lists:
        for item in lst:
            if item == target and item in seen:
                return True
            seen.add(item)

seen, dups = set(), set()
for l in chunks:
    dups = dups.union(seen.intersection(set(l)))
    seen = seen.union(set(l))
</code>```

I get some duplicates from this but now my problem is i dont know which line is from which list ? Is there any way to achieve this mapping which values corresponds to which list

答:
You can do something with re and defaultdict

```<code>def read_file(filehandle):
''' yields the chunks of the file, delimited by the `@TestRun`'''
    count = 0
    text = mmap.mmap(file.fileno(), 0)  # read all text in memory
    # https://stackoverflow.com/a/454589/1562285
    string_pattern = re.compile(rb'(?:\[\@TestRun(.+?)\].*?)*', re.DOTALL)
    for item in string_pattern.findall(text):
        if item:
            yield count, [i.strip() for i in item.decode('utf8').strip().split('\n')]
            count += 1

def parse_chunks(chunks):
""" puts the lines of these chunks into a dick, with the line as key and a list of the positions of this line `(chunk_no, line_no) as value`"""
    result = collections.defaultdict(list)
    for chunk_no, lines in chunks:
        for i, line in enumerate(lines):
            result[line].append((chunk_no, i))
    return dict(result)
</code>```

Then you can use this like this

```<code>with open(file, 'r') as file
    chunks = read_file(file)
    result = parse_chunks(chunks)
</code>```

```<code>{
    'And user set text "#Surname" on textbox name "surname"': [(0, 0), (1, 1), (2, 0), (3, 0)],
    'And user validate message on screen "Switch to paperless"': [(0, 1)],
    'And user click on "Manage accounts" label': [(0, 2)],
    'And user click link with label "View all online services"': [(0, 3)],
    'And user waits for 10 seconds': [(0, 4), (2, 8), (3, 2)],
    'Then page is successfully launched': [(0, 5), (0, 7), (0, 10), (0, 12), (0, 15), (0, 19), (1, 2), (1, 4), (1, 8), (2, 6), (3, 1), (3, 6)],
    'And user click link with label "Go paperless for complete convenience"': [(0, 6)],
    'And user validate message on screen "#EmailAddress"': [(0, 8)],
    'And user clicks on the button "Confirm"': [(0, 9)],
    'And user validate message on screen "#MessageValidate"': [(0, 11)],
    'And user click on "menu open user preferences" label': [(0, 13), (2, 4)],
    'And user clicks on the link "Statement and letter preferences"': [(0, 14), (2, 5)],
    'And user validate "Switch to paperless" button is disabled': [(0, 16)],
    'And user validate message on screen "Online only"': [(0, 17)],
    'When user click on "Log out" label': [(0, 18)],
    'And user click on link "Mobile site"': [(1, 0)],
    'And user click on link "#Account"': [(1, 3)],
    'And user verify message on screen "#Account"': [(1, 5)],
    'And user verify message on screen "Manage statements"': [(1, 6)],
    'And user verify message on screen "Step 1 of 3"': [(1, 7)],
    'And user verify message on screen "Current format type"': [(1, 9)],
    'And user verify message on screen "Online"': [(1, 10)],
    'When user selects the radio button "Paper"': [(1, 11)],
    'Then user wait for page load': [(2, 1), (2, 3)],
    'And user click on button "Continue to Online Banking"': [(2, 2)],
    'And page is successfully launched': [(2, 7)],
    'And user click checkbox "Telephone"': [(3, 3)],
    'And user click checkbox "Post"': [(3, 4)],
    'And user clicks on the button "Save"': [(3, 5)]
}
</code>```

You can filter those duplicates with

```<code>{key: value for key, value in result.items() if len(value)> 1}
</code>```

Body:
I want to find duplicates( not to remove these duplicates but extract those repeating values) from multiple lists which are in a single list for example : a have list called Chunks which has 13 lists inside it.

my data is as follows

[[@TestRun
    And user set text "#Surname" on textbox name "surname"
    And user validate message on screen "Switch to paperless"
    And user click on "Manage accounts" label
    And user click link with label "View all online services"
    And user waits for 10 seconds
    Then page is successfully launched
    And user click link with label "Go paperless for complete convenience"
    Then page is successfully launched
    And user validate message on screen "#EmailAddress"
    And user clicks on the button "Confirm"
    Then page is successfully launched
    And user validate message on screen "#MessageValidate"
    Then page is successfully launched
    And user click on "menu open user preferences" label
    And user clicks on the link "Statement and letter preferences"
    Then page is successfully launched
    And user validate "Switch to paperless" button is disabled
    And user validate message on screen "Online only"
    When user click on "Log out" label
    Then page is successfully launched]

[@TestRun
    And user click on link "Mobile site"
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
    And user click on link "#Account"
    Then page is successfully launched
    And user verify message on screen "#Account"
    And user verify message on screen "Manage statements"
    And user verify message on screen "Step 1 of 3"
    Then page is successfully launched
    And user verify message on screen "Current format type"
    And user verify message on screen "Online"
    When user selects the radio button "Paper" ]

[@TestRun
 And user set text "#Surname" on textbox name "surname"
Then user wait for page load
And user click on button "Continue to Online Banking"
Then user wait for page load
    And user click on "menu open user preferences" label
    And user clicks on the link "Statement and letter preferences"
    Then page is successfully launched
    And page is successfully launched
    And user waits for 10 seconds ]
[ @TestRun
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
    And user waits for 10 seconds
    And user click checkbox "Telephone"
    And user click checkbox "Post"
    And user clicks on the button "Save"
    Then page is successfully launched ]]

I have extracted every testcases in one list i.e lines betwwen two @testrun as one list

 import itertools as it
import more_itertools as mit
import pandas as pd
## got seperated all test case in seprate list i.e 13 test cases in 13 lists
with open('cust_pref.txt', "r") as f1:
    lines_1 = f1.readlines()

    pred_1 = lambda x: x.startswith("@TestRun")
    inv_pred_1 = lambda x: not pred_1(x)

    lines_1 = it.dropwhile(inv_pred_1, lines_1)
    chunks_1 = list(mit.split_before(lines_1, pred_1))
##print the list of testcases
print(chunks_1)

Now I need to find out how to find common in all this lists and how can I know from which list which are common

I tried out following

def get_duplicated_element(array):
    global result, checked_elements
    checked_elements = []
    result = -1
    def array_recursive_check(array):
        global result, checked_elements
        if result != -1: return
        for i in array:
            if type(i) == list:
                if i in checked_elements:
                    result = i
                    return
                checked_elements.append(i)
                array_recursive_check(i)
    array_recursive_check(array)
    return result

get_duplicated_element(chunks_1) ## this gives the answer as -1 , which is not expected

Expected output is: finding common values /lines(in my cases) and if possible which steps comes in which list number in python

Desired output is :

{
    And user set text "#Surname" on textbox name "surname"
    Then page is successfully launched
}

AS these steps are repeated in every list  so these sholud be the output

I have used following to get duplicates

def find_dupe(lists, target):
    seen = set()
    for lst in lists:
        for item in lst:
            if item == target and item in seen:
                return True
            seen.add(item)

seen, dups = set(), set()
for l in chunks:
    dups = dups.union(seen.intersection(set(l)))
    seen = seen.union(set(l))

I get some duplicates from this but now my problem is i dont know which line is from which list ? Is there any way to achieve this mapping which values corresponds to which list

Body:
You can do something with re and defaultdict

def read_file(filehandle):
''' yields the chunks of the file, delimited by the `@TestRun`'''
    count = 0
    text = mmap.mmap(file.fileno(), 0)  # read all text in memory
    # https://stackoverflow.com/a/454589/1562285
    string_pattern = re.compile(rb'(?:\[\@TestRun(.+?)\].*?)*', re.DOTALL)
    for item in string_pattern.findall(text):
        if item:
            yield count, [i.strip() for i in item.decode('utf8').strip().split('\n')]
            count += 1

def parse_chunks(chunks):
""" puts the lines of these chunks into a dick, with the line as key and a list of the positions of this line `(chunk_no, line_no) as value`"""
    result = collections.defaultdict(list)
    for chunk_no, lines in chunks:
        for i, line in enumerate(lines):
            result[line].append((chunk_no, i))
    return dict(result)

Then you can use this like this

with open(file, 'r') as file
    chunks = read_file(file)
    result = parse_chunks(chunks)

{
    'And user set text "#Surname" on textbox name "surname"': [(0, 0), (1, 1), (2, 0), (3, 0)],
    'And user validate message on screen "Switch to paperless"': [(0, 1)],
    'And user click on "Manage accounts" label': [(0, 2)],
    'And user click link with label "View all online services"': [(0, 3)],
    'And user waits for 10 seconds': [(0, 4), (2, 8), (3, 2)],
    'Then page is successfully launched': [(0, 5), (0, 7), (0, 10), (0, 12), (0, 15), (0, 19), (1, 2), (1, 4), (1, 8), (2, 6), (3, 1), (3, 6)],
    'And user click link with label "Go paperless for complete convenience"': [(0, 6)],
    'And user validate message on screen "#EmailAddress"': [(0, 8)],
    'And user clicks on the button "Confirm"': [(0, 9)],
    'And user validate message on screen "#MessageValidate"': [(0, 11)],
    'And user click on "menu open user preferences" label': [(0, 13), (2, 4)],
    'And user clicks on the link "Statement and letter preferences"': [(0, 14), (2, 5)],
    'And user validate "Switch to paperless" button is disabled': [(0, 16)],
    'And user validate message on screen "Online only"': [(0, 17)],
    'When user click on "Log out" label': [(0, 18)],
    'And user click on link "Mobile site"': [(1, 0)],
    'And user click on link "#Account"': [(1, 3)],
    'And user verify message on screen "#Account"': [(1, 5)],
    'And user verify message on screen "Manage statements"': [(1, 6)],
    'And user verify message on screen "Step 1 of 3"': [(1, 7)],
    'And user verify message on screen "Current format type"': [(1, 9)],
    'And user verify message on screen "Online"': [(1, 10)],
    'When user selects the radio button "Paper"': [(1, 11)],
    'Then user wait for page load': [(2, 1), (2, 3)],
    'And user click on button "Continue to Online Banking"': [(2, 2)],
    'And page is successfully launched': [(2, 7)],
    'And user click checkbox "Telephone"': [(3, 3)],
    'And user click checkbox "Post"': [(3, 4)],
    'And user clicks on the button "Save"': [(3, 5)]
}

You can filter those duplicates with

{key: value for key, value in result.items() if len(value)> 1}


问:
SQL Server 2012: dynamic SQL limitation ( > 4000 chars) (split)
I have this dynamic SQL in a stored procedure:

```<code>Declare @template nvarchar(max)
Declare @publishdetails nvarchar(max)

set @publishdetails= ',B.[PublishedBy]=suser_name(),
  B.[PublishedDate]=GETDATE() '

set @template='if NOT EXISTS(select * from ' +@DestinationDB+ '.[CLs] where id='+ str(@slid)+')
insert into  ' +@DestinationDB+ '.CLs (id,slid,slversion) VALUES ( '+ str(@id)+','+ str(@slid)+','+str(@slversion)+')

update  B set
      B.[Clientid]=A.clientid,
        --.........
      B.[CreatedDate] = A.CreatedDate,
      B.[ModifiedDate] = A.ModifiedDate,
      B.[CreatedBy] = A.CreatedBy,
      B.[ModifiedBy] = A.ModifiedBy '+@publishdetails+ --Added publishdetails
    'FROM  ' + @SourceDB + '.[CLs] as A, '+ @DestinationDB+ '.[CLs] as B
        where A.slversion = '+ str(@slversion)+' and A.id='+str(@slid) + 'B.slversion = '+ str(@slversion)+' and B.id='+str(@slid)

        print 'template is: ' + @template
exec sp_Executesql @template
</code>```

When exec sp_Executesql @template is executing, it fails. Because @template is > 4000 chars and is truncated. How can I split it in chunks and execute it the correct way?

答:
I suggest to use this approach:

```<code>Declare @template nvarchar(max) = N''
set @template = @template +N'.... -- Or SELECT instead of SET
</code>```

Update#1

I run this simple query on my test DB:

```<code>DECLARE @query nvarchar(max) = N'',
        @i int = 1

WHILE 1000 > @i
BEGIN
    SET @query = @query + N'SELECT @@version;'
    SET @i = @i+1
END

SELECT LEN (@query)

EXEC sp_executesql @query
</code>```

I got batch with length of 16983 characters. And execution goes well - no truncation. I guess the problem is inside @SourceDB + '.[CLs] and @DestinationDB+ '.[CLs] tables. Somewhere there you got data truncation.

Try to PRINT your query and run it manually.

Body:
I have this dynamic SQL in a stored procedure:

Declare @template nvarchar(max)
Declare @publishdetails nvarchar(max)

set @publishdetails= ',B.[PublishedBy]=suser_name(),
  B.[PublishedDate]=GETDATE() '

set @template='if NOT EXISTS(select * from ' +@DestinationDB+ '.[CLs] where id='+ str(@slid)+')
insert into  ' +@DestinationDB+ '.CLs (id,slid,slversion) VALUES ( '+ str(@id)+','+ str(@slid)+','+str(@slversion)+')

update  B set
      B.[Clientid]=A.clientid,
        --.........
      B.[CreatedDate] = A.CreatedDate,
      B.[ModifiedDate] = A.ModifiedDate,
      B.[CreatedBy] = A.CreatedBy,
      B.[ModifiedBy] = A.ModifiedBy '+@publishdetails+ --Added publishdetails
    'FROM  ' + @SourceDB + '.[CLs] as A, '+ @DestinationDB+ '.[CLs] as B
        where A.slversion = '+ str(@slversion)+' and A.id='+str(@slid) + 'B.slversion = '+ str(@slversion)+' and B.id='+str(@slid)

        print 'template is: ' + @template
exec sp_Executesql @template

When exec sp_Executesql @template is executing, it fails. Because @template is > 4000 chars and is truncated. How can I split it in chunks and execute it the correct way?

Body:
I suggest to use this approach:

Declare @template nvarchar(max) = N''
set @template = @template +N'.... -- Or SELECT instead of SET

Update#1

I run this simple query on my test DB:

DECLARE @query nvarchar(max) = N'',
        @i int = 1

WHILE 1000 > @i
BEGIN
    SET @query = @query + N'SELECT @@version;'
    SET @i = @i+1
END

SELECT LEN (@query)

EXEC sp_executesql @query

I got batch with length of 16983 characters. And execution goes well - no truncation. I guess the problem is inside @SourceDB + '.[CLs] and @DestinationDB+ '.[CLs] tables. Somewhere there you got data truncation.

Try to PRINT your query and run it manually.


问:
How to find a particular 'string' in previous nodes, but within some range of previous nodes not in entire previous nodes
How to find a particular 'string' in previous nodes, but within some range of previous nodes not in entire previous nodes.

For Example 1:

Input:

0Sum of [squares] test1
[Factor1 Section]A
2Sum of (squares) test2  test
[Factor2] (A)

Required Output:

If the the scenario is matched, I need to change the
 into

:

0Sum of [squares] test1

[Factor1 Section]A
2Sum of (squares) test2  test
[Factor2] (A)

Example 2:

It should be work within the para not one para to another para. You can see the below example xml, in this case it don't make any changes.

Input:

[A]

[0Sum of squares]

Required Output:

[A]

[0Sum of squares]

in that first I need to find the br[following-sibling::node()[1][matches(.,'^\[')], then need to find - If there is any "]" is present in previous nodes, but that finding range should be till the previous
 tag (i.e. one
 tag to previous
 tag).

Note: I have already make the code for that, here I have given below for your review. But I need better and straight forward code. Can some one help me out!

```<code><xsl:template match="br[(following-sibling::node()[1][matches(normalize-space(.),'^\[')] and preceding-sibling::node()[matches(.,'\]')]>
<xsl:variable name="brcounts" select="count(preceding-sibling::br)"/>
<xsl:if test="$brcounts > 0">
<xsl:choose>
<xsl:when test="(following-sibling::node()[1][matches(normalize-space(.),'^\[')] and preceding-sibling::node()[matches(.,'\]')]) and (preceding-sibling::node()[matches(.,'\]') and count(preceding-sibling::br) = $brcounts])">
</xsl:when>
<xsl:otherwise>
<xsl:copy />
</xsl:otherwise>
</xsl:choose>
</xsl:if>
<xsl:if test="$brcounts = 0">
<xsl:choose>
<xsl:when test="(following-sibling::node()[1][matches(normalize-space(.),'^\[')] and preceding-sibling::node()[matches(.,'\]')])">
</xsl:when>
<xsl:otherwise>
<xsl:copy />
</xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>
</code>```

答:
You can try this

```<code><!-- Identical Transform -->
<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="br[following-sibling::node()[1][matches(., '^\[')]]
    [preceding-sibling::node()[matches(., '\]')]]
    [generate-id(.) = generate-id(preceding-sibling::node()[matches(., '\]')][1]/following::br[1])]">
    <xsl:text disable-output-escaping="yes"></p><p></xsl:text>
</xsl:template>
</code>```

Output and Script

http://xsltransform.hikmatu.com/pPgCcom/3

Body:
How to find a particular 'string' in previous nodes, but within some range of previous nodes not in entire previous nodes.

For Example 1:

Input:

0Sum of [squares] test1
[Factor1 Section]A
2Sum of (squares) test2  test
[Factor2] (A)

Required Output:

If the the scenario is matched, I need to change the
 into

:

0Sum of [squares] test1

[Factor1 Section]A
2Sum of (squares) test2  test
[Factor2] (A)

Example 2:

It should be work within the para not one para to another para. You can see the below example xml, in this case it don't make any changes.

Input:

[A]

[0Sum of squares]

Required Output:

[A]

[0Sum of squares]

in that first I need to find the br[following-sibling::node()[1][matches(.,'^\[')], then need to find - If there is any "]" is present in previous nodes, but that finding range should be till the previous
 tag (i.e. one
 tag to previous
 tag).

Note: I have already make the code for that, here I have given below for your review. But I need better and straight forward code. Can some one help me out!

<xsl:template match="br[(following-sibling::node()[1][matches(normalize-space(.),'^\[')] and preceding-sibling::node()[matches(.,'\]')]>
<xsl:variable name="brcounts" select="count(preceding-sibling::br)"/>
<xsl:if test="$brcounts > 0">
<xsl:choose>
<xsl:when test="(following-sibling::node()[1][matches(normalize-space(.),'^\[')] and preceding-sibling::node()[matches(.,'\]')]) and (preceding-sibling::node()[matches(.,'\]') and count(preceding-sibling::br) = $brcounts])">
</xsl:when>
<xsl:otherwise>
<xsl:copy />
</xsl:otherwise>
</xsl:choose>
</xsl:if>
<xsl:if test="$brcounts = 0">
<xsl:choose>
<xsl:when test="(following-sibling::node()[1][matches(normalize-space(.),'^\[')] and preceding-sibling::node()[matches(.,'\]')])">
</xsl:when>
<xsl:otherwise>
<xsl:copy />
</xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>

Body:
You can try this

<!-- Identical Transform -->
<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="br[following-sibling::node()[1][matches(., '^\[')]]
    [preceding-sibling::node()[matches(., '\]')]]
    [generate-id(.) = generate-id(preceding-sibling::node()[matches(., '\]')][1]/following::br[1])]">
    <xsl:text disable-output-escaping="yes">&lt;/p>&lt;p></xsl:text>
</xsl:template>

Output and Script

http://xsltransform.hikmatu.com/pPgCcom/3


问:
Smaller instruction than "add esp, 4"
Me again.

I'm having a lot of "add esp, 4" in my program and I'm trying to reduce its size. Is there any smaller instruction that can replace "add esp, 4" ?

答:
If you are aligning stack after a call, the better way to do this is using RETN X, where X is the number of bytes to add on ESP...

```<code>PUSH EAX
CALL EBX (in this func, you use RETN 4)
<<here the stack is already aligned>>
</code>```

Or, use POPFD =x

Title: Smaller instruction than "add esp, 4"

Body:
If you are aligning stack after a call, the better way to do this is using RETN X, where X is the number of bytes to add on ESP...

PUSH EAX
CALL EBX (in this func, you use RETN 4)
<<here the stack is already aligned>>

Or, use POPFD =x


问:
JSOM/Javascript get content type name with all other columns
I have the following method which correctly gets list items from a sharepoint query, however the content type needs a special treatment and its not returned.

```<code>function getListItems(listId, camlQueryString, selectProperties){
                        var deferred = $q.defer();
                        var context = SP.ClientContext.get_current();
                        var web = context.get_web();

                        var list = web.get_lists().getById(listId);

                        var camlQuery = new SP.CamlQuery();
                            camlQuery.set_viewXml(camlQueryString);

                        var listItems = list.getItems(camlQuery);

                        //var includesString = "Include(ID,Title,AssignedTo, WorkflowOutcome, ApproverComments, FileRef, WorkflowItemId, Created, Modified)"; // + selectProperties.join(", ") +  ")";
                        if(selectProperties) {
                            var includesString = convertSelectPropertiesToIncludesString(selectProperties);
                            context.load(listItems, includesString);
                        } else {
                            context.load(listItems);
                        }
                        context.executeQueryAsync(
                           function() {
                                $log.info("Successfully retrieved list item result");

                                deferred.resolve(listItems);
                           },
                           function(error, errorInfo) {
                                $log.warn("Retrieving list item result failed");

                                deferred.reject(errorInfo);
                           }
                        );
                        return deferred.promise;
                    }
</code>```

I need the content type name to be returned in the same array of listitems as another field.

I have found a few examples, but I am not sure how to integrate that code into mine because it seems a double call is needed for eachitem.

Update 1

I  try to use the above method from this:

```<code>function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
                $log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
                var deferred = $q.defer();
                var webUrl = _spPageContextInfo.webAbsoluteUrl;
                var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
                // query must return the documents for the same client but in other bill cycles not the current one
                var camlQuery = '<View>' +   viewFields +
                        '<Query>' +
                            '<Where>' +
                                //'<And>' +
                                    '<Eq>' +
                                        '<FieldRef Name="ClientCode" />' +
                                        '<Value Type="Text">'+ clientCode + '</Value>' +
                                    '</Eq>' +
                                //  '<Neq>' +
                                //      '<FieldRef Name="ContentType" />' +
                                //      '<Value Type="Computed">Bill Cycle</Value>' +
                                //  '</Neq>' +
                                //'</And>' +
                            '</Where>' +
                            //'<QueryOptions>' +
                            //  '<ViewAttributes Scope="RecursiveAll" />' +
                            //'</QueryOptions>' +
                        '</Query>' +
                    '</View>';

                var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
                spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
                .then(function(listItems) {
                    var listItemsWithValues = [];
                    if(listItems) {
                        var enumerator = listItems.getEnumerator();
                        while (enumerator.moveNext()) {
                            var listItem = enumerator.get_current();
                            var listItemValues = [];
                            selectProperties
                            .forEach(function(propertyName) {
                                if(propertyName==='ContentType'){
                                    var value = listItem.get_item('ows_ContentType');
                                }else{
                                    var value = listItem.get_item(propertyName);
                                }
                                listItemValues[propertyName] = value;
                            });

                            listItemsWithValues.push(listItemValues);
                        }
                    }

                    // Create the full item url
                    listItemsWithValues.forEach(function(listItem) {
                        var fileDirRef = listItem["FileRef"];
                        var id = listItem["ID"];
                        var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");
                        var dispFormUrl = serverUrl + fileDirRef + "/DispForm.aspx?ID=" + id;
                        listItem["FileRef"] = dispFormUrl;
                    });

                    var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);
                    deferred.resolve(listItemsWithValues);
                })
                .catch (function (message) {
                    deferred.reject();
                });

                return deferred.promise;
            }
</code>```

as you can see I need a way to return content type name in the same array of values in a simple way

答:
You can use the ows_ContentType property to get the content type name.

So, add ows_ContentType in your includesString variable or selectProperties parameter.

After that, in your code you can use it as below:

```<code>context.executeQueryAsync(
   function() {
        var listItemEnumerator = listItems.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            console.log(oListItem.get_item('ows_ContentType'));
        }
   },
   function(error, errorInfo) {
        console.log(errorInfo);
   }
);
</code>```

Update - Full code

```<code>var context = SP.ClientContext.get_current();
var web = context.get_web();

var list = web.get_lists().getByTitle("Test");

var includesString = "Include(ID,Title,Created, Modified, ows_ContentType)";

var camlQuery = SP.CamlQuery.createAllItemsQuery();

var listItems = list.getItems(camlQuery);

context.load(listItems, includesString);

context.executeQueryAsync(
   function() {
        var listItemEnumerator = listItems.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            console.log(oListItem.get_item('ows_ContentType'));
        }
   },
   function(error, errorInfo) {
        console.log(errorInfo);
   }
);
</code>```

Body:
I have the following method which correctly gets list items from a sharepoint query, however the content type needs a special treatment and its not returned.

function getListItems(listId, camlQueryString, selectProperties){
                        var deferred = $q.defer();
                        var context = SP.ClientContext.get_current();
                        var web = context.get_web();

                        var list = web.get_lists().getById(listId);

                        var camlQuery = new SP.CamlQuery();
                            camlQuery.set_viewXml(camlQueryString);

                        var listItems = list.getItems(camlQuery);

                        //var includesString = "Include(ID,Title,AssignedTo, WorkflowOutcome, ApproverComments, FileRef, WorkflowItemId, Created, Modified)"; // + selectProperties.join(", ") +  ")";
                        if(selectProperties) {
                            var includesString = convertSelectPropertiesToIncludesString(selectProperties);
                            context.load(listItems, includesString);
                        } else {
                            context.load(listItems);
                        }
                        context.executeQueryAsync(
                           function() {
                                $log.info("Successfully retrieved list item result");

                                deferred.resolve(listItems);
                           },
                           function(error, errorInfo) {
                                $log.warn("Retrieving list item result failed");

                                deferred.reject(errorInfo);
                           }
                        );
                        return deferred.promise;
                    }

I need the content type name to be returned in the same array of listitems as another field.

I have found a few examples, but I am not sure how to integrate that code into mine because it seems a double call is needed for eachitem.

Update 1

I  try to use the above method from this:

function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
                $log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
                var deferred = $q.defer();
                var webUrl = _spPageContextInfo.webAbsoluteUrl;
                var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
                // query must return the documents for the same client but in other bill cycles not the current one
                var camlQuery = '<View>' +   viewFields +
                        '<Query>' +
                            '<Where>' +
                                //'<And>' +
                                    '<Eq>' +
                                        '<FieldRef Name="ClientCode" />' +
                                        '<Value Type="Text">'+ clientCode + '</Value>' +
                                    '</Eq>' +
                                //  '<Neq>' +
                                //      '<FieldRef Name="ContentType" />' +
                                //      '<Value Type="Computed">Bill Cycle</Value>' +
                                //  '</Neq>' +
                                //'</And>' +
                            '</Where>' +
                            //'<QueryOptions>' +
                            //  '<ViewAttributes Scope="RecursiveAll" />' +
                            //'</QueryOptions>' +
                        '</Query>' +
                    '</View>';

                var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
                spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
                .then(function(listItems) {
                    var listItemsWithValues = [];
                    if(listItems) {
                        var enumerator = listItems.getEnumerator();
                        while (enumerator.moveNext()) {
                            var listItem = enumerator.get_current();
                            var listItemValues = [];
                            selectProperties
                            .forEach(function(propertyName) {
                                if(propertyName==='ContentType'){
                                    var value = listItem.get_item('ows_ContentType');
                                }else{
                                    var value = listItem.get_item(propertyName);
                                }
                                listItemValues[propertyName] = value;
                            });

                            listItemsWithValues.push(listItemValues);
                        }
                    }

                    // Create the full item url
                    listItemsWithValues.forEach(function(listItem) {
                        var fileDirRef = listItem["FileRef"];
                        var id = listItem["ID"];
                        var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");
                        var dispFormUrl = serverUrl + fileDirRef + "/DispForm.aspx?ID=" + id;
                        listItem["FileRef"] = dispFormUrl;
                    });

                    var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);
                    deferred.resolve(listItemsWithValues);
                })
                .catch (function (message) {
                    deferred.reject();
                });

                return deferred.promise;
            }

as you can see I need a way to return content type name in the same array of values in a simple way

Body:
You can use the ows_ContentType property to get the content type name.

So, add ows_ContentType in your includesString variable or selectProperties parameter.

After that, in your code you can use it as below:

context.executeQueryAsync(
   function() {
        var listItemEnumerator = listItems.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            console.log(oListItem.get_item('ows_ContentType'));
        }
   },
   function(error, errorInfo) {
        console.log(errorInfo);
   }
);

Update - Full code

var context = SP.ClientContext.get_current();
var web = context.get_web();

var list = web.get_lists().getByTitle("Test");

var includesString = "Include(ID,Title,Created, Modified, ows_ContentType)";

var camlQuery = SP.CamlQuery.createAllItemsQuery();

var listItems = list.getItems(camlQuery);

context.load(listItems, includesString);

context.executeQueryAsync(
   function() {
        var listItemEnumerator = listItems.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            console.log(oListItem.get_item('ows_ContentType'));
        }
   },
   function(error, errorInfo) {
        console.log(errorInfo);
   }
);


问:
Sort table not sorting input
How can I sort the following table I used var rows = $('#mytable tbody tr').get(); should I also include the div and the span and input inorder for it to work? The sort is not working

HTML

```<code><table id="mytable" class="table">
            <thead>
                <tr>
                    <th id="employee" class="col-xs-2">Employee</th>
                    <th id="basic_pay" style="color:#337ab7;">basic pay</th>
                    <th id="tax" style="color:#337ab7;">tax</th>
                    <th id="loans" style="color:#337ab7;">loans</th>
                </tr>
            </thead>
            <tbody>
                <% @pay_list.each do |a| %>
                    <tr>
                        <td><%= a.user.profile.full_name %></td>
                        <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="12000.0" class="form-control
                                 currency" id="display_basic_pay_4">
                            </div>
                            <input type="hidden" id="child_num_<%= a.id %>" value="<%= a.user.profile.num_of_children%>" />
                        </td>
                            <td>
                            <div class="input-group">
                                <span class="input-group-addon">₱</span>
                                <input value="12000.0" class="form-control
                                 currency" id="display_basic_pay_4">
                            </div></td>
                        <% end %>
                    </tr>
                <% end %>
            </tbody>
        </table>
</code>```

Javascript

```<code><script>
function sortTable(f,n){
    var rows = $('#mytable tbody tr').get();
    rows.sort(function(a, b) {
        var A = getVal(a);
        var B = getVal(b);
        if(A < B) {
            return -1*f;
        }
        if(A > B) {
            return 1*f;
        }
        return 0;
    });
    function getVal(elm){
        var v = $(elm).children('td').eq(n).text().toUpperCase();
        if($.isNumeric(v)){
            v = parseInt(v,10);
        }
        return v;
    }
    $.each(rows, function(index, row) {
        $('#mytable').children('tbody').append(row);
    });
}

var f_basic_pay = 1;
var f_tax = 1;
$("#basic_pay").click(function(){
    f_basic_pay *= -1;
    var n = $(this).prevAll().length;
    sortTable(f_basic_pay,n);
});
$("#tax").click(function(){
    f_tax *= -1;
    var n = $(this).prevAll().length;
    sortTable(f_tax,n);
});
</code>```

Used rails for the <% values %>

答:
Looking to the documentation here, the function
  $.text() will returns all combined text
  contents. That means, it's an equivalent of .html() but combining all tag
  childrens.

What you want to do is sorting by a html attribute value : <input value="12000.0" ..., and text() can't read them.
You can use instead :

```<code>function getVal(elm){
    var v = $(elm).children('td input.currency').eq(n).val().toUpperCase();
    [...]
}
</code>```

Title: Sort table not sorting input

Body:
How can I sort the following table I used var rows = $('#mytable tbody tr').get(); should I also include the div and the span and input inorder for it to work? The sort is not working

HTML

                    Employee
                    basic pay
                    tax
                    loans

                <% @pay_list.each do |a| %>

                        <%= a.user.profile.full_name %>

                                ₱
                                <input value="12000.0" class="form-control
                                 currency" id="display_basic_pay_4">

                            <input type="hidden" id="child_num_<%= a.id %>" value="<%= a.user.profile.num_of_children%>" />

                                ₱
                                <input value="12000.0" class="form-control
                                 currency" id="display_basic_pay_4">

                        <% end %>

                <% end %>

Javascript

Body:
Looking to the documentation here, the function
  $.text() will returns all combined text
  contents. That means, it's an equivalent of .html() but combining all tag
  childrens.

What you want to do is sorting by a html attribute value : <input value="12000.0" ..., and text() can't read them.
You can use instead :

function getVal(elm){
    var v = $(elm).children('td input.currency').eq(n).val().toUpperCase();
    [...]
}


问:
GameObject selection within bounding area(Seleting gameObject in general direction via transform comparing)
I want to cast a ray / sphere from a vector(origin) which is inside of a BoxCollider bound and limit its maxDistance so that it won't exceed the bound area and hit only the objects inside this bound with layerMask. How does one achieve this?

Also, if I cast this as a sphereCast and multiple objects were hit how could I get only the object nearest to the center of the sphereCast? I've searched around for quite a while, but couldn't quite get it there.

Edit #1

While I thank you for the previous answers I update this edit for a better elaboration of what I really want to achieve.

When I asked you the initial question it was still vague for me how to resolve the missing rayCast / sphereCast which I do not want either which will eventually miss depending on the size of target / sphereCast radius.

The end goal is to have directional input to select a gameObject and never miss.  I already have this bounding box collecting transforms of gameObjects within in a List, and if I input with say gamepad analog stick giving normalized direction I wanted to choose the one in that general direction. However, I'm aware if I do it in just rayCast / sphereCast I'd have to do multiple casting per input to ensure not missing a target which I thought would be an unnecessary block of code. The ideal thing would be: if normalized input dir: vector2(1,0, 0) the purple target on 2 O'clock position from the origin would be selected.

答:
To get the closest to the Center you could get the hit colliders’ transforms and loop through them subtracting the position from the Center. Then pick out the minimum magnitude. You could use magnitude squared to improve performance. </p>

<p>As for only picking things inside a box collider, one way would be to use a spherecast of radius equal to the largest dimension of the box. This will reach outside the box too, but is guaranteed to get everything inside the box. Then you could manually check to see if they are inside the box collider using traditional collision checks. </p>

Body:
To get the closest to the Center you could get the hit colliders’ transforms and loop through them subtracting the position from the Center. Then pick out the minimum magnitude. You could use magnitude squared to improve performance.

As for only picking things inside a box collider, one way would be to use a spherecast of radius equal to the largest dimension of the box. This will reach outside the box too, but is guaranteed to get everything inside the box. Then you could manually check to see if they are inside the box collider using traditional collision checks.


问:
What is the naming convention W3C uses for html attributes?
Looking at html, there is a bunch of built-in attributes on tags:

I am trying to work out what HTML "on spec" attributes are named.

Note: I am not looking for an opinion - I want to determine/breakdown exactly what the W3C opinion is. This is so I can recreate it this naming convention in React.

As a best-guess, I generally stick to the phrase:

The thing [is/has x]

And is/hasX becomes my prop.

However, I do not have a good grasp of the lingo of grammar, and it can be difficult for me to keep it consistent.

Lets consider two inputs, one html and one React.

This sounds right to me:

My input is hovered

```<code><input checked selected active disabled />
<MyInput isHovered hasTooltip hasError />
</code>```

But isHovering also sounds correct , but I suspect this doesn't have the correct (past) tense:

My input is hovering

```<code><input activating checking />
<MyInput isHovering hasTooltip isErroring />
</code>```

When things start to get confusing, I realise I'm in the bad habit of trying to side-step doing the grammatical-gymnastics

My input is...hover

```<code><Myinput isHover hasError />
</code>```

But the props of the component no longer seem consistent.
Plus its not what html does:

```<code><input check />
</code>```

Question What is the correct (verb?) tense of html attributes according to the spec (I've looked, and didn't find anything in the spec about tense/verbs)?

Note: is/has is added because props, unlike attributes are variables, and this prefix helps with code clarity

答:
This question will probably get closed because it's a matter of opinion, but anyway:

I never saw the present progressive tense ('hovering', 'activating') being used anywhere.

In our project we have components with props in the past tense ('disabled', 'checked') which happens to conform with HTML. I'm in favor of this also because of brevity ('isDisabled' is lengthier, which could be ok if it adds to readability, but it doesn't).

Don't use an infinitive ('check') because it implies an action (so as a developer I might think it connects the component to some external control).

But above any other consideration - whatever you choose, be consistent.

Body:
Looking at html, there is a bunch of built-in attributes on tags:

I am trying to work out what HTML "on spec" attributes are named.

Note: I am not looking for an opinion - I want to determine/breakdown exactly what the W3C opinion is. This is so I can recreate it this naming convention in React.

As a best-guess, I generally stick to the phrase:

The thing [is/has x]

And is/hasX becomes my prop.

However, I do not have a good grasp of the lingo of grammar, and it can be difficult for me to keep it consistent.

Lets consider two inputs, one html and one React.

This sounds right to me:

My input is hovered

<input checked selected active disabled />
<MyInput isHovered hasTooltip hasError />

But isHovering also sounds correct , but I suspect this doesn't have the correct (past) tense:

My input is hovering

<input activating checking />
<MyInput isHovering hasTooltip isErroring />

When things start to get confusing, I realise I'm in the bad habit of trying to side-step doing the grammatical-gymnastics

My input is...hover

<Myinput isHover hasError />

But the props of the component no longer seem consistent.
Plus its not what html does:

<input check />

Question What is the correct (verb?) tense of html attributes according to the spec (I've looked, and didn't find anything in the spec about tense/verbs)?

Note: is/has is added because props, unlike attributes are variables, and this prefix helps with code clarity


问:
How to use definitions (define variable) in include
I am trying to create some "config.php" where I will have defined global variables, like default path to project. How can I use this defined variable in include?

My config.php:

```<code>$path = $_SERVER['DOCUMENT_ROOT'] . "/docme/";

require_once "resources/scripts/pdo.php";

ini_set('display_errors', TRUE);
date_default_timezone_set( "Europe/Prague" );

//Nastavení konstant webu
define('DB_NAME', 'project');
define('DB_USER', 'root');
define('DB_PASSWORD', 'pswd');
define('DB_HOST', '127.0.0.1');
define('SITETITLE', 'DocMe!');
define('PATH', $path);
</code>```

And now I need to use the PATH variable in include, is it even possible?

```<code><?php
   require_once "config.php";
   include_once PATH."/index.php";
?>
</code>```

Okay sorry here is the problem I didn't realize it's actually problem somewhere else. On localhost it's working fine, at website (live) it's not working, cuz   $path = $_SERVER['DOCUMENT_ROOT'] = returns me only "/".

答:
Yes you can use PATH /constant/ at any file which include your config.php file

but this is something weired for include index.php

include_once PATH."/index.php";

Body:
I am trying to create some "config.php" where I will have defined global variables, like default path to project. How can I use this defined variable in include?

My config.php:

$path = $_SERVER['DOCUMENT_ROOT'] . "/docme/";

require_once "resources/scripts/pdo.php";

ini_set('display_errors', TRUE);
date_default_timezone_set( "Europe/Prague" );

//Nastavení konstant webu
define('DB_NAME', 'project');
define('DB_USER', 'root');
define('DB_PASSWORD', 'pswd');
define('DB_HOST', '127.0.0.1');
define('SITETITLE', 'DocMe!');
define('PATH', $path);

And now I need to use the PATH variable in include, is it even possible?

<?php
   require_once "config.php";
   include_once PATH."/index.php";
?>

Okay sorry here is the problem I didn't realize it's actually problem somewhere else. On localhost it's working fine, at website (live) it's not working, cuz   $path = $_SERVER['DOCUMENT_ROOT'] = returns me only "/".


问:
What is the difference between these two ways to start an activity?
First off, I'm totally new at all of this and am mostly learning be searching the internet for directions on how to do what I want and then figuring out how to use it.

So I've found these two versions of how to start an activity, but I don't really understand the difference.  Is one better than the other?  Or should they be used in different circumstances?  Or are they just two different ways of doing the same thing?

```<code>Button home = (Button) findViewById(R.id.to_home);
    home.setOnClickListener (new View.OnClickListener() {
        public void onClick(View view) {
            Intent i = new Intent(view.getContext(), Home.class);
                startActivityForResult (i, 0);

        }
    });
</code>```

or this one

```<code>Button button = (Button)findViewById(R.id.b_cup);
    button.setOnClickListener (new View.OnClickListener() {
        public void onClick (View view) {
            Intent i = new Intent (Home.this, Cup.class);
            startActivity (i);

        }
    });
</code>```

答:
Sometimes you want to get a result back from an activity when it ends. For example, you may start an activity that lets the user pick a person in a list of contacts; when it ends, it returns the person that was selected. To do this, you call the startActivityForResult(Intent, int) version with a second integer parameter identifying the call. The result will come back through your onActivityResult(int, int, Intent) method.

Unless you want the new activity to return something, or you need to know when it finishes, startActivity() will be just fine.

See:
http://developer.android.com/reference/android/app/Activity.html

Body:
First off, I'm totally new at all of this and am mostly learning be searching the internet for directions on how to do what I want and then figuring out how to use it.

So I've found these two versions of how to start an activity, but I don't really understand the difference.  Is one better than the other?  Or should they be used in different circumstances?  Or are they just two different ways of doing the same thing?

Button home = (Button) findViewById(R.id.to_home);
    home.setOnClickListener (new View.OnClickListener() {
        public void onClick(View view) {
            Intent i = new Intent(view.getContext(), Home.class);
                startActivityForResult (i, 0);

        }
    });

or this one

Button button = (Button)findViewById(R.id.b_cup);
    button.setOnClickListener (new View.OnClickListener() {
        public void onClick (View view) {
            Intent i = new Intent (Home.this, Cup.class);
            startActivity (i);

        }
    });


问:
How to find node exists in JSON
I have following JSON

```<code>{"subscription":
 {
 "callbackReference": "xyz" ,
 "criteria": "Vote",
 "destinationAddress": "3456" ,
  "notificationFormat" : "JSON"
 }
}
</code>```

I want to check whether "notificationFormat" elements exits there using JSONPath expression. I can get the value of above element using following JSONPath expression.

```<code>$.subscription.notificationFormat
</code>```

Can I use similar kind of expression which returns boolean value checking whether elements exists ?

答:
```<code>    ReadContext ctx = JsonPath.parse("{}", com.jayway.jsonpath.Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS));

    assertThat(ctx.read("$.components"), nullValue());
</code>```

Title: How to find node exists in JSON

Body:
I have following JSON

{"subscription":
 {
 "callbackReference": "xyz" ,
 "criteria": "Vote",
 "destinationAddress": "3456" ,
  "notificationFormat" : "JSON"
 }
}

I want to check whether "notificationFormat" elements exits there using JSONPath expression. I can get the value of above element using following JSONPath expression.

$.subscription.notificationFormat

Can I use similar kind of expression which returns boolean value checking whether elements exists ?


答:
1:

I would suggest, have a look at Physics.OverlapBox

as it is perfect for your situation:

Find all colliders touching or inside of the given box.

You can pass in your box collider's center and size as parameters, this will return an array of overlapping (hit) colliders and you can use the first one.

2:

If you still want to use SphereCast, it populates RaycastHit object which has the first object that is hit in collider property

Title: GameObject selection within bounding area(Seleting gameObject in general direction via transform comparing)

Body:
I want to cast a ray / sphere from a vector(origin) which is inside of a BoxCollider bound and limit its maxDistance so that it won't exceed the bound area and hit only the objects inside this bound with layerMask. How does one achieve this?

Also, if I cast this as a sphereCast and multiple objects were hit how could I get only the object nearest to the center of the sphereCast? I've searched around for quite a while, but couldn't quite get it there.

Edit #1

While I thank you for the previous answers I update this edit for a better elaboration of what I really want to achieve.

When I asked you the initial question it was still vague for me how to resolve the missing rayCast / sphereCast which I do not want either which will eventually miss depending on the size of target / sphereCast radius.

The end goal is to have directional input to select a gameObject and never miss.  I already have this bounding box collecting transforms of gameObjects within in a List, and if I input with say gamepad analog stick giving normalized direction I wanted to choose the one in that general direction. However, I'm aware if I do it in just rayCast / sphereCast I'd have to do multiple casting per input to ensure not missing a target which I thought would be an unnecessary block of code. The ideal thing would be: if normalized input dir: vector2(1,0, 0) the purple target on 2 O'clock position from the origin would be selected.