问:
Linq to SQL: Many to Many support class
I'd like to have a support class to help with the Many to Many relationship.

As I see it now it could be a double generic class you would define in one or both of the entity partial classes surrounding the relationship.

Getting it to allow access to the other table without having to specifically mention the relationship table should be easy. However adding or removing from the collection is somewhat trickier. You would ahve to add a row into the relationship table aswell and commit it or remove it based on what is done.

Could this be done through a function that is passed into this generic class?

Does a class like this exists and if not is it something that can be viably done?

答:
You can create a IManyToManySet<TEntity> interface that can be returned from your many to many property and have a ManyToManySet<TSource, TCross, TDestination> implementation with the query insert and delete features.

The interface may look like this:

```<code>public interface IManyToManySet<TEntity> : IEnumerable<TEntity>
    where TEntity : class
{
    int Count { get; }
    void Add(TEntity entity);
    bool Remove(TEntity entity);
    void AddRange(IEnumerable<TEntity> collection);
}
</code>```

And the implementation might look like this:

```<code>public class ManyToManySet<TSource, TCross, TDestination>
    : IManyToManySet<TDestination>, IEnumerable<TDestination>
    where TDestination : class
    where TSource : class
    where TCross : class
{
    private TSource source;
    private EntitySet<TCross> crossSet;
    private Func<TCross, TDestination> destinationSelector;
    private Func<TSource, TDestination, TCross> crossFactory;

    public ManyToManySet(TSource source,
        EntitySet<TCross> crossSet,
        Func<TCross, TDestination> destinationSelector,
        Func<TSource, TDestination, TCross> crossFactory)
    {
        this.source = source;
        this.crossSet = crossSet;
        this.destinationSelector = destinationSelector;
        this.crossFactory = crossFactory;
    }

    public int Count
    {
        get { return this.crossSet.Count; }
    }

    public void Add(TDestination entity)
    {
        var newEntity = this.crossFactory(this.source, entity);
        this.crossSet.Add(newEntity);
    }

    public bool Remove(TDestination entity)
    {
        var existingEntity = (
            from c in this.crossSet
            where this.destinationSelector(c) == entity
            select c)
            .SingleOrDefault();

        if (existingEntity != null)
        {
            return this.crossSet.Remove(existingEntity);
        }

        return false;
    }

    public void AddRange(IEnumerable<TDestination> collection)
    {
        foreach (var entity in collection)
        {
            this.Add(entity);
        }
    }

    public IEnumerator<TDestination> GetEnumerator()
    {
        return this.crossSet.Select(this.destinationSelector)
            .GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}
</code>```

You need to supply a couple of things in this implementation:

The TSource instance, that points back at the entity that defines the property.

The EntitySet<TCross> that points to the list of entities that define the cross table.

A projection function that allows you to convert a TCross to the TDestination.

A factory function that allows you to create a new TCross based on the TSource and TDestination.

Translating this to a practical example (Using Product and Order), would give you the following property in the Order entity:

```<code>private IManyToManySet<Product> products;
public IManyToManySet<Product> Products
{
    get
    {
        if (this.products != null)
        {
            this.products = new ManyToManySet<Order, OrderProduct, Product>(
                this, this.OrderProducts, op => op.Product,
                (o, p) => new OrderProduct { Order = o, Product = p });
        }

        return this.products;
    }
}
</code>```

And the following property in the Product entity:

```<code>private IManyToManySet<Order> orders;
public IManyToManySet<Order> Orders
{
    get
    {
        if (this.orders == null)
        {
            this.orders = new ManyToManySet<Product, OrderProduct, Order>(
                this, this.OrderProducts, op => op.Order,
                (p, o) => new OrderProduct { Order = o, Product = p });
        }

        return this.orders;
    }
}
</code>```

The IManyToManySet<T> interface is in fact redundant, because you can return a ManyToMany<TSource, TCross, TDestination> directly. The interface however hides the TSource and TCross type arguments, which makes it a bit more readable to the user of this property.

Note that this implementation has the same loading behavior as LINQ to SQL's EntitySet<T>; When it is used, it loads the complete set of objects in memory. Just as with an EntitySet<T> using a where or First on the collection, still loads the complete collection from the database. You need to be aware of that.

Important difference is however that LINQ to SQL understands EntitySet<T> properties within LINQ queries. Having a IManyToManySet<T> inside a LINQ query will fail miserably.

I hope this helps.

Title: Linq to SQL: Many to Many support class

Body:
You can create a IManyToManySet<TEntity> interface that can be returned from your many to many property and have a ManyToManySet<TSource, TCross, TDestination> implementation with the query insert and delete features.

The interface may look like this:

public interface IManyToManySet<TEntity> : IEnumerable<TEntity>
    where TEntity : class
{
    int Count { get; }
    void Add(TEntity entity);
    bool Remove(TEntity entity);
    void AddRange(IEnumerable<TEntity> collection);
}

And the implementation might look like this:

public class ManyToManySet<TSource, TCross, TDestination>
    : IManyToManySet<TDestination>, IEnumerable<TDestination>
    where TDestination : class
    where TSource : class
    where TCross : class
{
    private TSource source;
    private EntitySet<TCross> crossSet;
    private Func<TCross, TDestination> destinationSelector;
    private Func<TSource, TDestination, TCross> crossFactory;

    public ManyToManySet(TSource source,
        EntitySet<TCross> crossSet,
        Func<TCross, TDestination> destinationSelector,
        Func<TSource, TDestination, TCross> crossFactory)
    {
        this.source = source;
        this.crossSet = crossSet;
        this.destinationSelector = destinationSelector;
        this.crossFactory = crossFactory;
    }

    public int Count
    {
        get { return this.crossSet.Count; }
    }

    public void Add(TDestination entity)
    {
        var newEntity = this.crossFactory(this.source, entity);
        this.crossSet.Add(newEntity);
    }

    public bool Remove(TDestination entity)
    {
        var existingEntity = (
            from c in this.crossSet
            where this.destinationSelector(c) == entity
            select c)
            .SingleOrDefault();

        if (existingEntity != null)
        {
            return this.crossSet.Remove(existingEntity);
        }

        return false;
    }

    public void AddRange(IEnumerable<TDestination> collection)
    {
        foreach (var entity in collection)
        {
            this.Add(entity);
        }
    }

    public IEnumerator<TDestination> GetEnumerator()
    {
        return this.crossSet.Select(this.destinationSelector)
            .GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

You need to supply a couple of things in this implementation:

The TSource instance, that points back at the entity that defines the property.

The EntitySet<TCross> that points to the list of entities that define the cross table.

A projection function that allows you to convert a TCross to the TDestination.

A factory function that allows you to create a new TCross based on the TSource and TDestination.

Translating this to a practical example (Using Product and Order), would give you the following property in the Order entity:

private IManyToManySet<Product> products;
public IManyToManySet<Product> Products
{
    get
    {
        if (this.products != null)
        {
            this.products = new ManyToManySet<Order, OrderProduct, Product>(
                this, this.OrderProducts, op => op.Product,
                (o, p) => new OrderProduct { Order = o, Product = p });
        }

        return this.products;
    }
}

And the following property in the Product entity:

private IManyToManySet<Order> orders;
public IManyToManySet<Order> Orders
{
    get
    {
        if (this.orders == null)
        {
            this.orders = new ManyToManySet<Product, OrderProduct, Order>(
                this, this.OrderProducts, op => op.Order,
                (p, o) => new OrderProduct { Order = o, Product = p });
        }

        return this.orders;
    }
}

The IManyToManySet<T> interface is in fact redundant, because you can return a ManyToMany<TSource, TCross, TDestination> directly. The interface however hides the TSource and TCross type arguments, which makes it a bit more readable to the user of this property.

Note that this implementation has the same loading behavior as LINQ to SQL's EntitySet<T>; When it is used, it loads the complete set of objects in memory. Just as with an EntitySet<T> using a where or First on the collection, still loads the complete collection from the database. You need to be aware of that.

Important difference is however that LINQ to SQL understands EntitySet<T> properties within LINQ queries. Having a IManyToManySet<T> inside a LINQ query will fail miserably.

I hope this helps.


来源: stackexchange

问:
The accuracy of oracle when compare two date in SQL
It is in two procedures which are running in order. In procedure one, the running timestamp of system time is 2019/5/30 12:02:58.100. The sql is as below

```<code>insert into A(xxx,xxx,cdate) values(xxx,xxx,sysdate)
</code>```

And I find the cdate field of this inserted row is 2019/5/30 12:02:58, without the millisecond.

And then procedure two runs, the running timestamp of system time is 2019/5/30 12:02:58.200. The SQL is as below

```<code>select xxx from A where cdate<sysdate
</code>```

This returns none result. It is weird because I just inserted a row with cdate 2019/5/30 12:02:58. This should be less than sysdate.

When Oracle stores date value like 2019/5/30 12:02:58, does it throw millsecond away or does it just store it in background and not show it?

While comparing cdate<sysdate, which two values does it use? I guess it is using 2019/5/30 12:02:58 < 2019/5/30 12:02:58, so this returns false.

答:
When Oracle stores date value like 2019/5/30 12:02:58, does it throw millsecond away or does it just store it in background and not show it?

A date value does not have any millisecond component to throw away. sysdate returns a DATE data type:

This data type contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND. It does not have fractional seconds or a time zone.

In your procedures you are looking at a TIMESTAMP value:

This data type contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND. It contains fractional seconds but does not have a time zone.

... or a variant that does have a time zone, like TIMESTAMP WITH TIME ZONE, as returned by systimestamp:

This data type contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, TIMEZONE_HOUR, and TIMEZONE_MINUTE. It has fractional seconds and an explicit time zone.

While comparing cdate<sysdate, which two values does it use? I guess it is using 2019/5/30 12:02:58 < 2019/5/30 12:02:58, so this returns false.

As your insert statement is using sysdate, it doesn't really matter at this point whether cdate is defined as DATE or TIMESTAMP, if the latter then the fraction seconds part is just truncated to zero. And sysdate also returns a DATE, so yes, it is either doing:

```<code>2019-05-30 12:02:58 < 2019-05-30 12:02:58
</code>```

or

```<code>2019-05-30 12:02:58.000 < 2019-05-30 12:02:58
</code>```

which may involve an implicit cast. Either way the result is indeed false.

If you want to compare values that might be within the same second then you have to use a TIMESTAMP. Define your column as one of the TIMESTAMP variants as appropriate, and then use systimestamp instead of sysdate both for your insert and for the comparison. It all has to be timestamps - if any part of what you do stays as a date then at some point the fractional seconds will be lost and you'll be in the same position you are now.

ContentLicense: CC BY-SA 4.0

Body:
It is in two procedures which are running in order. In procedure one, the running timestamp of system time is 2019/5/30 12:02:58.100. The sql is as below

insert into A(xxx,xxx,cdate) values(xxx,xxx,sysdate)

And I find the cdate field of this inserted row is 2019/5/30 12:02:58, without the millisecond.

And then procedure two runs, the running timestamp of system time is 2019/5/30 12:02:58.200. The SQL is as below

select xxx from A where cdate<sysdate

This returns none result. It is weird because I just inserted a row with cdate 2019/5/30 12:02:58. This should be less than sysdate.

When Oracle stores date value like 2019/5/30 12:02:58, does it throw millsecond away or does it just store it in background and not show it?

While comparing cdate<sysdate, which two values does it use? I guess it is using 2019/5/30 12:02:58 < 2019/5/30 12:02:58, so this returns false.

Body:
When Oracle stores date value like 2019/5/30 12:02:58, does it throw millsecond away or does it just store it in background and not show it?

A date value does not have any millisecond component to throw away. sysdate returns a DATE data type:

This data type contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND. It does not have fractional seconds or a time zone.

In your procedures you are looking at a TIMESTAMP value:

This data type contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND. It contains fractional seconds but does not have a time zone.

... or a variant that does have a time zone, like TIMESTAMP WITH TIME ZONE, as returned by systimestamp:

This data type contains the datetime fields YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, TIMEZONE_HOUR, and TIMEZONE_MINUTE. It has fractional seconds and an explicit time zone.

While comparing cdate<sysdate, which two values does it use? I guess it is using 2019/5/30 12:02:58 < 2019/5/30 12:02:58, so this returns false.

As your insert statement is using sysdate, it doesn't really matter at this point whether cdate is defined as DATE or TIMESTAMP, if the latter then the fraction seconds part is just truncated to zero. And sysdate also returns a DATE, so yes, it is either doing:

2019-05-30 12:02:58 < 2019-05-30 12:02:58

or

2019-05-30 12:02:58.000 < 2019-05-30 12:02:58

which may involve an implicit cast. Either way the result is indeed false.

If you want to compare values that might be within the same second then you have to use a TIMESTAMP. Define your column as one of the TIMESTAMP variants as appropriate, and then use systimestamp instead of sysdate both for your insert and for the comparison. It all has to be timestamps - if any part of what you do stays as a date then at some point the fractional seconds will be lost and you'll be in the same position you are now.


问:
How to check the login functionality is work or not in ruby on rails?
I'm new in ruby on rails. I create simple login function.

But the login page is didnot go sucess page even the credential is valid.

I didnot know why this is happen. Please any one help what mistake i done.

I enclose my code is below,

Controller userlists_controller.rb

```<code>  def login
  end

  def login_action
      user = Userlist.find_by(email: params[:email])
      if user and user.authenticate(params[:password])
        session[:user_id] = user.id
        session[:user_name] = user.name
        redirect_to user, alert: "User logged in successfully"
      else
        redirect_to login_url, alert: "Invalid user/password combination"
      end
  end
</code>```

View login.html.erb

```<code><h1>Login</h1>
<% if flash[:alert] %>
    <div id="error_explanation">
        <p id="notice"><%= flash[:alert] %></p>
    </div>
<% end %>

<%= form_tag do %>
    <div class="field">
        <%= label_tag :email, 'Email' %>
        <%= email_field_tag :email, params[:email] %>
    </div>
    <div class="field">
        <%= label_tag :password, 'Password' %>
        <%= password_field_tag :password, params[:password] %>
    </div>
    <div class="actions">
        <%=submit_tag "Login" %>
    </div>
<% end %>
</code>```

route routes.rb

```<code>  get 'login' => 'userlists#login'
  post 'login' => 'userlists#login_action'
</code>```

答:
I just want to post the comment here as an answer so people will know it works

Note: redirect_to user does work, because user is an instance of
  User and as such is the equivalent/shortcut of writing
  user_path(user). Instead op puts I would recommend using
  Rails.logger.debug "some message"

Body:
I'm new in ruby on rails. I create simple login function.

But the login page is didnot go sucess page even the credential is valid.

I didnot know why this is happen. Please any one help what mistake i done.

I enclose my code is below,

Controller userlists_controller.rb

  def login
  end

  def login_action
      user = Userlist.find_by(email: params[:email])
      if user and user.authenticate(params[:password])
        session[:user_id] = user.id
        session[:user_name] = user.name
        redirect_to user, alert: "User logged in successfully"
      else
        redirect_to login_url, alert: "Invalid user/password combination"
      end
  end

View login.html.erb

Login

<% if flash[:alert] %>

<%= flash[:alert] %>

<% end %>

<%= form_tag do %>

        <%= label_tag :email, 'Email' %>
        <%= email_field_tag :email, params[:email] %>

        <%= label_tag :password, 'Password' %>
        <%= password_field_tag :password, params[:password] %>

        <%=submit_tag "Login" %>

<% end %>

route routes.rb

  get 'login' => 'userlists#login'
  post 'login' => 'userlists#login_action'


问:
unrecognized selector sent to instance
I am getting the following error message which I cannot understand why its happening because I am not using any UIImageView.  Sometimes I get the same error but its a CALayer?!?

Its worth also mentioning that I have 2 nibs and 2 controllers and a base controller where this code resides.

EDIT:

This is the structure of my project

MainViewController & its nib
- HomeViewController in nib

MainViewController-Landscape & its nib
- HomeViewController-Landscape in nib

HomeViewControllerBase - no nib
- Base class where all outlets and item configuration code exists.
- Outlets are used by both child classes below.
- Outlets are linked to controls in each of the main nibs.

HomeViewController
- Inherits from HomeViewControllerBase

HomeViewController-Landscape
- Inherits from HomeViewControllerBase

So whats happening is that the child class is trying to dealloc its base class (which has all the outlets in it).  I have designed it this way to avoid duplication of code in the different orientation viewcontrollers.

```<code>@implementation MainViewController
- (void)orientationChanged:(NSNotification *)notification
{
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;

    if (UIDeviceOrientationIsLandscape(deviceOrientation) && !isShowingLandscapeView)
    {
        [self presentModalViewController:self.landscapeViewController
                                animated:YES];

        isShowingLandscapeView = YES;
    }
    else if (UIDeviceOrientationIsPortrait(deviceOrientation) && isShowingLandscapeView)
    {
        [self dismissModalViewControllerAnimated:YES];
        isShowingLandscapeView = NO;
    }
}

- (id)init
{
    self = [super initWithNibName:@"MainViewController" bundle:nil];

    if (self)
    {
        isShowingLandscapeView = NO;
        self.landscapeViewController = [[[MainViewController_Landscape alloc]
                                            initWithNibName:@"MainViewController-Landscape" bundle:nil] autorelease];

        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(orientationChanged:)
                                                     name:UIDeviceOrientationDidChangeNotification
                                                   object:nil];
    }

    return self;
}
@end

@implementation HomeViewControllerBase

    - (void)bestSellItemTapped:(id)sender
    {
        NSLog(@"best sell item tapped");
    }

    - (void)configureBestSellItems
    {
        [self startRetrievingRegions];

        // load all the images from our bundle and add them to the scroll view
        //  NSUInteger i;
        for (int i = 0; i <= 150; i++)
        {

            UILabel *itemTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
            itemTitle.text = @"Majorca";

            UILabel *itemPrice = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, 100, 50)];
            itemPrice.text = @"£249";

            NSString *imageName = @"tempImage.jpg";
            UIImage *image = [UIImage imageNamed:imageName];

            UIButton *mainButton = [[[UIButton alloc]init] autorelease];

            [mainButton addTarget:self action:@selector(bestSellItemTapped:) forControlEvents:UIControlEventTouchUpInside];
            [mainButton setBackgroundImage:image forState:UIControlStateNormal];

            // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
            CGRect rect = mainButton.frame;
            rect.size.height = kScrollObjHeight;
            rect.size.width = kScrollObjWidth;

            mainButton.frame = rect;
            mainButton.tag = i;

            [mainButton addSubview:itemTitle]; [itemTitle release];
            [mainButton addSubview:itemPrice]; [itemPrice release];

            [self.bestSellScrollView addSubview:mainButton];

        }

        [self layoutScrollImages];  // now place the photos in serial layout within the scrollview
    }

    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self configureBestSellItems];
    }

    - (void)layoutScrollImages
    {
        UIButton *view = nil;
        NSArray *subviews = [self.bestSellScrollView subviews];

        // reposition all image subviews in a horizontal serial fashion
        CGFloat curXLoc = 0;
        for (view in subviews)
        {
            if ([view isKindOfClass:[UIButton class]] && view.tag > 0)
            {
                CGRect frame = view.frame;
                frame.origin = CGPointMake(curXLoc, 0);
                view.frame = frame;

                curXLoc += (kScrollObjWidth + kScrollObjPadding);
            }
        }

        // set the content size so it can be scrollable
        [self.bestSellScrollView setContentSize:CGSizeMake((150 * kScrollObjWidth),
                                                           [self.bestSellScrollView bounds].size.height)];
    }

@end

@interface HomeViewController : HomeViewControllerBase
@end

@interface HomeViewController_Landscape : HomeViewControllerBase
@end

@implementation HomeViewController

- (void)dealloc
{
    [super dealloc]; //When I remove this it works
}

@end

@implementation HomeViewController_Landscape

- (void)dealloc
{
   [super dealloc]; //When I remove this it works
}

@end
</code>```

```<code>-[UIImageView bestSellItemTapped:]: unrecognized selector sent to instance 0x681c2b0 2011-04-12 15:45:26.665 [21532:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView bestSellItemTapped:]: unrecognized selector sent to instance 0x681c2b0'
*** Call stack at first throw: (    0   CoreFoundation                      0x00dc85a9 __exceptionPreprocess + 185  1   libobjc.A.dylib                   0x00f1c313 objc_exception_throw + 44  2   CoreFoundation                    0x00dca0bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187  3   CoreFoundation                      0x00d39966 ___forwarding___ + 966   4   CoreFoundation                      0x00d39522 _CF_forwarding_prep_0 + 50   5   UIKit                             0x0001a4fd -[UIApplication sendAction:to:from:forEvent:] + 119    6 UIKit                               0x000aa799 -[UIControl sendAction:to:forEvent:] + 67  7   UIKit                               0x000acc2b -[UIControl(Internal)
_sendActionsForEvents:withEvent:] + 527     8   UIKit                         0x000ab7d8 -[UIControl touchesEnded:withEvent:] + 458     9   UIKit                               0x002ad4de
_UIGestureRecognizerSortAndSendDelayedTouches
+ 3609  10  UIKit                               0x002adc53
_UIGestureRecognizerUpdateObserver + 927    11  CoreFoundation                0x00da989b
__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
+ 27    12  CoreFoundation                      0x00d3e6e7 __CFRunLoopDoObservers + 295     13  CoreFoundation                0x00d071d7 __CFRunLoopRun + 1575  14  CoreFoundation                      0x00d06840 CFRunLoopRunSpecific + 208   15  CoreFoundation                    0x00d06761 CFRunLoopRunInMode + 97    16 GraphicsServices                    0x010001c4 GSEventRunModal + 217     17  GraphicsServices                    0x01000289 GSEventRun + 115     18  UIKit 0x00028c93 UIApplicationMain + 1160   19                      0x000027a9 main + 121   20
                      0x00002725 start + 53 ) terminate called after throwing an instance of 'NSException'
</code>```

答:
When you alloced your UIButton , you flagged that as autorelease , this could be the reason of crash because there are possibilites of claiming  mainButton by the system ,

```<code>UIButton *mainButton = [[[UIButton alloc]init] autorelease];
</code>```

Check with removing autorelease and if it work make your UIButton as class variable or use UIButton's buttonWithtype to get the button from system .

ContentLicense: CC BY-SA 3.0

Title: unrecognized selector sent to instance

Body:
I am getting the following error message which I cannot understand why its happening because I am not using any UIImageView.  Sometimes I get the same error but its a CALayer?!?

Its worth also mentioning that I have 2 nibs and 2 controllers and a base controller where this code resides.

EDIT:

This is the structure of my project

MainViewController & its nib
- HomeViewController in nib

MainViewController-Landscape & its nib
- HomeViewController-Landscape in nib

HomeViewControllerBase - no nib
- Base class where all outlets and item configuration code exists.
- Outlets are used by both child classes below.
- Outlets are linked to controls in each of the main nibs.

HomeViewController
- Inherits from HomeViewControllerBase

HomeViewController-Landscape
- Inherits from HomeViewControllerBase

So whats happening is that the child class is trying to dealloc its base class (which has all the outlets in it).  I have designed it this way to avoid duplication of code in the different orientation viewcontrollers.

@implementation MainViewController
- (void)orientationChanged:(NSNotification *)notification
{
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;

    if (UIDeviceOrientationIsLandscape(deviceOrientation) && !isShowingLandscapeView)
    {
        [self presentModalViewController:self.landscapeViewController
                                animated:YES];

        isShowingLandscapeView = YES;
    }
    else if (UIDeviceOrientationIsPortrait(deviceOrientation) && isShowingLandscapeView)
    {
        [self dismissModalViewControllerAnimated:YES];
        isShowingLandscapeView = NO;
    }
}

- (id)init
{
    self = [super initWithNibName:@"MainViewController" bundle:nil];

    if (self)
    {
        isShowingLandscapeView = NO;
        self.landscapeViewController = [[[MainViewController_Landscape alloc]
                                            initWithNibName:@"MainViewController-Landscape" bundle:nil] autorelease];

        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(orientationChanged:)
                                                     name:UIDeviceOrientationDidChangeNotification
                                                   object:nil];
    }

    return self;
}
@end

@implementation HomeViewControllerBase

    - (void)bestSellItemTapped:(id)sender
    {
        NSLog(@"best sell item tapped");
    }

    - (void)configureBestSellItems
    {
        [self startRetrievingRegions];

        // load all the images from our bundle and add them to the scroll view
        //  NSUInteger i;
        for (int i = 0; i <= 150; i++)
        {

            UILabel *itemTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
            itemTitle.text = @"Majorca";

            UILabel *itemPrice = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, 100, 50)];
            itemPrice.text = @"£249";

            NSString *imageName = @"tempImage.jpg";
            UIImage *image = [UIImage imageNamed:imageName];

            UIButton *mainButton = [[[UIButton alloc]init] autorelease];

            [mainButton addTarget:self action:@selector(bestSellItemTapped:) forControlEvents:UIControlEventTouchUpInside];
            [mainButton setBackgroundImage:image forState:UIControlStateNormal];

            // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
            CGRect rect = mainButton.frame;
            rect.size.height = kScrollObjHeight;
            rect.size.width = kScrollObjWidth;

            mainButton.frame = rect;
            mainButton.tag = i;

            [mainButton addSubview:itemTitle]; [itemTitle release];
            [mainButton addSubview:itemPrice]; [itemPrice release];

            [self.bestSellScrollView addSubview:mainButton];

        }

        [self layoutScrollImages];  // now place the photos in serial layout within the scrollview
    }

    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self configureBestSellItems];
    }

    - (void)layoutScrollImages
    {
        UIButton *view = nil;
        NSArray *subviews = [self.bestSellScrollView subviews];

        // reposition all image subviews in a horizontal serial fashion
        CGFloat curXLoc = 0;
        for (view in subviews)
        {
            if ([view isKindOfClass:[UIButton class]] && view.tag > 0)
            {
                CGRect frame = view.frame;
                frame.origin = CGPointMake(curXLoc, 0);
                view.frame = frame;

                curXLoc += (kScrollObjWidth + kScrollObjPadding);
            }
        }

        // set the content size so it can be scrollable
        [self.bestSellScrollView setContentSize:CGSizeMake((150 * kScrollObjWidth),
                                                           [self.bestSellScrollView bounds].size.height)];
    }

@end

@interface HomeViewController : HomeViewControllerBase
@end

@interface HomeViewController_Landscape : HomeViewControllerBase
@end

@implementation HomeViewController

- (void)dealloc
{
    [super dealloc]; //When I remove this it works
}

@end

@implementation HomeViewController_Landscape

- (void)dealloc
{
   [super dealloc]; //When I remove this it works
}

@end

-[UIImageView bestSellItemTapped:]: unrecognized selector sent to instance 0x681c2b0 2011-04-12 15:45:26.665 [21532:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView bestSellItemTapped:]: unrecognized selector sent to instance 0x681c2b0'
*** Call stack at first throw: (    0   CoreFoundation                      0x00dc85a9 __exceptionPreprocess + 185  1   libobjc.A.dylib                   0x00f1c313 objc_exception_throw + 44  2   CoreFoundation                    0x00dca0bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187  3   CoreFoundation                      0x00d39966 ___forwarding___ + 966   4   CoreFoundation                      0x00d39522 _CF_forwarding_prep_0 + 50   5   UIKit                             0x0001a4fd -[UIApplication sendAction:to:from:forEvent:] + 119    6 UIKit                               0x000aa799 -[UIControl sendAction:to:forEvent:] + 67  7   UIKit                               0x000acc2b -[UIControl(Internal)
_sendActionsForEvents:withEvent:] + 527     8   UIKit                         0x000ab7d8 -[UIControl touchesEnded:withEvent:] + 458     9   UIKit                               0x002ad4de
_UIGestureRecognizerSortAndSendDelayedTouches
+ 3609  10  UIKit                               0x002adc53
_UIGestureRecognizerUpdateObserver + 927    11  CoreFoundation                0x00da989b
__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
+ 27    12  CoreFoundation                      0x00d3e6e7 __CFRunLoopDoObservers + 295     13  CoreFoundation                0x00d071d7 __CFRunLoopRun + 1575  14  CoreFoundation                      0x00d06840 CFRunLoopRunSpecific + 208   15  CoreFoundation                    0x00d06761 CFRunLoopRunInMode + 97    16 GraphicsServices                    0x010001c4 GSEventRunModal + 217     17  GraphicsServices                    0x01000289 GSEventRun + 115     18  UIKit 0x00028c93 UIApplicationMain + 1160   19                      0x000027a9 main + 121   20
                      0x00002725 start + 53 ) terminate called after throwing an instance of 'NSException'

Body:
When you alloced your UIButton , you flagged that as autorelease , this could be the reason of crash because there are possibilites of claiming  mainButton by the system ,

UIButton *mainButton = [[[UIButton alloc]init] autorelease];

Check with removing autorelease and if it work make your UIButton as class variable or use UIButton's buttonWithtype to get the button from system .


问:
How to fix failure to create function when deploying functions.pubsub.schedule
When I attempt to deploy the functions.pubsub.schedule like this on index.js:

```<code>const functions = firebase.functions;
var cronCount = 0;
exports.processPostsCron = functions.pubsub.schedule('* * * *
*').onRun(context => {
  cronCount++;
  console.log(`### this runs every minute. count: ${cronCount}`);
});
</code>```

Error occured:

functions: failed to create function processPostsCron
  HTTP Error: 400, The request has errors

How do I fix this error or am I doing it wrong?
I was referring to this https://github.com/firebase/functions-samples/blob/master/delete-unused-accounts-cron/functions/index.js

I am using firebase-admin@7.0.0 and firebase-functions@2.3.1.

Edit 1:

Debug result:

```<code>i  functions: creating Node.js 8 function processPostsCron(us-central1)...
[2019-05-29T17:19:41.712Z] Trigger is:  {"eventTrigger":{"resource":"projects/ticktock-d34b6/topics","eventType":"google.pubsub.topic.publish","service":"pubsub.googleapis.com"}}
[2019-05-29T17:19:41.714Z] >>> HTTP REQUEST POST https://cloudfunctions.googleapis.com/v1/projects/ticktock-d34b6/locations/us-central1/functions
 sourceUploadUrl=https://storage.googleapis.com/gcf-upload-us-central1-f74bb5e4-12fb-4381-9f5a-ba9e11a921a8/2fac50ef-9d15-4390-8836-21209adfa8b4.zip?GoogleAccessId=service-1096541131355@gcf-admin-robot.iam.gserviceaccount.com&Expires=1559152179&Signature=EzcN7sYYs05vuTyVu7%2BMyJGU8viklA5VWPZRmMeASBCmlK6Xl%2BtMhL1G%2Fv4JHempDcLJ3FmvLDGPbar1iP%2BtNiApL%2B%2Fn6wjQINbF4CmpmqKnjxieBqpzkRYUD40zNMyCGbRDnkhcsps6DBpI9reiHvxdKkqYqadBPCaCn10nZwo96zaHcxZYHWg5PIo4cPLoPyOI7PTl4WYdwwt%2FzOHKlQSdyh1VuRgZqwfgy0vgDQR9HY846k0Tkg6RB6fGex8MzysUxiZ4RfPdt1i0LGd1KpY%2ByhG0OlEsMODQY3bBQ4TMh6LNbVyC2s9%2F0wJPkzAdJpnTjarf3hOgsF9908VkOg%3D%3D, name=projects/ticktock-d34b6/locations/us-central1/functions/processPostsCron, entryPoint=processPostsCron, deployment-tool=cli-firebase, deployment-scheduled=true, runtime=nodejs8, resource=projects/ticktock-d34b6/topics, eventType=google.pubsub.topic.publish, service=pubsub.googleapis.com
[2019-05-29T17:19:42.141Z] <<< HTTP RESPONSE 400 vary=X-Origin, Referer, Origin,Accept-Encoding, content-type=application/json; charset=UTF-8, date=Wed, 29 May 2019 17:19:42 GMT, server=ESF, cache-control=private, x-xss-protection=0, x-frame-options=SAMEORIGIN, x-content-type-options=nosniff, alt-svc=quic=":443"; ma=2592000; v="46,44,43,39", accept-ranges=none, connection=close
[2019-05-29T17:19:42.141Z] <<< HTTP RESPONSE BODY code=400, message=The request has errors, status=INVALID_ARGUMENT, details=[@type=type.googleapis.com/google.rpc.BadRequest, fieldViolations=[field=pubsub_topic, description=Pub/Sub topic name projects/ticktock-d34b6/topics does not match the expected pattern]]
⚠  functions: failed to create function processPostsCron
HTTP Error: 400, The request has errors

Functions deploy had errors with the following functions:
    processPostsCron

To try redeploying those functions, run:
    firebase deploy --only functions:processPostsCron

To continue deploying other features (such as database), run:
    firebase deploy --except functions

Error: Functions did not deploy properly.
</code>```

Seems like the error occurs from:

```<code>fieldViolations=[field=pubsub_topic, description=Pub/Sub topic name projects/ticktock-d34b6/topics does not match the expected pattern]]
</code>```

答:
Firebase Support has given me the instruction to update CLI and it's all good after update. Here's the command:

```<code>npm install -g firebase-tools@latest
</code>```

It didn't worked for me at first, I have added 'unsafe-perm' option to proceed:

```<code>npm install -g firebase-tools@latest --unsafe-perm
</code>```

Body:
When I attempt to deploy the functions.pubsub.schedule like this on index.js:

const functions = firebase.functions;
var cronCount = 0;
exports.processPostsCron = functions.pubsub.schedule('* * * *
*').onRun(context => {
  cronCount++;
  console.log(`### this runs every minute. count: ${cronCount}`);
});

Error occured:

functions: failed to create function processPostsCron
  HTTP Error: 400, The request has errors

How do I fix this error or am I doing it wrong?
I was referring to this https://github.com/firebase/functions-samples/blob/master/delete-unused-accounts-cron/functions/index.js

I am using firebase-admin@7.0.0 and firebase-functions@2.3.1.

Edit 1:

Debug result:

i  functions: creating Node.js 8 function processPostsCron(us-central1)...
[2019-05-29T17:19:41.712Z] Trigger is:  {"eventTrigger":{"resource":"projects/ticktock-d34b6/topics","eventType":"google.pubsub.topic.publish","service":"pubsub.googleapis.com"}}
[2019-05-29T17:19:41.714Z] >>> HTTP REQUEST POST https://cloudfunctions.googleapis.com/v1/projects/ticktock-d34b6/locations/us-central1/functions
 sourceUploadUrl=https://storage.googleapis.com/gcf-upload-us-central1-f74bb5e4-12fb-4381-9f5a-ba9e11a921a8/2fac50ef-9d15-4390-8836-21209adfa8b4.zip?GoogleAccessId=service-1096541131355@gcf-admin-robot.iam.gserviceaccount.com&Expires=1559152179&Signature=EzcN7sYYs05vuTyVu7%2BMyJGU8viklA5VWPZRmMeASBCmlK6Xl%2BtMhL1G%2Fv4JHempDcLJ3FmvLDGPbar1iP%2BtNiApL%2B%2Fn6wjQINbF4CmpmqKnjxieBqpzkRYUD40zNMyCGbRDnkhcsps6DBpI9reiHvxdKkqYqadBPCaCn10nZwo96zaHcxZYHWg5PIo4cPLoPyOI7PTl4WYdwwt%2FzOHKlQSdyh1VuRgZqwfgy0vgDQR9HY846k0Tkg6RB6fGex8MzysUxiZ4RfPdt1i0LGd1KpY%2ByhG0OlEsMODQY3bBQ4TMh6LNbVyC2s9%2F0wJPkzAdJpnTjarf3hOgsF9908VkOg%3D%3D, name=projects/ticktock-d34b6/locations/us-central1/functions/processPostsCron, entryPoint=processPostsCron, deployment-tool=cli-firebase, deployment-scheduled=true, runtime=nodejs8, resource=projects/ticktock-d34b6/topics, eventType=google.pubsub.topic.publish, service=pubsub.googleapis.com
[2019-05-29T17:19:42.141Z] <<< HTTP RESPONSE 400 vary=X-Origin, Referer, Origin,Accept-Encoding, content-type=application/json; charset=UTF-8, date=Wed, 29 May 2019 17:19:42 GMT, server=ESF, cache-control=private, x-xss-protection=0, x-frame-options=SAMEORIGIN, x-content-type-options=nosniff, alt-svc=quic=":443"; ma=2592000; v="46,44,43,39", accept-ranges=none, connection=close
[2019-05-29T17:19:42.141Z] <<< HTTP RESPONSE BODY code=400, message=The request has errors, status=INVALID_ARGUMENT, details=[@type=type.googleapis.com/google.rpc.BadRequest, fieldViolations=[field=pubsub_topic, description=Pub/Sub topic name projects/ticktock-d34b6/topics does not match the expected pattern]]
⚠  functions: failed to create function processPostsCron
HTTP Error: 400, The request has errors

Functions deploy had errors with the following functions:
    processPostsCron

To try redeploying those functions, run:
    firebase deploy --only functions:processPostsCron

To continue deploying other features (such as database), run:
    firebase deploy --except functions

Error: Functions did not deploy properly.

Seems like the error occurs from:

fieldViolations=[field=pubsub_topic, description=Pub/Sub topic name projects/ticktock-d34b6/topics does not match the expected pattern]]

Body:
Firebase Support has given me the instruction to update CLI and it's all good after update. Here's the command:

npm install -g firebase-tools@latest

It didn't worked for me at first, I have added 'unsafe-perm' option to proceed:

npm install -g firebase-tools@latest --unsafe-perm


问:
Laravel Collection Transform/Map Method Inconsistent Behaviour
In my HTML frontend, I have a jQuery DataTable displaying all records fetched via AJAX from the database - a rather pretty straight forward thing. I use the Laravel Collection's ->transform(function($o){ . . . }) to iterate through the collection and return it in an array-esque manner. Just think of the following piece of code in a controller:

```<code>        $cAllRecords = DatabaseRecord::all();
        if(!empty($aData['sFilterIds']))
        {
            $cAllRecords = $cAllRecords->whereIn('creator', explode(',', $aData['sFilterIds']));
        }
        return response()->json(['data' => $cAllRecords->transform(function ($oDatabaseRecord) {
            /** @var $oDatabaseRecord DatabaseRecord */
            $sActionsHtml = '<a href="#">edit</a>';
            $sUrl = route('some.route', ['iDatabaseRecordId' => $oDatabaseRecord->getAttribute('od')]);
            return [
                $oDatabaseRecord->getAttribute('id'),
                $oDatabaseRecord->getAttribute('updated_at')->toDateTimeString(),
                $oDatabaseRecord->getAttribute('created_at')->toDateTimeString(),
                $sActionsHtml
            ];
        })]);
</code>```

I'm actually just filtering for records created by certain user IDs (the whereIn() call in line 4. However, the response sent back to the client looks different for different users filtered leading the jQuery table to show 'no records available', as it had received an malformed answer from the server. For one user, the response looks like this:

```<code>{
   "data":[
      [
         1,
         "2019-05-29 16:44:53",
         "2019-05-29 16:44:53",
         "<a href=\"#\">edit<\/a>"
      ]
   ]
}
</code>```

This is a correctly formed server response and will show up in the table regularly. Great! Now something that drives me insane - the same code for another user (ID 1, while the first request was for user ID 2) returns this:

```<code>{
   "data":{
      "1":[
         3,
         "2019-05-29 17:08:49",
         "2019-05-29 17:08:49",
         "<a href=\"#\">edit<\/a>"
      ]
   }
}
</code>```

which, pretty obviously, is malformed and is not correctly parsed by the datatable. OK, now combing them two filters and filtering for user ID 1 and 2 will, again, return the response correctly formatted:

```<code>{
   "data":[
      [
         1,
         "2019-05-29 16:44:53",
         "2019-05-29 16:44:53",
         "<a href=\"#\">edit<\/a>"
      ],
      [
         3,
         "2019-05-29 17:08:49",
         "2019-05-29 17:08:49",
         "<a href=\"#\">edit<\/a>"
      ]
   ]
}
</code>```

I tried a number of things, none of which had worked since it's merely guessing why it could work with one user and not with another. (Things like reversing the order of IDs to be filtered, etc., but I found out that the filtering is not the problem. It MUST be the transform, which behaves inconsistent.)

Any ideas on why this happens and how to tackle it? I mean, it's not the only way to achieve what I'm after, I was using ->each() and array_push for all the time before but wanted to get rid of it for the sake of making use of Laravel's helpers (or possibilites) - the manual iteration and array pushing process worked out seamlessly before, and even other parts of the app work well with the Collection transform over array iteration and pushing. Why doesn't it here?

Update: The ->map() collection method behaves exactly same. Map, as opposed by transform, does not alter the collection itself. However, this should not be a relevant part within this application any way. I really can't understand what's going wrong. Is this possibly Laravel's fault?

答:
Please note that transform method returns a Illuminate\Support\Collection.

It's better that you call all() after the transform to get an array result.

Like this:

```<code>...
return response()->json(['data' => $cAllRecords->transform(function ($oDatabaseRecord) {
            /** @var $oDatabaseRecord DatabaseRecord */
            $sActionsHtml = '<a href="#">edit</a>';
            $sUrl = route('some.route', ['iDatabaseRecordId' => $oDatabaseRecord->getAttribute('od')]);
            return [
                $oDatabaseRecord->getAttribute('id'),
                $oDatabaseRecord->getAttribute('updated_at')->toDateTimeString(),
                $oDatabaseRecord->getAttribute('created_at')->toDateTimeString(),
                $sActionsHtml
            ];
        })->all()]);

</code>```

Body:
In my HTML frontend, I have a jQuery DataTable displaying all records fetched via AJAX from the database - a rather pretty straight forward thing. I use the Laravel Collection's ->transform(function($o){ . . . }) to iterate through the collection and return it in an array-esque manner. Just think of the following piece of code in a controller:

        $cAllRecords = DatabaseRecord::all();
        if(!empty($aData['sFilterIds']))
        {
            $cAllRecords = $cAllRecords->whereIn('creator', explode(',', $aData['sFilterIds']));
        }
        return response()->json(['data' => $cAllRecords->transform(function ($oDatabaseRecord) {
            /** @var $oDatabaseRecord DatabaseRecord */
            $sActionsHtml = 'edit';
            $sUrl = route('some.route', ['iDatabaseRecordId' => $oDatabaseRecord->getAttribute('od')]);
            return [
                $oDatabaseRecord->getAttribute('id'),
                $oDatabaseRecord->getAttribute('updated_at')->toDateTimeString(),
                $oDatabaseRecord->getAttribute('created_at')->toDateTimeString(),
                $sActionsHtml
            ];
        })]);

I'm actually just filtering for records created by certain user IDs (the whereIn() call in line 4. However, the response sent back to the client looks different for different users filtered leading the jQuery table to show 'no records available', as it had received an malformed answer from the server. For one user, the response looks like this:

{
   "data":[
      [
         1,
         "2019-05-29 16:44:53",
         "2019-05-29 16:44:53",
         "edit<\/a>"
      ]
   ]
}

This is a correctly formed server response and will show up in the table regularly. Great! Now something that drives me insane - the same code for another user (ID 1, while the first request was for user ID 2) returns this:

{
   "data":{
      "1":[
         3,
         "2019-05-29 17:08:49",
         "2019-05-29 17:08:49",
         "edit<\/a>"
      ]
   }
}

which, pretty obviously, is malformed and is not correctly parsed by the datatable. OK, now combing them two filters and filtering for user ID 1 and 2 will, again, return the response correctly formatted:

{
   "data":[
      [
         1,
         "2019-05-29 16:44:53",
         "2019-05-29 16:44:53",
         "edit<\/a>"
      ],
      [
         3,
         "2019-05-29 17:08:49",
         "2019-05-29 17:08:49",
         "edit<\/a>"
      ]
   ]
}

I tried a number of things, none of which had worked since it's merely guessing why it could work with one user and not with another. (Things like reversing the order of IDs to be filtered, etc., but I found out that the filtering is not the problem. It MUST be the transform, which behaves inconsistent.)

Any ideas on why this happens and how to tackle it? I mean, it's not the only way to achieve what I'm after, I was using ->each() and array_push for all the time before but wanted to get rid of it for the sake of making use of Laravel's helpers (or possibilites) - the manual iteration and array pushing process worked out seamlessly before, and even other parts of the app work well with the Collection transform over array iteration and pushing. Why doesn't it here?

Update: The ->map() collection method behaves exactly same. Map, as opposed by transform, does not alter the collection itself. However, this should not be a relevant part within this application any way. I really can't understand what's going wrong. Is this possibly Laravel's fault?

Body:
Please note that transform method returns a Illuminate\Support\Collection.

It's better that you call all() after the transform to get an array result.

Like this:

...
return response()->json(['data' => $cAllRecords->transform(function ($oDatabaseRecord) {
            /** @var $oDatabaseRecord DatabaseRecord */
            $sActionsHtml = '<a href="#">edit</a>';
            $sUrl = route('some.route', ['iDatabaseRecordId' => $oDatabaseRecord->getAttribute('od')]);
            return [
                $oDatabaseRecord->getAttribute('id'),
                $oDatabaseRecord->getAttribute('updated_at')->toDateTimeString(),
                $oDatabaseRecord->getAttribute('created_at')->toDateTimeString(),
                $sActionsHtml
            ];
        })->all()]);


问:
Changing diameter of Angular material spinner breaks it
This is my code

```<code><mat-progress-spinner  [diameter]="50" mode="indeterminate" ></mat-progress-spinner>
</code>```

If i remove the diameter it will work properly but if i add diameter it will just show up as a circle and not spin.

Is there a way to resize it to make it smaller?

答:
You can change value diameter like this:

```<code><mat-progress-spinner  [diameter]="50" mode="indeterminate" ></mat-progress-spinner>
<mat-progress-spinner  [diameter]="30" mode="indeterminate" ></mat-progress-spinner>
<mat-progress-spinner  [diameter]="10" mode="indeterminate" ></mat-progress-spinner>
</code>```

Working Demo

Body:
This is my code

<mat-progress-spinner  [diameter]="50" mode="indeterminate" ></mat-progress-spinner>

If i remove the diameter it will work properly but if i add diameter it will just show up as a circle and not spin.

Is there a way to resize it to make it smaller?

Body:
You can change value diameter like this:

<mat-progress-spinner  [diameter]="50" mode="indeterminate" ></mat-progress-spinner>
<mat-progress-spinner  [diameter]="30" mode="indeterminate" ></mat-progress-spinner>
<mat-progress-spinner  [diameter]="10" mode="indeterminate" ></mat-progress-spinner>

Working Demo


问:
JSON Object to POJO dynamically
I want to store an array of JSON Object into POJO class dynamically how can I do this particular thing in java.</p>

```<code>[
{
"history":"L",
"loan":"12345"
"status":1
.
.
},
{
"History":"L",
"loan":"67890"
"status":1
.
.
},
....
]
</code>```

答:
First Create a POJO Class something like this:

public class Loan {
    private String history;
    private String loan;
    private int status;

    \\ generate getters,setters and toString method
}
```

<p>Now parse your json and convert into jSONArray (import json-simple library), </p>

<pre class="lang-java prettyprint-override"><code>        String path = "path to your json file";
        File f = new File(path);
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader(f));
        JSONArray jsonArray = (JSONArray) obj;

</code>```

Now

Create a new ObjectMapper's object (import jackson-databind library),

convert parsed JSONArray to json string using writeValueAsString method,

and again convert it into list of "Loan" Class.

        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(jsonArray);
        List<Loan> loanList = Arrays.asList(mapper.readValue(jsonStr, Loan[].class));
        for (Loan l : loanList)
            System.out.println(l);
```

Note : your json array contains different keys as history(first
  object) and History(second object). change it to history as in Loan
  class, data member is history.

Title: JSON Object to POJO dynamically

Body:
I want to store an array of JSON Object into POJO class dynamically how can I do this particular thing in java.

[
{
"history":"L",
"loan":"12345"
"status":1
.
.
},
{
"History":"L",
"loan":"67890"
"status":1
.
.
},
....
]

Body:
First Create a POJO Class something like this:

public class Loan {
    private String history;
    private String loan;
    private int status;

    \\ generate getters,setters and toString method
}

Now parse your json and convert into jSONArray (import json-simple library),

        String path = "path to your json file";
        File f = new File(path);
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader(f));
        JSONArray jsonArray = (JSONArray) obj;

Now

Create a new ObjectMapper's object (import jackson-databind library),

convert parsed JSONArray to json string using writeValueAsString method,

and again convert it into list of "Loan" Class.

        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(jsonArray);
        List<Loan> loanList = Arrays.asList(mapper.readValue(jsonStr, Loan[].class));
        for (Loan l : loanList)
            System.out.println(l);

Note : your json array contains different keys as history(first
  object) and History(second object). change it to history as in Loan
  class, data member is history.


问:
python: index out of range in txt file
I'm writing a script to automatically annotate a txt file.

I open the txt file and segment it into a list of lines. Then I iterate over every line. I want the PC to check if the previous element in the list (the line before in the text) is an empty element (the paragraph division in the text) and if it so to put an annotation.

```<code>final_list = []
something = open(x, 'r', encoding='utf8', errors='ignore')
file = something.read()
y = file.split("\n")
for position, i in enumerate(y):
    if position == 0:
        final_list.append(i)
    elif position > 0:
        z = i[position-1]
        if z == '':
            final_list.append("<p>"+i)
return final_list
</code>```

I expect to a have a final list with all the element of the previous line with some of them marked with the
 element, but when I iterate over the list Python gives me a

IndexError: string index out of range

I cannot understand where is the problem.

答:
As you are not using values of list, instead of enumerate take length of list and iterate.

You can try this,

```<code>for position in range(len(y)):
        if position == 0:
            final_list.append(i)
        elif position > 0:
            z = y[position-1]
            if z == '':
                final_list.append("<p>"+i)
</code>```

Title: python: index out of range in txt file

Body:
I'm writing a script to automatically annotate a txt file.

I open the txt file and segment it into a list of lines. Then I iterate over every line. I want the PC to check if the previous element in the list (the line before in the text) is an empty element (the paragraph division in the text) and if it so to put an annotation.

final_list = []
something = open(x, 'r', encoding='utf8', errors='ignore')
file = something.read()
y = file.split("\n")
for position, i in enumerate(y):
    if position == 0:
        final_list.append(i)
    elif position > 0:
        z = i[position-1]
        if z == '':
            final_list.append("
"+i)
return final_list

I expect to a have a final list with all the element of the previous line with some of them marked with the
 element, but when I iterate over the list Python gives me a

IndexError: string index out of range

I cannot understand where is the problem.

Body:
As you are not using values of list, instead of enumerate take length of list and iterate.

You can try this,

for position in range(len(y)):
        if position == 0:
            final_list.append(i)
        elif position > 0:
            z = y[position-1]
            if z == '':
                final_list.append("<p>"+i)


问:
js doesn't execute 'else' statement
I have an if-else statement in JavaScript which returns false, but doesn't execute the code inside 'else'.

part of the script inside the cshtml file:

```<code>if (@Session["mission"].ToString() != "1") {
    setInterval(function () { myTimer(ctxPoints, ctxLines); }, 1000 / @ViewBag.rate);
} else {
    alert("hi");
}
</code>```

In the debug the '@Session["mission"].ToString() != "1"' statement returns false, but nothing jumps to the screen.

答:
You should open your web browser Developer console and see the real script which reaches the browser.

The Razor parts, @Session["mission"].ToString() doesn't exists in the browser script, because they are evaluated in the server, before sending them to the browser. So it makes no sense to try @Session["mission"].ToString() != "1" this in the console. In the browser you will get something like:
if (1 != "1")
or even like
if ( != "1")
which would provoke an error.

JavaScript does coalescing, so 1 is equal to "1" when you use the comparers == or !=, so you don't need to include the qoutes around the value (unless you get the error mentioned above: in this case, if you included the quotes, you'd get if ("" != "1")).

Coalescing is avoided by using the !== or === which would consider 1 not equal to "1", so, including the quotes doesn't make any difference in this case.

Title: js doesn't execute 'else' statement

Body:
I have an if-else statement in JavaScript which returns false, but doesn't execute the code inside 'else'.

part of the script inside the cshtml file:

if (@Session["mission"].ToString() != "1") {
    setInterval(function () { myTimer(ctxPoints, ctxLines); }, 1000 / @ViewBag.rate);
} else {
    alert("hi");
}

In the debug the '@Session["mission"].ToString() != "1"' statement returns false, but nothing jumps to the screen.


问:
JQuery - How to add a class to every last list item?
Got some code here that isn't working:

```<code>$("#sidebar ul li:last").each(function(){
      $(this).addClass("last");
});
</code>```

Basically I have 3 lists and want to add a class (last) to each item appearing last in each unordered list.

```<code><ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li class="last">Item 3</li>
</ul>
</code>```

Hope that makes sense,
Cheers!

答:
you can try</p>

```<code>$('#sidebar ul li:last').addClass('last');
</code>```

OwnerDisplayName: Keith Donegan

ContentLicense: CC BY-SA 2.5

Body:
Got some code here that isn't working:

$("#sidebar ul li:last").each(function(){
      $(this).addClass("last");
});

Basically I have 3 lists and want to add a class (last) to each item appearing last in each unordered list.

Item 1

Item 2

Item 3

Hope that makes sense,
Cheers!

Body:
you can try

$('#sidebar ul li:last').addClass('last');

OwnerDisplayName: smoothdeveloper


问:
Reducing Gaps in dynamically generated TreeView
I'm working on a ASP.NET application that uses the in-built Treeview. For some reason, the vertical space between the nodes will not reduce no matter what I try in the CSS.

The nodes are dynamically generated, see the example bellow:

The tree is generated using:

```<code><asp:TreeView ID="rcmTree" runat="server" CssClass="treeView" ShowLines="true"></asp:TreeView>
</code>```

And then the CSS Code I have is:

```<code>.treeNode {
  text-indent: 2px;
  font-size: 13px;
}

.treeNode a {
  text-decoration: none;
  color: #000;
  vertical-align: middle;
}

.treeView tr {
  margin-top: -25px;
}

.treeView {
  margin-top: 6px;
}

#rcmTree td div {
  height: 20px !important;
}
</code>```

答:
Found the answer - I had to change the Doctype to:</p>

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code>```

Body:
I'm working on a ASP.NET application that uses the in-built Treeview. For some reason, the vertical space between the nodes will not reduce no matter what I try in the CSS.

The nodes are dynamically generated, see the example bellow:

The tree is generated using:

<asp:TreeView ID="rcmTree" runat="server" CssClass="treeView" ShowLines="true"></asp:TreeView>

And then the CSS Code I have is:

.treeNode {
  text-indent: 2px;
  font-size: 13px;
}

.treeNode a {
  text-decoration: none;
  color: #000;
  vertical-align: middle;
}

.treeView tr {
  margin-top: -25px;
}

.treeView {
  margin-top: 6px;
}

#rcmTree td div {
  height: 20px !important;
}

Body:
Found the answer - I had to change the Doctype to:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


问:
Google Sign-In with Backend Verification Flow Clarification
I've spent hours trawling through various tutorials and articles and am finally giving in to asking.

I want to enforce the use of Google Sign-In authentication for all users of my Angular 7 application. However, once Google authentication is complete, I want to first check that the user exists in my back-end DB (PostgreSQL). If they do, then I want to issue a JWT for two purposes:

Ensure that future calls to my Spring Boot REST services are only fulfilled for authorized users.

Protect my Angular routes using an AuthGuard that is aware of the token.

So far, I have been able to retrieve the id_token from the gapi auth2 auth response and forward it to my Spring Boot POST mapping, but I'm struggling to pin down exactly which OAuth 2.0/OpenId flows/grants I'm aiming for which is making life difficult when sourcing appropriate Spring Boot documentation/tutorials.

Is anyone able to clarify which flow/grant I should be aiming for and whether or not my current direction is valid?

答:
I am also working on Google Auth/OAuth 2.0/Credential Management API and can empathise with the disappointment from examples and rabbit holes on the web.

Not sure your question is answered by the following but it is what I am doing after completing the Credential Management API and Google front-end vetting: -

```<code>public String ValidateToken(string idToken, string accessToken)
{
    bool isValid = false;
    string errorMessage = "Illegal Access Token: ";

    if (accessToken != null)
    {
        var tokeninfoRequest = new Oauth2Service().Tokeninfo();
        tokeninfoRequest.AccessToken = accessToken;
        Tokeninfo tokeninfo = null;
        try
        {
            tokeninfo = tokeninfoRequest.Execute();
            if (tokeninfo.IssuedTo != CLIENT_ID)
            {
                errorMessage += "Imposter";
            }
        }
        catch (Exception e)
        {
            errorMessage += e.Message;
        }
        isValid = true;
    }

    if (!isValid) abortRequest(401, errorMessage);

    errorMessage = "Invalid ID Token";
    string gplus_id = "";
    JwtSecurityToken JWToken = new JwtSecurityToken(idToken);

    Byte[][] certBytes = getCertBytes(GOOGLE_CERTS);
    Dictionary<String, X509Certificate2> certificates = new Dictionary<String, X509Certificate2>();
    for (int i = 0; i < certBytes.Length; i++)
    {
        X509Certificate2 certificate = new X509Certificate2(certBytes[i]);
        certificates.Add(certificate.Thumbprint, certificate);
    }

    TokenValidationParameters JWTparams = new TokenValidationParameters()
    {
        ValidateActor = false,
        ValidateAudience = true,
        ValidAudience = CLIENT_ID,
        ValidateIssuer = true,
        ValidIssuers = VALID_ISSUERS,
        ValidateIssuerSigningKey = true,
        RequireSignedTokens = true,
        IssuerSigningKeys = certificates.Values.Select(x => new X509SecurityKey(x)),
        IssuerSigningKeyResolver = (tokenString, securityToken, kid, parameters) =>
        {
            return certificates
           .Where(x => x.Key.ToUpper() == kid.ToUpper())
           .Select(x => new X509SecurityKey(x.Value));
        },
        ValidateLifetime = true,
        RequireExpirationTime = true,
        ClockSkew = TimeSpan.FromHours(13)
    };

    Claim[] claims = JWToken.Claims.ToArray<Claim>();
    for (int i = 0; i < claims.Length; i++)
    {
        if (claims[i].Type.Equals("sub"))
        {
            gplus_id = claims[i].Value;
            break;
        }
    }

    if (gplus_id == null) abortRequest(401, "Invalid Google id");

    SecurityToken validatedToken;
    ClaimsPrincipal cp;
    JwtSecurityTokenHandler JWThndlr = new JwtSecurityTokenHandler();
    try
    {
        cp = JWThndlr.ValidateToken(idToken, JWTparams, out validatedToken);
    }
    catch
    {
        cp = null;
    }

    if (cp == null) abortRequest(401, "Invalid ID Token");

    return "{\"success\": true}";
}
</code>```

Body:
I am also working on Google Auth/OAuth 2.0/Credential Management API and can empathise with the disappointment from examples and rabbit holes on the web.

Not sure your question is answered by the following but it is what I am doing after completing the Credential Management API and Google front-end vetting: -

public String ValidateToken(string idToken, string accessToken)
{
    bool isValid = false;
    string errorMessage = "Illegal Access Token: ";

    if (accessToken != null)
    {
        var tokeninfoRequest = new Oauth2Service().Tokeninfo();
        tokeninfoRequest.AccessToken = accessToken;
        Tokeninfo tokeninfo = null;
        try
        {
            tokeninfo = tokeninfoRequest.Execute();
            if (tokeninfo.IssuedTo != CLIENT_ID)
            {
                errorMessage += "Imposter";
            }
        }
        catch (Exception e)
        {
            errorMessage += e.Message;
        }
        isValid = true;
    }

    if (!isValid) abortRequest(401, errorMessage);

    errorMessage = "Invalid ID Token";
    string gplus_id = "";
    JwtSecurityToken JWToken = new JwtSecurityToken(idToken);

    Byte[][] certBytes = getCertBytes(GOOGLE_CERTS);
    Dictionary<String, X509Certificate2> certificates = new Dictionary<String, X509Certificate2>();
    for (int i = 0; i < certBytes.Length; i++)
    {
        X509Certificate2 certificate = new X509Certificate2(certBytes[i]);
        certificates.Add(certificate.Thumbprint, certificate);
    }

    TokenValidationParameters JWTparams = new TokenValidationParameters()
    {
        ValidateActor = false,
        ValidateAudience = true,
        ValidAudience = CLIENT_ID,
        ValidateIssuer = true,
        ValidIssuers = VALID_ISSUERS,
        ValidateIssuerSigningKey = true,
        RequireSignedTokens = true,
        IssuerSigningKeys = certificates.Values.Select(x => new X509SecurityKey(x)),
        IssuerSigningKeyResolver = (tokenString, securityToken, kid, parameters) =>
        {
            return certificates
           .Where(x => x.Key.ToUpper() == kid.ToUpper())
           .Select(x => new X509SecurityKey(x.Value));
        },
        ValidateLifetime = true,
        RequireExpirationTime = true,
        ClockSkew = TimeSpan.FromHours(13)
    };

    Claim[] claims = JWToken.Claims.ToArray<Claim>();
    for (int i = 0; i < claims.Length; i++)
    {
        if (claims[i].Type.Equals("sub"))
        {
            gplus_id = claims[i].Value;
            break;
        }
    }

    if (gplus_id == null) abortRequest(401, "Invalid Google id");

    SecurityToken validatedToken;
    ClaimsPrincipal cp;
    JwtSecurityTokenHandler JWThndlr = new JwtSecurityTokenHandler();
    try
    {
        cp = JWThndlr.ValidateToken(idToken, JWTparams, out validatedToken);
    }
    catch
    {
        cp = null;
    }

    if (cp == null) abortRequest(401, "Invalid ID Token");

    return "{\"success\": true}";
}


答:
How about something like this :</p>

```<code>last_line = ''
output_lines = []
with open('file.txt', 'r') as f:
    for line in f:
        line = line.strip()
        if last_line == '':  # if last line was empty, start a new paragraph
            output_lines.append('<p>')
            output_lines.append(line)
        elif line == '':  # if current line is empty close the paragraph
            output_lines.append('</p>')
        else:
            output_lines.append(line)
        last_line = line
</code>```

Title: python: index out of range in txt file

Body:
How about something like this :

last_line = ''
output_lines = []
with open('file.txt', 'r') as f:
    for line in f:
        line = line.strip()
        if last_line == '':  # if last line was empty, start a new paragraph
            output_lines.append('<p>')
            output_lines.append(line)
        elif line == '':  # if current line is empty close the paragraph
            output_lines.append('</p>')
        else:
            output_lines.append(line)
        last_line = line


问:
If RDSADMIN is created by AWS, can Amazon actually access our database and data?
I created a new DB instance on AWS RDS. It created a default database as RDSADMIN. I created another DB for my project.

But my question is: can Amazon directly access my new DB data technically?

答:
Since Amazon can (and does) run modified versions of database server software, nothing technically prevents them from accessing all of you data. In-place and in-transit encryption does not matter as the data has to be decrypted on the server for SQL processing. The only technical way to guarantee that you data cannot be accessed by Amazon is to use client-side encryption on individual fields (which, of course, cannot be easily used for SQL query conditions afterwards).

That being said, there are legal and reputational restraints that prevent Amazon from doing that. However, those restraints do not cover cases where Amazon is required by law to provide access to you data to government agencies.


问:
How to populate dynamically added input fields with Json object
I have a this table of input fields which I can add rows dynamically with help of KnockoutJS

```<code>     <table id="sTypeTable" class="table table-bordered" hidden="hidden">
         <tr>
             <th> Name </th>
             <th> Value </th>
             <th> <a class="btn btn-primary btn-sm"  onclick="addReqField(0);"><i class="fa fa-plus"></i></a></th>
         </tr>
<!-- ko foreach: {data: requestFields, as: 'reqField'} -->
        <tr id="sRow">
           <td>
              <input id="sName" data-bind="value: reqField[0]" onblur="createJSON()"/>
           </td>
           <td>
              <input id="sValue" data-bind="value: reqField[0]" onblur="createJSON()"/>
           </td>
           <td>
              <a class="btn btn-warning  btn-sm" data-bind="click: removeResField2" ><i class="glyphicon glyphicon-remove"></i></a>
          </td>
       </tr>
<!-- /ko -->
 </table>
  <div class="col-md-11 ">
    <textarea style="font-size: larger; min-height: 200px" class="form-control" id="requestData" oninput="storeValueOfTextArea()"></textarea>
  </div>
</code>```

From this inputs I'm generating
following Json object on textarea (id="requestData")

```<code>[
  {
    "users": [
      {
        "name": "John",
        "value": "12"
      },
      {
        "name": "Sarah",
        "value": "13"
      },
      {
        "name": "Tom",
        "value": "14"
      }
    ]
  }
]
</code>```

It works well, but now I need populate these input fields from Json object,
When object entered to textarea.
I have tried following way

```<code><script th:inline="javascript">

 function storeValueOfTextArea() {
      var lines = $('#requestData').val();
      var texts = JSON.parse(lines);

  for (var i=0; i!== texts[0].users.length;i++){
      addReqField();  // method for adding new row of input fields

      let  v = texts[0].users[i];
      $("tr[id=sRow]").each(function() {
          $("#sName").val(v.name);
          $("#sValue").val(v.value);
      });
  }
 </script>
</code>```

but in result  only first input field gets the last object

```<code>{
   "name": "Tom",
   "value": "14"
 }
</code>```

others stays empty

答:
Thank you all who have answered to this question.
I have solved this problem by this way</p>

```<code> for (let i=0; i!== texts[0].values.length;i++){
      addReqField();
      let  v = texts[0].values[i];
          $("tr[id=sRow]").each(function(index) {
              if (index === i){
                 $(this).find("#sName").val(v.name);
                 $(this).find("#sValue").val(v.value);
               }

           });
 }
</code>```

Body:
I have a this table of input fields which I can add rows dynamically with help of KnockoutJS

              Name
              Value

              <input id="sName" data-bind="value: reqField[0]" onblur="createJSON()"/>

              <input id="sValue" data-bind="value: reqField[0]" onblur="createJSON()"/>

    <textarea style="font-size: larger; min-height: 200px" class="form-control" id="requestData" oninput="storeValueOfTextArea()"></textarea>

From this inputs I'm generating
following Json object on textarea (id="requestData")

[
  {
    "users": [
      {
        "name": "John",
        "value": "12"
      },
      {
        "name": "Sarah",
        "value": "13"
      },
      {
        "name": "Tom",
        "value": "14"
      }
    ]
  }
]

It works well, but now I need populate these input fields from Json object,
When object entered to textarea.
I have tried following way

but in result  only first input field gets the last object

{
   "name": "Tom",
   "value": "14"
 }

others stays empty

Body:
Thank you all who have answered to this question.
I have solved this problem by this way

 for (let i=0; i!== texts[0].values.length;i++){
      addReqField();
      let  v = texts[0].values[i];
          $("tr[id=sRow]").each(function(index) {
              if (index === i){
                 $(this).find("#sName").val(v.name);
                 $(this).find("#sValue").val(v.value);
               }

           });
 }


Title: Distance matrix to reshaped vector of distances sorted by positions

Body:
I have a data frame of 5 items, as follows:

df = structure(list(item1 = c(1, 1, 1, 1, 2, 2, 2, 3, 3, 4), item2 = c(0,
2, 3, 4, 0, 3, 4, 0, 4, 0)), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))

In addition, I have the distance matrix between the items:

Dist1 = structure(c(0, 1.0919530596119, 1.09195161858136, 1.0919463791331,
1.09194754111203, 1.0919530596119, 0, 1.7831197560388, 1.78314749640301,
1.78315668532962, 1.09195161858136, 1.7831197560388, 0, 1.78315765983813,
1.78314839437957, 1.0919463791331, 1.78314749640301, 1.78315765983813,
0, 1.78314787222978, 1.09194754111203, 1.78315668532962, 1.78314839437957,
1.78314787222978, 0), .Dim = c(5L, 5L), .Dimnames = list(c("1",
"2", "3", "4", "5"), c("1", "2", "3", "4", "5")))

I would like to add a third coulmn to df, that will contain the distances which will somehow be extracted from Dist1. They have to be in the same order specified by the indices in df, not contain the self dist, etc.

Now, this is almost the lower triangle of Dist1, but not quite. (Note also that the items in Dist1 are 1+ the item identities of df).

So, the expected output is:

df$Distances = c(1.091953, 1.783120, 1.783147, 1.783157, 1.091952, 1.783158,
1.783148, 1.091946, 1.783148, 1.091948)

How can I efficiently extract this (the actual data structures are much bigger)?

Body:
I think this is what you are trying to do

# Logic
df <- df %>%
  group_by(item1, item2) %>%
  mutate(Distance = Dist1[(item1)*5 + (item2 + 1)])

# Result
df
# A tibble: 10 x 3
# Groups:   item1, item2 [10]
   item1 item2 Distance
   <dbl> <dbl>    <dbl>
 1     1     0     1.09
 2     1     2     1.78
 3     1     3     1.78
 4     1     4     1.78
 5     2     0     1.09
 6     2     3     1.78
 7     2     4     1.78
 8     3     0     1.09
 9     3     4     1.78
10     4     0     1.09

df$Distance
 [1] 1.091953 1.783120 1.783147 1.783157 1.091952 1.783158 1.783148 1.091946
 [9] 1.783148 1.091948


问:
Comparing value of an object with null
The null literal can only be assigned to reference variables, and usually, we use the .equals() method in comparing with them

Why do we use the operators "equal to" and "not equal to" instead of the .equals() method if dealing with null?

答:
There are three reasons in the following order of importance:

Stability - The fear of NullPointerException which would most certainly happen if you tried to access equals() method from a object that holds a null value. This is pretty obvious but still had to be mentioned as the primary reason.

Visibility - However even if we could do that and it wouldn't throw an exception it would still not be more preferable to using the == operator. Why? Because the operator visually separates the elements making it more clear what is actually being compared. When we are comparing to a null we want it to be clear and visible within the code.

Consistency - Equals method is used for content comparison while the == operator is used for address comparison. Since null has no address because it doesn't exist the most logically consistent thing would be to first compare the lack of address before moving on to compare the actual content of two objects (which is what equals() does).

Title: Comparing value of an object with null


问:
How to escape '$' and '#' in Facelets/EL?
I'm using Java Facelets and jQuery, however the expression

```<code>$('...')
</code>```

in jQuery conflicts with EL expression, how do I escape the jQuery's one?

I'd like to escape a large chunk of Javascript, too.

ANSWERED

To convert the existing JSP to Facelets xhtml, it's convenient to just wrap the existing javascript by <![CDATA[ ... ]]>.  However, the output scripts for

=> <script></script>
```

<p>To resolve this problem, you should also comment out the CDATA:</p>

```<script>/* <![CDATA[ */ scripts... /* ]]> */</script>

=> <script></script>
```

See also When is a CDATA section necessary within a script tag?.

答:
Should anyone need to, the Expression Language Specification Version 2.2 Maintenance Release describes how to escape EL expressions:

To generate literal values that
  include the character sequence "${"
  or "#{", the developer can choose to
  use a composite expression as shown
  here:

```<code>${'${'}exprA}
#{'#{'}exprB}
</code>```

The resulting values would then be the
  strings ${exprA} and #{exprB}.

Alternatively, the escape characters
  \$ and \# can be used to escape
  what would otherwise be treated as an
  eval-expression. Given the
  literal-expressions:

```<code>\${exprA}
\#{exprB}
</code>```

Body:
I'm using Java Facelets and jQuery, however the expression

$('...')

in jQuery conflicts with EL expression, how do I escape the jQuery's one?

I'd like to escape a large chunk of Javascript, too.

ANSWERED

To convert the existing JSP to Facelets xhtml, it's convenient to just wrap the existing javascript by <![CDATA[ ... ]]>.  However, the output scripts for

=>

To resolve this problem, you should also comment out the CDATA:

=>

See also When is a CDATA section necessary within a script tag?.

Body:
Should anyone need to, the Expression Language Specification Version 2.2 Maintenance Release describes how to escape EL expressions:

To generate literal values that
  include the character sequence "${"
  or "#{", the developer can choose to
  use a composite expression as shown
  here:

${'${'}exprA}
#{'#{'}exprB}

The resulting values would then be the
  strings ${exprA} and #{exprB}.

Alternatively, the escape characters
  \$ and \# can be used to escape
  what would otherwise be treated as an
  eval-expression. Given the
  literal-expressions:

\${exprA}
\#{exprB}


问:
Places for Android API deprecated alternative
I was trying to implement the Places API. My code looked like this:

```<code>val builder = PlacePicker.IntentBuilder()
startActivityForResult(builder.build(mActivity), PLACE_PICKER_REQUEST)
</code>```

My maps credentials were correct, but for this call I got

Places API for Android does not seem to be enabled for your app. See https://developers.google.com/places/android/signup for more details.

However, when I tried to enable the "Places API for Android", I got this error.

You do not have sufficient permissions to view this page.

I tried logging out of my accounts, logging in again, incognito mode, Safari & Chrome. Nothing worked so I contacted support, which were extremely fast (thanks guys!)

The reason you are receiving an error when trying to enable the Places
  for Android API is that it has been deprecated. Places functionality
  for android will now be covered by having the Places API enabled.

I asked about my implementation and got this reply.

The place picker has also been deprecated. You can install the
  compatibility library to continue using the Place Picker until the
  deprecation period ends on July 29th. More about this can be red here:
  https://developers.google.com/places/android-sdk/client-migration#place_picker

The docs I find online now are a bit confusing, what is deprecated and what isn't? Can anyone point me in the right direction for this kind of functionality?

答:
The Google Play Services version of the Places SDK for Android (in Google Play Services 16.0.0) is deprecated as of January 29, 2019, and will be turned off on July 29, 2019. And if you check under the google API console, it only have the PLACES API and there is nothing like PLACES SDK FOR ANDROID anymore.

Migration guide to new places SDK client library can be found here

Or find custom implementation in my repo => NewGooglePlacesSDK

Body:
I was trying to implement the Places API. My code looked like this:

val builder = PlacePicker.IntentBuilder()
startActivityForResult(builder.build(mActivity), PLACE_PICKER_REQUEST)

My maps credentials were correct, but for this call I got

Places API for Android does not seem to be enabled for your app. See https://developers.google.com/places/android/signup for more details.

However, when I tried to enable the "Places API for Android", I got this error.

You do not have sufficient permissions to view this page.

I tried logging out of my accounts, logging in again, incognito mode, Safari & Chrome. Nothing worked so I contacted support, which were extremely fast (thanks guys!)

The reason you are receiving an error when trying to enable the Places
  for Android API is that it has been deprecated. Places functionality
  for android will now be covered by having the Places API enabled.

I asked about my implementation and got this reply.

The place picker has also been deprecated. You can install the
  compatibility library to continue using the Place Picker until the
  deprecation period ends on July 29th. More about this can be red here:
  https://developers.google.com/places/android-sdk/client-migration#place_picker

The docs I find online now are a bit confusing, what is deprecated and what isn't? Can anyone point me in the right direction for this kind of functionality?


问:
how to stop puppeteer-recorder recording
im using puppeteer-recorder to record a video from browser activity

this package
https://www.npmjs.com/package/puppeteer-recorder

here is my code

```<code>async function check_login()
{

    try {

        const page = await global_browser.newPage();
        await page.setViewport({width: 1000, height: 1100});

        record({
            browser: global_browser, // Optional: a puppeteer Browser instance,
            page: page, // Optional: a puppeteer Page instance,
            output: path + 'output.webm',
            fps: 60,
            frames: 60 * 5, // 5 seconds at 60 fps
            prepare: function () {}, // <-- add this line
            render: function () {} // <-- add this line

        });

        await page.goto('http://localhost/home_robot/mock.php', {timeout: 60000})
            .catch(function (error) {
                throw new Error('TimeoutBrows');
            });

        await page.close();

    }
    catch (e) {
        console.log(' LOGIN ERROR ---------------------');
        console.log(e);
    }
}
</code>```

it works fine but i dont know how to stop recording and so when i get to the end of function i get this error

```<code>(node:10000) UnhandledPromiseRejectionWarning: Error: Protocol error (Emulation.setDefaultBackgroundColorOverride): Target closed.
    at Promise (C:\wamp64\www\home_robot\node_modules\puppeteer\lib\Connection.js:202:56)
    at new Promise (<anonymous>)
    at CDPSession.send (C:\wamp64\www\home_robot\node_modules\puppeteer\lib\Connection.js:201:12)
    at Page._screenshotTask (C:\wamp64\www\home_robot\node_modules\puppeteer\lib\Page.js:806:26)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:10000) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (
rejection id: 1)
(node:10000) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

and i dont get a video file , i assume its because i close the page without stopping the record

unfortunately there's no documentation and the author doesn't answer the questions

答:
There is no way or need to stop recording with this module, look closely at the frames option of the record method:

```<code>frames: 60 * 5, // 5 seconds at 60 fps
</code>```

After getting 300 frames it will stop by itself.

However for it to work a very important requirement must be met and documentation won't mention it, but you can see it in the source of the module: it uses ffmpeg to make video from screenshots AND that must be in PATH. If not you should provide ffmpeg binary location in options:

```<code>const puppeteer = require('puppeteer');
const { record } = require('puppeteer-recorder');

puppeteer.launch({headless : false}).then(async browser => {
    const page = await browser.newPage();

    await page.goto('https://codepen.io/hexagoncircle/full/joqYEj', {waitUntil : 'networkidle2'});

    await record({
        ffmpeg: "c:\\ffmpeg\\bin\\ffmpeg.exe" // <-- provide full path to ffmpeg binary
        browser: browser, // Optional: a puppeteer Browser instance,
        page: page, // Optional: a puppeteer Page instance,
        output: 'output.webm',
        fps: 24,
        frames: 24, // desired seconds of recording multiplied by fps
        prepare: function (browser, page) { /* you could click on a button */ },
        render: function (browser, page, frame) { /* executed before each capture */ }
    });

    await browser.close();
});
</code>```

Result:

Body:
im using puppeteer-recorder to record a video from browser activity

this package
https://www.npmjs.com/package/puppeteer-recorder

here is my code

async function check_login()
{

    try {

        const page = await global_browser.newPage();
        await page.setViewport({width: 1000, height: 1100});

        record({
            browser: global_browser, // Optional: a puppeteer Browser instance,
            page: page, // Optional: a puppeteer Page instance,
            output: path + 'output.webm',
            fps: 60,
            frames: 60 * 5, // 5 seconds at 60 fps
            prepare: function () {}, // <-- add this line
            render: function () {} // <-- add this line

        });

        await page.goto('http://localhost/home_robot/mock.php', {timeout: 60000})
            .catch(function (error) {
                throw new Error('TimeoutBrows');
            });

        await page.close();

    }
    catch (e) {
        console.log(' LOGIN ERROR ---------------------');
        console.log(e);
    }
}

it works fine but i dont know how to stop recording and so when i get to the end of function i get this error

(node:10000) UnhandledPromiseRejectionWarning: Error: Protocol error (Emulation.setDefaultBackgroundColorOverride): Target closed.
    at Promise (C:\wamp64\www\home_robot\node_modules\puppeteer\lib\Connection.js:202:56)
    at new Promise (<anonymous>)
    at CDPSession.send (C:\wamp64\www\home_robot\node_modules\puppeteer\lib\Connection.js:201:12)
    at Page._screenshotTask (C:\wamp64\www\home_robot\node_modules\puppeteer\lib\Page.js:806:26)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:10000) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (
rejection id: 1)
(node:10000) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

and i dont get a video file , i assume its because i close the page without stopping the record

unfortunately there's no documentation and the author doesn't answer the questions

Body:
There is no way or need to stop recording with this module, look closely at the frames option of the record method:

frames: 60 * 5, // 5 seconds at 60 fps

After getting 300 frames it will stop by itself.

However for it to work a very important requirement must be met and documentation won't mention it, but you can see it in the source of the module: it uses ffmpeg to make video from screenshots AND that must be in PATH. If not you should provide ffmpeg binary location in options:

const puppeteer = require('puppeteer');
const { record } = require('puppeteer-recorder');

puppeteer.launch({headless : false}).then(async browser => {
    const page = await browser.newPage();

    await page.goto('https://codepen.io/hexagoncircle/full/joqYEj', {waitUntil : 'networkidle2'});

    await record({
        ffmpeg: "c:\\ffmpeg\\bin\\ffmpeg.exe" // <-- provide full path to ffmpeg binary
        browser: browser, // Optional: a puppeteer Browser instance,
        page: page, // Optional: a puppeteer Page instance,
        output: 'output.webm',
        fps: 24,
        frames: 24, // desired seconds of recording multiplied by fps
        prepare: function (browser, page) { /* you could click on a button */ },
        render: function (browser, page, frame) { /* executed before each capture */ }
    });

    await browser.close();
});

Result:


问:
Javascript ignore in loop particular element that contains a string of text
I have to loop through an html document that has the following:

```<code><a class="DetailLink" href="/cataloging/servlet/presentbrowseheadingdetailform.do?siteTypeID=-2&searchType=subject....>Legal research.</a>
<a class="DetailLink" href="/cataloging/servlet/presentbrowseheadingdetailform.do?siteTypeID=-2&searchType=subject....><img...></a>
</code>```

First a element contains the text that I want to capture, second is an a element that contains an image which I don't need.
I have the following codes to loop through it:

```<code>var Row = document.querySelector("#exploreTable");
var Cells = Row.querySelectorAll("li a[href*='&searchType=subject'] li a:not([alt*='Find It'])");

l = Cells.length
var number = 1
for (var i = 0; i < l; i++, number++ ) {
 console.log(number + ". " + Cells[i].innerText);
}
</code>```

I'm using querySelector in this case. Is there a way to add in querySelectorAll to ignore the a element that has an img element? How do I go through it? Or is there another way to do it? I'm trying to add an && condition after this:

```<code>li a[href*='&searchType=subject'
</code>```

but it seems it isn't the right way. Maybe there's another way to do it? Thanks and cheers!

答:
You could just do another querySelectorAll on top of all the found li a items
with Cells[i].querySelectorAll("img").length < 1 to check if there are img tags inside, then only print those where there are no img tags inside like this:

var Row = document.querySelector("#exploreTable");
var Cells = Row.querySelectorAll("li a[href*='&searchType=subject']");
l = Cells.length;
var number = 1;
var arr = [];
for (var i = 0; i < l; i++, number++) {
  if(Cells[i].querySelectorAll("img").length < 1){
    arr.push(Cells[i].innerText);
  }
}

for(var i=0; i< arr.length; i++){
console.log(i +". " + arr[i]);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="exploreTable">
  <li>
    Legal research.
  </li>
  <li>

    Image
      <img src=""/>

  </li>

    <li>

    No Image again

  </li>
</div></code>```

OR FOR BETTER PERFORMANCE

var Row = document.querySelector("#exploreTable");
var Cells = Row.querySelectorAll("li a[href*='&searchType=subject']");
l = Cells.length;
var number = 1;
for (var i = 0; i < l; i++) {
  if(Cells[i].querySelectorAll("img").length < 1){
    console.log(number +". " + Cells[i].innerText);
    number++
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="exploreTable">
  <li>
    Legal research.
  </li>
  <li>

    Image
      <img src=""/>

  </li>

    <li>

    No Image again

  </li>
</div></code>```

Body:
I have to loop through an html document that has the following:

Legal research.

First a element contains the text that I want to capture, second is an a element that contains an image which I don't need.
I have the following codes to loop through it:

var Row = document.querySelector("#exploreTable");
var Cells = Row.querySelectorAll("li a[href*='&searchType=subject'] li a:not([alt*='Find It'])");

l = Cells.length
var number = 1
for (var i = 0; i < l; i++, number++ ) {
 console.log(number + ". " + Cells[i].innerText);
}

I'm using querySelector in this case. Is there a way to add in querySelectorAll to ignore the a element that has an img element? How do I go through it? Or is there another way to do it? I'm trying to add an && condition after this:

li a[href*='&searchType=subject'

but it seems it isn't the right way. Maybe there's another way to do it? Thanks and cheers!

Body:
You could just do another querySelectorAll on top of all the found li a items
with Cells[i].querySelectorAll("img").length < 1 to check if there are img tags inside, then only print those where there are no img tags inside like this:

var Row = document.querySelector("#exploreTable");
var Cells = Row.querySelectorAll("li a[href*='&searchType=subject']");
l = Cells.length;
var number = 1;
var arr = [];
for (var i = 0; i < l; i++, number++) {
  if(Cells[i].querySelectorAll("img").length < 1){
    arr.push(Cells[i].innerText);
  }
}

for(var i=0; i< arr.length; i++){
console.log(i +". " + arr[i]);

}

<div id="exploreTable">
  <li>
    <a class="DetailLink" href="/cataloging/servlet/presentbrowseheadingdetailform.do?siteTypeID=-2&amp;searchType=subject....">Legal research.</a>
  </li>
  <li>

    <a class=" DetailLink " href="/cataloging/servlet/presentbrowseheadingdetailform.do?siteTypeID=-2&amp;searchType=subject....">Image
      <img src=""/>
    </a>
  </li>

    <li>

    <a class=" DetailLink " href="/cataloging/servlet/presentbrowseheadingdetailform.do?siteTypeID=-2&amp;searchType=subject....">No Image again
    </a>
  </li>
</div>

OR FOR BETTER PERFORMANCE

var Row = document.querySelector("#exploreTable");
var Cells = Row.querySelectorAll("li a[href*='&searchType=subject']");
l = Cells.length;
var number = 1;
for (var i = 0; i < l; i++) {
  if(Cells[i].querySelectorAll("img").length < 1){
    console.log(number +". " + Cells[i].innerText);
    number++
  }
}

<div id="exploreTable">
  <li>
    <a class="DetailLink" href="/cataloging/servlet/presentbrowseheadingdetailform.do?siteTypeID=-2&amp;searchType=subject....">Legal research.</a>
  </li>
  <li>

    <a class=" DetailLink " href="/cataloging/servlet/presentbrowseheadingdetailform.do?siteTypeID=-2&amp;searchType=subject....">Image
      <img src=""/>
    </a>
  </li>

    <li>

    <a class=" DetailLink " href="/cataloging/servlet/presentbrowseheadingdetailform.do?siteTypeID=-2&amp;searchType=subject....">No Image again
    </a>
  </li>
</div>