问:
Angular 4 - Router resolve not working with BehaviorSubject
Angular gurus your help is greatly appreciated in this regard.

Here is what I am trying to do, when I access main app page it calls getConfigs() from config.service.ts and get the data from backend then updates this.configStringSource.next(config).  Right after that I am trying to redirect it to this.router.navigate(['/clone/status']), but redirect is not happening.

app.routing.ts

```<code>import { Routes, RouterModule } from '@angular/router';

import { CloneComponent } from './clone/clone.component';
import { StatusComponent } from './status/status.component';
import { ConfigurationComponent } from './configuration/configuration.component';
import { LogsComponent } from './logs/logs.component';
import { ConfigResolver } from './_services/config-resolver.service';

const appRoutes: Routes = [
    { path: 'clone', component: CloneComponent, children: [
        {path: 'status', component: StatusComponent, resolve: {config: ConfigResolver} },
        ]
    },
    { path: 'logstream', component: LogstreamComponent },
];

export const AppRouting = RouterModule.forRoot(appRoutes);
</code>```

config.ts

```<code>export class Config {
    configID: string;
    sourceDbNodes: string;
    targetDbNodes: string;
}
</code>```

config.service.ts

```<code>import { Injectable, OnInit } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
//import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Router } from '@angular/router';
import {Subject} from 'rxjs/Subject';

import { Config } from '../_models/config';

@Injectable()
export class ConfigService {

    // Observable string source
    private configsStringSource = new BehaviorSubject<Config>({ configID: "", sourceDbNodes: "", targetDbNodes: ""});

    // Observable string stream
    configsString$ = this.configsStringSource.asObservable();

    // Service message commands
    updateConfigs(configs: Config) {
      this.configsStringSource.next(configs)
    }

    constructor(private http: Http, private router:Router) { }

    getConfigs() {
      let headers = new Headers();
      headers.append('Content-Type','application/json');
      return this.http.get('http://localhost:8080/sample1/api/config', { headers: headers })
        .map((response: Response) => response.json());
    }
}
</code>```

config-resolver.service.ts

```<code>import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';

import { ConfigService } from './config.service';
import { Config } from '../_models/config';

interface Server {
  id: number;
  name: string;
  status: string;
}

@Injectable()
export class ConfigResolver implements Resolve<Config> {

  config: Config;

  constructor(private configService: ConfigService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Config> | Promise<Config> | Config {
    return this.configService.configsString$.map(
      data => data[1]);
    }
}
</code>```

app.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Config } from './_models/config';
import { ConfigService } from './_services/config.service';

@Component({
  moduleId: module.id.toString(),
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  configs: Config[];

  constructor(private router:Router, private configService:ConfigService ) { }

  title = 'Angular 4 Proeject';

  private getConfigs() {
    this.configService.getConfigs().subscribe(configs => {
        this.configs = configs;
                this.configService.updateConfigs(configs);
console.log('app.component.ts sourceDbNode = '+this.configs[0].sourceDbNodes);
    });
  }

  ngOnInit() {
    this.getConfigs();
    this.router.navigate(['/clone/status']);
  }

}
</code>```

status.component.ts

```<code>import { Component, Input, OnInit, AfterContentChecked } from '@angular/core';
import { ActivatedRoute, Params, Router, Data } from '@angular/router';

import { Config } from '../_models/config';
import { ConfigService } from '../_services/config.service';

@Component({
  selector: 'app-status',
  template: `
    <p>
      status Works! {{config}}
    </p>
  `,
  styleUrls: ['./status.component.scss']
})

export class StatusComponent implements OnInit {

  configs: string;
  config: Config;
  servers: Array<any>;
  server: { id: number; name: string; status: string; };

  constructor(private configService:ConfigService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.route.data.subscribe(
        (data: Data) => {
          this.config = data['config'];
console.log('status.component.ts data = ', data['config']);
console.log('status.component.ts this.config = ', this.config);
        }
    );
  }
}
</code>```

答:
Your issue is that resolved observables need to complete, so you just need to add .take(1) or .first() to your resolver observable like:

```<code>resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Config> | Promise<Config> | Config {
    return this.configService.configsString$.map(
      data => data[1]).take(1);
}
</code>```

However, there's a much cleaner way of loading a config service:

```<code>import { Injectable, APP_INITIALIZER } from '@angular/core';
import { Config } from './_models/config';

@Injectable()
export class ConfigService {
  protected config: Config;

  constructor(private http: Http) {
  }

  getConfigs(): Observable<any> {
    let headers = new Headers();
    headers.append('Content-Type','application/json');
    return this.http.get('http://localhost:8080/sample1/api/config', { headers: headers })
               .map((response: Response) => response.json());
  }

  public load() {
     return new Promise((resolve, reject) => {
       this.getConfigs()
         .subscribe(
           config => {
             this.config = config;
             resolve(true);
           },
           err => resolve(err)
         );
     });
  }
}

export function ConfigServiceInitFactory(configService: ConfigService) {
  return () => configService.load();
}

export const ConfigServiceInitProvider = {
  provide: APP_INITIALIZER,
  useFactory: ConfigServiceInitFactory,
  deps: [ConfigService],
  multi: true
}
</code>```

then in your app module, import both ConfigService and ConfigServiceInitProvider and provide them both like this:

```<code>providers: [
  ConfigService,
  ConfigServiceInitProvider,
  ... remaining service providers..
]
</code>```

this will ensure that your config is loaded before pretty much anything else, and you can inject your config service where ever it's needed and the config will always be available in a synchronous manner.

Body:
Angular gurus your help is greatly appreciated in this regard.

Here is what I am trying to do, when I access main app page it calls getConfigs() from config.service.ts and get the data from backend then updates this.configStringSource.next(config).  Right after that I am trying to redirect it to this.router.navigate(['/clone/status']), but redirect is not happening.

app.routing.ts

import { Routes, RouterModule } from '@angular/router';

import { CloneComponent } from './clone/clone.component';
import { StatusComponent } from './status/status.component';
import { ConfigurationComponent } from './configuration/configuration.component';
import { LogsComponent } from './logs/logs.component';
import { ConfigResolver } from './_services/config-resolver.service';

const appRoutes: Routes = [
    { path: 'clone', component: CloneComponent, children: [
        {path: 'status', component: StatusComponent, resolve: {config: ConfigResolver} },
        ]
    },
    { path: 'logstream', component: LogstreamComponent },
];

export const AppRouting = RouterModule.forRoot(appRoutes);

config.ts

export class Config {
    configID: string;
    sourceDbNodes: string;
    targetDbNodes: string;
}

config.service.ts

import { Injectable, OnInit } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
//import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Router } from '@angular/router';
import {Subject} from 'rxjs/Subject';

import { Config } from '../_models/config';

@Injectable()
export class ConfigService {

    // Observable string source
    private configsStringSource = new BehaviorSubject<Config>({ configID: "", sourceDbNodes: "", targetDbNodes: ""});

    // Observable string stream
    configsString$ = this.configsStringSource.asObservable();

    // Service message commands
    updateConfigs(configs: Config) {
      this.configsStringSource.next(configs)
    }

    constructor(private http: Http, private router:Router) { }

    getConfigs() {
      let headers = new Headers();
      headers.append('Content-Type','application/json');
      return this.http.get('http://localhost:8080/sample1/api/config', { headers: headers })
        .map((response: Response) => response.json());
    }
}

config-resolver.service.ts

import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';

import { ConfigService } from './config.service';
import { Config } from '../_models/config';

interface Server {
  id: number;
  name: string;
  status: string;
}

@Injectable()
export class ConfigResolver implements Resolve<Config> {

  config: Config;

  constructor(private configService: ConfigService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Config> | Promise<Config> | Config {
    return this.configService.configsString$.map(
      data => data[1]);
    }
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Config } from './_models/config';
import { ConfigService } from './_services/config.service';

@Component({
  moduleId: module.id.toString(),
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  configs: Config[];

  constructor(private router:Router, private configService:ConfigService ) { }

  title = 'Angular 4 Proeject';

  private getConfigs() {
    this.configService.getConfigs().subscribe(configs => {
        this.configs = configs;
                this.configService.updateConfigs(configs);
console.log('app.component.ts sourceDbNode = '+this.configs[0].sourceDbNodes);
    });
  }

  ngOnInit() {
    this.getConfigs();
    this.router.navigate(['/clone/status']);
  }

}

status.component.ts

import { Component, Input, OnInit, AfterContentChecked } from '@angular/core';
import { ActivatedRoute, Params, Router, Data } from '@angular/router';

import { Config } from '../_models/config';
import { ConfigService } from '../_services/config.service';

@Component({
  selector: 'app-status',
  template: `

      status Works! {{config}}

  `,
  styleUrls: ['./status.component.scss']
})

export class StatusComponent implements OnInit {

  configs: string;
  config: Config;
  servers: Array<any>;
  server: { id: number; name: string; status: string; };

  constructor(private configService:ConfigService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.route.data.subscribe(
        (data: Data) => {
          this.config = data['config'];
console.log('status.component.ts data = ', data['config']);
console.log('status.component.ts this.config = ', this.config);
        }
    );
  }
}

Body:
Your issue is that resolved observables need to complete, so you just need to add .take(1) or .first() to your resolver observable like:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Config> | Promise<Config> | Config {
    return this.configService.configsString$.map(
      data => data[1]).take(1);
}

However, there's a much cleaner way of loading a config service:

import { Injectable, APP_INITIALIZER } from '@angular/core';
import { Config } from './_models/config';

@Injectable()
export class ConfigService {
  protected config: Config;

  constructor(private http: Http) {
  }

  getConfigs(): Observable<any> {
    let headers = new Headers();
    headers.append('Content-Type','application/json');
    return this.http.get('http://localhost:8080/sample1/api/config', { headers: headers })
               .map((response: Response) => response.json());
  }

  public load() {
     return new Promise((resolve, reject) => {
       this.getConfigs()
         .subscribe(
           config => {
             this.config = config;
             resolve(true);
           },
           err => resolve(err)
         );
     });
  }
}

export function ConfigServiceInitFactory(configService: ConfigService) {
  return () => configService.load();
}

export const ConfigServiceInitProvider = {
  provide: APP_INITIALIZER,
  useFactory: ConfigServiceInitFactory,
  deps: [ConfigService],
  multi: true
}

then in your app module, import both ConfigService and ConfigServiceInitProvider and provide them both like this:

providers: [
  ConfigService,
  ConfigServiceInitProvider,
  ... remaining service providers..
]

this will ensure that your config is loaded before pretty much anything else, and you can inject your config service where ever it's needed and the config will always be available in a synchronous manner.


来源: stackexchange

问:
Updating column with unique constraint/index in Firebird in multiple rows
I have a table that looks like this:

```<code>CREATE TABLE SCHEDULE (
    RCDNO              INTEGER NOT NULL,
    MASTCONNO          INTEGER NOT NULL,
    ROWNO              INTEGER DEFAULT 0 NOT NULL,
    EDITTIMESTAMP      TIMESTAMP
)
ALTER TABLE SCHEDULE ADD CONSTRAINT PK_SCHEDULE PRIMARY KEY (RCDNO);
CREATE UNIQUE INDEX IDX_SCHEDULE_3 ON SCHEDULE (MASTCONNO, ROWNO);
</code>```

I can run a query like this:

```<code>select mastconno, rowno, rcdno, edittimestamp
from schedule
where mastconno = 12
order by rowno desc
</code>```

and I get this:

Due to a bug in the app code, the time portion of the edittimestamp is missing but that's of no consequence here. The records are nonetheless listed in desc order of entry by ROWNO. That's what the design of this table is meant to facilitate.

What I tried to do is this...

```<code>update SCHEDULE
set ROWNO = (ROWNO + 1)
where MASTCONNO = 12
</code>```

... in preparation for the insert of a new ROWNO=0 record, I get this error:

```<code>attempt to store duplicate value (visible to active transactions) in unique index "IDX_SCHEDULE_3".
Problematic key value is ("MASTCONNO" = 12, "ROWNO" = 3).
</code>```

Incidently I have an exact copy of the table in MS SQL Server, and I didn't have this problem there. This seems to be specific to the way Firebird works.

So then I tried this, hoping that Firebird would "feed" values from the IN predicate to the UPDATE in a non-offending order.

```<code>update SCHEDULE
set ROWNO = (ROWNO + 1)
where MASTCONNO = 12 and
ROWNO in (select ROWNO from SCHEDULE
where MASTCONNO = 12 order by ROWNO DESC)
</code>```

Sadly the response was the same as before. ROWNO 3 is being duplicated by the update statement.

答:
Indeed, constraint checks and triggers Firebird runs per every row, not per transaction or per table.

So you would have to use the same loop-based approach you use in applications dealing with lists and arrays.

You have to use EXECUTE BLOCK and a properly directed loop.

http://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-dml-execblock.html

You take MAXimum ID that is of interest, and increment it.
Then you take previous value.
Then previous...

```<code>EXECUTE BLOCK
AS
  DECLARE ID INTEGER;
BEGIN
  ID = ( SELECT MAX(ROWNO) FROM SCHEDULE WHERE MASTCONNO = 12 );

/*
  ID = NULL;
  SELECT MAX(ROWNO) FROM SCHEDULE WHERE MASTCONNO = 12 INTO :ID;
  IF (ID IS NULL) raise-some-error-somehow
*/
  While (ID >= 0)
  Begin
    update SCHEDULE set ROWNO = (ID + 1)
       where MASTCONNO = 12 and :ID = ROWNO;
    ID = ID - 1;
  End
END
</code>```

DANGER!

If while you started are doing it some another transaction (maybe from another program working at another computer) inserts some new row with MASTCONNO = 12 and commits it - you have problems.

Firebird is multi-versions server, not table-blocking server, so there will be nothing in server, that prohibits this insert because your procedure is working on the table. Then you have race conditions, the fastest transaction would commit itself, and the slower one would fail with unique index violation.

You may also use FOR-SELECT loop instead of WHILE loop.

https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-psql-coding.html#fblangref25-psql-forselect

Like this

```<code>EXECUTE BLOCK
AS
BEGIN
  FOR
    SELECT * FROM SCHEDULE
      WHERE MASTCONNO = 12
      ORDER BY ROWNO DESCENDING  -- proper loop direction: ordering is key!
      AS CURSOR PTR
  DO
    UPDATE SCHEDULE SET ROWNO = ROWNO + 1
      WHERE CURRENT OF PTR;
END
</code>```

However, in Firebird 3 cursors-based positioning became rather slow.

ContentLicense: CC BY-SA 3.0

Body:
I have a table that looks like this:

CREATE TABLE SCHEDULE (
    RCDNO              INTEGER NOT NULL,
    MASTCONNO          INTEGER NOT NULL,
    ROWNO              INTEGER DEFAULT 0 NOT NULL,
    EDITTIMESTAMP      TIMESTAMP
)
ALTER TABLE SCHEDULE ADD CONSTRAINT PK_SCHEDULE PRIMARY KEY (RCDNO);
CREATE UNIQUE INDEX IDX_SCHEDULE_3 ON SCHEDULE (MASTCONNO, ROWNO);

I can run a query like this:

select mastconno, rowno, rcdno, edittimestamp
from schedule
where mastconno = 12
order by rowno desc

and I get this:

Due to a bug in the app code, the time portion of the edittimestamp is missing but that's of no consequence here. The records are nonetheless listed in desc order of entry by ROWNO. That's what the design of this table is meant to facilitate.

What I tried to do is this...

update SCHEDULE
set ROWNO = (ROWNO + 1)
where MASTCONNO = 12

... in preparation for the insert of a new ROWNO=0 record, I get this error:

attempt to store duplicate value (visible to active transactions) in unique index "IDX_SCHEDULE_3".
Problematic key value is ("MASTCONNO" = 12, "ROWNO" = 3).

Incidently I have an exact copy of the table in MS SQL Server, and I didn't have this problem there. This seems to be specific to the way Firebird works.

So then I tried this, hoping that Firebird would "feed" values from the IN predicate to the UPDATE in a non-offending order.

update SCHEDULE
set ROWNO = (ROWNO + 1)
where MASTCONNO = 12 and
ROWNO in (select ROWNO from SCHEDULE
where MASTCONNO = 12 order by ROWNO DESC)

Sadly the response was the same as before. ROWNO 3 is being duplicated by the update statement.

Body:
Indeed, constraint checks and triggers Firebird runs per every row, not per transaction or per table.

So you would have to use the same loop-based approach you use in applications dealing with lists and arrays.

You have to use EXECUTE BLOCK and a properly directed loop.

http://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-dml-execblock.html

You take MAXimum ID that is of interest, and increment it.
Then you take previous value.
Then previous...

EXECUTE BLOCK
AS
  DECLARE ID INTEGER;
BEGIN
  ID = ( SELECT MAX(ROWNO) FROM SCHEDULE WHERE MASTCONNO = 12 );

/*
  ID = NULL;
  SELECT MAX(ROWNO) FROM SCHEDULE WHERE MASTCONNO = 12 INTO :ID;
  IF (ID IS NULL) raise-some-error-somehow
*/
  While (ID >= 0)
  Begin
    update SCHEDULE set ROWNO = (ID + 1)
       where MASTCONNO = 12 and :ID = ROWNO;
    ID = ID - 1;
  End
END

DANGER!

If while you started are doing it some another transaction (maybe from another program working at another computer) inserts some new row with MASTCONNO = 12 and commits it - you have problems.

Firebird is multi-versions server, not table-blocking server, so there will be nothing in server, that prohibits this insert because your procedure is working on the table. Then you have race conditions, the fastest transaction would commit itself, and the slower one would fail with unique index violation.

You may also use FOR-SELECT loop instead of WHILE loop.

https://www.firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-psql-coding.html#fblangref25-psql-forselect

Like this

EXECUTE BLOCK
AS
BEGIN
  FOR
    SELECT * FROM SCHEDULE
      WHERE MASTCONNO = 12
      ORDER BY ROWNO DESCENDING  -- proper loop direction: ordering is key!
      AS CURSOR PTR
  DO
    UPDATE SCHEDULE SET ROWNO = ROWNO + 1
      WHERE CURRENT OF PTR;
END

However, in Firebird 3 cursors-based positioning became rather slow.


问:
Lock screen orientation when targeting Android API 27 with a non-opaque activity
I have an activity that has android:windowIsTranslucent set to true and android:windowBackground set to a translucent background. I just changed my target and compile sdk version to 27, and I get an exception when launching this activity now:

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

Since this is a new sdk, there isn't anything online about it yet (and it seems to result from this line of code: https://android.googlesource.com/platform/frameworks/base.git/+/master/core/java/android/app/Activity.java#987 )

Is there any way to get around this? The app doesn't crash if I take out android:screenOrientation="portrait" from my manifest for this activity, but I would like to be able to keep it like that.

答:
The workaround is to set targetSdk back to 26.

The reason why is your application crashes is here in this commit.

As you can see here, you are not the only one - this behavior has been reported to Google as issue. It has been fixed, but we don't know how and when it will be released.

I can also confirm what "sofakingforever" says in comments, if there is non-translucent activity with fixed orientation behind your translucent, the translucent will not rotate. So you can just remove android:screenOrientation="portrait" from manifest as well.


问:
Use of volatile keyword on the flag field
I try to understand the use of volatile in multithread context. In the following code from another source of knowledge on the Internet:

```<code>class Program
{
    static string _result;
    //static volatile bool _done;
    static bool _done;

    static void SetVolatile()
    {
        // Set the string.
        _result = "Dot Net Perls";
        // The volatile field must be set at the end of this method.
        _done = true;
    }

    static void Main()
    {
        // Run the above method on a new thread.
        new Thread(new ThreadStart(SetVolatile)).Start();

        // Wait a while.
        Thread.Sleep(200);

        // Read the volatile field.
        if (_done)
        {
            Console.WriteLine(_result);
        }
    }
}
</code>```

The demonstrated use of a volatile keyword should prevent a thread from reading a value stored in a cache. Instead of this it should check an actual value.

So without a volatile _done should still have a false value (read from the cache) and Console.WriteLine statement should not be executed.

Unfortunately running this code in Debug/Release mode without a volatile keyword always produces the output. What is the point of this particular example?

答:
As already said, not using volatile keyword does not mean all reads will necessary be cached in all circumstances. They may be cached, or may be not. But if you want more reproducable example, try this:

```<code>class Program {
    static string _result;
    //static volatile bool _done;
    static bool _done;
    static void SetVolatile() {
        // Set the string.
        _result = "Dot Net Perls";
        // The volatile field must be set at the end of this method.
        _done = true;
    }

    static void Main() {
        // Run the above method on a new thread.
        new Thread(new ThreadStart(SetVolatile)).Start();

        // prevent compiler to throw away empty while loop
        // by doing something in it
        int i = 0;
        while (!_done) {
            i++;
        }
        Console.WriteLine("done " + i);
    }
}
</code>```

Here you repeatedly read _done in a while loop, increasing possibility it will be cached. Program should terminate with "done" message but will not, because change to _done from another thread will not be noticed.

Body:
I try to understand the use of volatile in multithread context. In the following code from another source of knowledge on the Internet:

class Program
{
    static string _result;
    //static volatile bool _done;
    static bool _done;

    static void SetVolatile()
    {
        // Set the string.
        _result = "Dot Net Perls";
        // The volatile field must be set at the end of this method.
        _done = true;
    }

    static void Main()
    {
        // Run the above method on a new thread.
        new Thread(new ThreadStart(SetVolatile)).Start();

        // Wait a while.
        Thread.Sleep(200);

        // Read the volatile field.
        if (_done)
        {
            Console.WriteLine(_result);
        }
    }
}

The demonstrated use of a volatile keyword should prevent a thread from reading a value stored in a cache. Instead of this it should check an actual value.

So without a volatile _done should still have a false value (read from the cache) and Console.WriteLine statement should not be executed.

Unfortunately running this code in Debug/Release mode without a volatile keyword always produces the output. What is the point of this particular example?

Body:
As already said, not using volatile keyword does not mean all reads will necessary be cached in all circumstances. They may be cached, or may be not. But if you want more reproducable example, try this:

class Program {
    static string _result;
    //static volatile bool _done;
    static bool _done;
    static void SetVolatile() {
        // Set the string.
        _result = "Dot Net Perls";
        // The volatile field must be set at the end of this method.
        _done = true;
    }

    static void Main() {
        // Run the above method on a new thread.
        new Thread(new ThreadStart(SetVolatile)).Start();

        // prevent compiler to throw away empty while loop
        // by doing something in it
        int i = 0;
        while (!_done) {
            i++;
        }
        Console.WriteLine("done " + i);
    }
}

Here you repeatedly read _done in a while loop, increasing possibility it will be cached. Program should terminate with "done" message but will not, because change to _done from another thread will not be noticed.


问:
Load data in view in Laravel
I have a simple controller function that fetch all records from db. but when i am trying to show all these records it show nothing. In fact it shows me hard coded foreach loop like this.

```<code> @foreach ($compactData as $value) {{ $value->Name }} @endforeach
</code>```

this is my contoller function.

```<code>public function showallProducts()
{
    $productstock = Product::all()->stocks;
    $productoldprice = Product::all()->OldPrices;
    $productcurrentprice = Product::all()->CurrentPrice;
    $compactData=array('productstock', 'productoldprice', 'productcurrentprice');
    return view('welcome', compact($compactData));
}
</code>```

this is my view

```<code>       <!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>

 </head>
 <body>
    <div class="flex-center position-ref full-height">

        <div class="content">
            <div class="title m-b-md">
                Laravel
            </div>

            <div class="title m-b-md">
                All products
            </div>

            <table>

                <tbody>
                @foreach ($compactData as $value)
                    {{ $value->Name }}

                @endforeach

                </tbody>

            </table>
        </div>
    </div>
</body>
</code>```

 why it is behaving like this. any solution?? I am using phpstorm version 17. Is their any setting issue to run project because what ever project I ran it gives me the only page which i ran with only html?
My route is.

```<code>   Route::get('/', function () {

    $action = 'showallProducts';
    return App::make('ProductController')->$action();
 });
</code>```

答:
I think you didn't mention the blade in the name of the view file by which it is saved. So change the name of the file by which it is save to something like:

```<code>filename.blade.php
</code>```

and try again.

Explanation:

@foreach ($compactData as $value) this is the syntax of blade template engine, and to parse and excute it, you have to mention the blade extension in the name.

Title: Load data in view in Laravel

Body:
I have a simple controller function that fetch all records from db. but when i am trying to show all these records it show nothing. In fact it shows me hard coded foreach loop like this.

 @foreach ($compactData as $value) {{ $value->Name }} @endforeach

this is my contoller function.

public function showallProducts()
{
    $productstock = Product::all()->stocks;
    $productoldprice = Product::all()->OldPrices;
    $productcurrentprice = Product::all()->CurrentPrice;
    $compactData=array('productstock', 'productoldprice', 'productcurrentprice');
    return view('welcome', compact($compactData));
}

this is my view

       <!doctype html>
getLocale() }}">

                Laravel

                All products

                @foreach ($compactData as $value)
                    {{ $value->Name }}

                @endforeach

 why it is behaving like this. any solution?? I am using phpstorm version 17. Is their any setting issue to run project because what ever project I ran it gives me the only page which i ran with only html?
My route is.

   Route::get('/', function () {

    $action = 'showallProducts';
    return App::make('ProductController')->$action();
 });

Body:
I think you didn't mention the blade in the name of the view file by which it is saved. So change the name of the file by which it is save to something like:

filename.blade.php

and try again.

Explanation:

@foreach ($compactData as $value) this is the syntax of blade template engine, and to parse and excute it, you have to mention the blade extension in the name.


问:
KeyBinding with Command Binding dont work with TextBox UpdateSourceTrigger LostFocus
I'm using MVVM and have the following problem. My TextBox.Text is bound with UpdateSourceTrigger=LostFocus (thats what the user want). I have a Button with a SaveCommand CommandBinding - this works. Now i have a KeyBinding with Strg+S wich also execute the SaveCommand. And here is the problem: when i m in the Textbox and press Strg+s, the changes are not in the viewmodel.

is there any way to get MVVM Commands with KeyBinding and TextBox UpdateSourceTrigger=LostFocus working together?

some code to check out the problem

```<code><Window>
<Window.InputBindings>
    <KeyBinding Key="S" Modifiers="Control" Command="{Binding SaveCommand}"></KeyBinding>
</Window.InputBindings>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TextBox Grid.Row="0" Text="{Binding MyText1, UpdateSourceTrigger=LostFocus}" Width="100"></TextBox>
    <Button Grid.Row="1" Content="_Save" Command="{Binding SaveCommand}" IsDefault="True"></Button>
</Grid>
</Window>

public partial class MainWindow : Window
{
    private Viewmodel _data;
    public MainWindow()
    {
        _data = new Viewmodel();
        InitializeComponent();
        this.DataContext = _data;
    }
}

public class Viewmodel : INPCBase
{
    private string _myText1;
    private Lazy<DelegateCommand> _save;

    public Viewmodel()
    {
        this._save = new Lazy<DelegateCommand>(()=> new DelegateCommand(this.SaveCommandExecute));
    }

    private void SaveCommandExecute()
    {
        MessageBox.Show(MyText1);
    }

    public string MyText1
    {
        get { return _myText1; }
        set { _myText1 = value; this.NotifyPropertyChanged(()=>MyText1);}
    }

    public ICommand SaveCommand
    {
        get { return _save.Value; }
    }
}
</code>```

答:
I think I find the best solution for me. I mix solution @blindmeis and my previous one with using attached property.

I create command which update binding source of actual keyboard focused element:

```<code>public class CommitValueCommand : ICommand
{
    private static CommitValueCommand _instance;
    public static CommitValueCommand Command => _instance ?? (_instance = new CommitValueCommand());

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        if (Keyboard.FocusedElement is TextBox textBox)
        {
            BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty).UpdateSource();
        }
        //for combobox etc.
        else if (Keyboard.FocusedElement is Selector selector)
        {
            BindingOperations.GetBindingExpression(selector, Selector.SelectedValueProperty).UpdateSource();
        }
    }
}
</code>```

In Execute method of command SaveCommand just at beginning invoke CommitValueCommand.Command.Execute().

Body:
I'm using MVVM and have the following problem. My TextBox.Text is bound with UpdateSourceTrigger=LostFocus (thats what the user want). I have a Button with a SaveCommand CommandBinding - this works. Now i have a KeyBinding with Strg+S wich also execute the SaveCommand. And here is the problem: when i m in the Textbox and press Strg+s, the changes are not in the viewmodel.

is there any way to get MVVM Commands with KeyBinding and TextBox UpdateSourceTrigger=LostFocus working together?

some code to check out the problem

<Window>
<Window.InputBindings>
    <KeyBinding Key="S" Modifiers="Control" Command="{Binding SaveCommand}"></KeyBinding>
</Window.InputBindings>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TextBox Grid.Row="0" Text="{Binding MyText1, UpdateSourceTrigger=LostFocus}" Width="100"></TextBox>
    <Button Grid.Row="1" Content="_Save" Command="{Binding SaveCommand}" IsDefault="True"></Button>
</Grid>
</Window>

public partial class MainWindow : Window
{
    private Viewmodel _data;
    public MainWindow()
    {
        _data = new Viewmodel();
        InitializeComponent();
        this.DataContext = _data;
    }
}

public class Viewmodel : INPCBase
{
    private string _myText1;
    private Lazy<DelegateCommand> _save;

    public Viewmodel()
    {
        this._save = new Lazy<DelegateCommand>(()=> new DelegateCommand(this.SaveCommandExecute));
    }

    private void SaveCommandExecute()
    {
        MessageBox.Show(MyText1);
    }

    public string MyText1
    {
        get { return _myText1; }
        set { _myText1 = value; this.NotifyPropertyChanged(()=>MyText1);}
    }

    public ICommand SaveCommand
    {
        get { return _save.Value; }
    }
}

Body:
I think I find the best solution for me. I mix solution @blindmeis and my previous one with using attached property.

I create command which update binding source of actual keyboard focused element:

public class CommitValueCommand : ICommand
{
    private static CommitValueCommand _instance;
    public static CommitValueCommand Command => _instance ?? (_instance = new CommitValueCommand());

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        if (Keyboard.FocusedElement is TextBox textBox)
        {
            BindingOperations.GetBindingExpression(textBox, TextBox.TextProperty).UpdateSource();
        }
        //for combobox etc.
        else if (Keyboard.FocusedElement is Selector selector)
        {
            BindingOperations.GetBindingExpression(selector, Selector.SelectedValueProperty).UpdateSource();
        }
    }
}

In Execute method of command SaveCommand just at beginning invoke CommitValueCommand.Command.Execute().


问:
How to use glyphicon in HTML helpers?
I have this anchor element that displays glyphicon and some style:

```<code><a href="#" class="btn btn-3d btn-xlg btn-reveal btn-brown">
    <i class="glyphicon glyphicon-arrow-right"></i>
    <span>REVEAL EXTRA LARGE</span>
</a>
</code>```

In my project I use HTML helper to create anchor elements.

I have this html helper  to create anchor element:

```<code>@Html.ActionLink(item.Name, "About", "Home", item, new { @class = "btn btn-3d btn-xlg btn-reveal btn-brown" })
</code>```

But I don't know how to add    element to the HTML helper.

How can I define  inside HTML helper?

答:
Use @Url.Action

```<code><a href="@Url.Action("About", "Home")" class="btn btn-3d btn-xlg btn-reveal btn-brown">
  <i class="glyphicon glyphicon-arrow-right"></i>
  <span>REVEAL EXTRA LARGE</span>
</a>
</code>```

Title: How to use glyphicon in HTML helpers?

Body:
I have this anchor element that displays glyphicon and some style:

    REVEAL EXTRA LARGE

In my project I use HTML helper to create anchor elements.

I have this html helper  to create anchor element:

@Html.ActionLink(item.Name, "About", "Home", item, new { @class = "btn btn-3d btn-xlg btn-reveal btn-brown" })

But I don't know how to add    element to the HTML helper.

How can I define  inside HTML helper?

Body:
Use @Url.Action

<a href="@Url.Action("About", "Home")" class="btn btn-3d btn-xlg btn-reveal btn-brown">
  <i class="glyphicon glyphicon-arrow-right"></i>
  <span>REVEAL EXTRA LARGE</span>
</a>


问:
Fill HTML element with text based on input with JavaScript
The code right now works only to fill another input field. But I need it to fill a regular paragraph and not another input field. How can I do it?

$(".first").on('keydown',function(){
  $(".second").val($(this).val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="first" placeholder="type here">
<input type="text" class="second" placeholder="here it is the reuslt"></code>```

答:
Form fields have a value property (val() method in JQuery). Regular elements have a textContent property (or in JQuery, a text() method).

Also, you should use keyup to get all the text as it is typed.

$(".first").on('keyup',function(){
    $("#output").text($(this).val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="first" placeholder="type here">
<p id="output"></p></code>```

Body:
The code right now works only to fill another input field. But I need it to fill a regular paragraph and not another input field. How can I do it?

$(".first").on('keydown',function(){
  $(".second").val($(this).val());
});

<input type="text" class="first" placeholder="type here">
<input type="text" class="second" placeholder="here it is the reuslt">

Body:
Form fields have a value property (val() method in JQuery). Regular elements have a textContent property (or in JQuery, a text() method).

Also, you should use keyup to get all the text as it is typed.

$(".first").on('keyup',function(){
    $("#output").text($(this).val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="first" placeholder="type here">
<p id="output"></p>


问:
Get URL of variation image thumbnails in WooCommerce
I'm using the following code to grab the image of every variation for a particular product:

```<code>$product = new WC_Product_Variable( $product_id );
$variations = $product->get_available_variations();

foreach ( $variations as $variation ) {
  echo "<img src=" . $variation['image']['url'] .">";
}
</code>```

This returns the full size image.

Can anyone tell me how I would modify this to return the 'thumbnail' URL? (or any other size)

I'm sure it's a fairly simple change but I just can't figure it out.

答:
Use thumb_src instead of url.</p>

```<code>$product = new WC_Product_Variable( $product_id );
$variations = $product->get_available_variations();

foreach ( $variations as $variation ) {
  echo "<img src=" . $variation['image']['thumb_src'] .">";
}
</code>```

Body:
I'm using the following code to grab the image of every variation for a particular product:

$product = new WC_Product_Variable( $product_id );
$variations = $product->get_available_variations();

foreach ( $variations as $variation ) {
  echo "";
}

This returns the full size image.

Can anyone tell me how I would modify this to return the 'thumbnail' URL? (or any other size)

I'm sure it's a fairly simple change but I just can't figure it out.

Body:
Use thumb_src instead of url.

$product = new WC_Product_Variable( $product_id );
$variations = $product->get_available_variations();

foreach ( $variations as $variation ) {
  echo "<img src=" . $variation['image']['thumb_src'] .">";
}


问:
$timeout in inside the foreach
I Want to simulate player and move him using the reading below

```<code>$scope.playerPositions =
             [
                 { playerId: 2028, left: 180, top: 19, heading: 90 },
                 { playerId: 2028, left: 185, top: 19, heading: 100 },
                 { playerId: 2028, left: 190, top: 19, heading: 110 },
                 { playerId: 2028, left: 195, top: 19, heading: 120 },
                 { playerId: 2028, left: 200, top: 19, heading: 130 },
                 { playerId: 2028, left: 205, top: 19, heading: 140 },
                 { playerId: 2028, left: 210, top: 19, heading: 150 },
                 { playerId: 2028, left: 215, top: 19, heading: 160 },
                 { playerId: 2028, left: 220, top: 19, heading: 170 },
                 { playerId: 2028, left: 225, top: 19, heading: 180 },
                 { playerId: 2028, left: 230, top: 19, heading: 190 },
                 { playerId: 2028, left: 235, top: 19, heading: 200 },
                 { playerId: 2028, left: 240, top: 19, heading: 210 },
                 { playerId: 2028, left: 245, top: 19, heading: 220 }
                 ];
</code>```

and Loop on every Readings

```<code>angular.forEach(reading, function (value, key) {
                    $timeout(function () {
                        $scope[value.playerId].pos.left = value.left + "px";
                        $scope[value.playerId].pos.top = value.top + "px";
                        $scope[value.playerId].heading = value.heading;
                    }, 1000);
                });
</code>```

first time the loop and $timeout function is hitting correct. but the foreach continuously start the 2nd,3,rd looping without wait for the delay.

答:
If you are using lodash in your project then it becomes very easy

```<code>_.debounce(() => {

    console.log('do something after 500ms');

}, 500);
</code>```

If you want to use Observables then you can use debounceTime https://v4.angular.io/tutorial/toh-pt6#observables

Title: $timeout in inside the foreach

Body:
I Want to simulate player and move him using the reading below

$scope.playerPositions =
             [
                 { playerId: 2028, left: 180, top: 19, heading: 90 },
                 { playerId: 2028, left: 185, top: 19, heading: 100 },
                 { playerId: 2028, left: 190, top: 19, heading: 110 },
                 { playerId: 2028, left: 195, top: 19, heading: 120 },
                 { playerId: 2028, left: 200, top: 19, heading: 130 },
                 { playerId: 2028, left: 205, top: 19, heading: 140 },
                 { playerId: 2028, left: 210, top: 19, heading: 150 },
                 { playerId: 2028, left: 215, top: 19, heading: 160 },
                 { playerId: 2028, left: 220, top: 19, heading: 170 },
                 { playerId: 2028, left: 225, top: 19, heading: 180 },
                 { playerId: 2028, left: 230, top: 19, heading: 190 },
                 { playerId: 2028, left: 235, top: 19, heading: 200 },
                 { playerId: 2028, left: 240, top: 19, heading: 210 },
                 { playerId: 2028, left: 245, top: 19, heading: 220 }
                 ];

and Loop on every Readings

angular.forEach(reading, function (value, key) {
                    $timeout(function () {
                        $scope[value.playerId].pos.left = value.left + "px";
                        $scope[value.playerId].pos.top = value.top + "px";
                        $scope[value.playerId].heading = value.heading;
                    }, 1000);
                });

first time the loop and $timeout function is hitting correct. but the foreach continuously start the 2nd,3,rd looping without wait for the delay.

Body:
If you are using lodash in your project then it becomes very easy

_.debounce(() => {

    console.log('do something after 500ms');

}, 500);

If you want to use Observables then you can use debounceTime https://v4.angular.io/tutorial/toh-pt6#observables


问:
CakePHP 3 Passing value depending on which image button is clicked
I'm using CakePHP 3. I'm having a form with several elements e.g. text inputs. I would like to additionally add 6 images, one of which should be selected at a time. How can I pass a (hidden) value in a form depending on which image button is clicked (selected). I do not want to make the images the submit buttons. I would like to have them as one of several elements in a form, one on them should always be marked.</p>

答:
I would use Javascript with an onclick event handler on the images div.

https://www.w3schools.com/jsref/event_onclick.asp

On click you could inject a hidden field with e.g. an Image ID in the Form.


问:
How to make Ladda work with angular2 application
I am trying to integrate ladda with my angular2 app. I am basically trying to import the library and use the Ladda variable. Angular didnt seems to find that variable. any suggestions. </p>

答:
```<code>import Ladda from 'ladda';

export class someComponent implements AfterViewInit {
    @ViewChild('yourButton') yourButton: ElementRef;
    l: any;

    ngAfterViewInit() {
        this.l = Ladda.create(this.scbutton.nativeElement);
        this.l.start();
    }
}
</code>```


问:
nVarchar and SqlParameter
I'm developing an application which must support several languages. To solve the special characters problem I'm using NVarhcar for my text fields. So my SQL query for a text field is

```<code>insert into tbl_text(text)values(N'Chci tančit v oblasti')
</code>```

My problem is to put it in SqlCommand, wich is "insert into tbl_text(text)values(N@text)". It saves "N@text" in the DB table, sure.

Do you guys know someway to do it? I'm using C# and SQL 2008.

Sorry if it was hard to understand my question. My English is poor =/

答:
Add(string, object) has been deprecated for this reason (from Pablo Castro of the SQL Server team):

The problem is that both the C# and
  the VB.NET compilers will expose very
  weird behavior for this code:

command.Parameters.Add(“@p”, 0);

you may expect this to use the
  overload that takes an object and
  assign the value 0 to it, but instead
  it will pick the overload that takes a
  SqlDbType as the second parameter! In
  order to avoid this (and potentially
  others) ambiguity between the
  Add(string, sqldbtype) and Add(string,
  object), we deprecated Add(string,
  object) and introduced
  AddWithValue(string, object). In
  general, having multiple overloads
  where the distinguishing parameter
  type is “object” in one of them is a
  dangerous thing to do.

Title: nVarchar and SqlParameter

Body:
I'm developing an application which must support several languages. To solve the special characters problem I'm using NVarhcar for my text fields. So my SQL query for a text field is

insert into tbl_text(text)values(N'Chci tančit v oblasti')

My problem is to put it in SqlCommand, wich is "insert into tbl_text(text)values(N@text)". It saves "N@text" in the DB table, sure.

Do you guys know someway to do it? I'm using C# and SQL 2008.

Sorry if it was hard to understand my question. My English is poor =/

ContentLicense: CC BY-SA 2.5


答:
If you want to use $timeout to regularly call the angular.forEach, it won't work unless you chain the $timeout with its promise like below. Make sure your angular version is latest

```<code>let promise = $timeout();
angular.forEach(reading, function(value, key) {
     promise = promise.then(function() {
          $scope[value.playerId].pos.left = value.left + "px";
             $scope[value.playerId].pos.top = value.top + "px";
             $scope[value.playerId].heading = value.heading;
         return $timeout(1000);
     });
});
</code>```

You can achieve the same using setInterval function, which will call the function regularly at the interval of 1 second.

```<code>function wantedLooping() {
         angular.forEach(reading, function(value, key) {

             $scope[value.playerId].pos.left = value.left + "px";
             $scope[value.playerId].pos.top = value.top + "px";
             $scope[value.playerId].heading = value.heading;

         });
     }
     setInterval(function() {
         wantedLooping()
     }, 1000);
</code>```

Title: $timeout in inside the foreach

Body:
If you want to use $timeout to regularly call the angular.forEach, it won't work unless you chain the $timeout with its promise like below. Make sure your angular version is latest

let promise = $timeout();
angular.forEach(reading, function(value, key) {
     promise = promise.then(function() {
          $scope[value.playerId].pos.left = value.left + "px";
             $scope[value.playerId].pos.top = value.top + "px";
             $scope[value.playerId].heading = value.heading;
         return $timeout(1000);
     });
});

You can achieve the same using setInterval function, which will call the function regularly at the interval of 1 second.

function wantedLooping() {
         angular.forEach(reading, function(value, key) {

             $scope[value.playerId].pos.left = value.left + "px";
             $scope[value.playerId].pos.top = value.top + "px";
             $scope[value.playerId].heading = value.heading;

         });
     }
     setInterval(function() {
         wantedLooping()
     }, 1000);


问:
MySQL - Select row if appear more than x times in other table
Lets say I have two tables, Members and Orders with a 1:N relation:

```<code>Members         | Orders
UserID  Name    | OrderID   UserID  Name
111     Peter   | 777       111     Peter
222     Bart    | 888       333     Joe
333     Joe     | 999       111     Peter
444     Andrew  | 101       444     Andrew
                | 102       111     Peter
                | 103       333     Joe
</code>```

I am trying to get the Members ID from the Members table, in case that Member has more than 1 order in the Orders table.

So the result should be...

```<code>Members
UserID  Name
111     Peter
333     Joe
</code>```

...because Peter and Joe both have at least 2 orders in the Orders table.

I have tried to get a result with:

```<code>SELECT
    s.UserID,
FROM Members s
    INNER JOIN Orders o
        ON s.UserID = o.UserID
WHERE
    s.UserID IN
    (
        SELECT UserID
        FROM Orders
        GROUP BY UserID
        HAVING COUNT(*) > 5
    )
</code>```

But that gives me Peter back 3 times, and Joe 2 times; so I get duplicates instead of each UserID once. How can I get the result without duplicates?

答:
Here the answer, try to avoid DISTINCT</p>

```<code>SELECT
 UserID
 ,counts.count
FROM
 Members mem

JOIN (SELECT UserID,COUNT(*) as 'count' FROM Orders WHERE COUNT(*) > 1 GROUP BY UserID) counts
ON mem.UserID = counts.UserID
</code>```

Body:
Lets say I have two tables, Members and Orders with a 1:N relation:

Members         | Orders
UserID  Name    | OrderID   UserID  Name
111     Peter   | 777       111     Peter
222     Bart    | 888       333     Joe
333     Joe     | 999       111     Peter
444     Andrew  | 101       444     Andrew
                | 102       111     Peter
                | 103       333     Joe

I am trying to get the Members ID from the Members table, in case that Member has more than 1 order in the Orders table.

So the result should be...

Members
UserID  Name
111     Peter
333     Joe

...because Peter and Joe both have at least 2 orders in the Orders table.

I have tried to get a result with:

SELECT
    s.UserID,
FROM Members s
    INNER JOIN Orders o
        ON s.UserID = o.UserID
WHERE
    s.UserID IN
    (
        SELECT UserID
        FROM Orders
        GROUP BY UserID
        HAVING COUNT(*) > 5
    )

But that gives me Peter back 3 times, and Joe 2 times; so I get duplicates instead of each UserID once. How can I get the result without duplicates?

Body:
Here the answer, try to avoid DISTINCT

SELECT
 UserID
 ,counts.count
FROM
 Members mem

JOIN (SELECT UserID,COUNT(*) as 'count' FROM Orders WHERE COUNT(*) > 1 GROUP BY UserID) counts
ON mem.UserID = counts.UserID


问:
InkWell and GestureDetector, how to make them work?
I'd like to use a GestureDetector for it's onTapDown callback but also have a nice InkWell splash effect.

Is it possible to use these two together?

答:
You can pass a HitTestBehavior to GestureDetector to make it "non-blocking" by setting the value to "translucent"

Or you can also trigger it yourself using Material.of(context)


问:
Add beamer frame options in knitr/rmarkdown
I'm trying to add frame numbers to my Beamer presentation written in rmarkdown. However, I would like to suppress the numbers on the title page using the \begin{frame}[plain] option (from the second answer here: https://tex.stackexchange.com/questions/82794/removing-page-number-from-title-frame-without-changing-the-theme). However, when compiling from rmarkdown to tex, the \titlepage already creates a frame environment, so in effect I get a double frame and thus an error.

So when compiling this:

```<code>---
output:
  beamer_presentation:
    includes:
      in_header: header.tex
---

\begin{frame}[plain]
\titlepage
\end{frame}
</code>```

I get this in latex:

```<code>\begin{frame{

  \begin{frame}
     \titlepage
  \end{frame}

\end{frame}
</code>```

In the header.tex I have this:

```<code>\let\otp\titlepage
\renewcommand{\titlepage}{\otp\addtocounter{framenumber}{-1}}
</code>```

So my workaround now is to just use a plain \maketitle in rmarkdown, then compile to .tex, add the [plain] option, then compile to pdf. However, I would like to avoid that intermediate step. Is this possible in rmarkdown?

答:
Add {.plain} after the title as in:

```<code>----

# I'm the title {.plain}
</code>```

Source: Pandoc User’s Guide

Body:
I'm trying to add frame numbers to my Beamer presentation written in rmarkdown. However, I would like to suppress the numbers on the title page using the \begin{frame}[plain] option (from the second answer here: https://tex.stackexchange.com/questions/82794/removing-page-number-from-title-frame-without-changing-the-theme). However, when compiling from rmarkdown to tex, the \titlepage already creates a frame environment, so in effect I get a double frame and thus an error.

So when compiling this:

---
output:
  beamer_presentation:
    includes:
      in_header: header.tex
---

\begin{frame}[plain]
\titlepage
\end{frame}

I get this in latex:

\begin{frame{

  \begin{frame}
     \titlepage
  \end{frame}

\end{frame}

In the header.tex I have this:

\let\otp\titlepage
\renewcommand{\titlepage}{\otp\addtocounter{framenumber}{-1}}

So my workaround now is to just use a plain \maketitle in rmarkdown, then compile to .tex, add the [plain] option, then compile to pdf. However, I would like to avoid that intermediate step. Is this possible in rmarkdown?

Body:
Add {.plain} after the title as in:

----

# I'm the title {.plain}

Source: Pandoc User’s Guide


问:
sql- exceeding variable size in a exec?
I inherited some partially complete sql code that I can't get to work.

it accesses multiple databases, so it first searches for proper database using a userID number, then inserts that database name into a query. the part i'm having a problem with (extremely abbreviated) is...

```<code>DECLARE @sql AS VARCHAR(8000)
    SET @sql = 'INSERT INTO ['+@DatabaseName+'].dbo.[customer]
                  ( -- containing about 200 columns. )
                VALUES(...)'
PRINT @sql
EXEC(@sql)
</code>```

i would get errors in the middle of a column name, sometimes saying it's expecting a parenthesis or quote. i started deleting white space so that, ie, [first name],[last name] were on the same line and not two different lines and that would get me a little further down the query. i don't have much more white spaces i can delete and i'm only just getting into the Values(...) portion of it. the weird thing is. i copy and pasted just the columns portion and put it into Word and it comes up as being only about 3,000 characters, including white space.

am i missing something?

if it means anything, i'm running microsoft sql server 2005, and using the sql server management studio for editing

thanks!

答:
extremely abbreviated

Well, that doesn't really help since you have likely abbreviated away the cause of the issue.

If I were to guess, I have seen cases where NCHAR or CHAR variables/columns were involved.  These expand to their full length when used in string concatenation and it will cause the final statement to be too long.

For what it's worth for style or otherwise, use NVarchar(Max) always for SQL Server 2005 and onwards.  In fact, that is the expected type if you use sp_executesql.

If you check for fixed-width N/CHAR columns and switch to nvarchar(max), you may see the problem go away.

EDIT: Test showing NVarchar(Max) holding well in excess of 8000 bytes.

```<code>declare @sql nvarchar(max)

-- this CTE sets up the columns, 1 as field1, 2 as field2 etc
-- it creates 2000 columns
;with CTE(n, t) AS (
    select 1, convert(nvarchar(max),'1 as field1')
    union all
    select n+1, convert(nvarchar(max),RIGHT(n, 12) + ' as field'+RIGHT(n, 12))
    from cte
    where N < 2000)
select @sql = coalesce(@sql+',','') + t
from CTE
option (maxrecursion 2000)   -- needed, the default of 100 is not nearly enough

-- add the SELECT bit to make a proper SQL statement
set @sql = 'select ' + @sql

-- check the length : 33786
select LEN(@sql)

-- check the content
print @sql

-- execute to get the columns
exec (@sql)
</code>```

Title: sql- exceeding variable size in a exec?

Body:
I inherited some partially complete sql code that I can't get to work.

it accesses multiple databases, so it first searches for proper database using a userID number, then inserts that database name into a query. the part i'm having a problem with (extremely abbreviated) is...

DECLARE @sql AS VARCHAR(8000)
    SET @sql = 'INSERT INTO ['+@DatabaseName+'].dbo.[customer]
                  ( -- containing about 200 columns. )
                VALUES(...)'
PRINT @sql
EXEC(@sql)

i would get errors in the middle of a column name, sometimes saying it's expecting a parenthesis or quote. i started deleting white space so that, ie, [first name],[last name] were on the same line and not two different lines and that would get me a little further down the query. i don't have much more white spaces i can delete and i'm only just getting into the Values(...) portion of it. the weird thing is. i copy and pasted just the columns portion and put it into Word and it comes up as being only about 3,000 characters, including white space.

am i missing something?

if it means anything, i'm running microsoft sql server 2005, and using the sql server management studio for editing

thanks!

Body:
extremely abbreviated

Well, that doesn't really help since you have likely abbreviated away the cause of the issue.

If I were to guess, I have seen cases where NCHAR or CHAR variables/columns were involved.  These expand to their full length when used in string concatenation and it will cause the final statement to be too long.

For what it's worth for style or otherwise, use NVarchar(Max) always for SQL Server 2005 and onwards.  In fact, that is the expected type if you use sp_executesql.

If you check for fixed-width N/CHAR columns and switch to nvarchar(max), you may see the problem go away.

EDIT: Test showing NVarchar(Max) holding well in excess of 8000 bytes.

declare @sql nvarchar(max)

-- this CTE sets up the columns, 1 as field1, 2 as field2 etc
-- it creates 2000 columns
;with CTE(n, t) AS (
    select 1, convert(nvarchar(max),'1 as field1')
    union all
    select n+1, convert(nvarchar(max),RIGHT(n, 12) + ' as field'+RIGHT(n, 12))
    from cte
    where N < 2000)
select @sql = coalesce(@sql+',','') + t
from CTE
option (maxrecursion 2000)   -- needed, the default of 100 is not nearly enough

-- add the SELECT bit to make a proper SQL statement
set @sql = 'select ' + @sql

-- check the length : 33786
select LEN(@sql)

-- check the content
print @sql

-- execute to get the columns
exec (@sql)


问:
Matlab compare two matrixes with different dimension
I see people take ==, ~=, >, < between matrixes with a different dimension in parentheses following a matrix to get its entries, like this:

```<code>b =

     1     4     7
     2     5     8
     3     6     9

>> b == [1 2 3]

ans =

  3×3 logical array

   1   0   0
   0   0   0
   0   0   0

>> b == [1 4 7]

ans =

  3×3 logical array

   1   1   1
   0   0   0
   0   0   0

>> b == [1 4 5]

ans =

  3×3 logical array

   1   1   0
   0   0   0
   0   0   0

>> b == [1 5 4]

ans =

  3×3 logical array

   1   0   0
   0   1   0
   0   0   0

>> a

a =

     1     2     3     4     5     6     7     8     9    10
     1     2     3     4     5     6     7     8     9    10
     1     2     3     4     5     6     7     8     9    10

>> a(:, b == [1 4 5])

ans =

     1     4
     1     4
     1     4

>> a(:, b == [1 5 4])

ans =

     1     5
     1     5
     1     5

>> b

b =

     1     4     7
     2     5     8
     3     6     9

>> b > [1 3 2]

ans =

  3×3 logical array

   0   1   1
   1   1   1
   1   1   1
</code>```

However, I have no idea why these would work. Any explanation about this usage? (My English is not good to describe the question better, hope anyone could edit this question to make it more understandable? Thanks in advance!)

答:
Since R2016b, MATLAB uses implicit expansion. This means that inputs' singleton dimensions (dimensions of size 1) are repeated to be the same size as other inputs.

For example:

```<code>b = [1  4  7
     2  5  8
     3  6  9]

%% Singleton dimension as rows
b == [x y z]
% is equivalent to
b == repmat([x y z], size(b,1), 1)
% is equivalent to
b == [x  y  z
      x  y  z
      x  y  z]

%% Singleton dimension as columns
b == [x; y; z]
% is equivalent to
b == repmat([x; y; z], 1, size(b,2))
% is equivalent to
b == [x  x  x
      y  y  y
      z  z  z]
</code>```

All 3 of your examples are the "singleton dimension as rows" case, repeating your comparison row vector down and comparing to each row of b. You can easily see that the outputs are as expected.

Implicit expansion can be used in all versions of MATLAB (including pre-R2016b) with the use of bsxfun. This would look like so:

```<code>% Since 2016b
b == [1 2 3];
% All versions (@eq is the '==' equals function)
bsxfun(@eq, b, [1 2 3])
</code>```

Body:
I see people take ==, ~=, >, < between matrixes with a different dimension in parentheses following a matrix to get its entries, like this:

b =

     1     4     7
     2     5     8
     3     6     9

>> b == [1 2 3]

ans =

  3×3 logical array

   1   0   0
   0   0   0
   0   0   0

>> b == [1 4 7]

ans =

  3×3 logical array

   1   1   1
   0   0   0
   0   0   0

>> b == [1 4 5]

ans =

  3×3 logical array

   1   1   0
   0   0   0
   0   0   0

>> b == [1 5 4]

ans =

  3×3 logical array

   1   0   0
   0   1   0
   0   0   0

>> a

a =

     1     2     3     4     5     6     7     8     9    10
     1     2     3     4     5     6     7     8     9    10
     1     2     3     4     5     6     7     8     9    10

>> a(:, b == [1 4 5])

ans =

     1     4
     1     4
     1     4

>> a(:, b == [1 5 4])

ans =

     1     5
     1     5
     1     5

>> b

b =

     1     4     7
     2     5     8
     3     6     9

>> b > [1 3 2]

ans =

  3×3 logical array

   0   1   1
   1   1   1
   1   1   1

However, I have no idea why these would work. Any explanation about this usage? (My English is not good to describe the question better, hope anyone could edit this question to make it more understandable? Thanks in advance!)

Body:
Since R2016b, MATLAB uses implicit expansion. This means that inputs' singleton dimensions (dimensions of size 1) are repeated to be the same size as other inputs.

For example:

b = [1  4  7
     2  5  8
     3  6  9]

%% Singleton dimension as rows
b == [x y z]
% is equivalent to
b == repmat([x y z], size(b,1), 1)
% is equivalent to
b == [x  y  z
      x  y  z
      x  y  z]

%% Singleton dimension as columns
b == [x; y; z]
% is equivalent to
b == repmat([x; y; z], 1, size(b,2))
% is equivalent to
b == [x  x  x
      y  y  y
      z  z  z]

All 3 of your examples are the "singleton dimension as rows" case, repeating your comparison row vector down and comparing to each row of b. You can easily see that the outputs are as expected.

Implicit expansion can be used in all versions of MATLAB (including pre-R2016b) with the use of bsxfun. This would look like so:

% Since 2016b
b == [1 2 3];
% All versions (@eq is the '==' equals function)
bsxfun(@eq, b, [1 2 3])


问:
How to make thread wait for a certain event to occur
Could you help me, please?

What I'm trying to do is a printer example. There will be more printers and more documents waiting to be printed.

A Printer is a Thread, it sleeps until a document is arrived, then prints it, then goes to sleep again.

A PrinterManager is a thread too. It collects documents from a queue and sends to a free Printer. I am using a Semaphore for finding a free printer.

The problem is around the wait-notify pair. The printer should wait until the manager sends a document. Then it waits 1 second and "prints" it. As a lock object I use stick.

For some reason, it's not working. The document is sent succesfully to the printer, but the printer is not awaken. Can you help me, why?

Printer thread:

```<code>public class Printer extends Thread {

    private final Semaphore semaphore;
    private final Object stick;
    private String document;

    public Printer(Semaphore semaphore, Object stick) {
        this.semaphore = semaphore;
        this.stick = stick;
    }

    public void setDocument(String document) {
        this.document = document;
    }

    @Override
    public void run() {
        while (true) {
            try {
                stick.wait();
                Thread.sleep(1000);
                System.out.println("Printing: " + document);
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
</code>```

Manager thread:

```<code>public class PrinterManager extends Thread {

    private final Printer[] printers = new Printer[1];
    private final Object stick = new Object();
    private final Semaphore semaphore = new Semaphore(printers.length);
    private final DocumentQueue queue;

    public PrinterManager(DocumentQueue queue) {
        this.queue = queue;
        printers[0] = new Printer(semaphore, stick);
    }

    @Override
    public void run() {
        while (true) {
            try {
                semaphore.acquire();
                String toPrint = takeNextDocument();
                printers[0].setDocument(toPrint);
                synchronized (stick) {
                    stick.notify();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private String takeNextDocument() throws InterruptedException {
        return queue.take();
    }
}
</code>```

答:
I wonder how many times of 1000 runs the printer will print the document (will you conduct an experiment?).

But first put stick.wait() in Printer's run method in synchronized block, or you'll be getting IllegalMonitorStateException exception in there.

You've faced concurrency problems called race condition and deadlock. It means the result depends on order in which code is executed. Sometimes you might be lucky and the program would work as you expect. But in other times you're going to have a deadlock (that's another concurrency programming issue).

Imagine instructions are executed in that sequence:

PrinterManager.run() acquires semaphore

PrinterManager.run() sets document to the printer

PrinterManager.run() executes notify on stick

Printer.run() executes stick.wait()

...and this is how you get a deadlock.
PrinterManager notified the stick before Printer started to wait on it. Then PrinterManager acquired the last permit in semaphore and started to wait until Printer release some (it never will, it waits!). Both objects started to wait for each other and both got blocked.

But Printer could started to wait before PrinterManager notified objects on stick, than it would work as expected. That's why you have race condition, you can never predict what will happen and this is very bad.

As a simple solution (not the best, but quick and without help of additional techniques which you may find unfamiliar) you may get rid of stick. Introduce two counters instead:

numberOfFinishedPrintTasks (make Printer increment it after each turn)

and lastSubmittedPrintTaskNumber (make PrinterManager set it to numberOfFinishedPrintTasks + 1 after each submission).

PrinterManager must check the condition numberOfFinishedPrintTasks == lastSubmittedPrintTaskNumber it means that printer finished all work and new tasks can be submitted.

P.S. Don't inherit for Thread class. You don't add any new functionality to Thread, you just make it run a specific job.
For that you should create an object which implements Runnable interface and pass that object to new Thread instance.

Body:
Could you help me, please?

What I'm trying to do is a printer example. There will be more printers and more documents waiting to be printed.

A Printer is a Thread, it sleeps until a document is arrived, then prints it, then goes to sleep again.

A PrinterManager is a thread too. It collects documents from a queue and sends to a free Printer. I am using a Semaphore for finding a free printer.

The problem is around the wait-notify pair. The printer should wait until the manager sends a document. Then it waits 1 second and "prints" it. As a lock object I use stick.

For some reason, it's not working. The document is sent succesfully to the printer, but the printer is not awaken. Can you help me, why?

Printer thread:

public class Printer extends Thread {

    private final Semaphore semaphore;
    private final Object stick;
    private String document;

    public Printer(Semaphore semaphore, Object stick) {
        this.semaphore = semaphore;
        this.stick = stick;
    }

    public void setDocument(String document) {
        this.document = document;
    }

    @Override
    public void run() {
        while (true) {
            try {
                stick.wait();
                Thread.sleep(1000);
                System.out.println("Printing: " + document);
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Manager thread:

public class PrinterManager extends Thread {

    private final Printer[] printers = new Printer[1];
    private final Object stick = new Object();
    private final Semaphore semaphore = new Semaphore(printers.length);
    private final DocumentQueue queue;

    public PrinterManager(DocumentQueue queue) {
        this.queue = queue;
        printers[0] = new Printer(semaphore, stick);
    }

    @Override
    public void run() {
        while (true) {
            try {
                semaphore.acquire();
                String toPrint = takeNextDocument();
                printers[0].setDocument(toPrint);
                synchronized (stick) {
                    stick.notify();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private String takeNextDocument() throws InterruptedException {
        return queue.take();
    }
}


问:
BackgroundImage in css
how to put backgound image with help of css.
When an image file is stored locally on a desktop, CSS file and image are in the same folder. \Desktop\New folder\image:- image destination
\Desktop\New folder\css:- css file destination

答:
use background: url() in css for this

body {
  background: url("https://www.w3schools.com/howto/img_fjords.jpg");
  background-size: 80px 60px;
  background-repeat: no-repeat;
  padding-top: 40px;
}```

ContentLicense: CC BY-SA 4.0

Title: BackgroundImage in css


问:
Simulate mouse hover on an item of QTreeView
In Qt package, is it possible to achieve highlighting (as seen when hovering with the mouse) of an item in QTreeView programmatically?

I am able to select the item and it gives a similar impression, but I cannot use this method (since I am using selections in some other place).

The last option would be to store a flag in the item itself and return a background or a font from data() method for some role. But this approach seems very tedious.

答:
I ended up following vahancho advice.

In my model I have added the following in the data(QModelIndex index) method:

```<code>if (role == Qt::BackgroundColorRole)
{
    if (HasHighlighted && (index == LastHighlightedIndex))
    {
        return qVariantFromValue(QColor(229, 243, 255)); //highlighting color, at least on Windows10
    }
}
</code>```

To highlight I call

```<code>void TreeModel::SetHighlighted(QModelIndex & index)
{
    if (index != LastHighlightedIndex || !HasHighlighted)
    {
        if (HasHighlighted)
        {
            emit dataChanged(LastHighlightedIndex, LastHighlightedIndex); //clearing previous highlighted
        }
        LastHighlightedIndex = index;
        HasHighlighted = true;
        emit dataChanged(index, index);
    }

}
</code>```

In my case I use a proxy so I need to get the right index: with the GetModelIndex method

```<code>void CustomTreeView::SimulateHover(QModelIndex index)
{
    TreeProxyModel *proxy = dynamic_cast<TreeProxyModel*>(this->model());
    if (proxy != nullptr)
    {
        proxy->model()->SetHighlighted(proxy->GetModelIndex(index));
    }
}
</code>```

-

```<code>QModelIndex TreeProxyModel::GetModelIndex(QModelIndex & index)
    {
        return mapToSource(index);
    }
</code>```

In addition to clear last hover:

```<code>void CustomTreeView::ClearSimulatedHover()
{
    TreeProxyModel *proxy = dynamic_cast<TreeProxyModel*>(this->model());
    if (proxy != nullptr)
    {
        proxy->model()->ClearHighlighted();
    }
}
</code>```

Body:
I ended up following vahancho advice.

In my model I have added the following in the data(QModelIndex index) method:

if (role == Qt::BackgroundColorRole)
{
    if (HasHighlighted && (index == LastHighlightedIndex))
    {
        return qVariantFromValue(QColor(229, 243, 255)); //highlighting color, at least on Windows10
    }
}

To highlight I call

void TreeModel::SetHighlighted(QModelIndex & index)
{
    if (index != LastHighlightedIndex || !HasHighlighted)
    {
        if (HasHighlighted)
        {
            emit dataChanged(LastHighlightedIndex, LastHighlightedIndex); //clearing previous highlighted
        }
        LastHighlightedIndex = index;
        HasHighlighted = true;
        emit dataChanged(index, index);
    }

}

In my case I use a proxy so I need to get the right index: with the GetModelIndex method

void CustomTreeView::SimulateHover(QModelIndex index)
{
    TreeProxyModel *proxy = dynamic_cast<TreeProxyModel*>(this->model());
    if (proxy != nullptr)
    {
        proxy->model()->SetHighlighted(proxy->GetModelIndex(index));
    }
}

-

QModelIndex TreeProxyModel::GetModelIndex(QModelIndex & index)
    {
        return mapToSource(index);
    }

In addition to clear last hover:

void CustomTreeView::ClearSimulatedHover()
{
    TreeProxyModel *proxy = dynamic_cast<TreeProxyModel*>(this->model());
    if (proxy != nullptr)
    {
        proxy->model()->ClearHighlighted();
    }
}


问:
Jhipster/Spring Kafka Consumer with a Python Producer
I'm trying to make a Python Producer that sends a message to JHipster. I implemented the easy example proposed in their website:

http://www.jhipster.tech/using-kafka/

I'm trying to send the same message but instead of using a resource with a rest path, i use a Python script that sends a simple message.

Here is my python script, which sends a string to the same topic subscribableChannel:

```<code>from kafka import KafkaProducer
#  connect to Kafka
producer = KafkaProducer(bootstrap_servers='localhost:3000')
# Assign a topic
topic = 'subscribableChannel'

def send_a_message():
    producer.send_messages(topic, 'Nice_test').get(timeout=30)
    print('done emitting')

if __name__ == '__main__':
    send_a_message()
</code>```

When I run the code, it takes some time and then I get: kafka.errors.NoBrokersAvailable: NoBrokersAvailable. Therefore my question is what is the procedure to follow in order to implement this producer/consumer functionality

答:
Kafka runs on port 9092, not 3000</p>

```<code>producer = KafkaProducer(bootstrap_servers='localhost:9092')
</code>```

Body:
I'm trying to make a Python Producer that sends a message to JHipster. I implemented the easy example proposed in their website:

http://www.jhipster.tech/using-kafka/

I'm trying to send the same message but instead of using a resource with a rest path, i use a Python script that sends a simple message.

Here is my python script, which sends a string to the same topic subscribableChannel:

from kafka import KafkaProducer
#  connect to Kafka
producer = KafkaProducer(bootstrap_servers='localhost:3000')
# Assign a topic
topic = 'subscribableChannel'

def send_a_message():
    producer.send_messages(topic, 'Nice_test').get(timeout=30)
    print('done emitting')

if __name__ == '__main__':
    send_a_message()

When I run the code, it takes some time and then I get: kafka.errors.NoBrokersAvailable: NoBrokersAvailable. Therefore my question is what is the procedure to follow in order to implement this producer/consumer functionality

Body:
Kafka runs on port 9092, not 3000

producer = KafkaProducer(bootstrap_servers='localhost:9092')


答:
I'm  assuming (and hoping) that you're not storing the user's name twice, since that leads to data quality issues when the user changes their name.

Assuming the tables are structured like below:

```<code>CREATE TABLE
  Members
(
    UserID INT,
    Name VARCHAR(15)
);

INSERT INTO
  Members
VALUES
(111, 'Peter'),
(222, 'Bart'),
(333, 'Joe'),
(444, 'Andrew');

CREATE TABLE
  Orders
(
   OrderID INT,
   UserID INT
);

INSERT INTO
  Orders
VALUES
(777, 111),
(888, 333),
(999, 111),
(101, 444),
(102, 111),
(103, 333);
</code>```

You can use a GROUP BY and HAVING clause which would give you the UserID of all users with more than 1 (or whichever number you choose) orders. Then, you join that to the Members table to get the name.

```<code>SELECT
  Orders.UserID,
  Members.Name
FROM
  Orders
INNER JOIN
  Members
  ON Orders.UserID = Members.UserID
GROUP BY
  UserID,
  Members.Name
HAVING
  COUNT(OrderID) > 1;
</code>```

SQLFiddle: http://sqlfiddle.com/#!9/1dadc4/2

However, if you already have the names stored (and that's not changing), then you could skip the JOIN like below:

```<code>SELECT
  UserID,
  Name
FROM
  Orders
GROUP BY
  UserID,
  Name
HAVING
  COUNT(OrderID) > 1
</code>```

Title: MySQL - Select row if appear more than x times in other table

Body:
I'm  assuming (and hoping) that you're not storing the user's name twice, since that leads to data quality issues when the user changes their name.

Assuming the tables are structured like below:

CREATE TABLE
  Members
(
    UserID INT,
    Name VARCHAR(15)
);

INSERT INTO
  Members
VALUES
(111, 'Peter'),
(222, 'Bart'),
(333, 'Joe'),
(444, 'Andrew');

CREATE TABLE
  Orders
(
   OrderID INT,
   UserID INT
);

INSERT INTO
  Orders
VALUES
(777, 111),
(888, 333),
(999, 111),
(101, 444),
(102, 111),
(103, 333);

You can use a GROUP BY and HAVING clause which would give you the UserID of all users with more than 1 (or whichever number you choose) orders. Then, you join that to the Members table to get the name.

SELECT
  Orders.UserID,
  Members.Name
FROM
  Orders
INNER JOIN
  Members
  ON Orders.UserID = Members.UserID
GROUP BY
  UserID,
  Members.Name
HAVING
  COUNT(OrderID) > 1;

SQLFiddle: http://sqlfiddle.com/#!9/1dadc4/2

However, if you already have the names stored (and that's not changing), then you could skip the JOIN like below:

SELECT
  UserID,
  Name
FROM
  Orders
GROUP BY
  UserID,
  Name
HAVING
  COUNT(OrderID) > 1


问:
How to control the width of select tag?
I have a list of countries, some with a very long name:

```<code><select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>
</code>```

By default, the select box would be as long as the longest option in the list. I want to create a select box such that it exhibits the default behaviour when viewed from a wide browser window, but fit in nicely to 90% of container width when viewed from a narrow browser window, smaller than the length of the longest option.

I tried min-width: 90%;, but it didn't work. Can this be done by CSS styling alone?

答:
Add div wrapper

```<code><div id=myForm>
<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>
</div>
</code>```

and then write CSS

```<code>#myForm select {
width:200px; }

#myForm select:focus {
width:auto; }
</code>```

Hope this will help.

Title: How to control the width of select tag?

Body:
I have a list of countries, some with a very long name:

<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>

By default, the select box would be as long as the longest option in the list. I want to create a select box such that it exhibits the default behaviour when viewed from a wide browser window, but fit in nicely to 90% of container width when viewed from a narrow browser window, smaller than the length of the longest option.

I tried min-width: 90%;, but it didn't work. Can this be done by CSS styling alone?

Body:
Add div wrapper

<div id=myForm>
<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>
</div>

and then write CSS

#myForm select {
width:200px; }

#myForm select:focus {
width:auto; }

Hope this will help.


问:
Monitoring network changes in iOS
I have an application that needs to monitor network changes.

Let's say if Wi-Fi was dropped or reconnected then I need to use some web services.
How can I accomplish this in iOS?
 I have a captive network that marks users as authenticated after logging in. I want to make sure that the user is authenticated whenever Wi-Fi changes, otherwise I need to perform authentication.

All I want is to perform some HTTP requests on the basis of network changes.

Any help is appreciated. I have tried to use Reachability but that only works when user opens the application.

答:
Reachability allows the app to be notified when the network configuration change.

I used this method:

```<code>+ (instancetype)reachabilityForInternetConnection return [self connectivityWithAddress:&zeroAddress];
</code>```

My apps recieve regular callbacks when I play with the wifi connection.

Title: Monitoring network changes in iOS

Body:
Reachability allows the app to be notified when the network configuration change.

I used this method:

+ (instancetype)reachabilityForInternetConnection return [self connectivityWithAddress:&zeroAddress];

My apps recieve regular callbacks when I play with the wifi connection.


问:
Get column value of repeating table?
I have this table:

var table = document.getElementById('tableID'),
    cells = table.getElementsByTagName('td');

for (var x = 0, len = cells.length; x < len; x++) {
    cells[x].onclick = function () {
        console.log(this.innerHTML);
    };
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table table-striped" id="tableID">
    <tbody>
      <tr ng-repeat="cup in cups">
          <td>{{cup.cupnum}}</td>
          <td>{{::cup.contents.model}}</td>
          <td>{{::cup.contents.woa}}</td>
          <td>{{::cup.contents.perfBy}}</td>
          <td>{{::cup.contents.perfAt}}</td>
          <td>{{::cup.contents.loadEvent}}</td>
          <td>{{samples[cup.contents.sampleID-1].contents.name}}</td>
          <td>{{holders[cup.contents.holderID-1].contents.type}}</td>
      </tr>
    </tbody>
</table></code>```

How can I make it so that i'm just getting the value of the last column for each row without having to click? The: {{holders[cup.contents.holderID-1].contents.type}}
column

答:
try to use:

```<code>cells =  table.querySelector('td:last-child')
</code>```

This will always return the last td of the rows.

Title: Get column value of repeating table?

Body:
I have this table:

var table = document.getElementById('tableID'),
    cells = table.getElementsByTagName('td');

for (var x = 0, len = cells.length; x < len; x++) {
    cells[x].onclick = function () {
        console.log(this.innerHTML);
    };
}

          {{cup.cupnum}}
          {{::cup.contents.model}}
          {{::cup.contents.woa}}
          {{::cup.contents.perfBy}}
          {{::cup.contents.perfAt}}
          {{::cup.contents.loadEvent}}
          {{samples[cup.contents.sampleID-1].contents.name}}
          {{holders[cup.contents.holderID-1].contents.type}}

How can I make it so that i'm just getting the value of the last column for each row without having to click? The: {{holders[cup.contents.holderID-1].contents.type}}
column

Body:
try to use:

cells =  table.querySelector('td:last-child')

This will always return the last td of the rows.


问:
How to get the value of the href attribute?
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

```<code><a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>
</code>```

That is, to get the value of the href attribute if the link has a particular text.

答:
i think this is the best solution, you can use each of them as an array element</p>

```<code>$String=    '
<a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>
            ';

$array=get_all_string_between($String,'href="','">');
print_r($array);//just to see what is inside the array

//now get each of them
foreach($array as $value){
echo $value.'<br>';
}

function get_all_string_between($string, $start, $end)
{
    $result = array();
    $string = " ".$string;
    $offset = 0;
    while(true)
    {
        $ini = strpos($string,$start,$offset);
        if ($ini == 0)
            break;
        $ini += strlen($start);
        $len = strpos($string,$end,$ini) - $ini;
        $result[] = substr($string,$ini,$len);
        $offset = $ini+$len;
    }
    return $result;
}
</code>```

Body:
With the help of XPath, how to get the value of the href attribute in the following case (only grabbing the url that is the right one)?:

a wrong one
the right one
a wrong one

That is, to get the value of the href attribute if the link has a particular text.

Body:
i think this is the best solution, you can use each of them as an array element

$String=    '
<a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>
            ';

$array=get_all_string_between($String,'href="','">');
print_r($array);//just to see what is inside the array

//now get each of them
foreach($array as $value){
echo $value.'<br>';
}

function get_all_string_between($string, $start, $end)
{
    $result = array();
    $string = " ".$string;
    $offset = 0;
    while(true)
    {
        $ini = strpos($string,$start,$offset);
        if ($ini == 0)
            break;
        $ini += strlen($start);
        $len = strpos($string,$end,$ini) - $ini;
        $result[] = substr($string,$ini,$len);
        $offset = $ini+$len;
    }
    return $result;
}


问:
Python - Search multiple columns for string to set categorical variable value
I am very new to Python and Pandas, and am trying to use it for a statistical analysis of a very large dataset (10 million cases) because the other options (SPSS and R) are unable to handle the dataset on the authorized hardware.

In this analysis, I need to search a range of columns (30 to be exact) row-wise to extract individual strings (about 200 are possible, not sure how many will actually be present in the dataset) and then create a categorical variable for each string.

The data looks like this

```<code>  Dx1     Dx2     Dx3   etc...
  001     234     456
  231     001     444
  245     777     001
</code>```

What is needed is

```<code>Dx1     Dx2     Dx3  Var001   Var234  Var456  Var231   etc..
001     234     456  True     True    True    False
231     001     444  True     False   False   True
245     777     001  True     False   False   False
</code>```

Any thoughts on how to do this?

df.dtypes shows

```<code>AGE                      int64
DISPUNIFORM              int64
DRG                      int64
DRGVER                   int64
Readmit_30D              int64
DXCCS1                   int64
DXCCS2                   int64
DXCCS3                   int64
DXCCS4                   int64
...on to DXCCS30
</code>```

答:
I think you want to keep "one hot encoded" data set as a sparse matrix.

So try the following memory saving approach:

```<code>from sklearn.feature_extraction.text import CountVectorizer

cv = CountVectorizer()

r = pd.SparseDataFrame(cv.fit_transform(df.astype(str).add(' ').sum(axis=1)),
                       columns=cv.get_feature_names(),
                       index=df.index,
                       default_fill_value=0).add_prefix('Var')
</code>```

Result:

```<code>In [85]: r
Out[85]:
   Var001  Var231  Var234  Var245  Var444  Var456  Var777
0       1       0       1       0       0       1       0
1       1       1       0       0       1       0       0
2       1       0       0       1       0       0       1

In [86]: r.memory_usage()
Out[86]:
Index     80
Var001    24
Var231     8
Var234     8
Var245     8
Var444     8
Var456     8
Var777     8
dtype: int64
</code>```

Explanation:

I used the following trick in order to collect all data into one column:

```<code>In [89]: df.astype(str).add(' ').sum(axis=1)
Out[89]:
0    001 234 456
1    231 001 444
2    245 777 001
dtype: object
</code>```

PS don't join resulting sparse DF with the source DF as it may result in "exploding" it back to normal (not sparse) DF:

```<code>In [87]: df.join(r)
Out[87]:
   Dx1  Dx2  Dx3  Var001  Var231  Var234  Var245  Var444  Var456  Var777
0  001  234  456       1       0       1       0       0       1       0
1  231  001  444       1       1       0       0       1       0       0
2  245  777  001       1       0       0       1       0       0       1

In [88]: df.join(r).memory_usage()
Out[88]:
Index     80
Dx1       24
Dx2       24
Dx3       24
Var001    24
Var231    24
Var234    24
Var245    24
Var444    24
Var456    24
Var777    24
dtype: int64
</code>```

Body:
I am very new to Python and Pandas, and am trying to use it for a statistical analysis of a very large dataset (10 million cases) because the other options (SPSS and R) are unable to handle the dataset on the authorized hardware.

In this analysis, I need to search a range of columns (30 to be exact) row-wise to extract individual strings (about 200 are possible, not sure how many will actually be present in the dataset) and then create a categorical variable for each string.

The data looks like this

  Dx1     Dx2     Dx3   etc...
  001     234     456
  231     001     444
  245     777     001

What is needed is

Dx1     Dx2     Dx3  Var001   Var234  Var456  Var231   etc..
001     234     456  True     True    True    False
231     001     444  True     False   False   True
245     777     001  True     False   False   False

Any thoughts on how to do this?

df.dtypes shows

AGE                      int64
DISPUNIFORM              int64
DRG                      int64
DRGVER                   int64
Readmit_30D              int64
DXCCS1                   int64
DXCCS2                   int64
DXCCS3                   int64
DXCCS4                   int64
...on to DXCCS30

Body:
I think you want to keep "one hot encoded" data set as a sparse matrix.

So try the following memory saving approach:

from sklearn.feature_extraction.text import CountVectorizer

cv = CountVectorizer()

r = pd.SparseDataFrame(cv.fit_transform(df.astype(str).add(' ').sum(axis=1)),
                       columns=cv.get_feature_names(),
                       index=df.index,
                       default_fill_value=0).add_prefix('Var')

Result:

In [85]: r
Out[85]:
   Var001  Var231  Var234  Var245  Var444  Var456  Var777
0       1       0       1       0       0       1       0
1       1       1       0       0       1       0       0
2       1       0       0       1       0       0       1

In [86]: r.memory_usage()
Out[86]:
Index     80
Var001    24
Var231     8
Var234     8
Var245     8
Var444     8
Var456     8
Var777     8
dtype: int64

Explanation:

I used the following trick in order to collect all data into one column:

In [89]: df.astype(str).add(' ').sum(axis=1)
Out[89]:
0    001 234 456
1    231 001 444
2    245 777 001
dtype: object

PS don't join resulting sparse DF with the source DF as it may result in "exploding" it back to normal (not sparse) DF:

In [87]: df.join(r)
Out[87]:
   Dx1  Dx2  Dx3  Var001  Var231  Var234  Var245  Var444  Var456  Var777
0  001  234  456       1       0       1       0       0       1       0
1  231  001  444       1       1       0       0       1       0       0
2  245  777  001       1       0       0       1       0       0       1

In [88]: df.join(r).memory_usage()
Out[88]:
Index     80
Dx1       24
Dx2       24
Dx3       24
Var001    24
Var231    24
Var234    24
Var245    24
Var444    24
Var456    24
Var777    24
dtype: int64


问:
How to display both single quotes and double quotes in echo in unix
I need to display a string like Today's "program" as output in unix. But If i gave the below none of the options are working .

```<code>>echo "Today's "program""
Today's program

> echo "Today\'s "program""
Today\'s program

> echo 'Today's "program"'
>

echo 'Today\'s "program"'
>
</code>```

答:
```<code>> echo 'Today'\''s "program"'
Today's "program"
</code>```

Body:
I need to display a string like Today's "program" as output in unix. But If i gave the below none of the options are working .

>echo "Today's "program""
Today's program

> echo "Today\'s "program""
Today\'s program

> echo 'Today's "program"'
>

echo 'Today\'s "program"'
>


问:
Unable to upload app to iTunes Connect - iTunes Store operation failed. Authentication timeout
I'm trying to upload my app to iTunes Connect with Xcode. I chose product > archive, choose my account, it compiles and when I try to upload it hand for a long time on:

```<code>Uploading Archive
Sending API usage to iTunes Connect...
</code>```

Then it shows an error message:

I've restarted Xcode and the entire machine but still it keeps repeating itself.

What's wrong here?

答:
I was getting the same error. Application Loader didn't work.  I couldn't open any Apple Developer/Forum webpages either to find an answer there.  And iTunesConnect wouldn't let me log in.  I thought the site was down and I couldn't even access the Apple Status pages.

My VPN was connecting outside the US.  After turning off the VPN everything returned to normal.  I have been letting the VPN connect to random places around the globe, probably should keep it in my area.

Body:
I'm trying to upload my app to iTunes Connect with Xcode. I chose product > archive, choose my account, it compiles and when I try to upload it hand for a long time on:

Uploading Archive
Sending API usage to iTunes Connect...

Then it shows an error message:

I've restarted Xcode and the entire machine but still it keeps repeating itself.

What's wrong here?