问:
How is the image data interpreted for a grayscale image on an iPhone?
How do I make sense of the image data for a grayscale image given the following scenario: I capture video data from the "sample buffer" and extract an 80x20 section and then turn that into a grayscale UIImage. But when I examine the raw pixel bytes I am unable to make sense of them in a way that would allow me to go on and "binarize" them (my real goal).

When I simply save the UIImage to the photo album using UIImageWriteToSavedPhotosAlbum to verify just what kind of image data I have, I indeed get a plain, white 80x20 image (it's actually light-grayish).  I captured a plain white image to simplify things, expecting to see only values between, say, 200 or so and 255, and yet there are sections of the image data full of zeroes, that clearly suggest rows of black pixels.  Any help is appreciated.  The relevant code and the image data (16 pixels at a time) are below.

Here is how I create the 80x20 grayscale image from a portion of the CMSampleBufferRef video data:

```<code>UIImage *imageFromImage(UIImage *image, CGRect rect)
{
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);

    CGImageRef grayScaleImg = grayscaleCGImageFromCGImage(newImageRef);
    CGImageRelease(newImageRef);

    UIImage *newImage = [UIImage imageWithCGImage:grayScaleImg scale:1.0 orientation:UIImageOrientationLeft];

    return newImage;
}

CGImageRef grayscaleCGImageFromCGImage(CGImageRef inputImage)
{
    size_t width = CGImageGetWidth(inputImage);
    size_t height = CGImageGetHeight(inputImage);

    // Create a gray scale context and render the input image into that
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8,
                    4*width, colorspace, kCGBitmapByteOrderDefault);

    CGContextDrawImage(context, CGRectMake(0,0, width,height), inputImage);

    // Get an image representation of the grayscale context which the input
    //    was rendered into.
    CGImageRef outputImage = CGBitmapContextCreateImage(context);

    // Cleanup
    CGContextRelease(context);
    CGColorSpaceRelease(colorspace);

    return (CGImageRef)[(id)outputImage autorelease];
}
</code>```

and then, when I use the following code to dump the pixel data to the Console:

```<code>    CGImageRef inputImage = [imgIn CGImage];
CGDataProviderRef dataProvider = CGImageGetDataProvider(inputImage);
CFDataRef imageData = CGDataProviderCopyData(dataProvider);
const UInt8 *rawData = CFDataGetBytePtr(imageData);

size_t width = CGImageGetWidth(inputImage);
    size_t height = CGImageGetHeight(inputImage);

    size_t numPixels = height * width;
for (int i = 0; i < numPixels ; i++)
{
   if ((i % 16) == 0)
          NSLog(@" -%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-\n\n", rawData[i],
             rawData[i+1], rawData[i+2], rawData[i+3], rawData[i+4], rawData[i+5],
             rawData[i+6], rawData[i+7], rawData[i+8], rawData[i+9], rawData[i+10],
             rawData[i+11], rawData[i+12], rawData[i+13], rawData[i+14], rawData[i+15]);
}
</code>```

I consistently get output like following:

-216-217-214-215-217-215-216-213-214-214-214-215-215-217-216-216-

-219-219-216-219-220-217-212-214-215-214-217-220-219-217-214-219-

-216-216-218-217-218-221-217-213-214-212-214-212-212-214-214-213-

-213-213-212-213-212-214-216-214-212-210-211-210-213-210-213-208-

-212-208-208-210-206-207-206-207-210-205-206-208-209-210-210-207-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

(this pattern repeats for the remaining bytes, 80 bytes of pixel data in the 200's, depending on lighting, followed by 240 bytes of zeros -- there's a total of 1600 bytes since the image is 80x20)

答:
This:

```<code>CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8,
                4*width, colorspace, kCGBitmapByteOrderDefault);
</code>```

Should be:

```<code>CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8,
                width, colorspace, kCGBitmapByteOrderDefault);
</code>```

In other words, for an 8 bit gray image, the number of bytes per row is the same as the width.

Body:
How do I make sense of the image data for a grayscale image given the following scenario: I capture video data from the "sample buffer" and extract an 80x20 section and then turn that into a grayscale UIImage. But when I examine the raw pixel bytes I am unable to make sense of them in a way that would allow me to go on and "binarize" them (my real goal).

When I simply save the UIImage to the photo album using UIImageWriteToSavedPhotosAlbum to verify just what kind of image data I have, I indeed get a plain, white 80x20 image (it's actually light-grayish).  I captured a plain white image to simplify things, expecting to see only values between, say, 200 or so and 255, and yet there are sections of the image data full of zeroes, that clearly suggest rows of black pixels.  Any help is appreciated.  The relevant code and the image data (16 pixels at a time) are below.

Here is how I create the 80x20 grayscale image from a portion of the CMSampleBufferRef video data:

UIImage *imageFromImage(UIImage *image, CGRect rect)
{
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);

    CGImageRef grayScaleImg = grayscaleCGImageFromCGImage(newImageRef);
    CGImageRelease(newImageRef);

    UIImage *newImage = [UIImage imageWithCGImage:grayScaleImg scale:1.0 orientation:UIImageOrientationLeft];

    return newImage;
}

CGImageRef grayscaleCGImageFromCGImage(CGImageRef inputImage)
{
    size_t width = CGImageGetWidth(inputImage);
    size_t height = CGImageGetHeight(inputImage);

    // Create a gray scale context and render the input image into that
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8,
                    4*width, colorspace, kCGBitmapByteOrderDefault);

    CGContextDrawImage(context, CGRectMake(0,0, width,height), inputImage);

    // Get an image representation of the grayscale context which the input
    //    was rendered into.
    CGImageRef outputImage = CGBitmapContextCreateImage(context);

    // Cleanup
    CGContextRelease(context);
    CGColorSpaceRelease(colorspace);

    return (CGImageRef)[(id)outputImage autorelease];
}

and then, when I use the following code to dump the pixel data to the Console:

    CGImageRef inputImage = [imgIn CGImage];
CGDataProviderRef dataProvider = CGImageGetDataProvider(inputImage);
CFDataRef imageData = CGDataProviderCopyData(dataProvider);
const UInt8 *rawData = CFDataGetBytePtr(imageData);

size_t width = CGImageGetWidth(inputImage);
    size_t height = CGImageGetHeight(inputImage);

    size_t numPixels = height * width;
for (int i = 0; i < numPixels ; i++)
{
   if ((i % 16) == 0)
          NSLog(@" -%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-%i-\n\n", rawData[i],
             rawData[i+1], rawData[i+2], rawData[i+3], rawData[i+4], rawData[i+5],
             rawData[i+6], rawData[i+7], rawData[i+8], rawData[i+9], rawData[i+10],
             rawData[i+11], rawData[i+12], rawData[i+13], rawData[i+14], rawData[i+15]);
}

I consistently get output like following:

-216-217-214-215-217-215-216-213-214-214-214-215-215-217-216-216-

-219-219-216-219-220-217-212-214-215-214-217-220-219-217-214-219-

-216-216-218-217-218-221-217-213-214-212-214-212-212-214-214-213-

-213-213-212-213-212-214-216-214-212-210-211-210-213-210-213-208-

-212-208-208-210-206-207-206-207-210-205-206-208-209-210-210-207-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-

(this pattern repeats for the remaining bytes, 80 bytes of pixel data in the 200's, depending on lighting, followed by 240 bytes of zeros -- there's a total of 1600 bytes since the image is 80x20)

Body:
This:

CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8,
                4*width, colorspace, kCGBitmapByteOrderDefault);

Should be:

CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8,
                width, colorspace, kCGBitmapByteOrderDefault);

In other words, for an 8 bit gray image, the number of bytes per row is the same as the width.


来源: stackexchange

问:
Dropbox badge for MS Access who is working on the same file
My question is:
Is there a badge for MS Access files like this: https://blogs.dropbox.com/dropbox/2015/10/dropbox-badge-now-available/

And is it possible to collect Dropbox badge information with VBA as one of the notibles (Greg K) of Dropbox has mentioned 3 year ago.

currently isn't an interface for querying this information, but we'll
  consider this a feature request.

here: Excel VBA collect Dropbox badge information

Thanks in advance

Best Regards

Imran Bhatti

答:
The Dropbox Badge is supported for Word, Powerpoint, and Excel, but not Access. You can find more information here:

https://www.dropbox.com/help/business/badge-overview
https://www.dropbox.com/help/business/badge-issues

Also, there still isn't an API for querying this information programmatically. We're continuing to track it as a feature request.

ContentLicense: CC BY-SA 3.0


问:
Match a string after a string is matched in multiple line
I try to write a regex to search the port name with alias "USBBoard"
by using this:

Port name=(COM\d+).*Alias=BoardUSB

But it seems the group match 'COM10' instead of 'COM1'
Any advice to improve the regex? thanks

```<code>[Serial_COM10]
Port name=COM10
Baud rate=9600
Data bits=8
Timeout=2500
Alias=COM_PPS
Handshake=None
[Serial_COM1]
Port name=COM1
Baud rate=9600
Data bits=8
Timeout=2500
Alias=BoardUSB
Handshake=None
[Serial_COM3]
Port name=COM3
Baud rate=115200
Data bits=8
Timeout=2500
Alias=usb_hub
Handshake=None
</code>```

答:
You can use this pattern:

```<code>(?m)^Port name=(COM\d+)\r?\n(?:[^[].*\n)*Alias=BoardUSB
</code>```

[^[] ensures that the lines between "Port name" and "Alias" don't start with a [.

demo

Body:
I try to write a regex to search the port name with alias "USBBoard"
by using this:

Port name=(COM\d+).*Alias=BoardUSB

But it seems the group match 'COM10' instead of 'COM1'
Any advice to improve the regex? thanks

[Serial_COM10]
Port name=COM10
Baud rate=9600
Data bits=8
Timeout=2500
Alias=COM_PPS
Handshake=None
[Serial_COM1]
Port name=COM1
Baud rate=9600
Data bits=8
Timeout=2500
Alias=BoardUSB
Handshake=None
[Serial_COM3]
Port name=COM3
Baud rate=115200
Data bits=8
Timeout=2500
Alias=usb_hub
Handshake=None

Body:
You can use this pattern:

(?m)^Port name=(COM\d+)\r?\n(?:[^[].*\n)*Alias=BoardUSB

[^[] ensures that the lines between "Port name" and "Alias" don't start with a [.

demo


问:
WhyJava Bean Pattern is not threadsafe
Joshua Bloch states in Effective Java, 2nd Edition:

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

```<code>Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
</code>```

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

My Question:-
Is above code not thread safe? Am I missing any basic thing?

Thanks in Advance,

Surya

答:
The author says textually :

JavaBeans pattern precludes the possibility of making a class immutable and  requires a added effort on the part of the programmer
  to ensure thread safety.

I think that the author stresses on the fact that it makes no sense to provide methods that prevent the object immutability and may create consistency issues between threads if you object is designed to be immutable : that is it never needs to change once created.

Your question :

Why Java Bean Pattern is not threadsafe ?

Any class that provides a way to mutate a field is not thread safe.

It is true for JavaBeans methods (that generally don't use defensive copy) but it is also true for any mutable class.

Manipulating a no thread safe class is not necessary a problem if you use it in a context where you have no race conditions between threads.

For example this code is thread safe :

```<code>Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
</code>```

because the Pizza instance is not declared as a variable that is shared (instance or static field) but it is declared and used in a more restricted scope (probably a method but it could be also a initializer block).

The builder pattern provides a way to build an immutable and so by definition a thread safe object.

For example by using a builder to create a Pizza :

```<code>Pizza pizza = new Pizza.Builder().cheese(true).pepperoni(true).bacon(true).build();
</code>```

Only the call to build() creates and returns the Pizza object.

Previous calls manipulate a Builder object and return a Builder.

So, if the object is immutable, you don't need to worry about synchronizing these calls :

```<code>pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
</code>```

as these method don't need to be provided. So they cannot be called.

About how to have thread safe JavaBeans

If you are in a context where the Pizza instance could be shared among multiple threads, these calls should be done in a synchronized way  :

```<code>pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
</code>```

These could be declared as synchronized method and or Pizza fields could be volatile but these could not be enough.

Indeed, if a Pizza should change its state according to its own state or even according to another object, we should also synchronize the whole logic : do the checks until the state modification of the Pizza.

For example suppose the Pizza has to add some units of Pepperoni only one time :

The code could be :

```<code>  if (pizza.isWaitForPepperoni()){
      pizza.addPepperoni(5);
  }
</code>```

These statements are not atomic and so no thread safe.

pizza.addPepperoni(5); could be called by two concurrent threads even if the one of the threads already invoked pizza.addPepperoni(5);.

So we should ensure that no other thread calls pizza.addPepperoni(5) while it should not (The pizza will have too much Pepperoni) .

For example by doing a synchronized statement on the Pizza instance :

```<code>   synchronized(pizza){
      if (pizza.isWaitForPepperoni()){
          pizza.addPepperoni(5);
      }
   }
</code>```

Title: WhyJava Bean Pattern is not threadsafe

Body:
Joshua Bloch states in Effective Java, 2nd Edition:

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

My Question:-
Is above code not thread safe? Am I missing any basic thing?

Thanks in Advance,

Surya

Body:
The author says textually :

JavaBeans pattern precludes the possibility of making a class immutable and  requires a added effort on the part of the programmer
  to ensure thread safety.

I think that the author stresses on the fact that it makes no sense to provide methods that prevent the object immutability and may create consistency issues between threads if you object is designed to be immutable : that is it never needs to change once created.

Your question :

Why Java Bean Pattern is not threadsafe ?

Any class that provides a way to mutate a field is not thread safe.

It is true for JavaBeans methods (that generally don't use defensive copy) but it is also true for any mutable class.

Manipulating a no thread safe class is not necessary a problem if you use it in a context where you have no race conditions between threads.

For example this code is thread safe :

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

because the Pizza instance is not declared as a variable that is shared (instance or static field) but it is declared and used in a more restricted scope (probably a method but it could be also a initializer block).

The builder pattern provides a way to build an immutable and so by definition a thread safe object.

For example by using a builder to create a Pizza :

Pizza pizza = new Pizza.Builder().cheese(true).pepperoni(true).bacon(true).build();

Only the call to build() creates and returns the Pizza object.

Previous calls manipulate a Builder object and return a Builder.

So, if the object is immutable, you don't need to worry about synchronizing these calls :

pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

as these method don't need to be provided. So they cannot be called.

About how to have thread safe JavaBeans

If you are in a context where the Pizza instance could be shared among multiple threads, these calls should be done in a synchronized way  :

pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

These could be declared as synchronized method and or Pizza fields could be volatile but these could not be enough.

Indeed, if a Pizza should change its state according to its own state or even according to another object, we should also synchronize the whole logic : do the checks until the state modification of the Pizza.

For example suppose the Pizza has to add some units of Pepperoni only one time :

The code could be :

  if (pizza.isWaitForPepperoni()){
      pizza.addPepperoni(5);
  }

These statements are not atomic and so no thread safe.

pizza.addPepperoni(5); could be called by two concurrent threads even if the one of the threads already invoked pizza.addPepperoni(5);.

So we should ensure that no other thread calls pizza.addPepperoni(5) while it should not (The pizza will have too much Pepperoni) .

For example by doing a synchronized statement on the Pizza instance :

   synchronized(pizza){
      if (pizza.isWaitForPepperoni()){
          pizza.addPepperoni(5);
      }
   }


问:
c# - object reference not set to an instance of an object - LINQ
I'm trying to make a view where a user can see bookings they have made. I have a model that holds a list of 2 different kinds of bookings in different facilities, a hall and a room. So the model holds a list of hall bookings and a list of room bookings. In my controller, i'm trying to add all the hall bookings to the hall bookings list, and the same for the room bookings. But I am getting this error

"Object reference not set to an instance of an object."

Here is my model:

```<code>public class AllBookingsViewModel
{

    public List<HallActivityBooking> HallBookingsList { get; set; }

    public List<RoomBooking> RoomBookingsList { get; set; }

}
</code>```

Here is my controller:

```<code>public class BookingsController : BaseController
{
    // GET: Bookings
    public ActionResult Bookings()
    {

        //Get current user
        var userId = User.Identity.GetUserId();
        var currentUser = db.Users.Find(userId);

        AllBookingsViewModel model = new AllBookingsViewModel();

        //Fill activity booking
        foreach (HallActivityBooking hallBooking in db.HallBookings.Where(x => x.CustomerUser.Id == currentUser.Id))
        {
            model.HallBookingsList.Add(hallBooking); //<< This is where I get an exception
        }

        //Fill room bookings list
        foreach (RoomBooking roomBooking in db.RoomBookings.Where(x => x.CustomerUser.Id == currentUser.Id))
        {
            model.RoomBookingsList.Add(roomBooking);
        }

        return View(model);
    }
</code>```

Here's what I tried (these are no longer still in my code):

I've tried declaring the model like:

```<code>var model = new AllBookingsViewModel
</code>```

I've tried adding "FirstOrDefault" to the linq statement:

```<code>foreach (HallActivityBooking hallBooking in db.HallBookings.Where(x => x.CustomerUser.Id == currentUser.Id).FirstOrDefault())
{
    model.HallBookingsList.Add(hallBooking);
}
</code>```

This gives me this error:

Severity  Code    Description Project File    Line    Suppression State
  Error CS0446  Foreach cannot operate on a 'method group'. Did you
  intend to invoke the 'method group'? ...  26  Active

Help would be appreciated

SOLVED

Here is what I did to solve this problem:

The for-each was not necessary, I just needed to initialize the view model by giving it the value's of the LINQ statement:

```<code>        AllBookingsViewModel model = new AllBookingsViewModel();
        {
            model.HallBookingsList = db.HallBookings.Where(x => x.CustomerUser.Id == currentUser.Id);
            model.RoomBookingsList = db.RoomBookings.Where(x => x.CustomerUser.Id == currentUser.Id);
        };
</code>```

答:
What i think that's occuring here is that you may have one of your either HallBookings or RoomBookings with a CustomerUser in null.

So, when LINQ is executing your Func passed in the Where clause, one of your entities with CustomerUser in null, causes the error.

I don't know if your business logic permits that, but you can provide some null checks in the Func provided in the Where to avoid those null references.

Example:

```<code>//Fill activity booking
foreach (HallActivityBooking hallBooking in db.HallBookings.Where(x => x.CustomerUser != null ? x.CustomerUser.Id == currentUser.Id : false))
{
    model.HallBookingsList.Add(hallBooking);
}
</code>```

Body:
I'm trying to make a view where a user can see bookings they have made. I have a model that holds a list of 2 different kinds of bookings in different facilities, a hall and a room. So the model holds a list of hall bookings and a list of room bookings. In my controller, i'm trying to add all the hall bookings to the hall bookings list, and the same for the room bookings. But I am getting this error

"Object reference not set to an instance of an object."

Here is my model:

public class AllBookingsViewModel
{

    public List<HallActivityBooking> HallBookingsList { get; set; }

    public List<RoomBooking> RoomBookingsList { get; set; }

}

Here is my controller:

public class BookingsController : BaseController
{
    // GET: Bookings
    public ActionResult Bookings()
    {

        //Get current user
        var userId = User.Identity.GetUserId();
        var currentUser = db.Users.Find(userId);

        AllBookingsViewModel model = new AllBookingsViewModel();

        //Fill activity booking
        foreach (HallActivityBooking hallBooking in db.HallBookings.Where(x => x.CustomerUser.Id == currentUser.Id))
        {
            model.HallBookingsList.Add(hallBooking); //<< This is where I get an exception
        }

        //Fill room bookings list
        foreach (RoomBooking roomBooking in db.RoomBookings.Where(x => x.CustomerUser.Id == currentUser.Id))
        {
            model.RoomBookingsList.Add(roomBooking);
        }

        return View(model);
    }

Here's what I tried (these are no longer still in my code):

I've tried declaring the model like:

var model = new AllBookingsViewModel

I've tried adding "FirstOrDefault" to the linq statement:

foreach (HallActivityBooking hallBooking in db.HallBookings.Where(x => x.CustomerUser.Id == currentUser.Id).FirstOrDefault())
{
    model.HallBookingsList.Add(hallBooking);
}

This gives me this error:

Severity  Code    Description Project File    Line    Suppression State
  Error CS0446  Foreach cannot operate on a 'method group'. Did you
  intend to invoke the 'method group'? ...  26  Active

Help would be appreciated

SOLVED

Here is what I did to solve this problem:

The for-each was not necessary, I just needed to initialize the view model by giving it the value's of the LINQ statement:

        AllBookingsViewModel model = new AllBookingsViewModel();
        {
            model.HallBookingsList = db.HallBookings.Where(x => x.CustomerUser.Id == currentUser.Id);
            model.RoomBookingsList = db.RoomBookings.Where(x => x.CustomerUser.Id == currentUser.Id);
        };

Body:
What i think that's occuring here is that you may have one of your either HallBookings or RoomBookings with a CustomerUser in null.

So, when LINQ is executing your Func passed in the Where clause, one of your entities with CustomerUser in null, causes the error.

I don't know if your business logic permits that, but you can provide some null checks in the Func provided in the Where to avoid those null references.

Example:

//Fill activity booking
foreach (HallActivityBooking hallBooking in db.HallBookings.Where(x => x.CustomerUser != null ? x.CustomerUser.Id == currentUser.Id : false))
{
    model.HallBookingsList.Add(hallBooking);
}


问:
Ruby-on-Rails: How to get rid of "you are being redirected" page
I am overriding Devise's failure response so that I can set a 401 status code. However, when the user fails to sign in, they are redirected to a page with a "you are being redirected" link. If I remove this :status => 401 from the redirect it works fine.

```<code>class CustomFailure < Devise::FailureApp
    def redirect_url
      new_user_session_url(:subdomain => 'secure')
    end

    def respond
        if http_auth?
           http_auth
        else
           store_location!
           flash[:alert] = i18n_message unless flash[:notice]
           redirect_to redirect_url, :status => 401
        end
    end
end
</code>```

edit

Alternatively I would like to display the flash message and remain on the same page but adding this line of code:

```<code>render :text => "unauthorized", :status => 401
</code>```

causes ruby to complain:

```<code>undefined method `render' for #<CustomFailure:0x00000103367f28>
</code>```

What's happening here?

答:
When I have this problem what I have done in the past is something like this:

```<code>#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  after_filter :check_page_content
  ...
  private
  def check_page_content
    if response.body.include? "You are being"
      html_doc = Nokogiri::HTML(response.body)
      uri = html_doc.css('a').map { |link| link['href'] }.first
      response.body = "<script>
                         window.location.replace('#{uri}');
                       </script>"
    end
  end
end
</code>```

What I am doing is checking to see if the page content is "You are being". if this is true I know I am not where I want to be. and I just update the page to where I really want to be with some help of Javascript.
I know its not the most elegant solution but it really does help

Happy Hacking

ContentLicense: CC BY-SA 2.5

Body:
I am overriding Devise's failure response so that I can set a 401 status code. However, when the user fails to sign in, they are redirected to a page with a "you are being redirected" link. If I remove this :status => 401 from the redirect it works fine.

class CustomFailure < Devise::FailureApp
    def redirect_url
      new_user_session_url(:subdomain => 'secure')
    end

    def respond
        if http_auth?
           http_auth
        else
           store_location!
           flash[:alert] = i18n_message unless flash[:notice]
           redirect_to redirect_url, :status => 401
        end
    end
end

edit

Alternatively I would like to display the flash message and remain on the same page but adding this line of code:

render :text => "unauthorized", :status => 401

causes ruby to complain:

undefined method `render' for #<CustomFailure:0x00000103367f28>

What's happening here?

Body:
When I have this problem what I have done in the past is something like this:

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  after_filter :check_page_content
  ...
  private
  def check_page_content
    if response.body.include? "You are being"
      html_doc = Nokogiri::HTML(response.body)
      uri = html_doc.css('a').map { |link| link['href'] }.first
      response.body = "<script>
                         window.location.replace('#{uri}');
                       </script>"
    end
  end
end

What I am doing is checking to see if the page content is "You are being". if this is true I know I am not where I want to be. and I just update the page to where I really want to be with some help of Javascript.
I know its not the most elegant solution but it really does help

Happy Hacking


问:
Flash Builder "Burrito" : apk : invalid_apk , "parse error"
I've created an app in Flash Builder "Burrito". When I run the application there are no project warnings or errors. The .apk was compiled successfully.  The emulator is running Andorid 2.2. However, when I push the .apk to the emulator I get "Invalid Apk" error.
I tried installing  it into Galaxy Phone (Android 2.2) , de time i got "Parse error "
any1 had the same problem resolved ?</p>

答:
The .apk file generated by flashbuilder will not run successfully on the emulator. You have to generate an "emulator apk" using the adt.bat located in the bin directory of your AirSDK.

copy your files (appName.swf, appName-app.xml, cert_name.p12) to the bin directory and run the following command:

adt -package -target apk-emulator -storetype pkcs12 -keystore cert_name.p12 appName.apk appName-app.xml appName.swf

You can find a more detailed explanation here


问:
javascript password generator
What would be the best approach to creating a 8 character random password containing a-z, A-Z and 0-9?

Absolutely no security issues, this is merely for prototyping, I just want data that looks realistic.

I was thinking a for (0 to 7) Math.random to produce ASCII codes and convert them to characters. Do you have any other suggestions?

答:
Here is a function provides you more options to set min of special chars, min of upper chars, min of lower chars and min of number</p>

```<code>function randomPassword(len = 8, minUpper = 0, minLower = 0, minNumber = -1, minSpecial = -1) {
    let chars = String.fromCharCode(...Array(127).keys()).slice(33),//chars
        A2Z = String.fromCharCode(...Array(91).keys()).slice(65),//A-Z
        a2z = String.fromCharCode(...Array(123).keys()).slice(97),//a-z
        zero2nine = String.fromCharCode(...Array(58).keys()).slice(48),//0-9
        specials = chars.replace(/\w/g, '')
    if (minSpecial < 0) chars = zero2nine + A2Z + a2z
    if (minNumber < 0) chars = chars.replace(zero2nine, '')
    let minRequired = minSpecial + minUpper + minLower + minNumber
    let rs = [].concat(
        Array.from({length: minSpecial ? minSpecial : 0}, () => specials[Math.floor(Math.random() * specials.length)]),
        Array.from({length: minUpper ? minUpper : 0}, () => A2Z[Math.floor(Math.random() * A2Z.length)]),
        Array.from({length: minLower ? minLower : 0}, () => a2z[Math.floor(Math.random() * a2z.length)]),
        Array.from({length: minNumber ? minNumber : 0}, () => zero2nine[Math.floor(Math.random() * zero2nine.length)]),
        Array.from({length: Math.max(len, minRequired) - (minRequired ? minRequired : 0)}, () => chars[Math.floor(Math.random() * chars.length)]),
    )
    return rs.sort(() => Math.random() > Math.random()).join('')
}
randomPassword(12, 1, 1, -1, -1)// -> DDYxdVcvIyLgeB
randomPassword(12, 1, 1, 1, -1)// -> KYXTbKf9vpMu0
randomPassword(12, 1, 1, 1, 1)// -> hj|9)V5YKb=7
</code>```

Title: javascript password generator

Body:
Here is a function provides you more options to set min of special chars, min of upper chars, min of lower chars and min of number

function randomPassword(len = 8, minUpper = 0, minLower = 0, minNumber = -1, minSpecial = -1) {
    let chars = String.fromCharCode(...Array(127).keys()).slice(33),//chars
        A2Z = String.fromCharCode(...Array(91).keys()).slice(65),//A-Z
        a2z = String.fromCharCode(...Array(123).keys()).slice(97),//a-z
        zero2nine = String.fromCharCode(...Array(58).keys()).slice(48),//0-9
        specials = chars.replace(/\w/g, '')
    if (minSpecial < 0) chars = zero2nine + A2Z + a2z
    if (minNumber < 0) chars = chars.replace(zero2nine, '')
    let minRequired = minSpecial + minUpper + minLower + minNumber
    let rs = [].concat(
        Array.from({length: minSpecial ? minSpecial : 0}, () => specials[Math.floor(Math.random() * specials.length)]),
        Array.from({length: minUpper ? minUpper : 0}, () => A2Z[Math.floor(Math.random() * A2Z.length)]),
        Array.from({length: minLower ? minLower : 0}, () => a2z[Math.floor(Math.random() * a2z.length)]),
        Array.from({length: minNumber ? minNumber : 0}, () => zero2nine[Math.floor(Math.random() * zero2nine.length)]),
        Array.from({length: Math.max(len, minRequired) - (minRequired ? minRequired : 0)}, () => chars[Math.floor(Math.random() * chars.length)]),
    )
    return rs.sort(() => Math.random() > Math.random()).join('')
}
randomPassword(12, 1, 1, -1, -1)// -> DDYxdVcvIyLgeB
randomPassword(12, 1, 1, 1, -1)// -> KYXTbKf9vpMu0
randomPassword(12, 1, 1, 1, 1)// -> hj|9)V5YKb=7


问:
Test Angular Component Throws Error Fails With TypeError
I have defined a CustomError as

```<code>export class CustomError extends Error {
    constructor(message?: string) {
        super(message);
        Object.setPrototypeOf(this, CustomError.prototype);
    }
}
</code>```

and I want to throw CustomError from an angular component, e.g.,

```<code>@Component({
    moduleId: 'module.id',
    templateUrl: 'my.component.html'
})
export class MyComponent {
    someMethod(): void {
        throw new CustomError();
    }
}
</code>```

Now I want to test that CustomError is thrown, so I write the following test

```<code>describe('MyComponent', () => {

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [MyComponent]
        }).compileComponents();
    }));

    beforeEach(async(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
    }));

    it('throws CustomError', () => {
        expect(component.someMethod).toThrowError(CustomError);
    });
});
</code>```

This test passes as expected. However, if I now introduce someProperty into MyComponent, i.e.,

```<code>@Component({
    moduleId: 'module.id',
    templateUrl: 'my.component.html'
})
export class MyComponent {
    someProperty: string  = "Why does this break it?";

    someMethod(): void {
        console.log(this.someProperty);  // This breaks it, why?
        throw new CustomError();
    }
}
</code>```

and attempt to use that property in the function I'm testing (in this case writing to the console), my test fails because a TypeError is thrown - stack trace below:

```<code>Expected function to throw AuthError, but it threw TypeError.
        at Object.<anonymous> (webpack:///src/app/auth/login/login.component.spec.ts:46:32 <- config/karma-test-shim.js:68955:33) [ProxyZone]
        at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- config/karma-test-shim.js:65355:39) [ProxyZone]
        at Object.<anonymous> (webpack:///~/zone.js/dist/jasmine-patch.js:104:0 <- config/karma-test-shim.js:65071:34) [ProxyZone]
        at webpack:///~/@angular/core/@angular/core/testing.es5.js:96:0 <- config/karma-test-shim.js:20767:17 [ProxyZone]
        at AsyncTestZoneSpec.onInvoke (webpack:///~/zone.js/dist/async-test.js:49:0 <- config/karma-test-shim.js:64666:39) [ProxyZone]
        at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:76:0 <- config/karma-test-shim.js:65352:39) [ProxyZone]
        at AsyncTestZoneSpec._finishCallback (webpack:///~/@angular/core/@angular/core/testing.es5.js:91:0 <- config/karma-test-shim.js:20762:25) [<root>]
        at webpack:///~/zone.js/dist/async-test.js:38:0 <- config/karma-test-shim.js:64655:31 [<root>]
        at timer (webpack:///~/zone.js/dist/zone.js:1732:0 <- config/karma-test-shim.js:67191:29) [<root>]
</code>```

Why does this throw a TypeError and break my test?

答:
You lost context this.

```<code>getJasmineRequireObj().toThrowError = function(j$) {
  function toThrowError () {
    return {
      compare: function(actual) {
        var threw = false,
          pass = {pass: true},
          fail = {pass: false},
          thrown;

        if (typeof actual != 'function') {
          throw new Error('Actual is not a Function');
        }

        var errorMatcher = getMatcher.apply(null, arguments);

        try {
          actual(); // call function reference component.someMethod
</code>```

I would write

```<code>expect(component.someMethod.bind(component)).toThrowError(CustomError);
</code>```

Body:
I have defined a CustomError as

export class CustomError extends Error {
    constructor(message?: string) {
        super(message);
        Object.setPrototypeOf(this, CustomError.prototype);
    }
}

and I want to throw CustomError from an angular component, e.g.,

@Component({
    moduleId: 'module.id',
    templateUrl: 'my.component.html'
})
export class MyComponent {
    someMethod(): void {
        throw new CustomError();
    }
}

Now I want to test that CustomError is thrown, so I write the following test

describe('MyComponent', () => {

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [MyComponent]
        }).compileComponents();
    }));

    beforeEach(async(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
    }));

    it('throws CustomError', () => {
        expect(component.someMethod).toThrowError(CustomError);
    });
});

This test passes as expected. However, if I now introduce someProperty into MyComponent, i.e.,

@Component({
    moduleId: 'module.id',
    templateUrl: 'my.component.html'
})
export class MyComponent {
    someProperty: string  = "Why does this break it?";

    someMethod(): void {
        console.log(this.someProperty);  // This breaks it, why?
        throw new CustomError();
    }
}

and attempt to use that property in the function I'm testing (in this case writing to the console), my test fails because a TypeError is thrown - stack trace below:

Expected function to throw AuthError, but it threw TypeError.
        at Object.<anonymous> (webpack:///src/app/auth/login/login.component.spec.ts:46:32 <- config/karma-test-shim.js:68955:33) [ProxyZone]
        at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:79:0 <- config/karma-test-shim.js:65355:39) [ProxyZone]
        at Object.<anonymous> (webpack:///~/zone.js/dist/jasmine-patch.js:104:0 <- config/karma-test-shim.js:65071:34) [ProxyZone]
        at webpack:///~/@angular/core/@angular/core/testing.es5.js:96:0 <- config/karma-test-shim.js:20767:17 [ProxyZone]
        at AsyncTestZoneSpec.onInvoke (webpack:///~/zone.js/dist/async-test.js:49:0 <- config/karma-test-shim.js:64666:39) [ProxyZone]
        at ProxyZoneSpec.onInvoke (webpack:///~/zone.js/dist/proxy.js:76:0 <- config/karma-test-shim.js:65352:39) [ProxyZone]
        at AsyncTestZoneSpec._finishCallback (webpack:///~/@angular/core/@angular/core/testing.es5.js:91:0 <- config/karma-test-shim.js:20762:25) [<root>]
        at webpack:///~/zone.js/dist/async-test.js:38:0 <- config/karma-test-shim.js:64655:31 [<root>]
        at timer (webpack:///~/zone.js/dist/zone.js:1732:0 <- config/karma-test-shim.js:67191:29) [<root>]

Why does this throw a TypeError and break my test?

Body:
You lost context this.

getJasmineRequireObj().toThrowError = function(j$) {
  function toThrowError () {
    return {
      compare: function(actual) {
        var threw = false,
          pass = {pass: true},
          fail = {pass: false},
          thrown;

        if (typeof actual != 'function') {
          throw new Error('Actual is not a Function');
        }

        var errorMatcher = getMatcher.apply(null, arguments);

        try {
          actual(); // call function reference component.someMethod

I would write

expect(component.someMethod.bind(component)).toThrowError(CustomError);


问:
Getting clicked element id and using it in html using angularjs
I am creating ionic app(ionic version v1) with angular js.
I want to get the data of clicked element from one html file and use it in other html file.

app.js

```<code>angular.module('placementApp', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {

  // $ionicConfigProvider.views.transition('android'); //none, ios

  $stateProvider

    .state('home', {
      url: '/home',
      templateUrl: 'templates/main.html'
      // controller: 'AppCtrl'
    })

    .state('students', {
      url: '/students',
      templateUrl: 'templates/userList.html'
    })

    .state('companies', {
      url: '/companies',
      templateUrl: 'templates/companyList.html'
    })

    .state('editStudent', {
      url: '/editStudent',
      templateUrl: 'templates/editUser.html'
    });
});
</code>```

userList.component.js

```<code>var app = angular.module('placementApp');

app.controller('userListCtrl', function($scope) {
    $scope.students = [
        {
            name: "Pearl Adam",
            Branch: "CE",
            id: "10562",
            cgpa: "5.9"

        },

        {
            name: "Avrill White",
            Branch: "CSE",
            id: "10821",
            cgpa: "8.3"
        }
    ]

    $scope.getClickedStudent = function(event) {
        $scope.v = event.currentTarget.attributes.data;
        console.log($scope.v);
    }

})
</code>```

userList.html

```<code><ion-view>
    <ion-header-bar class="bar-stable">
        <h1 class="title">Student List</h1>
    </ion-header-bar>
    <ion-content class="has-header">
        <div ng-controller='userListCtrl' ng-init='v = "undefined"'>
            <ul class="list" ng-repeat="x in students">
                <li class="item">
                    <a ng-click="getClickedStudent($event)" data='{{x}}' class="item" href='#/editStudent' >
                        <p>Name: {{x.name}}</p>
                        <p>Roll No.: {{x.id}}</p>
                    </a>
                </li>
            </ul>
            {{v.name}}

        </div>
    </ion-content>
</ion-view>
</code>```

I need to get the data of clicked element and use it in editUser.html for eg. {{v.name}}, {{v.cgpa}}.
but v is getting {} value.

I am using v in following file and it is showing empty value of {{v}} instead.
editUser.html

```<code><ion-view>
    <ion-header-bar class="bar-stable">
        <div ng-controller="userListCtrl">
            <h1 class="title">{{v.name}}</h1>
        </div>
    </ion-header-bar>
    <ion-content class="has-header">
        <div ng-controller='userListCtrl'>
            <div class="list">
                <label class="item item-input">
                    <span class="input-label">Name</span>
                    {{v.name}}
                </label>
                <label class="item item-input">
                    <span class="input-label">Branch</span>
                    {{v.branch}}
                </label>
                <label class="item item-input">
                    <span class="input-label">Roll No.</span>
                    {{v.id}}
                </label>
                <label class="item item-input">
                    <span class="input-label">CGPA</span>
                    {{v.cgpa}}
                </label>

            </div>
        </div>
    </ion-content>
</ion-view>
</code>```

答:
Pass x object as parameter of function instead of $event</p>

```<code>   <a ng-click="getClickedStudent(x)" class="item" href='#/editStudent' >

   $scope.getClickedStudent = function(student) {
        console.log(student);
    }
</code>```

Body:
I am creating ionic app(ionic version v1) with angular js.
I want to get the data of clicked element from one html file and use it in other html file.

app.js

angular.module('placementApp', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {

  // $ionicConfigProvider.views.transition('android'); //none, ios

  $stateProvider

    .state('home', {
      url: '/home',
      templateUrl: 'templates/main.html'
      // controller: 'AppCtrl'
    })

    .state('students', {
      url: '/students',
      templateUrl: 'templates/userList.html'
    })

    .state('companies', {
      url: '/companies',
      templateUrl: 'templates/companyList.html'
    })

    .state('editStudent', {
      url: '/editStudent',
      templateUrl: 'templates/editUser.html'
    });
});

userList.component.js

var app = angular.module('placementApp');

app.controller('userListCtrl', function($scope) {
    $scope.students = [
        {
            name: "Pearl Adam",
            Branch: "CE",
            id: "10562",
            cgpa: "5.9"

        },

        {
            name: "Avrill White",
            Branch: "CSE",
            id: "10821",
            cgpa: "8.3"
        }
    ]

    $scope.getClickedStudent = function(event) {
        $scope.v = event.currentTarget.attributes.data;
        console.log($scope.v);
    }

})

userList.html

<ion-view>
    <ion-header-bar class="bar-stable">

Student List

    </ion-header-bar>
    <ion-content class="has-header">

Name: {{x.name}}

Roll No.: {{x.id}}

            {{v.name}}

    </ion-content>
</ion-view>

I need to get the data of clicked element and use it in editUser.html for eg. {{v.name}}, {{v.cgpa}}.
but v is getting {} value.

I am using v in following file and it is showing empty value of {{v}} instead.
editUser.html

<ion-view>
    <ion-header-bar class="bar-stable">

{{v.name}}

    </ion-header-bar>
    <ion-content class="has-header">

                    Name
                    {{v.name}}

                    Branch
                    {{v.branch}}

                    Roll No.
                    {{v.id}}

                    CGPA
                    {{v.cgpa}}

    </ion-content>
</ion-view>

Body:
Pass x object as parameter of function instead of $event

   <a ng-click="getClickedStudent(x)" class="item" href='#/editStudent' >

   $scope.getClickedStudent = function(student) {
        console.log(student);
    }


答:
You need to initialize properties

```<code>AllBookingsViewModel model = new AllBookingsViewModel();
model.HallBookingsList = new List<HallActivityBooking>();
model.RoomBookingsList = new List<RoomBooking>();
//Your existing code
</code>```

Or, You can use directly use LINQ result to set these properties.

```<code>AllBookingsViewModel model = new AllBookingsViewModel();
model.HallBookingsList = db.HallBookings.Where(x => x.CustomerUser.Id == currentUser.Id);
model.RoomBookingsList = db.RoomBookings.Where(x => x.CustomerUser.Id == currentUser.Id);
</code>```

Title: c# - object reference not set to an instance of an object - LINQ

Body:
You need to initialize properties

AllBookingsViewModel model = new AllBookingsViewModel();
model.HallBookingsList = new List<HallActivityBooking>();
model.RoomBookingsList = new List<RoomBooking>();
//Your existing code

Or, You can use directly use LINQ result to set these properties.

AllBookingsViewModel model = new AllBookingsViewModel();
model.HallBookingsList = db.HallBookings.Where(x => x.CustomerUser.Id == currentUser.Id);
model.RoomBookingsList = db.RoomBookings.Where(x => x.CustomerUser.Id == currentUser.Id);


问:
Azure Functions Precompiled & Blob Trigger : The function type name is invalid
I try to deploy a precompiled Azure Function that use Blob Trigger.
After publishing the function, I have the following error in Kudu and my function is not executed:

```<code>2017-05-30T14:34:11.436 Starting Host (HostId=sfl-data-forecast-dev-funcs, Version=1.0.10945.0, ProcessId=17328, Debug=True, Attempt=0)
2017-05-30T14:34:11.436 Development settings applied
2017-05-30T14:34:11.436 No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. config.UseServiceBus(), config.UseTimers(), etc.).
2017-05-30T14:34:11.436 Job host started
2017-05-30T14:34:11.436 The following 1 functions are in error:
Import: The function type name 'Forecasts.Functions.ImportForecastsFunction' is invalid.
</code>```

I do not understand why I have this error. The Azure function is in a web project that targeting framework 4.6.1. WebJob SDK, and Extensions nuget package were added. I have downgraded Newtonsoft.Json to version 9.01 but it didn't change anything.

I have the following function.json:

```<code>{
  "scriptFile": "..\\bin\\SFL.Data.Forecasts.Functions.dll",
  "entryPoint": "SFL.Data.Forecasts.Functions.ImportForecastsFunction.Run",
  "bindings": [
    {
      "name": "file",
      "type": "blobTrigger",
      "direction": "in",
      "path": "forecasts/{name}",
      "connection": "HotStorageAccount.ConnectionString"
    }
  ],
  "disabled": false
}
</code>```

答:
I solved the problem by providing a namespace for the Azure Function file.

namespace MyProject.AppFunctions

This is my class:

```<code>namespace MyProject.AppFunctions
{
    public static class SomeFunction
    {
        public static async Task<HttpResponseMessage> Run(...)
        {
            // CODE
        }
    }
}
</code>```

This is my functions.json file:

```<code>{
  "scriptFile": "..\\bin\\MyProject.AppFunctions.dll",
  "entryPoint": "MyProject.AppFunctions.SomeFunction.Run",
...
}
</code>```

Body:
I try to deploy a precompiled Azure Function that use Blob Trigger.
After publishing the function, I have the following error in Kudu and my function is not executed:

2017-05-30T14:34:11.436 Starting Host (HostId=sfl-data-forecast-dev-funcs, Version=1.0.10945.0, ProcessId=17328, Debug=True, Attempt=0)
2017-05-30T14:34:11.436 Development settings applied
2017-05-30T14:34:11.436 No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. config.UseServiceBus(), config.UseTimers(), etc.).
2017-05-30T14:34:11.436 Job host started
2017-05-30T14:34:11.436 The following 1 functions are in error:
Import: The function type name 'Forecasts.Functions.ImportForecastsFunction' is invalid.

I do not understand why I have this error. The Azure function is in a web project that targeting framework 4.6.1. WebJob SDK, and Extensions nuget package were added. I have downgraded Newtonsoft.Json to version 9.01 but it didn't change anything.

I have the following function.json:

{
  "scriptFile": "..\\bin\\SFL.Data.Forecasts.Functions.dll",
  "entryPoint": "SFL.Data.Forecasts.Functions.ImportForecastsFunction.Run",
  "bindings": [
    {
      "name": "file",
      "type": "blobTrigger",
      "direction": "in",
      "path": "forecasts/{name}",
      "connection": "HotStorageAccount.ConnectionString"
    }
  ],
  "disabled": false
}

Body:
I solved the problem by providing a namespace for the Azure Function file.

namespace MyProject.AppFunctions

This is my class:

namespace MyProject.AppFunctions
{
    public static class SomeFunction
    {
        public static async Task<HttpResponseMessage> Run(...)
        {
            // CODE
        }
    }
}

This is my functions.json file:

{
  "scriptFile": "..\\bin\\MyProject.AppFunctions.dll",
  "entryPoint": "MyProject.AppFunctions.SomeFunction.Run",
...
}


问:
How to take a selected option with PHP
I'm new here and I'm really sorry if the subject of this ticket do not have to be at this place.

I'm working on a PrestaShop website that use SMARTY. How could I display some products with the choice that a customer done in a select tag?

Can I do this with just PHP + HTML or do I need Javascript?

Here is my code :

Page de conseil pour PC & PC portable Gamer

Dites nous quel style de Gamer vous ètes, nous nous occupons du reste

Sélectionnez le type de joueur qui vous correspond

  <select class="gameplay">
   <option value="1" selected="selected">Sélectionnez</option>
   <option value="1">Casual (de temps en temps)</option>
   <option value="1">Normal (1 à 2h/jour)</option>
   <option value="1">Régulier (2 à 4h/jour)</option>
   <option value="1">Hard Core (>4h/jour)</option>
  </select>

Sélectionnez vos types de jeux

  <select class="game">
   <option value="1" selected="selected">Sélectionnez</option>
   <option value="1">MOBA & FPS peu gourmand (Counter Strike, LOL, DOTA, Heroes Of The Storm)</option>
   <option value="1">MMORPG (WOW, Blade and Soul), FPS (type overwatch, battlefield 3)</option>
   <option value="1">FPS poussé (Battlefield 1), Aventures</option>
   <option value="1">Tout en Ultra !</option>
  </select>

  <button type="button" name="submit" class="validation-game">
   Valider
  </button>

```

I need to display 3 products that's correspond to the choice of the customer in select when he will hit the validate button.

My PHP's knowledge is not really high, if someone can guide, I don't want especially the answer just a way where I can work on it.

Thanks in advance.

答:
You can do it by php Html too, just add form tag for code block you have mention along with name properly to each select. When you click submit button form will be posted and give you array of values in $_POST global array, you can get value of single select by below syntax,

echo $_POST['game'];

Here "game" is name of one select form Element.

Title: How to take a selected option with PHP

Body:
I'm new here and I'm really sorry if the subject of this ticket do not have to be at this place.

I'm working on a PrestaShop website that use SMARTY. How could I display some products with the choice that a customer done in a select tag?

Can I do this with just PHP + HTML or do I need Javascript?

Here is my code :

Page de conseil pour PC & PC portable Gamer

Dites nous quel style de Gamer vous ètes, nous nous occupons du reste

Sélectionnez le type de joueur qui vous correspond

  <select class="gameplay">
   <option value="1" selected="selected">Sélectionnez</option>
   <option value="1">Casual (de temps en temps)</option>
   <option value="1">Normal (1 à 2h/jour)</option>
   <option value="1">Régulier (2 à 4h/jour)</option>
   <option value="1">Hard Core (>4h/jour)</option>
  </select>

Sélectionnez vos types de jeux

  <select class="game">
   <option value="1" selected="selected">Sélectionnez</option>
   <option value="1">MOBA & FPS peu gourmand (Counter Strike, LOL, DOTA, Heroes Of The Storm)</option>
   <option value="1">MMORPG (WOW, Blade and Soul), FPS (type overwatch, battlefield 3)</option>
   <option value="1">FPS poussé (Battlefield 1), Aventures</option>
   <option value="1">Tout en Ultra !</option>
  </select>

  <button type="button" name="submit" class="validation-game">
   Valider
  </button>

I need to display 3 products that's correspond to the choice of the customer in select when he will hit the validate button.

My PHP's knowledge is not really high, if someone can guide, I don't want especially the answer just a way where I can work on it.

Thanks in advance.


问:
char conversion error when trying to use strcmp
I have a function which cuts a string and stores it to a new array,

```<code>char splitStr(int cutPoint){
    int i=0;
    char newStr[20]="";
    for(i=0;i<cutPoint;i++){
        newStr[i]=comm[i];
    }
    cout<<newStr;
}
</code>```

The array comm[20] is a global array. I split the string stored in this array and compare it with an other string using strcmp(). This is how I does it,

```<code>if(strcmp(splitStr(5),"print")==0){
        cout<<"yes";
}
</code>```

But when I does this checking, I get an error as follows,

```<code>C:\Users\U\Desktop\main.cpp [Error] invalid conversion from 'char' to 'const char*' [-fpermissive]
</code>```

How can I resolve this? What is the cause for this?

答:
Three problems, which will turn into four:

The first problem and the error you ask about is that you declare the function to return a single char. Not a pointer to a char, like a string. Change to return char*.

You declare that the function splitStr should return a char (or char* once you fix the first problem), but you don't actually return anything. That will lead to undefined behavior.

You never terminate the string in newStr. That means all C string functions you pass the string to will go out of bounds and again you'll have undefined behavior.

The fourth problem, once you fix the three above, is that you will return a pointer to the local array newStr. That local array will go out of scope once the function returns, leaving you with a pointer to data that no longer exists.

The two three problems are easy to solve. The fourth problem is harder. There are four common solutions to that fourth problem:

Make the array static. That means its lifetime will be the whole program, and a pointer to data in the array will never become invalid. Unfortunately that will also make the function non-reentrant, so it can never be used in threads or called for different objects.

Dynamically allocate the string and return the pointer returned by new[] (or a std::unique_ptr which is preferred for instead of raw pointers). The problem here is that when used as you show, then you will have a memory leak (which will be solved if you use std::unique_ptr).

Pass the string array into the function as an argument. Return that string.

And the best solution when dealing with strings in C++: Use std::string!

And if you use std::string then you should use its substring function instead of making up your own.

Body:
I have a function which cuts a string and stores it to a new array,

char splitStr(int cutPoint){
    int i=0;
    char newStr[20]="";
    for(i=0;i<cutPoint;i++){
        newStr[i]=comm[i];
    }
    cout<<newStr;
}

The array comm[20] is a global array. I split the string stored in this array and compare it with an other string using strcmp(). This is how I does it,

if(strcmp(splitStr(5),"print")==0){
        cout<<"yes";
}

But when I does this checking, I get an error as follows,

C:\Users\U\Desktop\main.cpp [Error] invalid conversion from 'char' to 'const char*' [-fpermissive]

How can I resolve this? What is the cause for this?


问:
Dropbox Python API: download public Dropbox folder
I'm working with Dropbox's Python API.  My end goal is that, given a link to a public dropbox folder (not saved in my Dropbox account), my program can download each image to a local Desktop folder.

Many of the Dropbox API calls require a path.  I'm currently constructing a path by concatenating the folder ID and name as described: "A path relative to a folder's ID can be constructed by using a slash (e.g. 'id:abc123xyz/hello.txt')".   I do this by calling a post request to /get_shared_link_metadata to receive the ID and name.

Hover, when I attempt downloading (via the following code):

```<code>with open("/Users/______/Desktop/ok.jpeg", "wb") as f:
    metadata, res = dbx.files_download(path='id:jSheWaU4yeYAAAAAAAADHw/DSC_0190.JPG')
    f.write(res.content)
</code>```

I get this error:

dropbox.exceptions.ApiError:
  ApiError('6c829586fd97ebc6e18aa40336e3aa94', DownloadError('path',
  LookupError('not_found', None)))

Any insight would be appreciated! Thank you.

答:
That is the valid syntax for constructing a path to a file relative to the parent folder's ID.

This error indicates that this path doesn't exist in the connected user's account though. A few things to check in that case:

If id:jSheWaU4yeYAAAAAAAADHw the ID of the file or the parent folder? If it is the ID of the file itself, you don't need to append the filename, and should instead supply id:jSheWaU4yeYAAAAAAAADHw only.

Is there something at that path in the connected user's account? Make sure that you have the correct file name (assuming id:jSheWaU4yeYAAAAAAAADHw is the ID of the parent folder), that there is something at that path, and that you are looking at the correct account.

Body:
I'm working with Dropbox's Python API.  My end goal is that, given a link to a public dropbox folder (not saved in my Dropbox account), my program can download each image to a local Desktop folder.

Many of the Dropbox API calls require a path.  I'm currently constructing a path by concatenating the folder ID and name as described: "A path relative to a folder's ID can be constructed by using a slash (e.g. 'id:abc123xyz/hello.txt')".   I do this by calling a post request to /get_shared_link_metadata to receive the ID and name.

Hover, when I attempt downloading (via the following code):

with open("/Users/______/Desktop/ok.jpeg", "wb") as f:
    metadata, res = dbx.files_download(path='id:jSheWaU4yeYAAAAAAAADHw/DSC_0190.JPG')
    f.write(res.content)

I get this error:

dropbox.exceptions.ApiError:
  ApiError('6c829586fd97ebc6e18aa40336e3aa94', DownloadError('path',
  LookupError('not_found', None)))

Any insight would be appreciated! Thank you.


问:
Using regex for the first time
I just started using regex and I'm trying to solve this problem, but it keeps return null. What is wrong with my code?
I want it to return this = (833) 741-2093</p>

```<code>function phoneNumber(numbers){
  var num = numbers.join('');
  var r = /\(\d{3}\)\s\d{3}\-\d{4}/;
  var match = num.match(r);
  return match;
}

var output = phoneNumber([8, 3, 3, 7, 4, 1, 2, 0, 9, 3]);

console.log(output);
</code>```

答:
Try this:

function phoneNumber (numbers) {
  var numberStr = numbers.join('');
  return numberStr.replace(/(\d{3})(\d{3})(\d{4})/, "\($1\) $2\-$3");
}

var output = phoneNumber([8, 3, 3, 7, 4, 1, 2, 0, 9, 3]);

console.log(output);```

You need to capture the three sets of numbers first, and then format them in the second parameter of .replace(). regex101 demo

Title: Using regex for the first time

Body:
I just started using regex and I'm trying to solve this problem, but it keeps return null. What is wrong with my code?
I want it to return this = (833) 741-2093

function phoneNumber(numbers){
  var num = numbers.join('');
  var r = /\(\d{3}\)\s\d{3}\-\d{4}/;
  var match = num.match(r);
  return match;
}

var output = phoneNumber([8, 3, 3, 7, 4, 1, 2, 0, 9, 3]);

console.log(output);

Body:
Try this:

function phoneNumber (numbers) {
  var numberStr = numbers.join('');
  return numberStr.replace(/(\d{3})(\d{3})(\d{4})/, "\($1\) $2\-$3");
}

var output = phoneNumber([8, 3, 3, 7, 4, 1, 2, 0, 9, 3]);

console.log(output);

You need to capture the three sets of numbers first, and then format them in the second parameter of .replace(). regex101 demo


问:
Wampp - I cannot login to phpmyadmin after new installation #2002
I've installed WAMPP server. Apache works correctly, but I cannot login to phpmyadmin. I get this error:

```<code>#2002 Cannot log in to the MySQL server
</code>```

I have Windows. Mysql is installed with Wampp. I cannot login to mysql from Mysql console (in wampp menu context) I don't know can I set this password.

In config.inc.php I set

```<code>$cfg['Servers'][$i]['password'] = 'yourNewpassword';
</code>```

but it doesn't help too.

I think that I have to setup password to mysql because when I installing wamp I didn't get any password. But I don't know how. I try run mysqld.exe in consle - won't to start.

Thanks

答: First of all allow wamp access by changing the firewall settings, or simply click on "allow access" button of firewall warning pop up after a fresh installation.Just After a fresh installation, click on the wampserver icon to run it-> wamp icon will appear on the right side of your taskbar, when you click on this wamp icon->select "start all services".(you will notice a change in its color) again click on wampicon on the taskbar and click-> phpmyAdmin, a login page will appear, you just have to enter the username as "root" and leave the password(no need to enter the password if you are a new user). enter go!!</p>

Body:
I've installed WAMPP server. Apache works correctly, but I cannot login to phpmyadmin. I get this error:

#2002 Cannot log in to the MySQL server

I have Windows. Mysql is installed with Wampp. I cannot login to mysql from Mysql console (in wampp menu context) I don't know can I set this password.

In config.inc.php I set

$cfg['Servers'][$i]['password'] = 'yourNewpassword';

but it doesn't help too.

I think that I have to setup password to mysql because when I installing wamp I didn't get any password. But I don't know how. I try run mysqld.exe in consle - won't to start.

Thanks


答:
You can use this regex:

```<code>Port\sname=(COM\d+)((?!Port)[\w\W])*Alias=BoardUSB
</code>```

In particular, ((?!Port)[\w\W])* excludes all strings containing the word "Port" between "Port" and "Alias", so that you don't read the Alias associated to another port.

Title: Match a string after a string is matched in multiple line

Body:
I try to write a regex to search the port name with alias "USBBoard"
by using this:

Port name=(COM\d+).*Alias=BoardUSB

But it seems the group match 'COM10' instead of 'COM1'
Any advice to improve the regex? thanks

[Serial_COM10]
Port name=COM10
Baud rate=9600
Data bits=8
Timeout=2500
Alias=COM_PPS
Handshake=None
[Serial_COM1]
Port name=COM1
Baud rate=9600
Data bits=8
Timeout=2500
Alias=BoardUSB
Handshake=None
[Serial_COM3]
Port name=COM3
Baud rate=115200
Data bits=8
Timeout=2500
Alias=usb_hub
Handshake=None

Body:
You can use this regex:

Port\sname=(COM\d+)((?!Port)[\w\W])*Alias=BoardUSB

In particular, ((?!Port)[\w\W])* excludes all strings containing the word "Port" between "Port" and "Alias", so that you don't read the Alias associated to another port.


问:
Have a
 fixed at a height only when scrolling down
So I have this sidebar:

```<code><div class="col-md-3">
        <h4 style="color: #404040; font-weight: bold;">
            Guides:
        </h4>
        <div class="sidebar">
             <!--auto-generated <ul>...-->
        </div>
</div>
</code>```

And I want it to follow the user as he scrolls down. I know that you can do it with position: fixed; in the styles. But I have a header, so if the div is fixed it remains in that height even if I scroll down.

But if I scroll down, it remains at that fixed point. Here's how it looks like when I scroll down it would look like this:

I want it to remain at the top. I read that I'm supposed to use javascript scroll functions, but I have no clue how, exactly.

答:
You can use position: sticky for an easy "sticky" element. It's a new property, so it doesn't have the best browser support, but easy to use and works well.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

      scroll down

            Guides: (look it's sticky!)

```

Title: Have a <div> fixed at a height only when scrolling down

Body:
So I have this sidebar:

            Guides:

And I want it to follow the user as he scrolls down. I know that you can do it with position: fixed; in the styles. But I have a header, so if the div is fixed it remains in that height even if I scroll down.

But if I scroll down, it remains at that fixed point. Here's how it looks like when I scroll down it would look like this:

I want it to remain at the top. I read that I'm supposed to use javascript scroll functions, but I have no clue how, exactly.

Body:
You can use position: sticky for an easy "sticky" element. It's a new property, so it doesn't have the best browser support, but easy to use and works well.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<style>
    .row {
      height: 200vh;
    }
    .row:nth-child(odd) {
      background: #eee;
    }
    .sticky-column {
      position: sticky;
      top: 1em;
    }
</style>

<div class="container">
  <div class="row">
    <div class="col-lg-12">
      scroll down
    </div>
  </div>
  <div class="row">
    <div class="col-md-3 sticky-column">
      <h4 style="color: #404040; font-weight: bold;">
            Guides: (look it's sticky!)
        </h4>
      <div class="sidebar">
        <!--auto-generated <ul>...-->
      </div>
    </div>
  </div>
  <div class="row"></div>
</div>


问:
Kotlin lambda with Interface as an argument
I'm a bit baffled by the Koltin lambdas and I wanted to know how to use it given the following snippet of code:

```<code>interface KotlinInterface {

    fun doStuff(str: String): String
}
</code>```

And the function that requires this Interface to be passed as a parameter:

```<code>fun kotlinInterfaceAsArgument(kotlinInterface: KotlinInterface): String{

   return kotlinInterface.doStuff("This was passed to Kotlin Interface method")
}

fun main(args: Array<String>){

    val newString = kotlinInterfaceAsArgument({
      str -> str + " | It's here" //error here (type mismatch)
    })
}
</code>```

However, the same logic but in Java compiles and runs as intended.

```<code>public class JavaClass {

   public String javaInterfaceAsArgument(JavaInterface javaInterface){

        String passedToInterfaceMethod = "This was passed to Java Interface method";
        return javaInterface.doStuff(passedToInterfaceMethod);
    }

   public interface JavaInterface {

        public String doStuff(String str);
    }
}
</code>```

and

```<code>public class Main {

    public static void main(String[] args) {

        JavaClass javaClass = new JavaClass();
        String newValue = javaClass.javaInterfaceAsArgument(str -> str + " | It's here!");

        System.out.println(newValue);
    }
}
</code>```

How can I utilize lambda in Kotlin in this case?

答:
SAM conversion (as of 1.1) only works with Java interfaces, not Kotlin ones.

Also note that this feature works only for Java interop; since Kotlin has proper function types, automatic conversion of functions into implementations of Kotlin interfaces is unnecessary and therefore unsupported.

You can see some ways to fix your code in this answer.

Edit: I've realized this is an exact duplicate of the other question, as even the error is the same.

Body:
I'm a bit baffled by the Koltin lambdas and I wanted to know how to use it given the following snippet of code:

interface KotlinInterface {

    fun doStuff(str: String): String
}

And the function that requires this Interface to be passed as a parameter:

fun kotlinInterfaceAsArgument(kotlinInterface: KotlinInterface): String{

   return kotlinInterface.doStuff("This was passed to Kotlin Interface method")
}

fun main(args: Array<String>){

    val newString = kotlinInterfaceAsArgument({
      str -> str + " | It's here" //error here (type mismatch)
    })
}

However, the same logic but in Java compiles and runs as intended.

public class JavaClass {

   public String javaInterfaceAsArgument(JavaInterface javaInterface){

        String passedToInterfaceMethod = "This was passed to Java Interface method";
        return javaInterface.doStuff(passedToInterfaceMethod);
    }

   public interface JavaInterface {

        public String doStuff(String str);
    }
}

and

public class Main {

    public static void main(String[] args) {

        JavaClass javaClass = new JavaClass();
        String newValue = javaClass.javaInterfaceAsArgument(str -> str + " | It's here!");

        System.out.println(newValue);
    }
}

How can I utilize lambda in Kotlin in this case?

ContentLicense: CC BY-SA 4.0


问:
Do I need a federated Identity Server for SSO if I'm a small service provider application?
Say I'm a small application (www.example.com) and I'm integrating with a much larger enterprise (www.acme.com).

In this scenario I am the service provider and they are the Identity provider.Their request is that I integrate into their auth ecosystem using SSO (specifically SAML 2.0).

For the standard IdP-initiated flow, users will sign in on their end and they will POST an XML assertion to my application, which will then verify the user and sign them in to my application (i.e. set a browser session).

The enterprise uses PingFederate as their identity server, and they are curious what implementation my application uses. At this time I have none.

If my application is a single monolith (e.g. a small Ruby on Rails app), do I even need a federated server? Ultimately they are just looking for a place to POST SAML data to, so I can set up an endpoint and go from there right?

What are some general benefits of a federated server? Why wouldn't every service provider application (small and large) just set up an endpoint to ingest SAML data and call it a day?

Thanks!

答: You don't necessarily need a Federation server. However, if you decide in the future to divide/expand your application into micro-services or integrate your service with other 3rd Parties, a server will allow you to scale without disrupting your current customers (great CX) and not have to manage separate security endpoints.


问:
Image Crop Editor Not working
I am having an issue in WordPress admin, where the images are not cropping in WP "edit image" for a site I am creating and I do not know what the cause is.

I've read a few similar topics, but nothing seems to make a dent. I've deactivated all plugins and checked the server, but things seem to be set up just fine.

Can someone possibly steer me in the right direction on how I can get it to work or what might be causing the issue?

答:
I found that in my OVH WordPress server, version 4.7.5, imagemagick was not installed and is required for this function to work properly:

```<code>sudo apt-get install imagemagick
sudo service apache2 restart
</code>```

Title: Image Crop Editor Not working

Body:
I found that in my OVH WordPress server, version 4.7.5, imagemagick was not installed and is required for this function to work properly:

sudo apt-get install imagemagick
sudo service apache2 restart


问:
Ternary operation with a "negative" variable
What does the negative variable do in a ternary? Why is the output -10 is 10?

```<code>public class Ternary {
    public static void main(String[] args) {
        int i, k;
        i = -10;
        k = i < 0 ? -i : i;
        System.out.print(i + " is " + k);
    }
}
</code>```

Can anyone explain the function of the variable in this scenario? What does -i mean?

答:
It's a unary operation -(-(1)) is 1. It's a longer way to write

```<code>int i = -10, k = Math.abs(i);
</code>```

Body:
What does the negative variable do in a ternary? Why is the output -10 is 10?

public class Ternary {
    public static void main(String[] args) {
        int i, k;
        i = -10;
        k = i < 0 ? -i : i;
        System.out.print(i + " is " + k);
    }
}

Can anyone explain the function of the variable in this scenario? What does -i mean?

Body:
It's a unary operation -(-(1)) is 1. It's a longer way to write

int i = -10, k = Math.abs(i);


问:
XHTML Setting line-breaks for multiple anchor tags with multiple images inside
Considering this sample code:

```<code><div style="width:300px;">
   <a href="#">
      <img src="images/bracket_open.png"/>
      <img src="images/1.png"/>
      <img src="images/bracket_close.png"/>
   </a>
   <a href="#">
      <img src="images/bracket_open.png"/>
      <img src="images/2.png"/>
      <img src="images/bracket_close.png"/>
   </a>
   <a href="#">
      <img src="images/bracket_open.png"/>
      <img src="images/3.png"/>
      <img src="images/bracket_close.png"/>
   </a>
</div>
</code>```

Basically a long list of anchor tags that contain multiple image tags (because of the font) that make up something like [1] [2] [3] and so on.

How can I make it so that the line breaks only occur between the anchor tags and never between the image tags inside of the anchor tags.

I would preffer a XHTML/CSS solution rather than JavaScript if such exists.

Thank you.

答:
Simple nowrap doesn't work?

```<code>div a {
    white-space:nowrap;
    }
</code>```

With HTML like

```<code><a href="#"><span>[</span><span>1</span><span>]</span></a><a href="#"><span>[</span><span>2</span><span>]</span></a><a href="#"><span>[</span><span>1</span><span>]</span></a>...
</code>```

You also can use:

```<code>div a {
    float:left;
    white-space:nowrap;
    }
</code>```

But it's not rather elegant due to making inline elements float with no weighty reason.

Body:
Considering this sample code:

Basically a long list of anchor tags that contain multiple image tags (because of the font) that make up something like [1] [2] [3] and so on.

How can I make it so that the line breaks only occur between the anchor tags and never between the image tags inside of the anchor tags.

I would preffer a XHTML/CSS solution rather than JavaScript if such exists.

Thank you.

Body:
Simple nowrap doesn't work?

div a {
    white-space:nowrap;
    }

With HTML like

<a href="#"><span>[</span><span>1</span><span>]</span></a><a href="#"><span>[</span><span>2</span><span>]</span></a><a href="#"><span>[</span><span>1</span><span>]</span></a>...

You also can use:

div a {
    float:left;
    white-space:nowrap;
    }

But it's not rather elegant due to making inline elements float with no weighty reason.


问:
mysqli_qeury does't work correctly. i need help^
i have problems with my mysqli_query, it wil not insert into the database but in phpmyadmin in sql it works but in website not.
here my code:</p>

```<code><form action="" method="POST">
    <input type="email" name="email" placeholder="Gelieve uw e mail in te voeren.">
    <input type="submit" name"submit" value="Subscribe">
</form>

<?php
    $db = mysqli_connect('**', '**', '**', '**');
    $email = $_POST['email'];
    if(isset($_POST["submit"])){
       mysqli_query($db, "insert into `t_nieuwsbrief` VALUES ('', '$email')");
    }
?>
</code>```

答:
use your mysql query with correct syntax

Try this

```<code>mysqli_query($db, 'INSERT INTO t_nieuwsbrief(email) VALUES ("'.$email.'")');
</code>```

Body:
i have problems with my mysqli_query, it wil not insert into the database but in phpmyadmin in sql it works but in website not.
here my code:

<form action="" method="POST">
    <input type="email" name="email" placeholder="Gelieve uw e mail in te voeren.">
    <input type="submit" name"submit" value="Subscribe">
</form>

<?php
    $db = mysqli_connect('**', '**', '**', '**');
    $email = $_POST['email'];
    if(isset($_POST["submit"])){
       mysqli_query($db, "insert into `t_nieuwsbrief` VALUES ('', '$email')");
    }
?>

Body:
use your mysql query with correct syntax

Try this

mysqli_query($db, 'INSERT INTO t_nieuwsbrief(email) VALUES ("'.$email.'")');


问:
mailx issue while sending the output in unix shell script
I've written a code where it will check the successful execution of the last run command and will mail the output with the subject.

```<code>#!/bin/ksh

SCHEDULER ID="abc123"
RUNNUM_INFO="1212"
DATE=`date '+%Y%m%d'`
FILE="OX_{DATE}.txt"

/usr/bin/ftp -n 93.179.136.9 << !EOF!
user abc passwd
cd "/0009/Codici Migrazione"
bin
get $FILE
bye
!EOF!

if [ $? -eq 0 ];
then
echo "Activity completed. \n
SCHEDULER ID : $SCHEDULE_ID \n BILL_RUN_NUM: $BILL_RUNNUM_INFO \n DATE: $DATE" | mailx -r "ashish@xyz.com" -s "Activity Completed - $DATE"
exit 0
fi
</code>```

But, on executing the script, I'm getting error:

```<code>The flags you gave are used only when sending mail.
</code>```

答:
Try adding a destination/To: email address, eg:

```<code>mailx -r "ashish@xyz.com" -s "Activity Completed - $DATE" recipient@abc.com
</code>```

You'll also want to review your variables as you've got a couple issues:

1 - SCHEDULER ID="abc123" => not a valid variable; then it looks like you're trying to reference it later via $SCHEDULE_ID (valid variable name, but different spelling)

2 - RUNNUM_INFO => valid variable name, but later you try to reference it via $BILL_RUNNUM_INFO (valid variable name, but different spelling)

Body:
I've written a code where it will check the successful execution of the last run command and will mail the output with the subject.

#!/bin/ksh

SCHEDULER ID="abc123"
RUNNUM_INFO="1212"
DATE=`date '+%Y%m%d'`
FILE="OX_{DATE}.txt"

/usr/bin/ftp -n 93.179.136.9 << !EOF!
user abc passwd
cd "/0009/Codici Migrazione"
bin
get $FILE
bye
!EOF!

if [ $? -eq 0 ];
then
echo "Activity completed. \n
SCHEDULER ID : $SCHEDULE_ID \n BILL_RUN_NUM: $BILL_RUNNUM_INFO \n DATE: $DATE" | mailx -r "ashish@xyz.com" -s "Activity Completed - $DATE"
exit 0
fi

But, on executing the script, I'm getting error:

The flags you gave are used only when sending mail.

Body:
Try adding a destination/To: email address, eg:

mailx -r "ashish@xyz.com" -s "Activity Completed - $DATE" recipient@abc.com

You'll also want to review your variables as you've got a couple issues:

1 - SCHEDULER ID="abc123" => not a valid variable; then it looks like you're trying to reference it later via $SCHEDULE_ID (valid variable name, but different spelling)

2 - RUNNUM_INFO => valid variable name, but later you try to reference it via $BILL_RUNNUM_INFO (valid variable name, but different spelling)


问:
Adding a fade opacity to my Div scroll function?
I've managed to get div(s) to stick at the top offset by 64px on scroll but I also want the same div's opacity to fade to 0. I can't figure out how to add this? An example of what I have done so far.</p>

```<code>$(window).scroll(function(){
  var scrollTop = $(this).scrollTop();
  $(".ComponentOne").css("top",Math.max(64,800-scrollTop));
});
</code>```

答:
Updated

Try below code:

jQuery

```<code>$(window).scroll(function() {
  var scrollTop = $(this).scrollTop();
  var offsetTop = $('.ComponentOne').position().top;
  console.log(offsetTop);
  $(".ComponentOne").css("top", Math.max(64, 800 - scrollTop));
  if (offsetTop === 64) {
    $(".ComponentOne").css("opacity", "0");
  } else {
    $(".ComponentOne").css("opacity", "1");
  }
});
</code>```

CSS

```<code>.ComponentOne {
  transition: opacity 500ms ease;
  height: 100px;
  background: #000;
  position: fixed;
  left: 0;
  right: 0;
}
</code>```

Body:
I've managed to get div(s) to stick at the top offset by 64px on scroll but I also want the same div's opacity to fade to 0. I can't figure out how to add this? An example of what I have done so far.

$(window).scroll(function(){
  var scrollTop = $(this).scrollTop();
  $(".ComponentOne").css("top",Math.max(64,800-scrollTop));
});

Body:
Updated

Try below code:

jQuery

$(window).scroll(function() {
  var scrollTop = $(this).scrollTop();
  var offsetTop = $('.ComponentOne').position().top;
  console.log(offsetTop);
  $(".ComponentOne").css("top", Math.max(64, 800 - scrollTop));
  if (offsetTop === 64) {
    $(".ComponentOne").css("opacity", "0");
  } else {
    $(".ComponentOne").css("opacity", "1");
  }
});

CSS

.ComponentOne {
  transition: opacity 500ms ease;
  height: 100px;
  background: #000;
  position: fixed;
  left: 0;
  right: 0;
}


问:
Separating vuex stores for dynamically created components
This was the question got me stuck for a little bit. Unfortunately, I coudn't find answer here (asking also didn't help). So after doing some research and asking here and there, it seems that I got the solution to this issue.

If you have a question that you already know the answer to, and you
  would like to document that knowledge in public so that others
  (including yourself) can find it later.

Of course, my answer may not be the ideal one, moreover I know it is not, that's the key point why I'm posting - to improve it.

Note, I'm not using actions in example. The idea is the same.

Let's begin with stating the problem:

Imagine we have App.vue which dynamically generates its local component named Hello.

```<code><template>
  <div id="app">
    <div>
      <hello v-for="i in jobs" :key="i" :id="i"></hello>
      <button @click="addJob">New</button>
    </div>
  </div>
</template>

<script>
import Hello from './components/Hello'

export default {
  components: {
    Hello
  }...
</code>```

store.js

```<code>export const store = new Vuex.Store({
  state: {
    jobs: []
  }
})
</code>```

We are using v-for directive to generate components by iterating through an array jobs. Our store as of now consists of only state with an empty array.
Button New should do 2 things:

1) create new component Hello, in other words add element to jobs (let it be numbers), which are going to be assigned as key and id of <hello>, and passed to local component as props.

2) generate local stores - modules - to keep any data scoped to newly created components.

Hello.vue

```<code><template>
  <div>
    <input type="number" :value="count">
    <button @click="updateCountPlus">+1</button>
  </div>
</template>

export default {
  props: ['id']
}
</code>```

Simple component - input with a button adding 1.

Our goal is to design something like this:

答:
For the first operation of NEW button - generating components - we add mutation to our store.js

```<code> mutations: {
    addJob (state) {
      state.jobs.push(state.jobs.length + 1)
...
}
</code>```

Second, creating local modules. Here we're going to use reusableModule to generated multiple instances of a module. That module we keep in separate file for convinience. Also, note use of function for declaring module state.

```<code>const state = () => {
  return {
    count: 0
  }
}

const getters = {
  count: (state) => state.count
}

const mutations = {
  updateCountPlus (state) {
    state.count++
  }
}

export default {
  state,
  getters,
  mutations
}
</code>```

To use reusableModule we import it and apply dynamic module registration.

store.js

```<code>import module from './reusableModule'

const {state: stateModule, getters, mutations} = module

export const store = new Vuex.Store({
  state: {
    jobs: []
  },
  mutations: {
    addJob (state) {
      state.jobs.push(state.jobs.length + 1)
      store.registerModule(`module${state.jobs.length}`, {
        state: stateModule,
        getters,
        mutations,
        namespaced: true // making our module reusable
      })
    }
  }
})
</code>```

After, we're going to link Hello.vue with its storage. We may need state, getters, mutations, actions from vuex. To access storage we need to create our getters. Same with mutations.

Home.vue

```<code><script>

export default {
  props: ['id'],
  computed: {
     count () {
        return this.$store.getters[`module${this.id}/count`]
     }
  },
  methods: {
    updateCountPlus () {
        this.$store.commit(`module${this.id}/updateCountPlus`)
     }
  }
}
</script>
</code>```

Imagine we have lots of getters, mutations and actions. Why not use {mapGetters} or {mapMutations}? When we have several modules and we know the path to module needed, we can do it. Unfortunately, we do not have access to module name.

The code is run when the component's module is executed (when your app
  is booting), not when the component is created. So these helpers can
  only be used if you know the module name ahead of time.

There is little help here. We can separate our getters and mutations and then import them as an object and keep it clean.

```<code><script>
import computed from '../store/moduleGetters'
import methods from '../store/moduleMutations'

export default {
  props: ['id'],
  computed,
  methods
}
</script>
</code>```

Returning to App component. We have to commit our mutation and also let's create some getter for App. To show how can we access data located into modules.

store.js

```<code>export const store = new Vuex.Store({
  state: {
    jobs: []
  },
  getters: {
    jobs: state => state.jobs,
    sumAll (state, getters) {
      let s = 0
      for (let i = 1; i <= state.jobs.length; i++) {
        s += getters[`module${i}/count`]
      }
      return s
    }
  }
...
</code>```

Finishing code in App component

```<code><script>
import Hello from './components/Hello'
import {mapMutations, mapGetters} from 'vuex'

    export default {
      components: {
        Hello
      },
      computed: {
        ...mapGetters([
          'jobs',
          'sumAll'
        ])
      },
      methods: {
        ...mapMutations([
          'addJob'
        ])
      }
    }
    </script>
</code>```

Body:
This was the question got me stuck for a little bit. Unfortunately, I coudn't find answer here (asking also didn't help). So after doing some research and asking here and there, it seems that I got the solution to this issue.

If you have a question that you already know the answer to, and you
  would like to document that knowledge in public so that others
  (including yourself) can find it later.

Of course, my answer may not be the ideal one, moreover I know it is not, that's the key point why I'm posting - to improve it.

Note, I'm not using actions in example. The idea is the same.

Let's begin with stating the problem:

Imagine we have App.vue which dynamically generates its local component named Hello.

<template>

      <hello v-for="i in jobs" :key="i" :id="i"></hello>
      <button @click="addJob">New</button>

</template>

Body:
For the first operation of NEW button - generating components - we add mutation to our store.js

 mutations: {
    addJob (state) {
      state.jobs.push(state.jobs.length + 1)
...
}

Second, creating local modules. Here we're going to use reusableModule to generated multiple instances of a module. That module we keep in separate file for convinience. Also, note use of function for declaring module state.

const state = () => {
  return {
    count: 0
  }
}

const getters = {
  count: (state) => state.count
}

const mutations = {
  updateCountPlus (state) {
    state.count++
  }
}

export default {
  state,
  getters,
  mutations
}

To use reusableModule we import it and apply dynamic module registration.

store.js

import module from './reusableModule'

const {state: stateModule, getters, mutations} = module

export const store = new Vuex.Store({
  state: {
    jobs: []
  },
  mutations: {
    addJob (state) {
      state.jobs.push(state.jobs.length + 1)
      store.registerModule(`module${state.jobs.length}`, {
        state: stateModule,
        getters,
        mutations,
        namespaced: true // making our module reusable
      })
    }
  }
})

After, we're going to link Hello.vue with its storage. We may need state, getters, mutations, actions from vuex. To access storage we need to create our getters. Same with mutations.

Home.vue

<script>

export default {
  props: ['id'],
  computed: {
     count () {
        return this.$store.getters[`module${this.id}/count`]
     }
  },
  methods: {
    updateCountPlus () {
        this.$store.commit(`module${this.id}/updateCountPlus`)
     }
  }
}
</script>

Imagine we have lots of getters, mutations and actions. Why not use {mapGetters} or {mapMutations}? When we have several modules and we know the path to module needed, we can do it. Unfortunately, we do not have access to module name.

The code is run when the component's module is executed (when your app
  is booting), not when the component is created. So these helpers can
  only be used if you know the module name ahead of time.

There is little help here. We can separate our getters and mutations and then import them as an object and keep it clean.

<script>
import computed from '../store/moduleGetters'
import methods from '../store/moduleMutations'

export default {
  props: ['id'],
  computed,
  methods
}
</script>

Returning to App component. We have to commit our mutation and also let's create some getter for App. To show how can we access data located into modules.

store.js

export const store = new Vuex.Store({
  state: {
    jobs: []
  },
  getters: {
    jobs: state => state.jobs,
    sumAll (state, getters) {
      let s = 0
      for (let i = 1; i <= state.jobs.length; i++) {
        s += getters[`module${i}/count`]
      }
      return s
    }
  }
...

Finishing code in App component

<script>
import Hello from './components/Hello'
import {mapMutations, mapGetters} from 'vuex'

    export default {
      components: {
        Hello
      },
      computed: {
        ...mapGetters([
          'jobs',
          'sumAll'
        ])
      },
      methods: {
        ...mapMutations([
          'addJob'
        ])
      }
    }
    </script>


问:
why does arr.reverse() reverses the orginal array
What I am looking for is to be able to reverse an array and store it to new array without modifing the orginal array. The syntax I used is as follows:

```<code>var arr= ["1", "2", "5"]
var arrTwo = arr.reverse();
console.log(arrTwo) \\ ["5" , "2" , "1"]
console.log(arr) \\["5" , "2" , "1"]
</code>```

When I output the values I am getting both values reversed. Can anyone help me identify what is wrong with my syntax?

答:
Nothing wrong with your syntax, but reverse() does its things in-place.
If you want to have a copy, clone the array before:

```<code>var arr= ["1", "2", "5"]
var arrTwo = arr.slice(0).reverse();
</code>```

Body:
What I am looking for is to be able to reverse an array and store it to new array without modifing the orginal array. The syntax I used is as follows:

var arr= ["1", "2", "5"]
var arrTwo = arr.reverse();
console.log(arrTwo) \\ ["5" , "2" , "1"]
console.log(arr) \\["5" , "2" , "1"]

When I output the values I am getting both values reversed. Can anyone help me identify what is wrong with my syntax?

Body:
Nothing wrong with your syntax, but reverse() does its things in-place.
If you want to have a copy, clone the array before:

var arr= ["1", "2", "5"]
var arrTwo = arr.slice(0).reverse();