问:
When adhering to Liskov Substitution Principle (LSP) can a child class implement additional interface?
Consider this ruby example

```<code>class Animal
  def walk
     # In our universe all animals walk, even whales
     puts "walking"
  end

  def run
    # Implementing to conform to LSP, even though only some animals run
    raise NotImplementedError
  end
end

class Cat < Animal
  def run
    # Dogs run differently, and Whales, can't run at all
    puts "running like a cat"
  end

  def sneer_majesticly
    # Only cats can do this.
    puts "meh"
  end
end
</code>```

Does method sneer_majesticly violate LSP, being defined only on Cat, since this interfaces is not implemented nor needed on Animal?

答:
The Liskov Substitution Principle has nothing to do with classes. It is about types. Ruby doesn't have types as a language feature, so it doesn't really make sense to talk about them in terms of language features.

In Ruby (and OO in general), types are basically protocols. Protocols describe which messages an object responds to, and how it responds to them. For example, one well-known protocol in Ruby is the iteration protocol, which consists of a single message each which takes a block, but no positional or keyword arguments and yields elements sequentially to the block. Note that there is no class or mixin corresponding to this protocol. There is no way for an object which conforms to this protocol to declare so.

There is a mixin which depends on this protocol, namely Enumerable. Again, since there is no Ruby construct which corresponds to the notion of "protocol", there is no way for Enumerable to declare this dependency. It is only mentioned in the introductory paragraph of the documentation (bold emphasis mine):

The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection.

That's it.

Protocols and types don't exist in Ruby. They do exist in Ruby documentation, in the Ruby community, in the heads of Ruby programmers, and in implicit assumptions in Ruby code, but they are never manifest in the code.

So, talking about the LSP in terms of Ruby classes makes no sense (because classes aren't types), but talking about the LSP in terms of Ruby types makes little sense either (because there are no types). You can only talk about the LSP in terms of the types in your head (because there aren't any in your code).

Okay, rant over. But that is really, really, really, REALLY important. The LSP is about types. Classes aren't types. There are languages like C++, Java, or C♯, where all classes are also automatically types, but even in those languages it is important to separate the notion of a type (which is a specification of rules and constraints) from the notion of a class (which is a template for the state and behavior of objects), if only because there are other things besides classes which are types in those languages as well (e.g. interfaces in Java and C♯ and primitives in Java). In fact, the interface in Java is a direct port of the protocol from Objective-C, which in turn comes from the Smalltalk community.

Phew. So, unfortunately none of this answers your question :-D

What, exactly, does the LSP mean? The LSP talks about subtyping. More precisely, it defines a (at the time it was invented) new notion of subtyping which is based on behaviorial substitutability. Very simply, the LSP says:

I can replace objects of type T with objects of type S <: T without changing the desirable properties of the program.

For example, "the program does not crash" is a desirable property, so I should not be able to make a program crash by replacing objects of a supertype with objects of a subtype. Or you can also view it from the other direction: if I can violate a desirable property of a program (e.g. make the program crash) by replacing an object of type T with an object of type S, then S is not a subtype of T.

There are a couple of rules we can follow to make sure that we don't violate the LSP:

Method parameter types are contravariant, i.e. if you override a method, the overriding method in the subtype must accept parameters of the same types or more general types as the overridden method.

Method return types are covariant, i.e. the overriding method in a subtype must return the same type or a more specific type as the overridden method.

These two rules are just the standard subtyping rules for functions, they were known long before Liskov.

Methods in subtypes must not raise any new exceptions that are not only raised by the overridden method in the supertype, except for exceptions whose types are themselves subtypes of the exceptions raised by the overridden method.

These three rules are static rules restricting the signature of methods. The key innovation of Liskov were the four behavioral rules, in particular the fourth rule ("History Rule"):

Preconditions cannot be strengthened in a subtype, i.e. if you replace an object with a subtype, you cannot impose additional restrictions on the caller, since the caller doesn't know about them.

Postconditions cannot be weakened in a subtype, i.e. you cannot relax guarantees that the supertype makes, since the caller may rely on them.

Invariants must be preserved, i.e. if the supertype guarantees that something will always be true, then it must also always be true in the subtype.

History Rule: Manipulating the object of a subtype must not create a history that is impossible to observe from objects of the supertype. (This one is a bit tricky, it means the following: if I observe an object of type S only through methods of type T, I should not be able to put the object in a state such that the observer sees a state that would not be possible with an object of type T, even if I use methods of S to manipulate it.)

The first three rules were known before Liskov, but they were formulated in a proof-theoretical manner which didn't take aliasing into account. The behavioral formulation of the rules, and the addition of the History Rule make the LSP applicable to modern OO languages.

Here is another way to look at the LSP: if I have an inspector who only knows and cares about T, and I hand him an object of type S, will he be able to spot that it is a "counterfeit" or can I fool him?

Okay, finally to your question: does adding the sneer_majesticly method violate the LSP? And the answer is: No. The only way that adding a new method can violate LSP is if this new method manipulates old state in such a way that is impossible to happen using only old methods. Since sneer_majesticly doesn't manipulate any state, adding it cannot possibly violate LSP. Remember: our inspector only knows about Animal, i.e. he only knows about walk and run. He doesn't know or care about sneer_majesticly.

If, OTOH, you were adding a method bite_off_foot after which the cat can no longer walk, then you violate LSP, because by calling bite_off_foot, the inspector can, by only using the methods he knows about (walk and run) observe a situation that is impossible to observe with an animal: animals can always walk, but our cat suddenly can't!

However! run could theoretically violate LSP. Remember: objects of a subtype cannot change desirable properties of the supertype. Now, the question is: what are the desirable properties of Animal? The problem is that you have not provided any documentation for Animal, so we have no idea what its desirable properties are. The only thing we can look at, is the code, which always raises a NotImplementedError (which BTW will actually raise a NameError, since there is no constant named NotImplementedError in the Ruby core library). So, the question is: is the raiseing of the exception part of the desirable properties or not? Without documentation, we cannot tell.

If Animal were defined like this:

```<code>class Animal
  # …

  # Makes the animal run.
  #
  # @return [void]
  # @raise [NotImplementedError] if the animal can't run
  def run
    raise NotImplementedError
  end
end
</code>```

Then it would not be an LSP violation.

However, if Animal were defined like this:

```<code>class Animal
  # …

  # Animals can't run.
  #
  # @return [never]
  # @raise [NotImplementedError] because animals never run
  def run
    raise NotImplementedError
  end
end
</code>```

Then it would be an LSP violation.

In other words: if the specification for run is "always raises an exception", then our inspector can spot a cat by calling run and observing that it doesn't raise an exception. However, if the specification for run is "makes the animal run or else raises an exception", then our inspector can not differentiate a cat from an animal.

You will note that whether or not Cat violates the LSP in this example is actually completely independent of Cat! And it is in fact also completely independent of the code inside Animal! It only depends on the documentation. That is because of what I tried to make clear in the very beginning: the LSP is about types. Ruby doesn't have types, so the types only exist in the programmer's head. Or in this example: in documentation comments.

Body:
Consider this ruby example

class Animal
  def walk
     # In our universe all animals walk, even whales
     puts "walking"
  end

  def run
    # Implementing to conform to LSP, even though only some animals run
    raise NotImplementedError
  end
end

class Cat < Animal
  def run
    # Dogs run differently, and Whales, can't run at all
    puts "running like a cat"
  end

  def sneer_majesticly
    # Only cats can do this.
    puts "meh"
  end
end

Does method sneer_majesticly violate LSP, being defined only on Cat, since this interfaces is not implemented nor needed on Animal?

Body:
The Liskov Substitution Principle has nothing to do with classes. It is about types. Ruby doesn't have types as a language feature, so it doesn't really make sense to talk about them in terms of language features.

In Ruby (and OO in general), types are basically protocols. Protocols describe which messages an object responds to, and how it responds to them. For example, one well-known protocol in Ruby is the iteration protocol, which consists of a single message each which takes a block, but no positional or keyword arguments and yields elements sequentially to the block. Note that there is no class or mixin corresponding to this protocol. There is no way for an object which conforms to this protocol to declare so.

There is a mixin which depends on this protocol, namely Enumerable. Again, since there is no Ruby construct which corresponds to the notion of "protocol", there is no way for Enumerable to declare this dependency. It is only mentioned in the introductory paragraph of the documentation (bold emphasis mine):

The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection.

That's it.

Protocols and types don't exist in Ruby. They do exist in Ruby documentation, in the Ruby community, in the heads of Ruby programmers, and in implicit assumptions in Ruby code, but they are never manifest in the code.

So, talking about the LSP in terms of Ruby classes makes no sense (because classes aren't types), but talking about the LSP in terms of Ruby types makes little sense either (because there are no types). You can only talk about the LSP in terms of the types in your head (because there aren't any in your code).

Okay, rant over. But that is really, really, really, REALLY important. The LSP is about types. Classes aren't types. There are languages like C++, Java, or C♯, where all classes are also automatically types, but even in those languages it is important to separate the notion of a type (which is a specification of rules and constraints) from the notion of a class (which is a template for the state and behavior of objects), if only because there are other things besides classes which are types in those languages as well (e.g. interfaces in Java and C♯ and primitives in Java). In fact, the interface in Java is a direct port of the protocol from Objective-C, which in turn comes from the Smalltalk community.

Phew. So, unfortunately none of this answers your question :-D

What, exactly, does the LSP mean? The LSP talks about subtyping. More precisely, it defines a (at the time it was invented) new notion of subtyping which is based on behaviorial substitutability. Very simply, the LSP says:

I can replace objects of type T with objects of type S <: T without changing the desirable properties of the program.

For example, "the program does not crash" is a desirable property, so I should not be able to make a program crash by replacing objects of a supertype with objects of a subtype. Or you can also view it from the other direction: if I can violate a desirable property of a program (e.g. make the program crash) by replacing an object of type T with an object of type S, then S is not a subtype of T.

There are a couple of rules we can follow to make sure that we don't violate the LSP:

Method parameter types are contravariant, i.e. if you override a method, the overriding method in the subtype must accept parameters of the same types or more general types as the overridden method.

Method return types are covariant, i.e. the overriding method in a subtype must return the same type or a more specific type as the overridden method.

These two rules are just the standard subtyping rules for functions, they were known long before Liskov.

Methods in subtypes must not raise any new exceptions that are not only raised by the overridden method in the supertype, except for exceptions whose types are themselves subtypes of the exceptions raised by the overridden method.

These three rules are static rules restricting the signature of methods. The key innovation of Liskov were the four behavioral rules, in particular the fourth rule ("History Rule"):

Preconditions cannot be strengthened in a subtype, i.e. if you replace an object with a subtype, you cannot impose additional restrictions on the caller, since the caller doesn't know about them.

Postconditions cannot be weakened in a subtype, i.e. you cannot relax guarantees that the supertype makes, since the caller may rely on them.

Invariants must be preserved, i.e. if the supertype guarantees that something will always be true, then it must also always be true in the subtype.

History Rule: Manipulating the object of a subtype must not create a history that is impossible to observe from objects of the supertype. (This one is a bit tricky, it means the following: if I observe an object of type S only through methods of type T, I should not be able to put the object in a state such that the observer sees a state that would not be possible with an object of type T, even if I use methods of S to manipulate it.)

The first three rules were known before Liskov, but they were formulated in a proof-theoretical manner which didn't take aliasing into account. The behavioral formulation of the rules, and the addition of the History Rule make the LSP applicable to modern OO languages.

Here is another way to look at the LSP: if I have an inspector who only knows and cares about T, and I hand him an object of type S, will he be able to spot that it is a "counterfeit" or can I fool him?

Okay, finally to your question: does adding the sneer_majesticly method violate the LSP? And the answer is: No. The only way that adding a new method can violate LSP is if this new method manipulates old state in such a way that is impossible to happen using only old methods. Since sneer_majesticly doesn't manipulate any state, adding it cannot possibly violate LSP. Remember: our inspector only knows about Animal, i.e. he only knows about walk and run. He doesn't know or care about sneer_majesticly.

If, OTOH, you were adding a method bite_off_foot after which the cat can no longer walk, then you violate LSP, because by calling bite_off_foot, the inspector can, by only using the methods he knows about (walk and run) observe a situation that is impossible to observe with an animal: animals can always walk, but our cat suddenly can't!

However! run could theoretically violate LSP. Remember: objects of a subtype cannot change desirable properties of the supertype. Now, the question is: what are the desirable properties of Animal? The problem is that you have not provided any documentation for Animal, so we have no idea what its desirable properties are. The only thing we can look at, is the code, which always raises a NotImplementedError (which BTW will actually raise a NameError, since there is no constant named NotImplementedError in the Ruby core library). So, the question is: is the raiseing of the exception part of the desirable properties or not? Without documentation, we cannot tell.

If Animal were defined like this:

class Animal
  # …

  # Makes the animal run.
  #
  # @return [void]
  # @raise [NotImplementedError] if the animal can't run
  def run
    raise NotImplementedError
  end
end

Then it would not be an LSP violation.

However, if Animal were defined like this:

class Animal
  # …

  # Animals can't run.
  #
  # @return [never]
  # @raise [NotImplementedError] because animals never run
  def run
    raise NotImplementedError
  end
end

Then it would be an LSP violation.

In other words: if the specification for run is "always raises an exception", then our inspector can spot a cat by calling run and observing that it doesn't raise an exception. However, if the specification for run is "makes the animal run or else raises an exception", then our inspector can not differentiate a cat from an animal.

You will note that whether or not Cat violates the LSP in this example is actually completely independent of Cat! And it is in fact also completely independent of the code inside Animal! It only depends on the documentation. That is because of what I tried to make clear in the very beginning: the LSP is about types. Ruby doesn't have types, so the types only exist in the programmer's head. Or in this example: in documentation comments.


来源: stackexchange

问:
What's the quickest way to assign a variables based on an array?
What's the quickest way, from a readability/typing standpoint, to assign a value to a specific variable based on a related variable?

```<code>var abbrev;

if(state=='Pennsylvania'){
    abbrev='PA';
}else if(state=='New Jersey'){
    abbrev='NJ';
}else if(state=='Delaware'){
    abbrev='DE';
}
//and so on...
</code>```

I'm trying to avoid making one array for the state name and a another array for the abbreviation because the relationship is lost with separate declarations.

答: just a suggestion, have you tried using CASE? it looks more clean and readable</p>

ContentLicense: CC BY-SA 3.0

Body:
What's the quickest way, from a readability/typing standpoint, to assign a value to a specific variable based on a related variable?

var abbrev;

if(state=='Pennsylvania'){
    abbrev='PA';
}else if(state=='New Jersey'){
    abbrev='NJ';
}else if(state=='Delaware'){
    abbrev='DE';
}
//and so on...

I'm trying to avoid making one array for the state name and a another array for the abbreviation because the relationship is lost with separate declarations.


问:
Finding a dynamically added control on an aspx page
I have an asp page "A" and I've created a user control "B"

When I do A.Controls.Add(B), I would like to make an element, say a TableRow which is defined inside control "B", invisible via code behind.

When looking through Controls of "A", I cannot seem to find that table row.

Any hints?

I'm sure it is something really simple I'm missing.

Thank you.

答:
you can use the FindControl method from Page to find a specific control by its Id,
I'm not sure if you want to find that UserControl 'A' you've added or a control inside it, you should be able to use the same method to find the control inside as long as you know the Id and if this table row was declared through the xml, it has the runat="server" attribute set.

hope it helps!

ContentLicense: CC BY-SA 2.5


问:
Web Config Connection Setting
I heve designed a website in which every pages are given connection with SQL server by writing the codes in each page....Can anybody helps me out to do this job only in the web config file at once...

Thanks in advance..!

答:
In web.config file </p>

```<code>    <add name="ConnectionString" connectionString="server=(local);
database=DbName; uid=*username*; password=*password*;"
providerName="System.Data.SqlClient" />
</code>```

Title: Web Config Connection Setting

Body:
In web.config file

    <add name="ConnectionString" connectionString="server=(local);
database=DbName; uid=*username*; password=*password*;"
providerName="System.Data.SqlClient" />


问:
issue with angular2 routing
i have an issue using Angular2 routings , i build an application with three buttons , each button takes me to a specific route.
This is my app-routing.module page :

/***** importation Components****/
import {NgModule} from '@angular/core';

import {DashboardComponent} from './dashboard/dashboard.component';
import {PlayersComponent} from './players/players.component';
import {PlayerDetailsComponent} from './player-details/player-details.component';
import {RouterModule,Routes} from '@angular/router';

const routes : Routes=[
{ path : '',redirectTo:'dashboard',pathMatch: 'full'},
{ path: 'dashboard',component:DashboardComponent},
{ path: 'players',component:PlayersComponent},
{ path: 'detail/:id',component:PlayerDetailsComponent}

] ;

@NgModule({
   imports: [ RouterModule.forRoot(routes) ],
     exports: [ RouterModule ]

})
export class AppRoutingModule {}```
</div>
</div>
</p>

<p>This is my app.component.html page that containes the buttons :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="nav nav-pills nav-justified" >
   <li class="element" role="presentation"  >Dashboard</li>
  <li class="element" role="presentation" >Players</li>
  <li class="element" role="presentation" >Statistics</li>
</ul>
<router-outlet></router-outlet></code>```

My app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
/***********Importation Components********************/
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { PlayersComponent } from './players/players.component';
import { PlayerDetailsComponent } from './player-details/player-details.component';

/*****Importaion Service*******************************/
import {PlayerService} from './player.service';
/**** Importation fichier routing**************/
import {AppRoutingModule} from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    PlayersComponent,
    PlayerDetailsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [PlayerService],
  bootstrap: [AppComponent]
})
export class AppModule { }```
</div>
</div>
</p>

<p>and when i click a button it dosen't take me to component i want , On the other hand if i type the path in adress bar it take me to the component adequate .
i guess my routing version is this : </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"scripts": {},
  "typings": "./router.d.ts",
  "version": "4.1.3"
}</code>```

EDIT :
i found out that after removing recent updates i have done the routing starts working again.
Those are my 2 pages i have updated.
dashboard.component.html

import { Component, OnInit } from '@angular/core';
import {Player} from '../player';
import {PlayerService} from '../player.service';
import {Router} from '@angular/router';
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  players : Player[] = [];
 bestPlayer:Player;
 data:Player[];

max:number =0;
  constructor(private playerService : PlayerService ,private router: Router) { }

  ngOnInit() {

   this.playerService.getPlayers()
   .then(players=> this.players = players);
    this.data=this.playerService.getDatas();
  for (var i = 0; i <= this.data.length; i++) {
    if (this.data[i].likes>this.max) {
      this.max=this.data[i].likes;
      this.bestPlayer=this.data[i];

     }
  }

    }
    viewDetails(bestPlayer: Player):void{
      this.router.navigate(['/detail',this.bestPlayer.id]);

    }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container well-sm bloc" >
 <div class="row"><h1 style="font-family: 'Lobster', cursive;color: white"><span class="glyphicon glyphicon-star" style="color: #FFC153"></span> Player of the week is </h1> </div>
 <div >
 <h2>{{bestPlayer.name}} <span class="badge badge1">{{bestPlayer.number}}</span></h2>
 <h2>with : {{max}} Likes <span class="glyphicon glyphicon-heart " style="color: red"></span></h2>
 <br><button class="btn btn-success" (click)="viewDetails(bestPlayer)">View player details</button>
 </div>

</div></code>```

答:
try with:

In app.component.html

```<code><a [routerLink]="['dashboard']">Dashboard</a>
<a [routerLink]="['players']">Players</a>
<router-outlet></router-outlet>
</code>```

router config

```<code>const routes : Routes=[
{ path : '',redirectTo:'dashboard',pathMatch: 'full'},
{ path: 'dashboard',component:DashboardComponent},
{ path: 'players',component:PlayersComponent},
{ path: 'detail/:id',component:PlayerDetailsComponent}

] ;

@NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]

})
export class AppRoutingModule {}

import {AppRoutingModule} from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    PlayersComponent,
    PlayerDetailsComponent
  ],
  imports: [
    AppRoutingModule,
    BrowserModule,
    FormsModule,
    HttpModule,

  ],
  providers: [PlayerService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Be careful: you can only call RouterModule.forRoot() once. It seems that you have to calls of this function in your app

Title: issue with angular2 routing

Body:
i have an issue using Angular2 routings , i build an application with three buttons , each button takes me to a specific route.
This is my app-routing.module page :

/***** importation Components****/
import {NgModule} from '@angular/core';

import {DashboardComponent} from './dashboard/dashboard.component';
import {PlayersComponent} from './players/players.component';
import {PlayerDetailsComponent} from './player-details/player-details.component';
import {RouterModule,Routes} from '@angular/router';

const routes : Routes=[
{ path : '',redirectTo:'dashboard',pathMatch: 'full'},
{ path: 'dashboard',component:DashboardComponent},
{ path: 'players',component:PlayersComponent},
{ path: 'detail/:id',component:PlayerDetailsComponent}

] ;

@NgModule({
   imports: [ RouterModule.forRoot(routes) ],
     exports: [ RouterModule ]

})
export class AppRoutingModule {}

This is my app.component.html page that containes the buttons :

Dashboard

Players

Statistics

<router-outlet></router-outlet>

My app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
/***********Importation Components********************/
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { PlayersComponent } from './players/players.component';
import { PlayerDetailsComponent } from './player-details/player-details.component';

/*****Importaion Service*******************************/
import {PlayerService} from './player.service';
/**** Importation fichier routing**************/
import {AppRoutingModule} from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    PlayersComponent,
    PlayerDetailsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [PlayerService],
  bootstrap: [AppComponent]
})
export class AppModule { }

and when i click a button it dosen't take me to component i want , On the other hand if i type the path in adress bar it take me to the component adequate .
i guess my routing version is this :

"scripts": {},
  "typings": "./router.d.ts",
  "version": "4.1.3"
}

EDIT :
i found out that after removing recent updates i have done the routing starts working again.
Those are my 2 pages i have updated.
dashboard.component.html

import { Component, OnInit } from '@angular/core';
import {Player} from '../player';
import {PlayerService} from '../player.service';
import {Router} from '@angular/router';
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  players : Player[] = [];
 bestPlayer:Player;
 data:Player[];

max:number =0;
  constructor(private playerService : PlayerService ,private router: Router) { }

  ngOnInit() {

   this.playerService.getPlayers()
   .then(players=> this.players = players);
    this.data=this.playerService.getDatas();
  for (var i = 0; i <= this.data.length; i++) {
    if (this.data[i].likes>this.max) {
      this.max=this.data[i].likes;
      this.bestPlayer=this.data[i];

     }
  }

    }
    viewDetails(bestPlayer: Player):void{
      this.router.navigate(['/detail',this.bestPlayer.id]);

    }

}

 Player of the week is

{{bestPlayer.name}} {{bestPlayer.number}}

with : {{max}} Likes

<button class="btn btn-success" (click)="viewDetails(bestPlayer)">View player details</button>

Body:
try with:

In app.component.html

<a [routerLink]="['dashboard']">Dashboard</a>
<a [routerLink]="['players']">Players</a>
<router-outlet></router-outlet>

router config

const routes : Routes=[
{ path : '',redirectTo:'dashboard',pathMatch: 'full'},
{ path: 'dashboard',component:DashboardComponent},
{ path: 'players',component:PlayersComponent},
{ path: 'detail/:id',component:PlayerDetailsComponent}

] ;

@NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]

})
export class AppRoutingModule {}

import {AppRoutingModule} from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    PlayersComponent,
    PlayerDetailsComponent
  ],
  imports: [
    AppRoutingModule,
    BrowserModule,
    FormsModule,
    HttpModule,

  ],
  providers: [PlayerService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Be careful: you can only call RouterModule.forRoot() once. It seems that you have to calls of this function in your app


问:
Start/Stop mule flow programmatically
I keep one of my flow say 'flow A' in "stopped" as a initial state. Then in another flow say 'flow B', using groovy script or MEL expression; I am starting the same 'flow A'. At the end of the 'flow A', I am programmatically stopping the flow.

Now, If I again start the 'flow A' through 'flow B' it fails saying 'flow A' is already started; can not be restarted.

Any solution for this.

I want to start my flow any time I want, keeping initial state as stopped & again at the end stopping the flow using script.

Here is the code:

```<code><flow name="FlowB">
    <poll doc:name="Poll">
        <logger level="INFO" doc:name="Logger"/>
    </poll>
    <logger level="INFO" doc:name="Logger" message="triggered"/>
    <scripting:component doc:name="Groovy">
        <scripting:script engine="Groovy"><![CDATA[muleContext.registry.lookupFlowConstruct('FlowB').start()]]></scripting:script>
    </scripting:component>
    <logger level="INFO" doc:name="Logger"/>
    <expression-component doc:name="Expression"><![CDATA[app.registry.FlowA.stop();]]></expression-component>
</flow>
<flow name="FlowA" initialState="stopped">
    <sqs:receive-messages config-ref="Amazon_SQS__Configuration" doc:name="Amazon SQS (Streaming)"/>
    <logger level="INFO" doc:name="Logger"/>
</flow>
</code>```

I am using poller to start the flow A. So, if I again run the flow B to start the flow A; Its throwing an exception.

答:
This is quite simple to handle and in a very easy way. You can use If else condition to control that. If the FlowA is already started it will ignore else it will start as following.

```<code>  <flow name="flowA" initialState="stopped">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/flowA" doc:name="HTTP"/>
        <logger message="In flow A" level="INFO" doc:name="Logger"/>
    </flow>

    <flow name="flowB">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/flowB" doc:name="HTTP"/>
        <scripting:component>
    <scripting:script engine="groovy">
    if(muleContext.registry.lookupFlowConstruct('flowA').isStarted())
    {
    System.out.println("flowA already started ... ignoring and do nothing")
    }
    else
    {
      muleContext.registry.lookupFlowConstruct('flowA').start()
     }
    </scripting:script>
</scripting:component>
    </flow>
</code>```

UPDATE

```<code><flow name="FlowB">
    <poll doc:name="Poll">
        <fixed-frequency-scheduler frequency="3000" />
        <logger level="INFO" doc:name="Logger" message="FlowB" />
    </poll>
    <logger message="test" level="INFO" doc:name="Logger" />

    <scripting:component doc:name="Script">
        <scripting:script engine="groovy"><![CDATA[
if(muleContext.registry.lookupFlowConstruct('FlowA').isStarted())
{
System.out.println("flowA already started ... ignoring and do nothing")
}
else
{
  muleContext.registry.lookupFlowConstruct('FlowA').start()
 }]]>
        </scripting:script>
    </scripting:component>

    <flow-ref name="FlowA" doc:name="FlowA" />
    <expression-component doc:name="Expression"><![CDATA[app.registry.FlowA.stop();]]></expression-component>
</flow>

<flow name="FlowA" initialState="stopped">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP" />
    <logger level="INFO" doc:name="Logger" message="In flowA" />
</flow>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Start/Stop mule flow programmatically

Body:
I keep one of my flow say 'flow A' in "stopped" as a initial state. Then in another flow say 'flow B', using groovy script or MEL expression; I am starting the same 'flow A'. At the end of the 'flow A', I am programmatically stopping the flow.

Now, If I again start the 'flow A' through 'flow B' it fails saying 'flow A' is already started; can not be restarted.

Any solution for this.

I want to start my flow any time I want, keeping initial state as stopped & again at the end stopping the flow using script.

Here is the code:

<flow name="FlowB">
    <poll doc:name="Poll">
        <logger level="INFO" doc:name="Logger"/>
    </poll>
    <logger level="INFO" doc:name="Logger" message="triggered"/>

    </scripting:component>
    <logger level="INFO" doc:name="Logger"/>
    <expression-component doc:name="Expression"><![CDATA[app.registry.FlowA.stop();]]></expression-component>
</flow>
<flow name="FlowA" initialState="stopped">
    <sqs:receive-messages config-ref="Amazon_SQS__Configuration" doc:name="Amazon SQS (Streaming)"/>
    <logger level="INFO" doc:name="Logger"/>
</flow>

I am using poller to start the flow A. So, if I again run the flow B to start the flow A; Its throwing an exception.

Body:
This is quite simple to handle and in a very easy way. You can use If else condition to control that. If the FlowA is already started it will ignore else it will start as following.

  <flow name="flowA" initialState="stopped">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/flowA" doc:name="HTTP"/>
        <logger message="In flow A" level="INFO" doc:name="Logger"/>
    </flow>

    <flow name="flowB">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/flowB" doc:name="HTTP"/>
        <scripting:component>
    <scripting:script engine="groovy">
    if(muleContext.registry.lookupFlowConstruct('flowA').isStarted())
    {
    System.out.println("flowA already started ... ignoring and do nothing")
    }
    else
    {
      muleContext.registry.lookupFlowConstruct('flowA').start()
     }
    </scripting:script>
</scripting:component>
    </flow>

UPDATE

<flow name="FlowB">
    <poll doc:name="Poll">
        <fixed-frequency-scheduler frequency="3000" />
        <logger level="INFO" doc:name="Logger" message="FlowB" />
    </poll>
    <logger message="test" level="INFO" doc:name="Logger" />

    <scripting:component doc:name="Script">
        <scripting:script engine="groovy"><![CDATA[
if(muleContext.registry.lookupFlowConstruct('FlowA').isStarted())
{
System.out.println("flowA already started ... ignoring and do nothing")
}
else
{
  muleContext.registry.lookupFlowConstruct('FlowA').start()
 }]]>
        </scripting:script>
    </scripting:component>

    <flow-ref name="FlowA" doc:name="FlowA" />
    <expression-component doc:name="Expression"><![CDATA[app.registry.FlowA.stop();]]></expression-component>
</flow>

<flow name="FlowA" initialState="stopped">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP" />
    <logger level="INFO" doc:name="Logger" message="In flowA" />
</flow>


问:
How to flip a UIView around the x-axis while simultaneously switching subviews
This question has been asked before but in a slightly different way and I was unable to get any of the answers to work the way I wanted, so I am hoping somebody with great Core Animation skills can help me out.

I have a set of cards on a table. As the user swipes up or down the set of cards move up and down the table. There are 4 cards visible on the screen at any given time, but only the second card is showing its face. As the user swipes the second card flips back onto its face and the next card (depending on the swipe direction) lands in it's place showing its face.

I have set up my card view class like this:

```<code>@interface WLCard : UIView {
    UIView *_frontView;
    UIView *_backView;
    BOOL flipped;
}
</code>```

And I have tried flipping the card using this piece of code:

```<code>- (void) flipCard {
    [self.flipTimer invalidate];
    if (flipped){
        return;
    }

    id animationsBlock = ^{
            self.backView.alpha = 1.0f;
            self.frontView.alpha = 0.0f;
            [self bringSubviewToFront:self.frontView];
            flipped = YES;

            CALayer *layer = self.layer;
            CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
            rotationAndPerspectiveTransform.m34 = 1.0 / 500;
            rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, M_PI, 1.0f, 0.0f, 0.0f);
            layer.transform = rotationAndPerspectiveTransform;
    };
    [UIView animateWithDuration:0.25
                          delay:0.0
                        options: UIViewAnimationCurveEaseInOut
                     animations:animationsBlock
                     completion:nil];

}
</code>```

This code works but it has the following problems with it that I can't seem to figure out:

Only half of the card across the x-axis is animated.

Once flipped, the face of the card is upside down and mirrored.

Once I've flipped the card I cannot get the animation to ever run again. In other words, I can run the animation block as many times as I want, but only the first time will animate. The subsequent times I try to animate lead to just a fade in and out between the subviews.

Also, bear in mind that I need to be able to interact with the face of the card. i.e. it has buttons on it.

If anybody has run into these issues it would be great to see your solutions. Even better would be to add a perspective transform to the animation to give it that extra bit of realism.

答:
Based on Paul.s this is updated for Swift 3 and will flip a card diagonally:

```<code>func createLayers(){
  transformationLayer = CATransformLayer(layer: CALayer())
  transformationLayer.frame = CGRect(x: 15, y: 100, width: view.frame.width - 30, height: view.frame.width - 30)

  let black = CALayer()
  black.zPosition = 2
  black.frame = transformationLayer.bounds
  black.backgroundColor = UIColor.black.cgColor

  transformationLayer.addSublayer(black)

  let blue = CALayer()
  blue.frame = transformationLayer.bounds
  blue.zPosition = 1
  blue.backgroundColor = UIColor.blue.cgColor

  transformationLayer.addSublayer(blue)

  let tgr = UITapGestureRecognizer(target: self, action: #selector(recTap))
  view.addGestureRecognizer(tgr)
  view.layer.addSublayer(transformationLayer)
}
</code>```

Animate a full 360 but since the layers have different zPositions the different 'sides' of the layers will show

```<code>func recTap(){
    let animation = CABasicAnimation(keyPath: "transform")
    animation.delegate = self
    animation.duration = 2.0
    animation.fillMode = kCAFillModeForwards
    animation.isRemovedOnCompletion = false
    animation.toValue = NSValue(caTransform3D: CATransform3DMakeRotation(CGFloat(Float.pi), 1, -1, 0))
    transformationLayer.add(animation, forKey: "arbitrarykey")
  }
</code>```

Body:
This question has been asked before but in a slightly different way and I was unable to get any of the answers to work the way I wanted, so I am hoping somebody with great Core Animation skills can help me out.

I have a set of cards on a table. As the user swipes up or down the set of cards move up and down the table. There are 4 cards visible on the screen at any given time, but only the second card is showing its face. As the user swipes the second card flips back onto its face and the next card (depending on the swipe direction) lands in it's place showing its face.

I have set up my card view class like this:

@interface WLCard : UIView {
    UIView *_frontView;
    UIView *_backView;
    BOOL flipped;
}

And I have tried flipping the card using this piece of code:

- (void) flipCard {
    [self.flipTimer invalidate];
    if (flipped){
        return;
    }

    id animationsBlock = ^{
            self.backView.alpha = 1.0f;
            self.frontView.alpha = 0.0f;
            [self bringSubviewToFront:self.frontView];
            flipped = YES;

            CALayer *layer = self.layer;
            CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
            rotationAndPerspectiveTransform.m34 = 1.0 / 500;
            rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, M_PI, 1.0f, 0.0f, 0.0f);
            layer.transform = rotationAndPerspectiveTransform;
    };
    [UIView animateWithDuration:0.25
                          delay:0.0
                        options: UIViewAnimationCurveEaseInOut
                     animations:animationsBlock
                     completion:nil];

}

This code works but it has the following problems with it that I can't seem to figure out:

Only half of the card across the x-axis is animated.

Once flipped, the face of the card is upside down and mirrored.

Once I've flipped the card I cannot get the animation to ever run again. In other words, I can run the animation block as many times as I want, but only the first time will animate. The subsequent times I try to animate lead to just a fade in and out between the subviews.

Also, bear in mind that I need to be able to interact with the face of the card. i.e. it has buttons on it.

If anybody has run into these issues it would be great to see your solutions. Even better would be to add a perspective transform to the animation to give it that extra bit of realism.

Body:
Based on Paul.s this is updated for Swift 3 and will flip a card diagonally:

func createLayers(){
  transformationLayer = CATransformLayer(layer: CALayer())
  transformationLayer.frame = CGRect(x: 15, y: 100, width: view.frame.width - 30, height: view.frame.width - 30)

  let black = CALayer()
  black.zPosition = 2
  black.frame = transformationLayer.bounds
  black.backgroundColor = UIColor.black.cgColor

  transformationLayer.addSublayer(black)

  let blue = CALayer()
  blue.frame = transformationLayer.bounds
  blue.zPosition = 1
  blue.backgroundColor = UIColor.blue.cgColor

  transformationLayer.addSublayer(blue)

  let tgr = UITapGestureRecognizer(target: self, action: #selector(recTap))
  view.addGestureRecognizer(tgr)
  view.layer.addSublayer(transformationLayer)
}

Animate a full 360 but since the layers have different zPositions the different 'sides' of the layers will show

func recTap(){
    let animation = CABasicAnimation(keyPath: "transform")
    animation.delegate = self
    animation.duration = 2.0
    animation.fillMode = kCAFillModeForwards
    animation.isRemovedOnCompletion = false
    animation.toValue = NSValue(caTransform3D: CATransform3DMakeRotation(CGFloat(Float.pi), 1, -1, 0))
    transformationLayer.add(animation, forKey: "arbitrarykey")
  }


问:
How do I store the location of an image in a database?
I have a list of colors, with textures that I want to show to particular users, so I need to load the image of the colors that a particular user has, the color's information is contained in a ObjecDTO and one of the properties is its image path. My question is how should I store the image path in the database, are there any special rules, for example since the database and the image file are on the same server should I store a complete file URL, or a relative url, what characters should I escape etcetera, or are there better approaches than mine?

I've searched the web but mostly point to storing BLOBs in the database, which I've found  to be a bad practice.

Any guidance is really appreciated.

regards Tristian.

答:
This is really been asked a lot:

store image in database or in a system file?


问:
Where is my Electron App located
I have an electron app, that also operates on files in the same directory. These are not files the user selects, or files bundled inside the electron application, but I do need to reference them

for example:

/Users/test/Documents/myapp.app

/Users/test/Documents/example.zip

I need to know where that application is located, e.g.:

/Users/test/Documents

But instead when test.app is ran I get:

/Users/test/Documents/myapp.app/Contents/Resources/app/

Resulting in errors when it tries to access /Users/test/Documents/myapp.app/Contents/Resources/app/test.zip, or if I use a relative path, /test.zip.

How would I reliably access example.zip in this scenario? Note that I cannot bundle it with my app, it's being placed there by somebody else, so moving it is not an option, and it's a file I'm expecting to be there.

答:
A friend and I looked up how Atom does it and arrived at this solution:</p>

```<code>function getAppRoot() {
  if ( process.platform === 'win32' ) {
    return path.join( app.getAppPath(), '/../../../' );
  }  else {
    return path.join( app.getAppPath(), '/../../../../' );
  }
}
</code>```

Title: Where is my Electron App located

Body:
A friend and I looked up how Atom does it and arrived at this solution:

function getAppRoot() {
  if ( process.platform === 'win32' ) {
    return path.join( app.getAppPath(), '/../../../' );
  }  else {
    return path.join( app.getAppPath(), '/../../../../' );
  }
}


问:
How to create a SAP Variable that must be specified by user like prompts do?
I am trying to build reports using RESTful API for Business Objects 4.2.
In the "SAP BusinessObjects RESTful Web Service SDK User Guide for Web Intelligence and the BI Semantic Layer", section "6.5.1 Parameter Response Body Schemas" mentioned that parameter may be a context, prompt or sapVariable.  I was able to create a report with context selection and prompt. But what is sapVariable?

```<code><parameters>
    <parameter type="context|prompt|sapVariable" optional="Boolean" dpId="string">
</code>```

How is it possible to create a variable that will require an input from the user?

Thanks in advance.

答:
I'm not sure what a SAP variable is (It's hardly described in the IDT guide, mostly to do with HANA variables in the context of semantic layer). Seeing that there is no mention of Sap variable in the context of parameters, business layers etc., it's quite conceivable that it's a Universe feature that didn't make the cut in 4.2, but may become available later. In which case, I suppose it could give the ability to leverage HANA variables in the business layer directly.

I'm not sure if I understand your question regarding creating a variable that requires a user input, since you mentioned that you have already created a report that supports context and prompts. There is a UserResponse function in Webi you can use to get the prompt values. Alternatively, you can also create a universe object with @Prompt that you can incorporate in the result of your query, and manipulate that directly into your report.

Body:
I am trying to build reports using RESTful API for Business Objects 4.2.
In the "SAP BusinessObjects RESTful Web Service SDK User Guide for Web Intelligence and the BI Semantic Layer", section "6.5.1 Parameter Response Body Schemas" mentioned that parameter may be a context, prompt or sapVariable.  I was able to create a report with context selection and prompt. But what is sapVariable?

<parameters>
    <parameter type="context|prompt|sapVariable" optional="Boolean" dpId="string">

How is it possible to create a variable that will require an input from the user?

Thanks in advance.


问:
Writing all bytes 0x00-0xFF to a file in Batch
I'm trying to use batch to write all the bytes from 0x00 to 0xFF to a file. I've tried looking for this, and all I found was various workarounds for specific bytes (e.g. the CR character). I'm looking for something like

```<code>echo \x00\x1b\xff > file
</code>```

resulting in file being 3 bytes long with the contents 001bff.

Does this sort of thing exist in batch?

答:
you need to (ab)use certutil:

```<code>(echo 00 1b ff)>file.hex
certutil -decodehex file.hex file.bin
</code>```

Check this and this for more info

Body:
I'm trying to use batch to write all the bytes from 0x00 to 0xFF to a file. I've tried looking for this, and all I found was various workarounds for specific bytes (e.g. the CR character). I'm looking for something like

echo \x00\x1b\xff > file

resulting in file being 3 bytes long with the contents 001bff.

Does this sort of thing exist in batch?

Body:
you need to (ab)use certutil:

(echo 00 1b ff)>file.hex
certutil -decodehex file.hex file.bin

Check this and this for more info


问:
How do I swap this link out with Rails?
I am trying to take this link..

```<code>http://www.youtube.com/watch?v=4lzi_3SM9-o
</code>```

And turn it into this:

```<code>http://www.youtube.com/v/4lzi_3SM9-o
</code>```

To do this I need some way to capture watch?v= and switch it with v/

And I would like to accomplish this in my model with def tube_link

Any ideas?

Title: How do I swap this link out with Rails?

Body:
I am trying to take this link..

http://www.youtube.com/watch?v=4lzi_3SM9-o

And turn it into this:

http://www.youtube.com/v/4lzi_3SM9-o

To do this I need some way to capture watch?v= and switch it with v/

And I would like to accomplish this in my model with def tube_link

Any ideas?

Body: "http://www.youtube.com/watch?v=4lzi_3SM9-o".gsub("watch?v=", "v/")


问:
Emulating Ajax request via Scrapy - Can't decode unicode response
I am succesfully emulating Ajax requests in my code, here is part of the exact response I am getting (written to file/printed to console)

\u003ctr\u003e\u003ctd class=\"box_pro_high1\"  style=\"width:166px;height:302px;\"\u003e\r\n  \u003cdiv  align=\"center\"\u003e\r\n    \u003cdiv style=\"width:160px;height:100px;display:table-cell;vertical-align:middle;text-align:center;\"\u003e\r\n      \u003ca href=\"/antennas-connectors-accessories/adaptors-connectors/sma-r-a-8906/sma390-8153/pd/\" rel=\"pd.aspx?\u0026amp;pid=8153\u0026amp;fid=8906\u0026amp;cid=WES1863229926N\u0026amp;pcr=WES596880305N\u0026amp;Path=hJhp9Eo4i4SmypehwrGDk1dSIV1a%2fzDdQ39QdmWB6NLz%2bOfhVWXfF%2buXHGazJfLb25nPLAnzP5cA1EMeQ6IUDQMZmGxNYGTr8ARSiPUbiPN8GaSYHamQH9%2bSCQaRu3yY8Nv8%2fB75yy4UdDKkWwfIpY9zTNKSLx0anQ%2fNUrFOtGvph5cABhGlLBWHi%2fFJQEXw4P9%2bLdS%2fn1Q%3d\"  class=\"tx_3\"\u003e\r\n       \r\n        \u003cimg data-original=\"/prodimages/section7_th/sma390.jpg\" style=\"max-height:100px; max-width:100px;\" border=\"0\" alt=\"SMA390 SMA R/A\"  class=\"lazy\" src=\"\"/\u003e\r\n      \u003c/a\u003e\r\n    \u003c/div\u003e\r\n    \u003cdiv class=\"familyheader\" style=\"height:30px;\"\u003e\r\n \r\n      \u003ca href=\"/antennas-connectors-accessories/adaptors-connectors/sma-r-a-8906/sma390-8153/pd/\"

I am trying to pass it to BeautifulSoup/lxml but it (understandably) fails.

Via simple google search I have found this site: http://www.online-toolz.com/tools/text-unicode-entities-convertor.php

that "decodes" (I am not sure it's correct term) this string with one click to:

```<code>    <img data-original="/prodimages/section7_th/sma390.jpg" style="max-height:100px; max-width:100px;" border="0" alt="SMA390 SMA R/A"  class="lazy" src=""/>
  </a>
</div>
<div class="familyheader" style="height:30px;">

  <a href="/antennas-connectors-accessories/adaptors-connectors/sma-r-a-8906/sma390-8153/pd/"
</code>```

Which is exactly what I want. But I can't emulate this behavior in python.

I have tried using ord(), decode(), etc. but can't seem to solve it.

答:
this is unicode escaped strings, you can simply turn it into readable html:

```<code>s = "\u003ctr\u003e\u003c ......."
s = s.decode('unicode-escape')
</code>```

Now you can treat the s string as the correct response to use with beautifulsoup or scrapy's selectors.

for python3 is even simpler

```<code>s = str.encode(s)
</code>```

Body:
I am succesfully emulating Ajax requests in my code, here is part of the exact response I am getting (written to file/printed to console)

\u003ctr\u003e\u003ctd class=\"box_pro_high1\"  style=\"width:166px;height:302px;\"\u003e\r\n  \u003cdiv  align=\"center\"\u003e\r\n    \u003cdiv style=\"width:160px;height:100px;display:table-cell;vertical-align:middle;text-align:center;\"\u003e\r\n      \u003ca href=\"/antennas-connectors-accessories/adaptors-connectors/sma-r-a-8906/sma390-8153/pd/\" rel=\"pd.aspx?\u0026amp;pid=8153\u0026amp;fid=8906\u0026amp;cid=WES1863229926N\u0026amp;pcr=WES596880305N\u0026amp;Path=hJhp9Eo4i4SmypehwrGDk1dSIV1a%2fzDdQ39QdmWB6NLz%2bOfhVWXfF%2buXHGazJfLb25nPLAnzP5cA1EMeQ6IUDQMZmGxNYGTr8ARSiPUbiPN8GaSYHamQH9%2bSCQaRu3yY8Nv8%2fB75yy4UdDKkWwfIpY9zTNKSLx0anQ%2fNUrFOtGvph5cABhGlLBWHi%2fFJQEXw4P9%2bLdS%2fn1Q%3d\"  class=\"tx_3\"\u003e\r\n       \r\n        \u003cimg data-original=\"/prodimages/section7_th/sma390.jpg\" style=\"max-height:100px; max-width:100px;\" border=\"0\" alt=\"SMA390 SMA R/A\"  class=\"lazy\" src=\"\"/\u003e\r\n      \u003c/a\u003e\r\n    \u003c/div\u003e\r\n    \u003cdiv class=\"familyheader\" style=\"height:30px;\"\u003e\r\n \r\n      \u003ca href=\"/antennas-connectors-accessories/adaptors-connectors/sma-r-a-8906/sma390-8153/pd/\"

I am trying to pass it to BeautifulSoup/lxml but it (understandably) fails.

Via simple google search I have found this site: http://www.online-toolz.com/tools/text-unicode-entities-convertor.php

that "decodes" (I am not sure it's correct term) this string with one click to:

  <a href="/antennas-connectors-accessories/adaptors-connectors/sma-r-a-8906/sma390-8153/pd/"

Which is exactly what I want. But I can't emulate this behavior in python.

I have tried using ord(), decode(), etc. but can't seem to solve it.

Body:
this is unicode escaped strings, you can simply turn it into readable html:

s = "\u003ctr\u003e\u003c ......."
s = s.decode('unicode-escape')

Now you can treat the s string as the correct response to use with beautifulsoup or scrapy's selectors.

for python3 is even simpler

s = str.encode(s)


问:
Where to find ag-grid version wise features
I'm new to ag-grid.. I want to know whether ag-grid Master/ Detail grid is supported in ag-grid 5.1.0 which is used in existing frame work.. How can I get these details (version wise features).

Thanks

I found master detail view feature works over v5.3.0 by going through
  ag-grid.js , which was a pain :( . I hope there should be a version
  vise api !

答: They have a ChangeLog. Just a little searching after that should help you find what you need</p>


问:
Simple Injector - Delayed Initialization
Could someone assist me with one question please?

I have two services.

GAuth:

```<code>public class GAuth : IGAuth
{
    public async Task<UserCredential> AuthorizeAsync(ClientSecrets clientSecrets)
    {
        using (var cts = new CancellationTokenSource())
        {
            var localServerCodeReceiver = new LocalServerCodeReceiver();

            cts.CancelAfter(TimeSpan.FromMinutes(1));

            return await GoogleWebAuthorizationBroker.AuthorizeAsync(
                clientSecrets,
                _scopes,
                User,
                cts.Token,
                new FileDataStore(string.Empty), localServerCodeReceiver
            );
        }
    }
}
</code>```

GDrive:

```<code>public class GDrive : IGDrive
{
    private readonly DriveService _driveService;

    public GDrive(UserCredential userCredential)
    {
        _driveService = new DriveService(new BaseClientService.Initializer
        {
            HttpClientInitializer = userCredential,
            ApplicationName = string.Empty
        });
    }
}
</code>```

And registration part:

```<code>container.Register<IGAuth, GAuth>(Lifestyle.Singleton);
container.Register<IGDrive, GDrive>(Lifestyle.Singleton);
</code>```

As you can see GAuth service returns UserCredentials object after authorization. And this UserCredentials is required for GDrive service.
It's simplified example, but in general I need to initialize GDrive service with correct UserCredentials object after user press Auth button on the application form.

Is there any way to do that?

Thanks in advance.

答:
From a design perspective, injection constructors should be simple, fast and reliable. This isn't the case in your case, since the building of the object graph depends on I/O.

Instead, you should postpone the IO till after the constructor has ran.

There are two things that come to my mind that you can do. Either you inject the IGAuth into the GDrive and make sure it is called after the constructor has ran, or you inject a lazy async UserCredential that can be requested after the constructor has ran.

Here's an example of the latter:

```<code>public class GDrive : IGDrive
{
    private readonly Lazy<Task<DriveService>> _driveService;

    public GDrive(Lazy<Task<UserCredential>> userCredential)
    {
        _driveService = new Lazy<Task<DriveService>>(async () =>
            new DriveService(new BaseClientService.Initializer
            {
                HttpClientInitializer = await userCredential.Value,
                ApplicationName = string.Empty
            }));
    }

    public async Task SomeMethod()
    {
        var service = await _driveService.Value;

        service.DoSomeStuff();
    }
}
</code>```

You can configure this GDrive as follows:

```<code>var auth = new GAuth();
var credentials = new Lazy<Task<UserCredential>>(
    () => auth.AuthorizeAsync(new ClientSecrets()));

container.RegisterSingleton<IGDrive>(new GDrive(credentials));
</code>```

The other option is to inject the GAuth into the GDrive. That would result in something as follows:

```<code>public class GDrive : IGDrive
{
    private readonly Lazy<Task<DriveService>> _driveService;

    public GDrive(IGAuth auth)
    {
        _driveService = new Lazy<Task<DriveService>>(async () =>
            new DriveService(new BaseClientService.Initializer
            {
                HttpClientInitializer = await auth.AuthorizeAsync(new ClientSecrets()),
                ApplicationName = string.Empty
            }));
    }

    public async Task SomeMethod()
    {
        var service = await _driveService.Value;

        service.DoSomeStuff();
    }
}
</code>```

Note that in both cases a Lazy<Async<T>> is created that will ensure that the asynchronous operation is only triggered when Lazy<T>.Value is called for the first time.

Body:
Could someone assist me with one question please?

I have two services.

GAuth:

public class GAuth : IGAuth
{
    public async Task<UserCredential> AuthorizeAsync(ClientSecrets clientSecrets)
    {
        using (var cts = new CancellationTokenSource())
        {
            var localServerCodeReceiver = new LocalServerCodeReceiver();

            cts.CancelAfter(TimeSpan.FromMinutes(1));

            return await GoogleWebAuthorizationBroker.AuthorizeAsync(
                clientSecrets,
                _scopes,
                User,
                cts.Token,
                new FileDataStore(string.Empty), localServerCodeReceiver
            );
        }
    }
}

GDrive:

public class GDrive : IGDrive
{
    private readonly DriveService _driveService;

    public GDrive(UserCredential userCredential)
    {
        _driveService = new DriveService(new BaseClientService.Initializer
        {
            HttpClientInitializer = userCredential,
            ApplicationName = string.Empty
        });
    }
}

And registration part:

container.Register<IGAuth, GAuth>(Lifestyle.Singleton);
container.Register<IGDrive, GDrive>(Lifestyle.Singleton);

As you can see GAuth service returns UserCredentials object after authorization. And this UserCredentials is required for GDrive service.
It's simplified example, but in general I need to initialize GDrive service with correct UserCredentials object after user press Auth button on the application form.

Is there any way to do that?

Thanks in advance.

Body:
From a design perspective, injection constructors should be simple, fast and reliable. This isn't the case in your case, since the building of the object graph depends on I/O.

Instead, you should postpone the IO till after the constructor has ran.

There are two things that come to my mind that you can do. Either you inject the IGAuth into the GDrive and make sure it is called after the constructor has ran, or you inject a lazy async UserCredential that can be requested after the constructor has ran.

Here's an example of the latter:

public class GDrive : IGDrive
{
    private readonly Lazy<Task<DriveService>> _driveService;

    public GDrive(Lazy<Task<UserCredential>> userCredential)
    {
        _driveService = new Lazy<Task<DriveService>>(async () =>
            new DriveService(new BaseClientService.Initializer
            {
                HttpClientInitializer = await userCredential.Value,
                ApplicationName = string.Empty
            }));
    }

    public async Task SomeMethod()
    {
        var service = await _driveService.Value;

        service.DoSomeStuff();
    }
}

You can configure this GDrive as follows:

var auth = new GAuth();
var credentials = new Lazy<Task<UserCredential>>(
    () => auth.AuthorizeAsync(new ClientSecrets()));

container.RegisterSingleton<IGDrive>(new GDrive(credentials));

The other option is to inject the GAuth into the GDrive. That would result in something as follows:

public class GDrive : IGDrive
{
    private readonly Lazy<Task<DriveService>> _driveService;

    public GDrive(IGAuth auth)
    {
        _driveService = new Lazy<Task<DriveService>>(async () =>
            new DriveService(new BaseClientService.Initializer
            {
                HttpClientInitializer = await auth.AuthorizeAsync(new ClientSecrets()),
                ApplicationName = string.Empty
            }));
    }

    public async Task SomeMethod()
    {
        var service = await _driveService.Value;

        service.DoSomeStuff();
    }
}

Note that in both cases a Lazy<Async<T>> is created that will ensure that the asynchronous operation is only triggered when Lazy<T>.Value is called for the first time.


问:
SQL Server, Does 'sum' funcation works fine in large tables?
I'm building a market sell points system using C# winForms, SQL Server 2014
My problem is the idea of storing the products and quantities
the program should display the quantity of some product when making a new sell bill
so before user make a sell he should know the quantity of this product, and see if it enough for the order or not
i created this table for items
Item_ID,     Item,     Buy_Price,     Sell_Price,     Quantity

but this makes confusions when user edit some bills , sell bills or buy bills
so for example when user edit some buy bill(invoice), edit the quantity in the buy bill
then the product quantity cell in items table will not match the quantity in buybills table
so i want to make it little more dynamic and remove the quantity cell from items table
and using the bills table to get the quantity of any item
that means when user search for an item(Product) to sell, system uses a sum funcation buy sql statement
quantity = sum(item_quantity) in buy_bills - sum(item_quantity) in sell_bills
does it works? or this will be so heavey when databases size and records count get larger?

答:
I want to make it little more dynamic and remove the quantity cell from items table and using the bills table to get the quantity of any item that means when user search for an item(Product) to sell, system uses a sum funcation buy sql statement quantity = sum(item_quantity) in buy_bills - sum(item_quantity) in sell_bills does it works?

Assuming you have your syntax correct, it is possible to sum a column using the sum function. You can subtract two sums in a single statement. Ie, SUM(Column_1) - SUM(Column2) AS Column3. This assumes that you have everything else set up correctly.

or this will be so heavey when databases size and records count get larger?

This is 100% relative to your database setup and not answerable here. It is possible that it will slow down when the database gets larger. But, if your database is set up correctly, it should not be by much.

It is also possible, later on, to get around that issue by pre-loading the data.


问:
How to make a regex not match if the string has a space at the end
I'm trying to create a regular expression that matches a string ONLY if a string does not have a space at the end.

For example these should match: "Jake" "John" "Mary Anne"

These shouldn't match: "Don " "David  "

Is this possible? I'm able to write a simple expression that disallows spaces altogether but that is an issue for some inputs.

答:
Yes, it is possible.

Try the regex below:

```<code>^.*\S$
</code>```

It allows everything that does not ends with a space character.

DEMO with explation

Body:
Yes, it is possible.

Try the regex below:

^.*\S$

It allows everything that does not ends with a space character.

DEMO with explation


问:
Vinyl FTP for Gulp configuration
I'm using Gulp to generate CSS from LESS-CSS on file save. I want the css file to be uploaded to the server immediately, so I'm experimenting with Vinyl-FTP. I'm a newbie at NPM/NodeJS/Gulp/JavaScript, so I need some help.

In my gulpfile.js I have included this code (hiding of course host, user and password):

```<code>// Vinyl FTP
gulp.task( 'deploy', function () {

    var conn = ftp.create( {
        host:     'ftp-server',
        user:     'user',
        password: 'password',
        parallel: 10,
        log:      gutil.log
    } );

    var globs = [
        '../site/templates/templatename/css/bootstrap.min.css'
    ];

    return gulp.src( globs, { base: '.', buffer: false } )
        .pipe( conn.newer( '/public_html/dev2/templates/templatename/css' ) )
        .pipe( conn.dest( '/public_html/dev2/templates/templatename/css' ) );

} );
</code>```

I want the bootstrap.min.css file uploaded each time I hit 'save'. The file is located at ../site/templates/templatename/css/bootstrap.min.css relative to my gulp directory. I want it uploaded to my development site which is located at /public_html/dev2/templates/templatename/css on the server (yes, this is Joomla).

Apparently, I'm using the wrong path, because this is what it churns out:

```<code>    [14:44:21] Using gulpfile /mnt/e/Sites/successfulspeakernow.com/gulp/gulpfile.js
[14:44:21] Starting 'less'...
[14:44:21] Finished 'less' after 20 ms
[14:44:21] Starting 'watch'...
[14:44:21] Finished 'watch' after 267 ms
[14:44:21] Starting 'deploy'...
[14:44:21] CONN
[14:44:23] READY
[14:44:23] MLSD  /public_html/dev2/templates/templatename/site/templates/templatename/css
[14:44:23] MLSD  /public_html/dev2/templates/templatename/site/templates/templatename
[14:44:23] MLSD  /public_html/dev2/templates/templatename/site/templates
[14:44:23] MLSD  /public_html/dev2/templates/templatename/site
[14:44:23] MLSD  /public_html/dev2/templates/templatename
[14:44:23] MLSD  /public_html/dev2/templates
[14:44:23] MKDIR /public_html/dev2/templates/templatename/site
[14:44:23] MKDIR /public_html/dev2/templates/templatename/site/templates
[14:44:23] MKDIR /public_html/dev2/templates/templatename/site/templates/templatename
[14:44:23] MKDIR /public_html/dev2/templates/templatename/site/templates/templatename/css
[14:44:23] PUT   /public_html/dev2/templates/templatename/site/templates/templatename/css/bootstrap.min.css
[14:44:23] UP     37% /public_html/dev2/templates/templatename/site/templates/templatename/css/bootstrap.min.css
[14:44:23] UP     74% /public_html/dev2/templates/templatename/site/templates/templatename/css/bootstrap.min.css
[14:44:23] UP    100% /public_html/dev2/templates/templatename/site/templates/templatename/css/bootstrap.min.css
[14:44:23] Finished 'deploy' after 1.86 s
[14:44:23] Starting 'default'...
[14:44:23] Finished 'default' after 8.9 μs
[14:44:23] DISC
</code>```

and when I go there with my FTP program, I find this:

```<code>/public_html/dev2/templates/templatename/site/templates/templatename/css/bootstrap.min.css
</code>```

Can you explain what to adjust so the bootstrap.min.css file gets uploaded to the right directory on the server?

Thanx,

Thom

答:
I had the same problem. Vinylftp creates source folder structure in destination folder. To avoid that problem, just change destination to root of your webserver.
My code is little bit different, but it shows where is the problem is.</p>

```<code>var gulp = require('gulp');
var gutil = require( 'gulp-util' );
var ftp = require( 'vinyl-ftp' );

/** Configuration **/
var user = 'username';
var password = 'password';
var host = 'hostname';
var port = 21;
var localFilesGlob = ['public_html/templates/protostar/css/template.css'];
var remoteFolder = ''; // <- HERE MUST BE AN EMPTY STRING TO POINT THE VINYLFTP TO ROOT

function getFtpConnection() {
    return ftp.create({
        host: host,
        port: port,
        user: user,
        password: password,
        parallel: 5,
        log: gutil.log
    });
}

gulp.task('ftp-deploy', function() {

    var conn = getFtpConnection();

    return gulp.src(localFilesGlob, { base: '.', buffer: false })
        .pipe( conn.newer( remoteFolder ) ) // only upload newer files
        .pipe( conn.dest( remoteFolder ) )
    ;
});
</code>```

Title: Vinyl FTP for Gulp configuration

Body:
I'm using Gulp to generate CSS from LESS-CSS on file save. I want the css file to be uploaded to the server immediately, so I'm experimenting with Vinyl-FTP. I'm a newbie at NPM/NodeJS/Gulp/JavaScript, so I need some help.

In my gulpfile.js I have included this code (hiding of course host, user and password):

// Vinyl FTP
gulp.task( 'deploy', function () {

    var conn = ftp.create( {
        host:     'ftp-server',
        user:     'user',
        password: 'password',
        parallel: 10,
        log:      gutil.log
    } );

    var globs = [
        '../site/templates/templatename/css/bootstrap.min.css'
    ];

    return gulp.src( globs, { base: '.', buffer: false } )
        .pipe( conn.newer( '/public_html/dev2/templates/templatename/css' ) )
        .pipe( conn.dest( '/public_html/dev2/templates/templatename/css' ) );

} );

I want the bootstrap.min.css file uploaded each time I hit 'save'. The file is located at ../site/templates/templatename/css/bootstrap.min.css relative to my gulp directory. I want it uploaded to my development site which is located at /public_html/dev2/templates/templatename/css on the server (yes, this is Joomla).

Apparently, I'm using the wrong path, because this is what it churns out:

    [14:44:21] Using gulpfile /mnt/e/Sites/successfulspeakernow.com/gulp/gulpfile.js
[14:44:21] Starting 'less'...
[14:44:21] Finished 'less' after 20 ms
[14:44:21] Starting 'watch'...
[14:44:21] Finished 'watch' after 267 ms
[14:44:21] Starting 'deploy'...
[14:44:21] CONN
[14:44:23] READY
[14:44:23] MLSD  /public_html/dev2/templates/templatename/site/templates/templatename/css
[14:44:23] MLSD  /public_html/dev2/templates/templatename/site/templates/templatename
[14:44:23] MLSD  /public_html/dev2/templates/templatename/site/templates
[14:44:23] MLSD  /public_html/dev2/templates/templatename/site
[14:44:23] MLSD  /public_html/dev2/templates/templatename
[14:44:23] MLSD  /public_html/dev2/templates
[14:44:23] MKDIR /public_html/dev2/templates/templatename/site
[14:44:23] MKDIR /public_html/dev2/templates/templatename/site/templates
[14:44:23] MKDIR /public_html/dev2/templates/templatename/site/templates/templatename
[14:44:23] MKDIR /public_html/dev2/templates/templatename/site/templates/templatename/css
[14:44:23] PUT   /public_html/dev2/templates/templatename/site/templates/templatename/css/bootstrap.min.css
[14:44:23] UP     37% /public_html/dev2/templates/templatename/site/templates/templatename/css/bootstrap.min.css
[14:44:23] UP     74% /public_html/dev2/templates/templatename/site/templates/templatename/css/bootstrap.min.css
[14:44:23] UP    100% /public_html/dev2/templates/templatename/site/templates/templatename/css/bootstrap.min.css
[14:44:23] Finished 'deploy' after 1.86 s
[14:44:23] Starting 'default'...
[14:44:23] Finished 'default' after 8.9 μs
[14:44:23] DISC

and when I go there with my FTP program, I find this:

/public_html/dev2/templates/templatename/site/templates/templatename/css/bootstrap.min.css

Can you explain what to adjust so the bootstrap.min.css file gets uploaded to the right directory on the server?

Thanx,

Thom

Body:
I had the same problem. Vinylftp creates source folder structure in destination folder. To avoid that problem, just change destination to root of your webserver.
My code is little bit different, but it shows where is the problem is.

var gulp = require('gulp');
var gutil = require( 'gulp-util' );
var ftp = require( 'vinyl-ftp' );

/** Configuration **/
var user = 'username';
var password = 'password';
var host = 'hostname';
var port = 21;
var localFilesGlob = ['public_html/templates/protostar/css/template.css'];
var remoteFolder = ''; // <- HERE MUST BE AN EMPTY STRING TO POINT THE VINYLFTP TO ROOT

function getFtpConnection() {
    return ftp.create({
        host: host,
        port: port,
        user: user,
        password: password,
        parallel: 5,
        log: gutil.log
    });
}

gulp.task('ftp-deploy', function() {

    var conn = getFtpConnection();

    return gulp.src(localFilesGlob, { base: '.', buffer: false })
        .pipe( conn.newer( remoteFolder ) ) // only upload newer files
        .pipe( conn.dest( remoteFolder ) )
    ;
});


问:
PromiseKit catch multiple arguments
I'm integrating PromiseKit into our current system and I need the catch part of the chain to use 2 arguments. I'd like my catch to use error, fetcher instead of just error. What is the best way to do this?

```<code>infoPromise.then { objects in
    print(objects)
}.catch { error in /* error, fetcher in */
    print(error)
}
</code>```

I've thought of including the fetcher as part of the userInfo dictionary on NSError, but I'd prefer it as a separate argument if possible.

Edit - More Info:

Here is the adapter I'm using. The fetcher is returned in the onError from my existing system.

```<code>- (AnyPromise *)fetchAll:(NSString *)entityName {
    return [AnyPromise promiseWithAdapterBlock:^(PMKAdapter  _Nonnull adapter) {
        [self fetchAll:entityName onComplete:^(NSArray *results) {
            adapter(results,nil);
        } onError:^(ICSHTTPFetcher *fetcher, NSError *error) {
            adapter(nil,error);
        }];
    }];
}
</code>```

答:
I have not used promises much in Objective C. But if you are able to write the fetchAll function in swift then you could wrap the error and fetcher in a Swift error. Below is a rough example of this - it won't compile, it's just to give you an idea. It would probably be better to make a few more specific PromiseErrors indicating the actual error, than just the one as I have done and then not pass the NSError through.</p>

```<code>enum PromiseErrors: Error {
    case fetchAll(NSError, ICSHTTPFetcher)
}

struct Test {
    func fetchAll() -> Promise<Any> {
        return fetchAll(entityName, onComplete: { results in
            return Promise(value: results)
        }, error: { fetcher, error in
            return Promise(error: PromiseErrors.fetchAll(error, fetcher))
        })
    }

    func test() {
        infoPromise.then { objects in
            print(objects)
        }.catch { error in
            if let case PromiseErrors.fetchAll(error, fetcher) = error {

            }
        }
    }
}
</code>```

Title: PromiseKit catch multiple arguments

Body:
I'm integrating PromiseKit into our current system and I need the catch part of the chain to use 2 arguments. I'd like my catch to use error, fetcher instead of just error. What is the best way to do this?

infoPromise.then { objects in
    print(objects)
}.catch { error in /* error, fetcher in */
    print(error)
}

I've thought of including the fetcher as part of the userInfo dictionary on NSError, but I'd prefer it as a separate argument if possible.

Edit - More Info:

Here is the adapter I'm using. The fetcher is returned in the onError from my existing system.

- (AnyPromise *)fetchAll:(NSString *)entityName {
    return [AnyPromise promiseWithAdapterBlock:^(PMKAdapter  _Nonnull adapter) {
        [self fetchAll:entityName onComplete:^(NSArray *results) {
            adapter(results,nil);
        } onError:^(ICSHTTPFetcher *fetcher, NSError *error) {
            adapter(nil,error);
        }];
    }];
}

Body:
I have not used promises much in Objective C. But if you are able to write the fetchAll function in swift then you could wrap the error and fetcher in a Swift error. Below is a rough example of this - it won't compile, it's just to give you an idea. It would probably be better to make a few more specific PromiseErrors indicating the actual error, than just the one as I have done and then not pass the NSError through.

enum PromiseErrors: Error {
    case fetchAll(NSError, ICSHTTPFetcher)
}

struct Test {
    func fetchAll() -> Promise<Any> {
        return fetchAll(entityName, onComplete: { results in
            return Promise(value: results)
        }, error: { fetcher, error in
            return Promise(error: PromiseErrors.fetchAll(error, fetcher))
        })
    }

    func test() {
        infoPromise.then { objects in
            print(objects)
        }.catch { error in
            if let case PromiseErrors.fetchAll(error, fetcher) = error {

            }
        }
    }
}


问:
angular 2 ngif not working even though function return true
I'm using Angular 2. I have an array and I am looping through each item and setting a boolean. I'm console logging to make sure it's being set properly.  However when I use this function against an *ngif it doesn't work. What crucial piece am I missing here?

template:

```<code> <div *ngFor="let item of viewableItems>
        <div class="thermometerMercury" *ngIf="showThermometer"></div>
 </div>
</code>```

.ts

```<code>  processedItems: Item[] = [];
  showThermometer: boolean;

  checkDonation() {
      for (let i = 0; i < this.processedItems.length; i++) {
          let out = this.processedItems[i];
      if (out.isDonation && out.donationAmountDonatedByClient === 0) {
        this.showThermometer = true;
      } else {
        this.showThermometer = false;
      }
      console.log(i, this.showThermometer);
    }
  }
</code>```

答:
template:

```<code> <div *ngFor="let item of viewableItems>
        <div class="thermometerMercury" *ngIf="item.showThermometer"></div>
 </div>
</code>```

.ts

```<code>  processedItems: Item[] = [];
  showThermometer: boolean;

  checkDonation() {
      for (let i = 0; i < this.processedItems.length; i++) {
         let out = this.processedItems[i];
         this.showThermometer = false;
         if (out.isDonation && out.donationAmountDonatedByClient === 0)
         {
           this.showThermometer = true;
         }
         out['showThermometer'] = this.showThermometer;
         console.log(i, this.showThermometer);
       }
   }
</code>```

Body:
I'm using Angular 2. I have an array and I am looping through each item and setting a boolean. I'm console logging to make sure it's being set properly.  However when I use this function against an *ngif it doesn't work. What crucial piece am I missing here?

template:

.ts

  processedItems: Item[] = [];
  showThermometer: boolean;

  checkDonation() {
      for (let i = 0; i < this.processedItems.length; i++) {
          let out = this.processedItems[i];
      if (out.isDonation && out.donationAmountDonatedByClient === 0) {
        this.showThermometer = true;
      } else {
        this.showThermometer = false;
      }
      console.log(i, this.showThermometer);
    }
  }

Body:
template:

 <div *ngFor="let item of viewableItems>
        <div class="thermometerMercury" *ngIf="item.showThermometer"></div>
 </div>

.ts

  processedItems: Item[] = [];
  showThermometer: boolean;

  checkDonation() {
      for (let i = 0; i < this.processedItems.length; i++) {
         let out = this.processedItems[i];
         this.showThermometer = false;
         if (out.isDonation && out.donationAmountDonatedByClient === 0)
         {
           this.showThermometer = true;
         }
         out['showThermometer'] = this.showThermometer;
         console.log(i, this.showThermometer);
       }
   }


问:
SSRS Report Viewer Print Button Not Working
I'm using SSRS 2016 and am currently generating several reports using the

```<code>http://[servername]/ReportServer/Pages/ReportViewer.aspx?/[Report Path]&rc:Parameters=false
</code>```

interface.  The report renders correctly with all parameters supplied by the forwarding page.  However, in the rendered report viewer, the Print Button is entirely non-functional.  I've tried in Chrome, IE, & Edge, and none of them are able to even open a printer prompt, the print button just registers and click and, nothing.

I've ensured Client Printing is enabled in the SSRS settings.  I'm trying to avoid forcing the operator to export to PDF (which does work on the standard toolbar) and using Adobe's print function.

Any help would be greatly appreciated!

答: I have had this issue in the past.  I fixed it by opening my browser with "Run as Administrator".   This may not be the solution for your problem... but it may help someone who stumbles on this question, so I decided to post as a potential answer.

Body:
I'm using SSRS 2016 and am currently generating several reports using the

http://[servername]/ReportServer/Pages/ReportViewer.aspx?/[Report Path]&rc:Parameters=false

interface.  The report renders correctly with all parameters supplied by the forwarding page.  However, in the rendered report viewer, the Print Button is entirely non-functional.  I've tried in Chrome, IE, & Edge, and none of them are able to even open a printer prompt, the print button just registers and click and, nothing.

I've ensured Client Printing is enabled in the SSRS settings.  I'm trying to avoid forcing the operator to export to PDF (which does work on the standard toolbar) and using Adobe's print function.

Any help would be greatly appreciated!


问:
JOptionPane won't show its dialog on top of other windows
I have problem currently for my swing reminder application, which able to minimize to tray on close. My problem here is, I need JOptionPane dialog to pop up on time according to what I set, but problem here is, when I minimize it, the dialog will pop up, but not in the top of windows when other application like explorer, firefox is running, anyone know how to pop up the dialog box on top of windows no matter what application is running?</p>

答:
Are you using one of the canned JOptionPanes?  (Like JOptionPane.showCOnfirmDialog(...))

You may want to look at extending JDialog and making your own dialog panel, and then calling myDialog.setAlwaysOnTop(true);

OwnerDisplayName: Dickson

OwnerDisplayName: KaosDG


问:
compatibility of ASP.net Pages with other OS es
I was Planing to make my website and thought that either use ASP.net or Php as i have not used php but know c# so can do ASP.net.but problem that i came to mind as i make desktop apps are only for windows. what if i make a website in dot net (cross platform compatibility dose not hold for desktop apps) would users be able to open pages at their systems independent of os.</p>

答: ASP.Net is a framework that produces HTML as an output, i.e. content generated in ASP.Net can be accessed by any platform that can display HTML. You could have problems with devices with no/limited javaScript support (old phones etc) but otherwise you're fine.</p>


问:
LDAP searchFilter samAccountName from variable defined by user input ? java JNDI. DOes anybody know how to do it?
The user input:

```<code>String  usersearch = UserSearchField.getText();
</code>```

I want searchFilter to take the variable usersearch

```<code>String searchFilter ="(&(samAccountName=usersearch))"
</code>```

But can not figure out exactly how to do it.

答:
Your search filter is literally searching for an account name "usersearch". You need to format your string to correctly create the search filter. Try this:

```<code>String searchFilter = String.format("samAccountName=%s", usersearch);
</code>```

This code will replace the %s with the value of usersearch. Additionally you don't need the (& because that's for when you have more than one filter and you need to apply a boolean AND operator to them. See the JNDI search filter docs for more information.

Body:
The user input:

String  usersearch = UserSearchField.getText();

I want searchFilter to take the variable usersearch

String searchFilter ="(&(samAccountName=usersearch))"

But can not figure out exactly how to do it.

Body:
Your search filter is literally searching for an account name "usersearch". You need to format your string to correctly create the search filter. Try this:

String searchFilter = String.format("samAccountName=%s", usersearch);

This code will replace the %s with the value of usersearch. Additionally you don't need the (& because that's for when you have more than one filter and you need to apply a boolean AND operator to them. See the JNDI search filter docs for more information.


问:
javascript optimization for pair finding algorithm
I am working on a javascript function which takes an array of integers and a target as arguments. The task is to find the first pair of integers in the array whose sum is equal to the target.  I have tried this several different ways, but I keep getting a timeout error for larger input arrays. Can someone please give me some pointers on how to better optimize this code? Thanks!</p>

```<code>var sum_pairs = function(ints, s){
  var r = [];
  var a = true;
  var l = ints.length;
  for(var j = 0; j < l; j++){
    if(a){
      for(var i = 0; i < j; i++){
        if(ints[j] + ints[i] == s){
          r[0] = ints[i];
          r[1] = ints[j];
          a = false;
          break;
        }
      }
    }
    else{
      console.log('breaking');
      break;
    }
  }
return r[0] == null ? null : r;
}
</code>```

答:
For each number that we encounter while iterating the array, we add that number's expected partner target - number into a Set. As soon as we encounter a number that is already in our set, we know that its partner has already been encountered and return this pair as the solution:

// Return the first two values of 'numbers' summing up to 'target':
function sum_pairs(numbers, target) {
  let paired = new Set();
  for (let number of numbers) {
    if (paired.has(number)) return [target - number, number];
    paired.add(target - number);
  }
}

// Examples:
console.log(...sum_pairs([9, 3, 7, 5, 1], 10)); // [3, 7]
console.log(...sum_pairs([4, 3, 2, 3, 4],  6)); // [4, 2]
console.log(...sum_pairs([9, 3, 6, 4, 1], 10)); // [6, 4]```

This implementation has a linear runtime complexity and is therefore faster for long input arrays, but it comes with an additional memory cost.

If you are going for raw speed, replace the for-of loop with a traditional for-loop and the let variable binding with a var declaration.

Body:
I am working on a javascript function which takes an array of integers and a target as arguments. The task is to find the first pair of integers in the array whose sum is equal to the target.  I have tried this several different ways, but I keep getting a timeout error for larger input arrays. Can someone please give me some pointers on how to better optimize this code? Thanks!

var sum_pairs = function(ints, s){
  var r = [];
  var a = true;
  var l = ints.length;
  for(var j = 0; j < l; j++){
    if(a){
      for(var i = 0; i < j; i++){
        if(ints[j] + ints[i] == s){
          r[0] = ints[i];
          r[1] = ints[j];
          a = false;
          break;
        }
      }
    }
    else{
      console.log('breaking');
      break;
    }
  }
return r[0] == null ? null : r;
}

Body:
For each number that we encounter while iterating the array, we add that number's expected partner target - number into a Set. As soon as we encounter a number that is already in our set, we know that its partner has already been encountered and return this pair as the solution:

// Return the first two values of 'numbers' summing up to 'target':
function sum_pairs(numbers, target) {
  let paired = new Set();
  for (let number of numbers) {
    if (paired.has(number)) return [target - number, number];
    paired.add(target - number);
  }
}

// Examples:
console.log(...sum_pairs([9, 3, 7, 5, 1], 10)); // [3, 7]
console.log(...sum_pairs([4, 3, 2, 3, 4],  6)); // [4, 2]
console.log(...sum_pairs([9, 3, 6, 4, 1], 10)); // [6, 4]

This implementation has a linear runtime complexity and is therefore faster for long input arrays, but it comes with an additional memory cost.

If you are going for raw speed, replace the for-of loop with a traditional for-loop and the let variable binding with a var declaration.


问:
Spark - calculate the sum of features for each sample
If I have a RDD which looks like below then I know how to calculate the sum of my features per sample data:

```<code>import numpy as np
from pyspark import SparkContext

x = np.arange(10) # first sample with 10 features [0 1 2 3 4 5 6 7 8 9]
y = np.arange(10) # second sample with 10 features [0 1 2 3 4 5 6 7 8 9]
z = (x,y)
sc = SparkContext()
rdd1 = sc.parallelize(z)
rdd1.sum()
</code>```

The output will be an array like this: ([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18]), which is what I want.

My Question is:
If I construct a RDD by parsing a csv file as below, in which each element of the RDD is a tuple or list. How can I calculate the sum of each tuple/list elements (each feature) like above? If I use the sum I get this error:

```<code>Rdd :  [(0.00217010083485, 0.00171658370653), (7.24521659993e-05, 4.18413109325e-06), ....]

TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
</code>```

[EDIT] To be more specific:

```<code>rdd = sc.parallelize([(1,3),(2,4)])
</code>```

I want my output to be [3,7].  Each tuple is a data instance that I have, and each element of tuple is my feature.  I want to calculate the sum of each feature per all data samples.

答:
You can do something like this:

```<code>z = zip(x, y)
#z is [(0, 0), (1, 1), (2, 2) ......]
map(np.sum, z)
</code>```

that should do the trick.

Body:
If I have a RDD which looks like below then I know how to calculate the sum of my features per sample data:

import numpy as np
from pyspark import SparkContext

x = np.arange(10) # first sample with 10 features [0 1 2 3 4 5 6 7 8 9]
y = np.arange(10) # second sample with 10 features [0 1 2 3 4 5 6 7 8 9]
z = (x,y)
sc = SparkContext()
rdd1 = sc.parallelize(z)
rdd1.sum()

The output will be an array like this: ([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18]), which is what I want.

My Question is:
If I construct a RDD by parsing a csv file as below, in which each element of the RDD is a tuple or list. How can I calculate the sum of each tuple/list elements (each feature) like above? If I use the sum I get this error:

Rdd :  [(0.00217010083485, 0.00171658370653), (7.24521659993e-05, 4.18413109325e-06), ....]

TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

[EDIT] To be more specific:

rdd = sc.parallelize([(1,3),(2,4)])

I want my output to be [3,7].  Each tuple is a data instance that I have, and each element of tuple is my feature.  I want to calculate the sum of each feature per all data samples.

Body:
You can do something like this:

z = zip(x, y)
#z is [(0, 0), (1, 1), (2, 2) ......]
map(np.sum, z)

that should do the trick.


问:
How to monitor operation response time for AWS Elasticache Redis?
I'm using CloudWatch to monitor other metrics but I can't find response time metric. Am I missing something here?</p>

答:
Pls configure the following cloudwatch metrics

Read - SelectLatency
Write - DMLLatency


问:
VueJS + VUEX - Problems Concerning Data Transfer
My component:

```<code><div id="event-picker">
  <template v-for="event in $store.state.events">
    <a href="#" v-on:click.prevent="$store.dispatch('prepareEventForm', event)">{{ event.artist }}</a>
  </template>
</div>
</code>```

My store (mutations):

```<code>prepareEventForm(state, event) {
  state.form.time = event.time
  state.form.date = event.date
  state.form.event = event.event
  state.form.artist = event.artist
  state.form.organizer = event.organizer
  state.form.location = event.location
  state.showForm = true
}
</code>```

The error I get is Cannot read property 'time' of undefined

Where could the problem be?

EDIT:

This is my action method:

```<code>prepareEventForm({ commit }) {
  commit('prepareEventForm')
}
</code>```

答:
The reason you are getting that error is that the event object being passed to your prepareEventForm mutation is undefined.

This is because when you call $store.dispatch('prepareEventForm', event), it calls your prepareEventForm action, passing event in as the second parameter.

You need to add event as the second parameter of your action and pass that as the second parameter in your commit call (which is what calls the prepareEventForm mutation):

```<code>prepareEventForm({ commit }, event) {
  commit('prepareEventForm', event)
}
</code>```

Body:
My component:

  <template v-for="event in $store.state.events">
    {{ event.artist }}
  </template>

My store (mutations):

prepareEventForm(state, event) {
  state.form.time = event.time
  state.form.date = event.date
  state.form.event = event.event
  state.form.artist = event.artist
  state.form.organizer = event.organizer
  state.form.location = event.location
  state.showForm = true
}

The error I get is Cannot read property 'time' of undefined

Where could the problem be?

EDIT:

This is my action method:

prepareEventForm({ commit }) {
  commit('prepareEventForm')
}

Body:
The reason you are getting that error is that the event object being passed to your prepareEventForm mutation is undefined.

This is because when you call $store.dispatch('prepareEventForm', event), it calls your prepareEventForm action, passing event in as the second parameter.

You need to add event as the second parameter of your action and pass that as the second parameter in your commit call (which is what calls the prepareEventForm mutation):

prepareEventForm({ commit }, event) {
  commit('prepareEventForm', event)
}