问:
view doesn't change when login, but change after registering
I'm currently having problem with my login in the main page(I got template from w3layout to practice).

I'm using authentication with default middle ware(guest, user).

After I registered, the auth:check() worked and only show log out link in the main page.

But when I try to login the login pop up modal still there in the main view.

I'm currently new to laravel.

I hope you can help me :D

my route

```<code>Route::get('/', function () {
    return view('mainpage');
});
Route::get('/mail',function(){
    return view('mail');
});
Route::group(['prefix'=>'user'],function(){
    Route::group(['middleware' => 'guest'], function() {
        Route::post('/register',[
            'uses'=>'UserController@postSignup',
            'as'=>'signup',
        ]);
        Route::post('/login',[
            'uses'=>'UserController@postSignin',
            'as'=>'signin',
        ]);
    });
    Route::group(['middleware' => 'auth'], function() {
        Route::get('/logout',[
            'uses'=>'UserController@getLogout',
            'as'=>'logout',
        ]);
    });
});
</code>```

My UserController

```<code>public function postSignup(Request $request){
    $this->validate($request,[
        'name'=>'required',
        'email'=>'email|required|unique:users',
        'password'=>'required|min:4',
        'birthday'=>'required',
        'address'=>'required',
    ]);

    $user = new User([
        'name'=>$request->input('name'),
        'email'=>$request->input('email'),
        'password'=>bcrypt($request->input('password')),
        'birthday'=>$request->input('birthday'),
        'address'=>$request->input('address'),
    ]);
    $user->save();
    Auth::login($user);
    return redirect()->back();
}
public function postSignin(Request $request){
    $this->validate($request,[
        'email'=>'email|required|unique:users',
        'password'=>'required|min:4',
    ]);
    if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
        return redirect()->back();
    }
    return redirect()->back();
}
public function getLogout(){
    Auth::logout();
    return redirect()->back();
}
</code>```

AND IN THE MAIN PAGE

```<code>@if(\Illuminate\Support\Facades\Auth::check())
    <div><a href="{{route('logout')}}">LOG OUT</a></div>
@else
    <div class="w3l_login">
        <a href="#" data-toggle="modal" data-target="#myModal88"><span class="glyphicon glyphicon-user" aria-hidden="true"></span></a>
    </div>
    <div class="modal fade" id="myModal88" tabindex="-1" role="dialog" aria-labelledby="myModal88" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="myModalLabel">Don't Wait, Login now!</h4>
                </div>
                <div class="modal-body modal-body-sub">
                    <div class="row">
                        <div class="col-md-8 modal_body_left modal_body_left1" style="border-right: 1px dotted #C2C2C2;padding-right:3em;">
                            <div class="sap_tabs">
                                <div id="horizontalTab" style="display: block; width: 100%; margin: 0px;">
                                    <ul>
                                        <li class="resp-tab-item" aria-controls="tab_item-0"><span>Sign in</span></li>
                                        <li class="resp-tab-item" aria-controls="tab_item-1"><span>Sign up</span></li>
                                    </ul>
                                    <div class="tab-1 resp-tab-content" aria-labelledby="tab_item-0">
                                        <div class="facts">
                                            <div class="register">
                                                <form action="{{route('signin')}}" method="post">
                                                    <input name="email" placeholder="Email Address" type="text" required="">
                                                    <input name="password" placeholder="Password" type="password" required="">
                                                    <div class="sign-up"><input type="submit"/>{{csrf_field()}}</div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="tab-2 resp-tab-content" aria-labelledby="tab_item-1">
                                        <div class="facts">
                                            <div class="register">
                                                <form action="{{route('signup')}}" method="post">
                                                    <input placeholder="Name" name="name" type="text" required="">
                                                    <input placeholder="Email Address" name="email" type="email" required="">
                                                    <input placeholder="Password" name="password" type="password" required="">
                                                    <input placeholder="Confirm Password" name="password" type="password" required="">
                                                    <input placeholder="Birthday" name="birthday" type="text" required="">
                                                    <input placeholder="Address" name="address" type="text" required="">
                                                    @if(count($errors)>0)
                                                           <div class="alert alert-danger">
                                                           @foreach($errors->all() as $error))
                                                            <p>{{$error}}</p>
                                                           @endforeach
                                                          </div>
                                                    @endif
                                                    <div class="sign-up">
                                                        <input type="submit"/>
                                                        {{csrf_field()}}
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="OR" class="hidden-xs">OR</div>
                        </div>
                        <div class="col-md-4 modal_body_right modal_body_right1">
                            <div class="row text-center sign-with">
                                <div class="col-md-12">
                                    <h3 class="other-nw">Sign in with</h3>
                                </div>
                                <div class="col-md-12">
                                    <ul class="social">
                                        <li class="social_facebook"><a href="#" class="entypo-facebook"></a></li>
                                        <li class="social_dribbble"><a href="#" class="entypo-dribbble"></a></li>
                                        <li class="social_twitter"><a href="#" class="entypo-twitter"></a></li>
                                        <li class="social_behance"><a href="#" class="entypo-behance"></a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endif
</code>```

答:
Maybe the problem is in the validation?

```<code>public function postSignin(Request $request){
$this->validate($request,[
    'email'=>'email|required|unique:users',
</code>```

This validation fails for an existing email.
Try it:

```<code>    'email'=>'email|required',
</code>```

Body:
I'm currently having problem with my login in the main page(I got template from w3layout to practice).

I'm using authentication with default middle ware(guest, user).

After I registered, the auth:check() worked and only show log out link in the main page.

But when I try to login the login pop up modal still there in the main view.

I'm currently new to laravel.

I hope you can help me :D

my route

Route::get('/', function () {
    return view('mainpage');
});
Route::get('/mail',function(){
    return view('mail');
});
Route::group(['prefix'=>'user'],function(){
    Route::group(['middleware' => 'guest'], function() {
        Route::post('/register',[
            'uses'=>'UserController@postSignup',
            'as'=>'signup',
        ]);
        Route::post('/login',[
            'uses'=>'UserController@postSignin',
            'as'=>'signin',
        ]);
    });
    Route::group(['middleware' => 'auth'], function() {
        Route::get('/logout',[
            'uses'=>'UserController@getLogout',
            'as'=>'logout',
        ]);
    });
});

My UserController

public function postSignup(Request $request){
    $this->validate($request,[
        'name'=>'required',
        'email'=>'email|required|unique:users',
        'password'=>'required|min:4',
        'birthday'=>'required',
        'address'=>'required',
    ]);

    $user = new User([
        'name'=>$request->input('name'),
        'email'=>$request->input('email'),
        'password'=>bcrypt($request->input('password')),
        'birthday'=>$request->input('birthday'),
        'address'=>$request->input('address'),
    ]);
    $user->save();
    Auth::login($user);
    return redirect()->back();
}
public function postSignin(Request $request){
    $this->validate($request,[
        'email'=>'email|required|unique:users',
        'password'=>'required|min:4',
    ]);
    if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
        return redirect()->back();
    }
    return redirect()->back();
}
public function getLogout(){
    Auth::logout();
    return redirect()->back();
}

AND IN THE MAIN PAGE

@if(\Illuminate\Support\Facades\Auth::check())

LOG OUT

@else

                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Don't Wait, Login now!

Sign in

Sign up

                                                <form action="{{route('signin')}}" method="post">
                                                    <input name="email" placeholder="Email Address" type="text" required="">
                                                    <input name="password" placeholder="Password" type="password" required="">

<input type="submit"/>{{csrf_field()}}

                                                </form>

                                                <form action="{{route('signup')}}" method="post">
                                                    <input placeholder="Name" name="name" type="text" required="">
                                                    <input placeholder="Email Address" name="email" type="email" required="">
                                                    <input placeholder="Password" name="password" type="password" required="">
                                                    <input placeholder="Confirm Password" name="password" type="password" required="">
                                                    <input placeholder="Birthday" name="birthday" type="text" required="">
                                                    <input placeholder="Address" name="address" type="text" required="">
                                                    @if(count($errors)>0)

                                                           @foreach($errors->all() as $error))

{{$error}}

                                                           @endforeach

                                                    @endif

                                                        <input type="submit"/>
                                                        {{csrf_field()}}

                                                </form>

OR

Sign in with

@endif

Body:
Maybe the problem is in the validation?

public function postSignin(Request $request){
$this->validate($request,[
    'email'=>'email|required|unique:users',

This validation fails for an existing email.
Try it:

    'email'=>'email|required',


来源: stackexchange

问:
How does one use Swift protocol extensions to create shared code that can modify private properties?
Hypothetical scenario:

There are classes: ClassA; and ClassB. Both implement ProtocolC, which contains the single requirement func createKey(). ProtocolC has an extension that implements createKey() because in respect of this function, the functionality required by ClassA and ClassB is identical. However, the implementation of createKey() needs to access a private variable named uniqueKey that both ClassA and ClassB contain, the value of which needs to be different in the two classes (as you might imagine). The extension of createKey() in ProtocolC therefore becomes useless - because the variable are fileprivate - meaning its code has to be duplicated in both ClassA and ClassB. But duplicated code is a programming no-no. A solution could be to use a superclass rather than a protocol extension, but this cuts against the grain of what Swift is trying to achieve. Inheritance is a Swift no-no.

```<code>// the ideal:

class ClassA: ProtocolC {
    fileprivate var uniqueKey: String?
}

class ClassB: ProtocolC {
    fileprivate var uniqueKey: String?
}

protocol ProtocolC {
    func createKey()
}

extension ProtocolC {
    func createKey(){
        uniqueKey = NSUUID().uuidString
    }
}

// the reality:

class ClassA: ProtocolC {
    fileprivate var uniqueKey: String?
    func createKey(){
        uniqueKey = NSUUID().uuidString
    }
}

class ClassB: ProtocolC {
    fileprivate var uniqueKey: String?
    func createKey(){
        uniqueKey = NSUUID().uuidString
    }
}
</code>```

uniqueKey needs to be locked inside the two classes, not settable nor gettable from without. What is the solution in Swift to writing: generic code that can access private properties; whilst avoiding inheritance?

Thank you for reading.

答:
You are trying to access something that is not defined in the protocol. Extensions are supposed to be based only on their public details. You're not supposed to access their privates.

I think what you actually want is "sharing implementation" rather than fighting with access control and type system. If you need to share implementation, just make an explicit implementation and share them.

```<code>protocol ProtocolC {
    func createKey()
}

class ClassA: ProtocolC {
    private var impl = Impl()
    func createKey() {
        impl.createKey()
    }
}

class ClassB: ProtocolC {
    private var impl = Impl()
    func createKey() {
        impl.createKey()
    }
}

private struct Impl {
    private(set) var uniqueKey: String?
    mutating func createKey(){
        // Lock here.
        uniqueKey = NSUUID().uuidString
        // Unlock here.
    }
}
</code>```

Avoiding dependency to private details is one of intention and design goal of extensions because such dependencies make code fragile, and such fragility is one of major problem of subclassing.

ContentLicense: CC BY-SA 3.0

Body:
Hypothetical scenario:

There are classes: ClassA; and ClassB. Both implement ProtocolC, which contains the single requirement func createKey(). ProtocolC has an extension that implements createKey() because in respect of this function, the functionality required by ClassA and ClassB is identical. However, the implementation of createKey() needs to access a private variable named uniqueKey that both ClassA and ClassB contain, the value of which needs to be different in the two classes (as you might imagine). The extension of createKey() in ProtocolC therefore becomes useless - because the variable are fileprivate - meaning its code has to be duplicated in both ClassA and ClassB. But duplicated code is a programming no-no. A solution could be to use a superclass rather than a protocol extension, but this cuts against the grain of what Swift is trying to achieve. Inheritance is a Swift no-no.

// the ideal:

class ClassA: ProtocolC {
    fileprivate var uniqueKey: String?
}

class ClassB: ProtocolC {
    fileprivate var uniqueKey: String?
}

protocol ProtocolC {
    func createKey()
}

extension ProtocolC {
    func createKey(){
        uniqueKey = NSUUID().uuidString
    }
}

// the reality:

class ClassA: ProtocolC {
    fileprivate var uniqueKey: String?
    func createKey(){
        uniqueKey = NSUUID().uuidString
    }
}

class ClassB: ProtocolC {
    fileprivate var uniqueKey: String?
    func createKey(){
        uniqueKey = NSUUID().uuidString
    }
}

uniqueKey needs to be locked inside the two classes, not settable nor gettable from without. What is the solution in Swift to writing: generic code that can access private properties; whilst avoiding inheritance?

Thank you for reading.

Body:
You are trying to access something that is not defined in the protocol. Extensions are supposed to be based only on their public details. You're not supposed to access their privates.

I think what you actually want is "sharing implementation" rather than fighting with access control and type system. If you need to share implementation, just make an explicit implementation and share them.

protocol ProtocolC {
    func createKey()
}

class ClassA: ProtocolC {
    private var impl = Impl()
    func createKey() {
        impl.createKey()
    }
}

class ClassB: ProtocolC {
    private var impl = Impl()
    func createKey() {
        impl.createKey()
    }
}

private struct Impl {
    private(set) var uniqueKey: String?
    mutating func createKey(){
        // Lock here.
        uniqueKey = NSUUID().uuidString
        // Unlock here.
    }
}

Avoiding dependency to private details is one of intention and design goal of extensions because such dependencies make code fragile, and such fragility is one of major problem of subclassing.


问:
Error in the standards?
§5/4 C++ standard

```<code>i = 7, i++, i++;  // i becomes 9
i = ++i + 1;  //the behavior is unspecified
</code>```

That should be changed to

```<code>i = 7, i++, i++;  // the behavior is undefined
i = ++i + 1;  //the behavior is undefined
</code>```

right?

答:
No, the standard is right. The comma operator guarantees that any side effects of previous operands are completed before evaluating the next.

These guarantees are provided by sequence points, which the comma operator (as well as && and ||) are.

Note that you are correct on the wording change for the second statement. It is undefined, not unspecified.

ContentLicense: CC BY-SA 2.5

Title: Error in the standards?

Body:
§5/4 C++ standard

i = 7, i++, i++;  // i becomes 9
i = ++i + 1;  //the behavior is unspecified

That should be changed to

i = 7, i++, i++;  // the behavior is undefined
i = ++i + 1;  //the behavior is undefined

right?


问:
Divide excel column to N equal groups
I have a column with ordinal values. I want to have another column that ranks them in equal groups (relatively to their value).

Example: If I have a score and I want to divide to 5 equal groups:

Score

100

90

80

70

60

50

40

30

20

10

What function do I use in the new column to get this eventually:

Score   Group

100          5

90         5

80         4

70         4

60         3

50         3

40         2

30         2

20         1

10         1

Thanks! (I'm guessing the solution is somewhere in mod, row and count - but I couldn't find any good solution for this specific problem)

答:
If you don't care about how the groups are split for groups that aren't evenly divisible, you can use this formula and drag down as far as necessary:

```<code>= FLOOR(5*(COUNTA(A:A)-COUNTA(INDEX(A:A,1):INDEX(A:A,ROW())))/COUNTA(A:A),1)+1
</code>```

Possibly a more efficient solution exists, but this is the first way I thought to do it.

Obviously you'll have to change the references to the A column if you want it in a different column.

See below for working example.

Title: Divide excel column to N equal groups

Body:
If you don't care about how the groups are split for groups that aren't evenly divisible, you can use this formula and drag down as far as necessary:

= FLOOR(5*(COUNTA(A:A)-COUNTA(INDEX(A:A,1):INDEX(A:A,ROW())))/COUNTA(A:A),1)+1

Possibly a more efficient solution exists, but this is the first way I thought to do it.

Obviously you'll have to change the references to the A column if you want it in a different column.

See below for working example.


问:
How to disable cascade delete for link tables in EF code-first?
I want to disable cascade deletes for a link table with entity framework code-first.  For example, if many users have many roles, and I try to delete a role, I want that delete to be blocked unless there are no users currently associated with that role.  I already remove the cascade delete convention in my OnModelCreating:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder) {
    ...
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
</code>```

And then I set up the user-role link table:

```<code>modelBuilder.Entity<User>()
    .HasMany(usr => usr.Roles)
    .WithMany(role => role.Users)
    .Map(m => {
        m.ToTable("UsersRoles");
        m.MapLeftKey("UserId");
        m.MapRightKey("RoleId");
    });
</code>```

Yet when EF creates the database, it creates a delete cascade for the foreign key relationships, eg.

```<code>ALTER TABLE [dbo].[UsersRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.UsersRoles_dbo.User_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[User] ([UserId])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[UsersRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.UsersRoles_dbo.Role_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[Role] ([RoleId])
ON DELETE CASCADE
GO
</code>```

How can I stop EF generating this delete cascade?

答:
I believe that turning off ManyToManyCascadeDeleteConvention globally is not a wise option. Instead, it's better to turn it off only for the concerned table.

This can be achieved through editing the generated migration file, for property cascadeDelete. For example:

AddForeignKey("dbo.UsersRoles", "UserId", "dbo.User", "UserId", cascadeDelete: false);

Body:
I want to disable cascade deletes for a link table with entity framework code-first.  For example, if many users have many roles, and I try to delete a role, I want that delete to be blocked unless there are no users currently associated with that role.  I already remove the cascade delete convention in my OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
    ...
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

And then I set up the user-role link table:

modelBuilder.Entity<User>()
    .HasMany(usr => usr.Roles)
    .WithMany(role => role.Users)
    .Map(m => {
        m.ToTable("UsersRoles");
        m.MapLeftKey("UserId");
        m.MapRightKey("RoleId");
    });

Yet when EF creates the database, it creates a delete cascade for the foreign key relationships, eg.

ALTER TABLE [dbo].[UsersRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.UsersRoles_dbo.User_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[User] ([UserId])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[UsersRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.UsersRoles_dbo.Role_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[Role] ([RoleId])
ON DELETE CASCADE
GO

How can I stop EF generating this delete cascade?


问:
Asynchronous image downloader error Obj-c SDWebimage
Im working in a simple app that shows products in a tableview, i get the data from a json api. the problem is the table get laggy because of synchronous download of the images. im trying to use SDWebimage framework to solve this but i get this error:

"'NSInvalidArgumentException', reason: '-[UIImageView sd_setImageWithURL:placeholderImage:]: unrecognized selector sent to instance "

the code i have is this:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    NSDictionary *dictionary = [self.json objectAtIndex:indexPath.row];
    cell.textLabel.text=[dictionary objectForKey:@"name"];
    cell.detailTextLabel.text = [dictionary objectForKey:@"description"];

    //old synchronous code
   /* NSString *path = [[[[dictionary objectForKey:@"images"] objectAtIndex:0] valueForKey:@"thumb"] valueForKey:@"url"];
    NSString *ruta = [NSString stringWithFormat:@"http://18.221.78.126/ecoferia%@",path];
    NSURL *url = [NSURL URLWithString:ruta];
    NSData *imgData = [NSData dataWithContentsOfURL:url];
    cell.imageView.image = [UIImage imageWithData:imgData];
    */

    //trying to do asynchronous download of the images
    NSString *path = [[[[dictionary objectForKey:@"images"] objectAtIndex:0] valueForKey:@"thumb"] valueForKey:@"url"];
    NSString *ruta = [NSString stringWithFormat:@"http://18.221.78.126/ecoferia%@",path];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:ruta]
                 placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    return cell;
}
</code>```

also i have the SDWebimage installed in my proyect and imported in the .m file like this:

```<code>#import "SDWebImage/UIImageView+WebCache.h"
</code>```

im super new to objective-c so all the tips are appreciated.

REGARds..

答:
The solution was put $(inherited) in Build Settings -> Other Linker flags.
Working good :)</p>

Body:
Im working in a simple app that shows products in a tableview, i get the data from a json api. the problem is the table get laggy because of synchronous download of the images. im trying to use SDWebimage framework to solve this but i get this error:

"'NSInvalidArgumentException', reason: '-[UIImageView sd_setImageWithURL:placeholderImage:]: unrecognized selector sent to instance "

the code i have is this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    NSDictionary *dictionary = [self.json objectAtIndex:indexPath.row];
    cell.textLabel.text=[dictionary objectForKey:@"name"];
    cell.detailTextLabel.text = [dictionary objectForKey:@"description"];

    //old synchronous code
   /* NSString *path = [[[[dictionary objectForKey:@"images"] objectAtIndex:0] valueForKey:@"thumb"] valueForKey:@"url"];
    NSString *ruta = [NSString stringWithFormat:@"http://18.221.78.126/ecoferia%@",path];
    NSURL *url = [NSURL URLWithString:ruta];
    NSData *imgData = [NSData dataWithContentsOfURL:url];
    cell.imageView.image = [UIImage imageWithData:imgData];
    */

    //trying to do asynchronous download of the images
    NSString *path = [[[[dictionary objectForKey:@"images"] objectAtIndex:0] valueForKey:@"thumb"] valueForKey:@"url"];
    NSString *ruta = [NSString stringWithFormat:@"http://18.221.78.126/ecoferia%@",path];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:ruta]
                 placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    return cell;
}

also i have the SDWebimage installed in my proyect and imported in the .m file like this:

#import "SDWebImage/UIImageView+WebCache.h"

im super new to objective-c so all the tips are appreciated.

REGARds..


答:
this should do the trick:

SELECT
    MIN(logdate_logout) AS logdate_logout,logdate_login,user,location,id_login,id_logout
FROM (
    SELECT
        MAX(logdate_login) AS logdate_login, logdate_logout,user,location,id_login,id_logout
    FROM (
        SELECT
            t1.id       AS id_login,
            t1.logdate  AS logdate_login,
            t1.user,
            t1.location,
            t2.id       AS id_logout,
            t2.logdate  AS logdate_logout
        FROM logtable AS t1
        JOIN logtable AS t2
        ON (t1.user = t2.user AND t1.location = t2.location AND t1.action = 'login' AND t2.action = 'logout' AND t2.id > t1.id)
        ORDER BY t1.logdate,t2.logdate
    ) results_naive_approach
    GROUP BY logdate_logout,user,location
) inner_query
GROUP BY logdate_login,user,location

this will make sure you only have the logins that are right before the matching logouts and the logouts that are right after the matching logins

Title: Structuring a complex query to match rows in a log file

Body:
I have a log table in MySQL which looks like this:

mysql> describe logtable;
+----------+------------------+------+-----+---------+-------+
| Field    | Type             | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+-------+
| id       | int(10) unsigned | NO   |     | NULL    |       |
| logdate  | datetime         | NO   |     | NULL    |       |
| host     | varchar(100)     | NO   |     | NULL    |       |
| action   | varchar(100)     | NO   |     | NULL    |       |
| user     | varchar(100)     | NO   |     | NULL    |       |
| org      | varchar(100)     | NO   |     | NULL    |       |
| location | varchar(1000)    | NO   |     | NULL    |       |
+----------+------------------+------+-----+---------+-------+

and here's a sample of its contents (not all fields shown):

+----------+---------------------+--------+----------------------+----------+
|    id    |       logdate       | action |         user         | location |
+----------+---------------------+--------+----------------------+----------+
| 13933768 | 2017-01-03 08:42:25 | login  | user1@somewhere.com  | place1   |
| 13934110 | 2017-01-03 08:58:38 | login  | user2@somewhere.com  | place2   |
| 13935532 | 2017-01-03 11:02:31 | logout | user1@somewhere.com  | place1   |
| 13935622 | 2017-01-03 11:11:25 | logout | user2@somewhere.com  | place2   |
| 13935772 | 2017-01-03 11:27:27 | login  | user3@somewhere.com  | place3   |
| 13935942 | 2017-01-03 11:52:16 | login  | user4@somewhere.com  | place4   |
| 13936217 | 2017-01-03 12:25:08 | logout | user3@somewhere.com  | place3   |
| 13936293 | 2017-01-03 12:33:16 | logout | user4@somewhere.com  | place4   |
| 13937676 | 2017-01-03 15:33:59 | login  | user3@somewhere.com  | place5   |
| 13937859 | 2017-01-03 15:51:53 | logout | user3@somewhere.com  | place5   |
| 13942394 | 2017-01-04 08:31:26 | login  | user5@somewhere.com  | place2   |
| 13943946 | 2017-01-04 09:46:04 | login  | user4@somewhere.com  | place4   |
| 13944372 | 2017-01-04 10:17:25 | login  | user4@somewhere.com  | place6   |
| 13944373 | 2017-01-04 10:17:27 | login  | user4@somewhere.com  | place6   |
| 13944374 | 2017-01-04 10:17:29 | login  | user4@somewhere.com  | place6   |
| 13944375 | 2017-01-04 10:19:22 | login  | user4@somewhere.com  | place4   |
| 13944575 | 2017-01-04 10:36:48 | login  | user4@somewhere.com  | place6   |
| 13946830 | 2017-01-04 14:56:36 | login  | user6@somewhere.com  | place7   |
| 13947791 | 2017-01-04 16:41:26 | logout | user5@somewhere.com  | place2   |
| 13947795 | 2017-01-04 16:41:59 | login  | user4@somewhere.com  | place4   |
| 13948181 | 2017-01-04 17:19:19 | logout | user4@somewhere.com  | place7   |
| 13948200 | 2017-01-04 17:22:18 | logout | user4@somewhere.com  | place4   |
| 13948201 | 2017-01-04 17:22:18 | logout | user4@somewhere.com  | place6   |
| 13948824 | 2017-01-04 20:23:15 | login  | user7@somewhere.com  | place8   |
| 13948870 | 2017-01-04 20:44:42 | logout | user7@somewhere.com  | place8   |
| 13949945 | 2017-01-05 02:26:35 | logout | user6@somewhere.com  | place7   |
| 13951697 | 2017-01-05 08:49:37 | login  | user8@somewhere.com  | place6   |
| 13951863 | 2017-01-05 08:56:37 | login  | user9@somewhere.com  | place9   |
| 13951886 | 2017-01-05 08:57:06 | login  | user10@somewhere.com | place9   |
+----------+---------------------+--------+----------------------+----------+

And I would like to produce a table showing each user's cumulative time logged in to the various locations. In theory, the login and logout entries for each person & place combination should be in pairs, but various things like client glitches and network oddities sometimes means there is a mismatch. It's also possible to log in to a second place before logging out of the first place, so the pairs may overlap each other. In addition, the pairs may not match in one of the following ways:

a login event with no matching logout

a logout event with no matching login (sounds strange, but the software logs interrupted logins like this

multiple login events (retries) with only one corresponding logout

I've got so far by joining the table to itself on the user and location, and subtracting logout times from login times. I'm also ensuring the id of the logout event is higher than the login event, as they're always increasing. But since there could be multiple entries, I'm getting all combinations. Take this simple example:

Example 1

+----------+---------------------+--------+----------------------+----------+
|    id    |       logdate       | action |         user         | location |
+----------+---------------------+--------+----------------------+----------+
| 1        | 2017-01-03 08:42:25 | login  | user1@somewhere.com  | place1   |
| 2        | 2017-01-03 11:02:31 | logout | user1@somewhere.com  | place1   |
| 3        | 2017-01-03 11:27:27 | login  | user1@somewhere.com  | place1   |
| 4        | 2017-01-03 12:25:08 | logout | user1@somewhere.com  | place1   |
+----------+---------------------+--------+----------------------+----------+

My naive approach:

select * from logtable as t1
join logtable as t2
on t1.user = t2.user and t1.location = t2.location
and t1.action = 'login' and t2.action = 'logout'
and t2.id > t1.id

gives me 3 results: ids 1→2, 1→4 and 3→4. And since it might also look like this:

Example 2

+----------+---------------------+--------+----------------------+----------+
|    id    |       logdate       | action |         user         | location |
+----------+---------------------+--------+----------------------+----------+
| 1        | 2017-01-03 08:42:25 | login  | user1@somewhere.com  | place1   |
| 2        | 2017-01-03 08:43:35 | login  | user1@somewhere.com  | place1   |
| 3        | 2017-01-03 08:44:45 | login  | user1@somewhere.com  | place1   |
| 4        | 2017-01-03 12:25:08 | logout | user1@somewhere.com  | place1   |
+----------+---------------------+--------+----------------------+----------+

which is 3 attempts at login before it succeeded, followed by a logout, I should only get 1 result not 3, and the required answer is the difference between id 3 and id 4.

I can kind of describe what I'm after, but not translate it into SQL—at least not without multiple nested SELECTs which just run for hours (the log file is 8500 lines).

For each matching user and location, find the last of any logins and the  first of any logouts where the logout is after the login.

Calculate the time difference between those 2 events

Ignore logins that have no matching logout and vice versa

Sum the cumulative time per user

In Example 1 above, that should give 2 'login / logout' events (ids 1→2 = 2:20:06 and 3→4 = 0:57:41) summed into 1 output row = 3:17:47, and for Example 2 it should give a single 'event' (ids 3→4 = 3:40:23) summed into 1 row.


答:
Yes, please see this defect report: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#351 .

Clarification: the example is wrong but your 'fix' is incorrect for the first statement. The first statement is correctly commented in the standard. It is only the second comment that is inaccurate.

Title: Error in the standards?


问:
Find and replace characters in brackets
I have a string kind of:

```<code>String text = "(plum) some other words, [apple], another words {pear}.";
</code>```

I have to find and replace the words in brackets, don't replacing the brackets themselves.

If I write:

```<code>text = text.replaceAll("(\\(|\\[|\\{).*?(\\)|\\]|\\})", "fruit");
</code>```

I get:

```<code>fruit some other words, fruit, another words fruit.
</code>```

So the brackets went away with the fruits, but I need to keep them.

Desired output:

```<code>(fruit) some other words, [fruit], another words {fruit}.
</code>```

答:
GCP showed how to use look aheads and look behinds to exclude the brackets from the matched part. But you can also match them, and refer to them in your replacement string with capturing groups:

```<code>text.replaceAll("([\\(\\[\\{]).*?([\\)\\]\\}])", "$1fruit$2");
</code>```

Also note that you can replace the | ORs by a character group [].

Title: Find and replace characters in brackets

Body:
I have a string kind of:

String text = "(plum) some other words, [apple], another words {pear}.";

I have to find and replace the words in brackets, don't replacing the brackets themselves.

If I write:

text = text.replaceAll("(\\(|\\[|\\{).*?(\\)|\\]|\\})", "fruit");

I get:

fruit some other words, fruit, another words fruit.

So the brackets went away with the fruits, but I need to keep them.

Desired output:

(fruit) some other words, [fruit], another words {fruit}.

Body:
GCP showed how to use look aheads and look behinds to exclude the brackets from the matched part. But you can also match them, and refer to them in your replacement string with capturing groups:

text.replaceAll("([\\(\\[\\{]).*?([\\)\\]\\}])", "$1fruit$2");

Also note that you can replace the | ORs by a character group [].


问:
EventHook AFTER the view has completely re-rendered
I am trying to include webpack into an Angular2 project and run into a problem I already faced in previous scenarios. The common problem is that I need to wait until the view is completely rendered and THEN perform some action. I know there is the ngAfterViewInit lifecycle hook which is however only triggered the first time the view is rendered. When it is being re-rendered because of data changes within the component, its not being called again. Take a look at my code:

```<code>ngOnInit() {
  this.store.select('trips').subscribe(trips => {
    // forces view to re-render
    this.trips = trips;

    // doesn't work because the updated DOM doesn't exist yet
    let Packery: any = require('packery');
    new Packery(this.grid.nativeElement, {
      itemSelector: '.grid-item',
      gutter: 10
    });
  });

  this.store.dispatch(new TripActions.LoadTrips());
}
</code>```

A slight modification makes the code work as expected (most of the time) but comes with the caveat that the website looks extremly ugly for about a second every time new data is loaded, which is not a solution. It shows the problem however.

```<code>ngOnInit() {
  this.store.select('trips').subscribe(trips => {
    // forces view to re-render
    this.trips = trips;

    setTimeout(() => {
      // now it works (most of the time) because after 0.5s
      // the updated DOM elements usually exist...
      let Packery: any = require('packery');
      new Packery(this.grid.nativeElement, {
        itemSelector: '.grid-item',
        gutter: 10
      });
    }, 500);
  });

  this.store.dispatch(new TripActions.LoadTrips());
}
</code>```

答:
What you're probably looking for is ngAfterViewChecked(). Here's a quote from the documentation.

Respond after Angular checks the component's views and child views.
  Called after the ngAfterViewInit and every subsequent
  ngAfterContentChecked().

This means it's not only called once after initialization, but also after every ngAfterContentChecked() that is called when your data changes. On every call you can check if your data is already there and then respond with your code. One problem is that it may be called even after you've done your Packery things, which is why you have to make sure that you only do that once.

Check the lifecycle hook page out for more information.

Body:
I am trying to include webpack into an Angular2 project and run into a problem I already faced in previous scenarios. The common problem is that I need to wait until the view is completely rendered and THEN perform some action. I know there is the ngAfterViewInit lifecycle hook which is however only triggered the first time the view is rendered. When it is being re-rendered because of data changes within the component, its not being called again. Take a look at my code:

ngOnInit() {
  this.store.select('trips').subscribe(trips => {
    // forces view to re-render
    this.trips = trips;

    // doesn't work because the updated DOM doesn't exist yet
    let Packery: any = require('packery');
    new Packery(this.grid.nativeElement, {
      itemSelector: '.grid-item',
      gutter: 10
    });
  });

  this.store.dispatch(new TripActions.LoadTrips());
}

A slight modification makes the code work as expected (most of the time) but comes with the caveat that the website looks extremly ugly for about a second every time new data is loaded, which is not a solution. It shows the problem however.

ngOnInit() {
  this.store.select('trips').subscribe(trips => {
    // forces view to re-render
    this.trips = trips;

    setTimeout(() => {
      // now it works (most of the time) because after 0.5s
      // the updated DOM elements usually exist...
      let Packery: any = require('packery');
      new Packery(this.grid.nativeElement, {
        itemSelector: '.grid-item',
        gutter: 10
      });
    }, 500);
  });

  this.store.dispatch(new TripActions.LoadTrips());
}


问:
PHPexcel array values to column
I have a problem filling columns with array values with PHPexcel i got my query results into arrays. Column A,B,C... not rows !

```<code>while (($red = pg_fetch_assoc($resultID))) {
$nivelacija[] = $red ['nivelacija'];
$dokument[] = $red ['dokument'];
$sifra[] = $red ['sifra'];
$naziv[] = $red ['naziv'];
$kol[] = $red ['kol'];
$pdv[] = $red ['pdv'];
$datum[] = $red ['datum'];
$stara[] = $red ['stara'];
$nova[] = $red ['nova'];
$marza[] = $red ['marza'];
$razlika[] = $red ['razlika'];
$zaduzenje[] = $red ['zaduzenje'];

    }
</code>```

I have tried doing it like

```<code>    for ($i = 1; $i <= 10; $i++) {
$objPHPExcel->getActiveSheet()->fromArray($nivelacija, null, 'A' . $i);
}
</code>```

but no success, looks like fromArray function can only target specific cell. So i have tried changing to this

```<code>for ($i = 1 , $vrednost=0; $i <= 50; $i++ , $vrednost++ ) {
$objPHPExcel->getActiveSheet()->setCellValue('A' .$i, "$nivelacija[$vrednost]" ); }
</code>```

but like this I get results in Column A but everywhere it writes Array(0) to Array (49)

I have tested this it works when I write "$nivelacija[0]" it writes value to targeted column.

I have no idea how to get my array values for each array to a diffrent column, all i have managed to do is to export it to a row but that just doesnt do the job for me.

Can i get somehow pg query directly to excel without arrays ? Even so i would like to solve array to column problem.

EDITS:

result of var_dump ($nivelacija);

```<code>array(8) { [0]=> string(8) "NMP03945" [1]=> string(8) "NMP03944" [2]=> string(8) "NMP03943" [3]=> string(8) "NMP03942" [4]=> string(8) "NMP03942" [5]=> string(8) "NMP03942" [6]=> string(8) "NMP03941" [7]=> string(8) "NMP03940" }
</code>```

It has only 8 values cause the date is selected for only 1 day. It suppose to be used monthly withunknown numbers of values

----Added $sve array

```<code>$sve = array($nivelacija, $dokument, $sifra, $naziv, $kol, $pdv, $datum, $stara, $nova, $marza, $razlika, $zaduzenje);
</code>```

result of var_dumping

```<code>array(12) { [0]=> array(8) { [0]=> string(8) "NMP03945" [1]=> string(8) "NMP03944" [2]=> string(8) "NMP03943" [3]=> string(8) "NMP03942" [4]=> string(8) "NMP03942" [5]=> string(8) "NMP03942" [6]=> string(8) "NMP03941" [7]=> string(8) "NMP03940" } [1]=> array(8) { [0]=> string(8) "RNB15269" [1]=> string(8) "RNB15266" [2]=> string(8) "RNB15264" [3]=> string(8) "RNB15261" [4]=> string(8) "RNB15261" [5]=> string(8) "RNB15261" [6]=> string(8) "RNB15262" [7]=> string(8) "RNB15255" } [2]=> array(8) { [0]=> string(7) "0670723" [1]=> string(7) "4610602" [2]=> string(7) "4610800" [3]=> string(7) "1011910" [4]=> string(7) "4320350" [5]=> string(7) "0291415" [6]=> string(7) "2631463" [7]=> string(7) "4610513" } [3]=> array(8) { [0]=> string(40) "Gree Viola Profi inverter Wifi klima 18k" [1]=> string(16) "Matrix HDMI 1.5m" [2]=> string(31) "CCP-USB2-AMBM-10 USB Printer 3m" [3]=> string(28) "Green PC G1840/H81/4GB/320GB" [4]=> string(21) "HP LaserJet Pro M102a" [5]=> string(31) "Monitor 19 Philips 193V5LSB2/10" [6]=> string(25) "Maxell speedboat USB 16GB" [7]=> string(20) "PC-186 naponski kabl" } [4]=> array(8) { [0]=> string(1) "1" [1]=> string(1) "3" [2]=> string(1) "1" [3]=> string(1) "1" [4]=> string(1) "1" [5]=> string(1) "1" [6]=> string(1) "1" [7]=> string(1) "1" } [5]=> array(8) { [0]=> string(2) "20" [1]=> string(2) "20" [2]=> string(2) "20" [3]=> string(2) "20" [4]=> string(2) "20" [5]=> string(2) "20" [6]=> string(2) "20" [7]=> string(2) "20" } [6]=> array(8) { [0]=> string(10) "2017-11-18" [1]=> string(10) "2017-11-18" [2]=> string(10) "2017-11-18" [3]=> string(10) "2017-11-18" [4]=> string(10) "2017-11-18" [5]=> string(10) "2017-11-18" [6]=> string(10) "2017-11-18" [7]=> string(10) "2017-11-18" } [7]=> array(8) { [0]=> string(10) "94990.0000" [1]=> string(8) "280.0000" [2]=> string(8) "290.0000" [3]=> string(10) "22990.0000" [4]=> string(9) "9990.0000" [5]=> string(9) "9990.0000" [6]=> string(9) "1190.0000" [7]=> string(8) "290.0000" } [8]=> array(8) { [0]=> string(10) "94000.0000" [1]=> string(8) "200.0000" [2]=> string(8) "150.0000" [3]=> string(10) "22000.0000" [4]=> string(9) "9500.0000" [5]=> string(9) "8700.0000" [6]=> string(9) "1050.0000" [7]=> string(8) "250.0000" } [9]=> array(8) { [0]=> string(7) "-1.0422" [1]=> string(8) "-28.5714" [2]=> string(8) "-48.2759" [3]=> string(7) "-4.3062" [4]=> string(7) "-4.9049" [5]=> string(8) "-12.9129" [6]=> string(8) "-11.7647" [7]=> string(8) "-13.7931" } [10]=> array(8) { [0]=> string(9) "-990.0000" [1]=> string(8) "-80.0000" [2]=> string(9) "-140.0000" [3]=> string(9) "-990.0000" [4]=> string(9) "-490.0000" [5]=> string(10) "-1290.0000" [6]=> string(9) "-140.0000" [7]=> string(8) "-40.0000" } [11]=> array(8) { [0]=> string(4) "-990" [1]=> string(4) "-240" [2]=> string(4) "-140" [3]=> string(4) "-990" [4]=> string(4) "-490" [5]=> string(5) "-1290" [6]=> string(4) "-140" [7]=> string(3) "-40" } }
</code>```

答:
ok i found out best solution

```<code>$row = 4; // 1-based index
while($row_data = pg_fetch_assoc($resultID)) {
    $col = 0;
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}
</code>```

and its working fine thanks for help

Title: PHPexcel array values to column

Body:
I have a problem filling columns with array values with PHPexcel i got my query results into arrays. Column A,B,C... not rows !

while (($red = pg_fetch_assoc($resultID))) {
$nivelacija[] = $red ['nivelacija'];
$dokument[] = $red ['dokument'];
$sifra[] = $red ['sifra'];
$naziv[] = $red ['naziv'];
$kol[] = $red ['kol'];
$pdv[] = $red ['pdv'];
$datum[] = $red ['datum'];
$stara[] = $red ['stara'];
$nova[] = $red ['nova'];
$marza[] = $red ['marza'];
$razlika[] = $red ['razlika'];
$zaduzenje[] = $red ['zaduzenje'];

    }

I have tried doing it like

    for ($i = 1; $i <= 10; $i++) {
$objPHPExcel->getActiveSheet()->fromArray($nivelacija, null, 'A' . $i);
}

but no success, looks like fromArray function can only target specific cell. So i have tried changing to this

for ($i = 1 , $vrednost=0; $i <= 50; $i++ , $vrednost++ ) {
$objPHPExcel->getActiveSheet()->setCellValue('A' .$i, "$nivelacija[$vrednost]" ); }

but like this I get results in Column A but everywhere it writes Array(0) to Array (49)

I have tested this it works when I write "$nivelacija[0]" it writes value to targeted column.

I have no idea how to get my array values for each array to a diffrent column, all i have managed to do is to export it to a row but that just doesnt do the job for me.

Can i get somehow pg query directly to excel without arrays ? Even so i would like to solve array to column problem.

EDITS:

result of var_dump ($nivelacija);

array(8) { [0]=> string(8) "NMP03945" [1]=> string(8) "NMP03944" [2]=> string(8) "NMP03943" [3]=> string(8) "NMP03942" [4]=> string(8) "NMP03942" [5]=> string(8) "NMP03942" [6]=> string(8) "NMP03941" [7]=> string(8) "NMP03940" }

It has only 8 values cause the date is selected for only 1 day. It suppose to be used monthly withunknown numbers of values

----Added $sve array

$sve = array($nivelacija, $dokument, $sifra, $naziv, $kol, $pdv, $datum, $stara, $nova, $marza, $razlika, $zaduzenje);

result of var_dumping

array(12) { [0]=> array(8) { [0]=> string(8) "NMP03945" [1]=> string(8) "NMP03944" [2]=> string(8) "NMP03943" [3]=> string(8) "NMP03942" [4]=> string(8) "NMP03942" [5]=> string(8) "NMP03942" [6]=> string(8) "NMP03941" [7]=> string(8) "NMP03940" } [1]=> array(8) { [0]=> string(8) "RNB15269" [1]=> string(8) "RNB15266" [2]=> string(8) "RNB15264" [3]=> string(8) "RNB15261" [4]=> string(8) "RNB15261" [5]=> string(8) "RNB15261" [6]=> string(8) "RNB15262" [7]=> string(8) "RNB15255" } [2]=> array(8) { [0]=> string(7) "0670723" [1]=> string(7) "4610602" [2]=> string(7) "4610800" [3]=> string(7) "1011910" [4]=> string(7) "4320350" [5]=> string(7) "0291415" [6]=> string(7) "2631463" [7]=> string(7) "4610513" } [3]=> array(8) { [0]=> string(40) "Gree Viola Profi inverter Wifi klima 18k" [1]=> string(16) "Matrix HDMI 1.5m" [2]=> string(31) "CCP-USB2-AMBM-10 USB Printer 3m" [3]=> string(28) "Green PC G1840/H81/4GB/320GB" [4]=> string(21) "HP LaserJet Pro M102a" [5]=> string(31) "Monitor 19 Philips 193V5LSB2/10" [6]=> string(25) "Maxell speedboat USB 16GB" [7]=> string(20) "PC-186 naponski kabl" } [4]=> array(8) { [0]=> string(1) "1" [1]=> string(1) "3" [2]=> string(1) "1" [3]=> string(1) "1" [4]=> string(1) "1" [5]=> string(1) "1" [6]=> string(1) "1" [7]=> string(1) "1" } [5]=> array(8) { [0]=> string(2) "20" [1]=> string(2) "20" [2]=> string(2) "20" [3]=> string(2) "20" [4]=> string(2) "20" [5]=> string(2) "20" [6]=> string(2) "20" [7]=> string(2) "20" } [6]=> array(8) { [0]=> string(10) "2017-11-18" [1]=> string(10) "2017-11-18" [2]=> string(10) "2017-11-18" [3]=> string(10) "2017-11-18" [4]=> string(10) "2017-11-18" [5]=> string(10) "2017-11-18" [6]=> string(10) "2017-11-18" [7]=> string(10) "2017-11-18" } [7]=> array(8) { [0]=> string(10) "94990.0000" [1]=> string(8) "280.0000" [2]=> string(8) "290.0000" [3]=> string(10) "22990.0000" [4]=> string(9) "9990.0000" [5]=> string(9) "9990.0000" [6]=> string(9) "1190.0000" [7]=> string(8) "290.0000" } [8]=> array(8) { [0]=> string(10) "94000.0000" [1]=> string(8) "200.0000" [2]=> string(8) "150.0000" [3]=> string(10) "22000.0000" [4]=> string(9) "9500.0000" [5]=> string(9) "8700.0000" [6]=> string(9) "1050.0000" [7]=> string(8) "250.0000" } [9]=> array(8) { [0]=> string(7) "-1.0422" [1]=> string(8) "-28.5714" [2]=> string(8) "-48.2759" [3]=> string(7) "-4.3062" [4]=> string(7) "-4.9049" [5]=> string(8) "-12.9129" [6]=> string(8) "-11.7647" [7]=> string(8) "-13.7931" } [10]=> array(8) { [0]=> string(9) "-990.0000" [1]=> string(8) "-80.0000" [2]=> string(9) "-140.0000" [3]=> string(9) "-990.0000" [4]=> string(9) "-490.0000" [5]=> string(10) "-1290.0000" [6]=> string(9) "-140.0000" [7]=> string(8) "-40.0000" } [11]=> array(8) { [0]=> string(4) "-990" [1]=> string(4) "-240" [2]=> string(4) "-140" [3]=> string(4) "-990" [4]=> string(4) "-490" [5]=> string(5) "-1290" [6]=> string(4) "-140" [7]=> string(3) "-40" } }

Body:
ok i found out best solution

$row = 4; // 1-based index
while($row_data = pg_fetch_assoc($resultID)) {
    $col = 0;
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

and its working fine thanks for help


问:
How to zoom out from Google maps in Android Emulator?
I am testing a map based app on the emulator. I have zoomed into the map by double clicking with the mouse on the screen, but can not zoom out.

Please tell me how to zoom out?

答:
On windows +  android studio emulator, press the ctrl key when emulator is in focus and mouse is inside the emulator / google maps app. You will see two green spots connected by a green line pop up. Move the mouse away from the center point while still holding the Ctrl key.

Left click (while still having the Ctrl key pressed) to confirm the zoom.

The longer the line, the more the map will zoom out.

Double click to zoom in.


问:
How make a filter "does not contain" in Google Stackdriver logs
In Google Stackdriver advanced filter I can insert something like:

```<code>resource.type="container"
resource.labels.cluster_name="mycluster"
textPayload!="Metric stackdriver_sink_successfully_sent_entry_count was not found in the cache."
severity="INFO"
textPayload:(helloworld)
</code>```

The last rule means that the field textPayload should contain the string helloworld.
But I'm not able to find a way to add a NOT operator.

I would use something like:

```<code>textPayload:!(helloworld)
</code>```

but doesn't work

答:
just add AND NOT between two rows:</p>

```<code>resource.type="container"
resource.labels.cluster_name="mycluster"
textPayload!="Metric stackdriver_sink_successfully_sent_entry_count was not found in the cache."
severity="INFO" AND NOT
textPayload:(helloworld)
</code>```

Body:
In Google Stackdriver advanced filter I can insert something like:

resource.type="container"
resource.labels.cluster_name="mycluster"
textPayload!="Metric stackdriver_sink_successfully_sent_entry_count was not found in the cache."
severity="INFO"
textPayload:(helloworld)

The last rule means that the field textPayload should contain the string helloworld.
But I'm not able to find a way to add a NOT operator.

I would use something like:

textPayload:!(helloworld)

but doesn't work

Body:
just add AND NOT between two rows:

resource.type="container"
resource.labels.cluster_name="mycluster"
textPayload!="Metric stackdriver_sink_successfully_sent_entry_count was not found in the cache."
severity="INFO" AND NOT
textPayload:(helloworld)


问:
How to save the whole class in file named after hashed input?
The initialization of my class takes some time (for about an hour). But the result is four arrays of small length. Is there a way to save the result on hard drive and load it if class is fed by same input? I thought it might be like this:

```<code>    class class_1(a,b):

       def __init__(self):
           self.a = a
           self.b = b

       def load_class(self):
           hashed_input = ...
           if os.path.isdir('data/'+hashed_input):
               ...load out....
           else: self.calc_out()

       def calc_out(self):

       ...takes an hour...

       def save_class(self):
           hashed_input = ...
           dir = '/data/'+hashed_input
           import pathlib
           pathlib.Path(dir).mkdir(parents=True, exist_ok=True)
           np.savez('dir/File.npz', out=self.out)

    args = {a:1, b:2}
    foo = class_1(**args)
    foo.save_class()
</code>```

but I need to use args dict inside the class.

答:
Maybe pass foo.save as a callback into calc_out?

```<code>def calc_out(self, cb):
    ...
    ...
    cb()

foo.call_out(foo.save)
</code>```

Body:
The initialization of my class takes some time (for about an hour). But the result is four arrays of small length. Is there a way to save the result on hard drive and load it if class is fed by same input? I thought it might be like this:

    class class_1(a,b):

       def __init__(self):
           self.a = a
           self.b = b

       def load_class(self):
           hashed_input = ...
           if os.path.isdir('data/'+hashed_input):
               ...load out....
           else: self.calc_out()

       def calc_out(self):

       ...takes an hour...

       def save_class(self):
           hashed_input = ...
           dir = '/data/'+hashed_input
           import pathlib
           pathlib.Path(dir).mkdir(parents=True, exist_ok=True)
           np.savez('dir/File.npz', out=self.out)

    args = {a:1, b:2}
    foo = class_1(**args)
    foo.save_class()

but I need to use args dict inside the class.

Body:
Maybe pass foo.save as a callback into calc_out?

def calc_out(self, cb):
    ...
    ...
    cb()

foo.call_out(foo.save)


问:
ReactiveUI command unsubscription
I have 2 Views and 2 ViewModels:

First View:

```<code>public partial class FirstView : Page
{
    FirstViewModel ViewModel;
    public FirstView()
    {
        ViewModel = new FirstViewModel();
        ViewModel.ShowSecondView.Subscribe(_ =>
        {
            NavigationService.Navigate(new SecondView(ViewModel.ChildViewModel));
        });

        this.DataContext = ViewModel;
        InitializeComponent();
    }
}
</code>```

First ViewModel:

```<code>public class FirstViewModel
{
    SecondViewModel ChildViewModel;
    public ReactiveCommand<Unit, Unit> ShowSecondView { get; set; }
    public FirstViewModel()
    {
        ChildViewModel = new SecondViewModel();
        ShowSecondView = ReactiveCommand.Create(() =>
        {
             ChildViewModel.Reconfigure(...);
        });
    }
}
</code>```

Second View:

```<code>public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}
</code>```

Second ViewModel:

```<code>public class SecondViewModel
{
    public ReactiveCommand<Unit, Unit> GoBack { get; set; }
    public FirstViewModel()
    {
        VeryLongInitialization();
        GoBack = ReactiveCommand.Create(() => { });
    }
    public void Reconfigure(...)
    { ... }
}
</code>```

So, when I run FirstViewModel.ShowSecondView several times and run SecondViewModel.GoBack several times, DoSomethingHard() execute also several times on each created SecondView.

Why do I want create ChildViewModel in FilstViewModel once? Because creating of SecondViewModel takes long time. And I don't recreate every time SecondViewModel but only reconfigure it.

My question is how can I unsubscribe ViewModel.GoBack.Subscribe in SecondView?

P.S. Maybe I should not recreate SecondView in FirstView but reconfigure it as well as SecondViewModel?

UPDATE 1 (thanks to Julien Mialon)

I add IDisposable goBackSubscr and it works! Am I right to implement it?

```<code>public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    IDisposable goBackSubscr;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        goBackSubscr = ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
            goBackSubscr.Dispose();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}
</code>```

答: The subscribe method return an IDisposable, you should store it and dispose it when you want to unsubscribe.</p>

Title: ReactiveUI command unsubscription

Body:
I have 2 Views and 2 ViewModels:

First View:

public partial class FirstView : Page
{
    FirstViewModel ViewModel;
    public FirstView()
    {
        ViewModel = new FirstViewModel();
        ViewModel.ShowSecondView.Subscribe(_ =>
        {
            NavigationService.Navigate(new SecondView(ViewModel.ChildViewModel));
        });

        this.DataContext = ViewModel;
        InitializeComponent();
    }
}

First ViewModel:

public class FirstViewModel
{
    SecondViewModel ChildViewModel;
    public ReactiveCommand<Unit, Unit> ShowSecondView { get; set; }
    public FirstViewModel()
    {
        ChildViewModel = new SecondViewModel();
        ShowSecondView = ReactiveCommand.Create(() =>
        {
             ChildViewModel.Reconfigure(...);
        });
    }
}

Second View:

public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}

Second ViewModel:

public class SecondViewModel
{
    public ReactiveCommand<Unit, Unit> GoBack { get; set; }
    public FirstViewModel()
    {
        VeryLongInitialization();
        GoBack = ReactiveCommand.Create(() => { });
    }
    public void Reconfigure(...)
    { ... }
}

So, when I run FirstViewModel.ShowSecondView several times and run SecondViewModel.GoBack several times, DoSomethingHard() execute also several times on each created SecondView.

Why do I want create ChildViewModel in FilstViewModel once? Because creating of SecondViewModel takes long time. And I don't recreate every time SecondViewModel but only reconfigure it.

My question is how can I unsubscribe ViewModel.GoBack.Subscribe in SecondView?

P.S. Maybe I should not recreate SecondView in FirstView but reconfigure it as well as SecondViewModel?

UPDATE 1 (thanks to Julien Mialon)

I add IDisposable goBackSubscr and it works! Am I right to implement it?

public partial class SecondView : Page
{
    SecondViewModel ViewModel;
    IDisposable goBackSubscr;
    public SecondView(SecondViewModel viewModel)
    {
        ViewModel = viewModel;
        goBackSubscr = ViewModel.GoBack.Subscribe(_ =>
        {
            DoSomethingHard();
            if(NavigationService != null)  NavigationService.GoBack();
            goBackSubscr.Dispose();
        });
        this.DataContext = ViewModel;
        InitializeComponent();
    }
}


问:
"is unavailable" error for elements in viewController file
In my new quest to learn objective c, I have can't get past the error in my viewController that a button (which I have declared in the header file - IBOutlet) is unavailable.

in the header.h file:

```<code>#import <UIKit/UIKit.h>

@interface MessageContactViewController : TTTemplateViewController
{
    __weak IBOutlet UIButton *showBtn;
    __weak IBOutlet UIView *photoView;
}
@end
</code>```

code in .m file

```<code>import "header.h"
@implementation MessageContactViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IS_IOS_7) {
        [showBtn.titleLabel setFont:[UIFont fontWithName:FONT_GOTHAM_BOOK size:17]]; // this gives the error: "showBtn" is unavailable
    //some extra code for labels and button

}
</code>```

Please help me out in this and forgive my ignorance.

答:
please edit your line with below and try...

```<code>@property (nonatomic, weak) IBOutlet UIButton * showBtn;
</code>```

pls ensure: you had check Target Membership for .m file

Body:
In my new quest to learn objective c, I have can't get past the error in my viewController that a button (which I have declared in the header file - IBOutlet) is unavailable.

in the header.h file:

#import <UIKit/UIKit.h>

@interface MessageContactViewController : TTTemplateViewController
{
    __weak IBOutlet UIButton *showBtn;
    __weak IBOutlet UIView *photoView;
}
@end

code in .m file

import "header.h"
@implementation MessageContactViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IS_IOS_7) {
        [showBtn.titleLabel setFont:[UIFont fontWithName:FONT_GOTHAM_BOOK size:17]]; // this gives the error: "showBtn" is unavailable
    //some extra code for labels and button

}

Please help me out in this and forgive my ignorance.

Body:
please edit your line with below and try...

@property (nonatomic, weak) IBOutlet UIButton * showBtn;

pls ensure: you had check Target Membership for .m file


问:
How to know if your .ipa is 64-Bit
I've built an .ipa file with following flags armv7 armv7s and arm64.
Is there any way/ tool through which i can make sure the .ipa does have the 64-Bit support?

How does apple find out during app submission if the app binary does have 64-Bit support.

答:
I have created a script that takes .ipa file as an input and returns what architecture the app supports -
(replace  and  with yours)

```<code>ORIGINAL_FILE="<file path>"
FILE_NAME=$(basename $ORIGINAL_FILE)
EXPANDED_DIR="/Users/<username>/Downloads/expanded_app/$FILE_NAME"
PLIST_FILE="$APP_DIR/Info.plist"
APP_DIR="$EXPANDED_DIR/Payload/*.app"
unzip -q "$ORIGINAL_FILE" -d "$EXPANDED_DIR"

executable_file_name=$(/user/rover/PlistBuddy -c "Print CFBundleExecutable" $PLIST_FILE)
EXECUTABLE_FILE="$APP_DIR/$executable_file_name"
app_architecture_list=$(lipo -info $EXECUTABLE_FILE)
echo $app_architecture_list
</code>```

Now, this app_architecture_list will give you result that will contain armv6 or armv7 or arm64, by which you can figure out.

Note - you will need PlistBuddy for this.

Title: How to know if your .ipa is 64-Bit

Body:
I have created a script that takes .ipa file as an input and returns what architecture the app supports -
(replace  and  with yours)

ORIGINAL_FILE="<file path>"
FILE_NAME=$(basename $ORIGINAL_FILE)
EXPANDED_DIR="/Users/<username>/Downloads/expanded_app/$FILE_NAME"
PLIST_FILE="$APP_DIR/Info.plist"
APP_DIR="$EXPANDED_DIR/Payload/*.app"
unzip -q "$ORIGINAL_FILE" -d "$EXPANDED_DIR"

executable_file_name=$(/user/rover/PlistBuddy -c "Print CFBundleExecutable" $PLIST_FILE)
EXECUTABLE_FILE="$APP_DIR/$executable_file_name"
app_architecture_list=$(lipo -info $EXECUTABLE_FILE)
echo $app_architecture_list

Now, this app_architecture_list will give you result that will contain armv6 or armv7 or arm64, by which you can figure out.

Note - you will need PlistBuddy for this.

ContentLicense: CC BY-SA 4.0


问:
When to use @QueryParam vs @PathParam
I am not asking the question that is already asked here:
What is the difference between @PathParam and @QueryParam

This is a "best practices" or convention question.

When would you use @PathParam vs @QueryParam.

What I can think of that the decision might be using the two to differentiate the information pattern. Let me illustrate below my LTPO - less than perfect observation.

PathParam use could be reserved for information category, which would fall nicely into a branch of an information tree. PathParam could be used to drill down to entity class hierarchy.

Whereas, QueryParam could be reserved for specifying attributes to locate the instance of a class.

For example,

/Vehicle/Car?registration=123

/House/Colonial?region=newengland

/category?instance

```<code>@GET
@Path("/employee/{dept}")
Patient getEmployee(@PathParam("dept")Long dept, @QueryParam("id")Long id) ;
</code>```

vs /category/instance

```<code>@GET
@Path("/employee/{dept}/{id}")
Patient getEmployee(@PathParam("dept")Long dept, @PathParam("id")Long id) ;
</code>```

vs ?category+instance

```<code>@GET
@Path("/employee")
Patient getEmployee(@QueryParam("dept")Long dept, @QueryParam("id")Long id) ;
</code>```

I don't think there is a standard convention of doing it. Is there? However, I would like to hear of how people use PathParam vs QueryParam to differentiate their information like I exemplified above. I would also love to hear the reason behind the practice.

答:
You can support both query parameters and path parameters, e.g., in the case of aggregation of resources -- when the collection of sub-resources makes sense on its own.

```<code>/departments/{id}/employees
/employees?dept=id
</code>```

Query parameters can support hierarchical and non-hierarchical subsetting; path parameters are hierarchical only.

Resources can exhibit multiple hierarchies.  Support short paths if you will be querying broad sub-collections that cross hierarchical boundaries.

```<code>/inventory?make=toyota&model=corolla
/inventory?year=2014
</code>```

Use query parameters to combine orthogonal hierarchies.

```<code>/inventory/makes/toyota/models/corolla?year=2014
/inventory/years/2014?make=toyota&model=corolla
/inventory?make=toyota&model=corolla&year=2014
</code>```

Use only path parameters in the case of composition -- when a resource doesn't make sense divorced from its parent, and the global collection of all children is not a useful resource in itself.

```<code>/words/{id}/definitions
/definitions?word=id   // not useful
</code>```

Title: When to use @QueryParam vs @PathParam

Body:
I am not asking the question that is already asked here:
What is the difference between @PathParam and @QueryParam

This is a "best practices" or convention question.

When would you use @PathParam vs @QueryParam.

What I can think of that the decision might be using the two to differentiate the information pattern. Let me illustrate below my LTPO - less than perfect observation.

PathParam use could be reserved for information category, which would fall nicely into a branch of an information tree. PathParam could be used to drill down to entity class hierarchy.

Whereas, QueryParam could be reserved for specifying attributes to locate the instance of a class.

For example,

/Vehicle/Car?registration=123

/House/Colonial?region=newengland

/category?instance

@GET
@Path("/employee/{dept}")
Patient getEmployee(@PathParam("dept")Long dept, @QueryParam("id")Long id) ;

vs /category/instance

@GET
@Path("/employee/{dept}/{id}")
Patient getEmployee(@PathParam("dept")Long dept, @PathParam("id")Long id) ;

vs ?category+instance

@GET
@Path("/employee")
Patient getEmployee(@QueryParam("dept")Long dept, @QueryParam("id")Long id) ;

I don't think there is a standard convention of doing it. Is there? However, I would like to hear of how people use PathParam vs QueryParam to differentiate their information like I exemplified above. I would also love to hear the reason behind the practice.

Body:
You can support both query parameters and path parameters, e.g., in the case of aggregation of resources -- when the collection of sub-resources makes sense on its own.

/departments/{id}/employees
/employees?dept=id

Query parameters can support hierarchical and non-hierarchical subsetting; path parameters are hierarchical only.

Resources can exhibit multiple hierarchies.  Support short paths if you will be querying broad sub-collections that cross hierarchical boundaries.

/inventory?make=toyota&model=corolla
/inventory?year=2014

Use query parameters to combine orthogonal hierarchies.

/inventory/makes/toyota/models/corolla?year=2014
/inventory/years/2014?make=toyota&model=corolla
/inventory?make=toyota&model=corolla&year=2014

Use only path parameters in the case of composition -- when a resource doesn't make sense divorced from its parent, and the global collection of all children is not a useful resource in itself.

/words/{id}/definitions
/definitions?word=id   // not useful


问:
How query a MySQL in ASP.NET?
I am trying to link my asp.net Formview to a MySQL database, but with no success.

Take a look at my code and please tell my where is my mistake:

```<code><asp:FormView ID="FormView1" runat="server" DataKeyNames="ImageID"
        DataSourceID="SqlDataSource1" EnableModelValidation="True">
        <EditItemTemplate>
            ImageID:
            <asp:Label ID="ImageIDLabel1" runat="server" Text='<%# Eval("ImageID") %>' />
            <br />
            Title:
            <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title") %>' />
            <br />
            Description:
            <asp:TextBox ID="DescriptionTextBox" runat="server"
                Text='<%# Bind("Description") %>' />
            <br />
            <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
                CommandName="Update" Text="Update" />
             <asp:LinkButton ID="UpdateCancelButton" runat="server"
                CausesValidation="False" CommandName="Cancel" Text="Cancel" />
        </EditItemTemplate>
        <InsertItemTemplate>
            Title:
            <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title") %>' />
            <br />
            Description:
            <asp:TextBox ID="DescriptionTextBox" runat="server"
                Text='<%# Bind("Description") %>' />
            <br />
            <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
                CommandName="Insert" Text="Insert" />
             <asp:LinkButton ID="InsertCancelButton" runat="server"
                CausesValidation="False" CommandName="Cancel" Text="Cancel" />
        </InsertItemTemplate>
        <ItemTemplate>
            ImageID:
            <asp:Label ID="ImageIDLabel" runat="server" Text='<%# Eval("ImageID") %>' />
            <br />
            Title:
            <asp:Label ID="TitleLabel" runat="server" Text='<%# Bind("Title") %>' />
            <br />
            Description:
            <asp:Label ID="DescriptionLabel" runat="server"
                Text='<%# Bind("Description") %>' />
            <br />
            <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False"
                CommandName="Edit" Text="Edit" />
             <asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
                CommandName="Delete" Text="Delete" />
             <asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
                CommandName="New" Text="New" />
        </ItemTemplate>
    </asp:FormView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:cmsConnectionString %>"
        InsertCommand="INSERT INTO [tbimages] ([ImageID], [Title], [Description]) VALUES (ImageID, Title, Description)"
        ProviderName="<%$ ConnectionStrings:cmsConnectionString.ProviderName %>"
        SelectCommand="SELECT ImageID, Title, Description FROM tbimages"
        UpdateCommand="UPDATE [tbimages] SET [Title] = ?, [Description] = ? WHERE [ImageID] = ?">

        <InsertParameters>
            <asp:Parameter Name="ImageID" Type="Int64" />
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
            <asp:Parameter Name="ImageID" Type="Int64" />
        </UpdateParameters>
    </asp:SqlDataSource>
</code>```

i already define my connection string in the web config :

```<code>    <connectionStrings>
    <add name="cmsConnectionString" connectionString="server=localhost;User Id=root;password=123;database=cms" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
</code>```

Please if you have any idea to solve this let me know.

答: check the insert command definition of your datasource. See also: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.insertcommand.aspx</p>

Title: How query a MySQL in ASP.NET?

Body:
I am trying to link my asp.net Formview to a MySQL database, but with no success.

Take a look at my code and please tell my where is my mistake:

<asp:FormView ID="FormView1" runat="server" DataKeyNames="ImageID"
        DataSourceID="SqlDataSource1" EnableModelValidation="True">
        <EditItemTemplate>
            ImageID:
            <asp:Label ID="ImageIDLabel1" runat="server" Text='<%# Eval("ImageID") %>' />

            Title:
            <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title") %>' />

            Description:
            <asp:TextBox ID="DescriptionTextBox" runat="server"
                Text='<%# Bind("Description") %>' />

            <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
                CommandName="Update" Text="Update" />
             <asp:LinkButton ID="UpdateCancelButton" runat="server"
                CausesValidation="False" CommandName="Cancel" Text="Cancel" />
        </EditItemTemplate>
        <InsertItemTemplate>
            Title:
            <asp:TextBox ID="TitleTextBox" runat="server" Text='<%# Bind("Title") %>' />

            Description:
            <asp:TextBox ID="DescriptionTextBox" runat="server"
                Text='<%# Bind("Description") %>' />

            <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
                CommandName="Insert" Text="Insert" />
             <asp:LinkButton ID="InsertCancelButton" runat="server"
                CausesValidation="False" CommandName="Cancel" Text="Cancel" />
        </InsertItemTemplate>
        <ItemTemplate>
            ImageID:
            <asp:Label ID="ImageIDLabel" runat="server" Text='<%# Eval("ImageID") %>' />

            Title:
            <asp:Label ID="TitleLabel" runat="server" Text='<%# Bind("Title") %>' />

            Description:
            <asp:Label ID="DescriptionLabel" runat="server"
                Text='<%# Bind("Description") %>' />

            <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False"
                CommandName="Edit" Text="Edit" />
             <asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
                CommandName="Delete" Text="Delete" />
             <asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
                CommandName="New" Text="New" />
        </ItemTemplate>
    </asp:FormView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:cmsConnectionString %>"
        InsertCommand="INSERT INTO [tbimages] ([ImageID], [Title], [Description]) VALUES (ImageID, Title, Description)"
        ProviderName="<%$ ConnectionStrings:cmsConnectionString.ProviderName %>"
        SelectCommand="SELECT ImageID, Title, Description FROM tbimages"
        UpdateCommand="UPDATE [tbimages] SET [Title] = ?, [Description] = ? WHERE [ImageID] = ?">

        <InsertParameters>
            <asp:Parameter Name="ImageID" Type="Int64" />
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
            <asp:Parameter Name="ImageID" Type="Int64" />
        </UpdateParameters>
    </asp:SqlDataSource>

i already define my connection string in the web config :

    <connectionStrings>
    <add name="cmsConnectionString" connectionString="server=localhost;User Id=root;password=123;database=cms" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>

Please if you have any idea to solve this let me know.


问:
Precise definition of "functional interface" in Java 8
Recently I started exploring Java 8 and I can't quite understand the concept of "functional interface" that is essential to Java's implementation of lambda expressions. There is a pretty comprehensive guide to lambda functions in Java, but I got stuck on the chapter that gives definition to the concept of functional interfaces. The definition reads:

More precisely, a functional interface is defined as any interface that has exactly one abstract method.

An then he proceeds to examples, one of which is Comparator interface:

```<code>public interface Comparator<T> {
    int compare(T o1, T o2);
    boolean equals(Object obj);
}
</code>```

I was able to test that I can use a lambda function in place of Comparator argument and it works(i.e. Collections.sort(list, (a, b) -> a-b)).

But in the Comparator interface both compare and equals methods are abstract, which means it has two abstract methods. So how can this be working, if the definition requires an interface to have exactly one abstract method? What am I missing here?

答:
Definition:

If an interface contains only one abstract method, then such type of interface is called functional interface.

Usage:

Once we write Lambda expression "->" to invoke its functionality ,
then in this context we require Functional Interface.

We can use the Functional Interface reference to refer Lambda
expression.

Inside functional interface we can have one abstract method and n
number of default/static methods.

Functional interface with respect to inheritance:

If an interface extends Functional interface and the child interface does not contain any abstract method , then the child interface is also considered to be Functional Interface.

Functional interface is not new to java, its already used in following interface API's:

Runnable : contains run() method only.

Callable : contains call() method only.

Comparable : contains compareTo() method only.

Body:
Recently I started exploring Java 8 and I can't quite understand the concept of "functional interface" that is essential to Java's implementation of lambda expressions. There is a pretty comprehensive guide to lambda functions in Java, but I got stuck on the chapter that gives definition to the concept of functional interfaces. The definition reads:

More precisely, a functional interface is defined as any interface that has exactly one abstract method.

An then he proceeds to examples, one of which is Comparator interface:

public interface Comparator<T> {
    int compare(T o1, T o2);
    boolean equals(Object obj);
}

I was able to test that I can use a lambda function in place of Comparator argument and it works(i.e. Collections.sort(list, (a, b) -> a-b)).

But in the Comparator interface both compare and equals methods are abstract, which means it has two abstract methods. So how can this be working, if the definition requires an interface to have exactly one abstract method? What am I missing here?


问:
Dynamic Range in Excel VBA
I have a UserForm with some Checkboxes and TextFields and when I press on the "Insert" button the inputs are pasted in row 1 column A - 7.

I have the following problem:

After I press the button, I want to fill out the UserForm again and paste the data in row 2 and then 3, 4, 5, 6 and so on. Can someone tell me how I can jump dynamically to the next row and insert there the data?

My codesnippet for a checkbox is the following:

```<code>If UserForm1.eig_hand.Value = True Then
    Range("E3").Value = "Yes"
End If
</code>```

This snippet will be executed after I press the "Insert button" and it would be very helpful, when I can close and reopen the Excel file and continue in the row where I closed the file. I know that I have a static expression in the Code snippet but I'm a completly beginner in VBA

Edit:

I found a solution for my problem.
I have a counter variable in a cell for example cell(5,1) and my code looks like this:

```<code>Dim counter_var As Integer
counter_var = Cells(5, 1)
If UserForm1.eig_hand.Value = True Then
Cells(counter_var, 4).Value = "Ja"
End If
If UserForm1.eig_kmu.Value = True Then
Cells(counter_var, 5).Value = "Ja"
End If
</code>```

And at the end of my code i set the counter_var += 1.
Ty for all the replies :)

答:
Something like:</p>

```<code>Sub ButtonCode()
    Dim E2 As Range, n As Long

    Set E2 = Range("E2")

    If E2 = "" Then
        E2 = "yes"
    Else
        n = Cells(Rows.Count, "E").End(xlUp).Row + 1
        Range("E2:E" & n) = "yes"
    End If
End Sub
</code>```

Title: Dynamic Range in Excel VBA

Body:
I have a UserForm with some Checkboxes and TextFields and when I press on the "Insert" button the inputs are pasted in row 1 column A - 7.

I have the following problem:

After I press the button, I want to fill out the UserForm again and paste the data in row 2 and then 3, 4, 5, 6 and so on. Can someone tell me how I can jump dynamically to the next row and insert there the data?

My codesnippet for a checkbox is the following:

If UserForm1.eig_hand.Value = True Then
    Range("E3").Value = "Yes"
End If

This snippet will be executed after I press the "Insert button" and it would be very helpful, when I can close and reopen the Excel file and continue in the row where I closed the file. I know that I have a static expression in the Code snippet but I'm a completly beginner in VBA

Edit:

I found a solution for my problem.
I have a counter variable in a cell for example cell(5,1) and my code looks like this:

Dim counter_var As Integer
counter_var = Cells(5, 1)
If UserForm1.eig_hand.Value = True Then
Cells(counter_var, 4).Value = "Ja"
End If
If UserForm1.eig_kmu.Value = True Then
Cells(counter_var, 5).Value = "Ja"
End If

And at the end of my code i set the counter_var += 1.
Ty for all the replies :)

Body:
Something like:

Sub ButtonCode()
    Dim E2 As Range, n As Long

    Set E2 = Range("E2")

    If E2 = "" Then
        E2 = "yes"
    Else
        n = Cells(Rows.Count, "E").End(xlUp).Row + 1
        Range("E2:E" & n) = "yes"
    End If
End Sub


问:
Entity Framework many-to-many relationship error
I have two classes:

```<code>public class Cluster
{
    public int Id { get; set; }
    public virtual ICollection<Blob> Blobs { get; set; }
}

public class Blob
{
    public int Id { get; set; }
    public virtual ICollection<Cluster> Clusters { get; set; }
}

public ClusterConfiguration ()
{
    this.HasKey(p => p.Id)
        .HasRequired(p => p.Frame)
        .WithMany(p => p.Clusters)
        .HasForeignKey(p => p.FrameId)
        .WillCascadeOnDelete(true)
        ;

    this.HasMany(p => p.Blobs)
        .WithMany(p => p.Clusters)
        ;
}

public BlobConfiguration ()
{
    this.HasKey(p => p.Id)
        .HasRequired(p => p.Frame)
        .WithMany(p => p.Blobs)
        .HasForeignKey(p => p.FrameId)
        .WillCascadeOnDelete(true)
        ;

    this.HasMany(p => p.Clusters)
        .WithMany(p => p.Blobs)
        ;
}
</code>```

There are references to other tables in these classes but I do not think that is the problem. The error is:

[{"Introducing FOREIGN KEY constraint 'FK_dbo.ClusterBlobs_dbo.Blob_Blob_Id' on table 'ClusterBlobs' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.\r\nCould not create constraint. See previous errors."}].

I'm not quite sure how to tell EF to cascade delete Blobs if Clusters are deleted but not to delete Clusters if Blobs are deleted. Please advise.

UPDATE: Using EF5 by the way.

答:
I believe that turning off ManyToManyCascadeDeleteConvention globally is not a wise option. Instead, it's better to turn it off only for the concerned table.

This can be achieved through editing the generated migration file, for property cascadeDelete. For example:

AddForeignKey("dbo.ClusterBlobs", "Blob_Id", "dbo.Blob", "Blob_Id", cascadeDelete: false);

Body:
I have two classes:

public class Cluster
{
    public int Id { get; set; }
    public virtual ICollection<Blob> Blobs { get; set; }
}

public class Blob
{
    public int Id { get; set; }
    public virtual ICollection<Cluster> Clusters { get; set; }
}

public ClusterConfiguration ()
{
    this.HasKey(p => p.Id)
        .HasRequired(p => p.Frame)
        .WithMany(p => p.Clusters)
        .HasForeignKey(p => p.FrameId)
        .WillCascadeOnDelete(true)
        ;

    this.HasMany(p => p.Blobs)
        .WithMany(p => p.Clusters)
        ;
}

public BlobConfiguration ()
{
    this.HasKey(p => p.Id)
        .HasRequired(p => p.Frame)
        .WithMany(p => p.Blobs)
        .HasForeignKey(p => p.FrameId)
        .WillCascadeOnDelete(true)
        ;

    this.HasMany(p => p.Clusters)
        .WithMany(p => p.Blobs)
        ;
}

There are references to other tables in these classes but I do not think that is the problem. The error is:

[{"Introducing FOREIGN KEY constraint 'FK_dbo.ClusterBlobs_dbo.Blob_Blob_Id' on table 'ClusterBlobs' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.\r\nCould not create constraint. See previous errors."}].

I'm not quite sure how to tell EF to cascade delete Blobs if Clusters are deleted but not to delete Clusters if Blobs are deleted. Please advise.

UPDATE: Using EF5 by the way.


问:
"Unable to launch the IIS Express Web server" error
I receive this error when trying to launch IIS Express from Visual Studio with a project that's configured to listen to an address other than localhost.  Visual Studio freezes for about 30 seconds before giving the error "Unable to launch the IIS Express Web server".

I've tried all the solutions posted to similar questions and I think I've done everything correctly.  Here are the steps that I have taken:

Add the following reservation to HTTP.SYS:

netsh http add urlacl url=http://+:36899/ user=Everyone

Run Visual Studio 2012 as an administrator (technically I don't think I should even have to since I set up HTTP.SYS manually).

Disable Windows Firewall.

Delete my IISExpress folder in my My Documents folder to ensure the default settings.

Allow Visual Studio to create the entry in applicationhost.config for my web project.  Then manually edit the config file to change localhost to 192.168.0.100 which is my local IP.  Then go back into the project properties in Visual Studio and change localhost to the IP and save the project so that my project is now set to http://192.168.0.100:36899.

I also tried changing the port and repeating the above steps just incase the port was in use for some reason.

I want to make my IIS Express developer instance accessible from my IP on the Internet for remote testing.

答:
I had the same issue with my computer having loads of windows updates.

Spent few hours trying to resolve the issue using above answers with no luck.

In past we have different issues due to anti-virus which caused the application to be blocked by it, so thought to try by disabling it.


问:
StatusUpdaterBolt: Could not find unacked tuple for ID
I have a very simple topology that spouts from an ES index (AggregationSpout), fetches the pages (FetcherBolt) and uses StatusUpdaterBolt to update the ES status to "FETCHED".

However, I noticed such warnings in the log files:

[WARN] Could not find unacked tuple for 357dc2fcb59c6457884a8f7a83794c4cf77f490a3acfd849a792a35153ed4665

The corresponding debug info looks like:
...

2017-12-06 12:44:53.572 o.e.t.T.tracer
  elasticsearch[client][transport_client_boss][T#2] [TRACE]
  [214][indices:data/write/bulk] received response from
  [{ESPatentNode-1}{S4C2h8WjRuu6MpM25oM-3w}{Fvjny3VaQl2w45hPXZ5A9g}{127.0.0.1}{127.0.0.1:9300}]
  2017-12-06 12:44:53.572 c.d.s.e.p.StatusUpdaterBolt
  elasticsearch[client][listener][T#1] [DEBUG] afterBulk [105] with 47
  responses 2017-12-06 12:44:53.572 c.d.s.e.p.StatusUpdaterBolt
  elasticsearch[client][listener][T#1] [DEBUG] Acked 1 tuple(s) for ID
  5967f802c84e3e9c6ac22a3184e0665b850779cba9050fa4ec910a41f9f90655
  2017-12-06 12:44:53.573 c.d.s.e.p.StatusUpdaterBolt
  elasticsearch[client][listener][T#1] [DEBUG] Acked 2 tuple(s) for ID
  357dc2fcb59c6457884a8f7a83794c4cf77f490a3acfd849a792a35153ed4665
  2017-12-06 12:44:53.573 c.d.s.e.p.StatusUpdaterBolt
  elasticsearch[client][listener][T#1] [DEBUG] Acked 1 tuple(s) for ID
  092e59cd1ebb004884babfaf1d6ca4b7505b3dcb1b3cb3a52b9072d647fb7a93
  2017-12-06 12:44:53.573 c.d.s.e.p.StatusUpdaterBolt
  elasticsearch[client][listener][T#1] [WARN] Could not find unacked
  tuple for
  357dc2fcb59c6457884a8f7a83794c4cf77f490a3acfd849a792a35153ed4665

What I would like to understand is:

why several tuples can be attached to an ID

how it is possible to come accross twice the same "waitAck" cache element looping through "response" in the afterBulk method of StatusUpdaterBolt

Thanks in advance for your help!

答:
These warnings are pretty normal, see explanation below.

tuples will have the same ID if they have the same URL. With the log at debug level, you should see the mappings => 'Sent to ES buffer {} with ID {}'

because the status is FETCHED, the tuples are sent to ES (unlike DISCOVERED) more than once, then in the pseudo ack method we store both tuples as value with the ID in the cache. When processing the returns from ES, we get 2 different results, the first one acks both tuples the second does nothing but triggers the message you saw.

The question is why would you get the same URL more than once if all you do is fetching. That's probably worth investigating.

Thanks!


问:
How to serialize list of polymorphic objects using built_value and StandardJsonPlugin?
Given a class hierarchy of animals like in the built_value polymorphism example:

```<code>Animal
    - Cat
    - Fish
</code>```

I want to be able to (de)serialize a list of animals to JSON

```<code>class Zoo implements Built<Zoo, ZooBuilder>  {
    static Serializer<Zoo> get serializer => _$zooSerializer;
    BuiltList<Animal> animals;
}
</code>```

I would like the type of animal to be encoded in each item. For example the json output could look like:

```<code>{
"animals": [
    {"type": "cat", "legs": 2},
    {"type": "fish", "fins": 3}
]}
</code>```

答:
Edit: this question/answer are now out of date; StandardJsonPlugin now supports polymorphism out of the box, as of version 4.5.0.

StandardJsonPlugin does not currently support polymorphism. According to the docs:

```<code>/// The default serialization format is more powerful, supporting polymorphism
/// and more collection types.
</code>```

This issue, "Swagger / OpenAPI support", includes adding polymorphism support to StandardJsonPlugin:

https://github.com/google/built_value.dart/issues/92

One question: why do you need StandardJsonPlugin in the first place? If you stop using it, you have polymorphism support :)

Body:
Given a class hierarchy of animals like in the built_value polymorphism example:

Animal
    - Cat
    - Fish

I want to be able to (de)serialize a list of animals to JSON

class Zoo implements Built<Zoo, ZooBuilder>  {
    static Serializer<Zoo> get serializer => _$zooSerializer;
    BuiltList<Animal> animals;
}

I would like the type of animal to be encoded in each item. For example the json output could look like:

{
"animals": [
    {"type": "cat", "legs": 2},
    {"type": "fish", "fins": 3}
]}

Body:
Edit: this question/answer are now out of date; StandardJsonPlugin now supports polymorphism out of the box, as of version 4.5.0.

StandardJsonPlugin does not currently support polymorphism. According to the docs:

/// The default serialization format is more powerful, supporting polymorphism
/// and more collection types.

This issue, "Swagger / OpenAPI support", includes adding polymorphism support to StandardJsonPlugin:

https://github.com/google/built_value.dart/issues/92

One question: why do you need StandardJsonPlugin in the first place? If you stop using it, you have polymorphism support :)


问:
How can I extract a filename from a path using Perl?
I have a Perl variable I populate from the database. Its name is $path. I need to get another variable $file which has just the filename from the pathname.

I tried:

```<code>$file = $path =~ s/.*\///;
</code>```

I am very new to Perl.

答:
```<code>use File::Basename
</code>```

Check the below link for a detailed description on how it works:

http://p3rl.org/File::Basename

Body:
I have a Perl variable I populate from the database. Its name is $path. I need to get another variable $file which has just the filename from the pathname.

I tried:

$file = $path =~ s/.*\///;

I am very new to Perl.

Body:
use File::Basename

Check the below link for a detailed description on how it works:

http://p3rl.org/File::Basename


问:
Embedding Google Photos album to HTML
I have an images slideshow that is based on a Picasa widget.

A few months ago Picasa stopped working and everything moved to Google Photos & Google Drive.

Iv'e searched the web for a compatible widget that will corporate with Google Photos without any luck.

I'm looking for such (simple) widget that works with Google Photos for showing my images as a slideshow.

Any suggestions?

答:
I was just looking for a way to do this myself and found that the easiest way would be using Google Drive to store the photos instead and then embedding them with HTML as per the instructions here:
https://confluence.biola.edu/display/itservices/How+to+Embed+Images+from+Google+Drive+in+a+Web+Page

It may need some styling or free source code to look like a slideshow (or copy part of the iframe code from YouTube's embed button perhaps?)

Title: Embedding Google Photos album to HTML