问:
Observable that emit items on demand
I want to create an Observable that will emit items on demand, that means I want a single subscribe to Observable and notify Observable that I need new item based on my request.

This is what I have done using PublishSubject:

```<code>public class RecognizeSubject {

PublishSubject<Bitmap> mSubject;

private Context mContext;
private FaceDetector mFaceDetecor;

public RecognizeSubject(Context mContext) {
    this.mContext = mContext;
    this.mSubject = PublishSubject.create();
}

public void detect(Bitmap btm){
    mSubject.onNext(btm);
}

public Flowable<SinglePhotoId> execute() {
    return mSubject.toFlowable(BackpressureStrategy.DROP)
            .observeOn(Schedulers.newThread())
            .map(bitmap1 -> recognize(bitmap1))
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(disposable -> initialize())
            .doFinally(() -> release());
}

private void initialize() {
    mFaceDetecor = new FaceDetector.Builder(mContext)
            .setTrackingEnabled(false)
            .setLandmarkType(FaceDetector.ALL_LANDMARKS)
            .build();
}

private void release() {
    if (mFaceDetecor != null)
        mFaceDetecor.release();
}

private SinglePhotoId recognize(Bitmap bitmap) {
    //SystemClock.sleep(3000);
   //make hard background work and return SinglePhotoId object
}
</code>```

}

and here is a usage in Activity class:

```<code>private void takeSubjectSnap() {
    if (mSubject == null)
        mSubject = new RecognizeSubject(getBaseContext());

    if (mDisposable == null || mDisposable.isDisposed()) {
        mDisposable = mSubject.execute()
                .subscribe(this::handleDetectionSuccess,
                        this::handleDetectionError,
                        this::handleDetectionCompleted);
    }

    mSnapshotButton.setProgress(true);
    mSubject.detect(myVideoView.getBitmap());
}
</code>```

So basically I subscribe to Flowable object and pass Bitmap object to my Subject class to proceed and return result via Flowable, is that solution right or can produce some memory leaks?

Is there any better solution to send an object to Observable to proceed and return result via a standard onNext() method?

答:
OK, I have read your answer and changed my code a little, here is a diagram that illustrates what I want to achieve:

So my Subject class will process received data on background thread and emit processed items via onNext() method to their Observer. I made a simple Subject that receives Integer object and convert it to String object, here is the code:

```<code>public class MySubject {

private String TAG = "MySubject";

private PublishSubject<Integer> subject;
private final Observable<String> observable;

public MySubject() {
   Log.d(TAG, "---> MySubject() called");
   this.subject = PublishSubject.create();
   this.observable = subject
           .doOnSubscribe(disposable -> init())
           .doFinally(() -> relese()) //try do after terminate
           .observeOn(Schedulers.newThread())
           .map(this::myMap)
           .observeOn(AndroidSchedulers.mainThread());
}

private void init(){
   Log.d(TAG, "---> init() called");
}

private void relese(){
   Log.d(TAG, "---> relese() called");
}

private String myMap(Integer integer){
   Log.d(TAG, "---> myMap() called int: " + integer);
   SystemClock.sleep(3000);
   return " :) " + String.valueOf(integer);
}

public void decode(Integer integer){
   subject.onNext(integer);
}

public Observable<String> getObservable(){
   return observable;
}
</code>```

}

And here is a usage in Activity class:

```<code>Disposable disposable = Disposables.disposed();
MySubject subject = new MySubject();

void onButton1() {

   if(disposable.isDisposed()){
       disposable = subject.getObservable()
               .subscribe(s -> {
                   Log.d(TAG, "---> onNext() called " + s);
               }, throwable -> {
                   Log.d(TAG, "---> onError() called " + throwable.getMessage());
               }, () -> {
                   Log.d(TAG, "---> onCompleted() called ");
               });
   }

   Random generator = new Random();
   int i = generator.nextInt(100) + 1;
   subject.decode(i);
}
</code>```

Every time that method onButton1() is called I post new random int to subject object and after that I received processed data via onNext() method when it is finished.

Is that solution correct and doesn't cause any side effect or memory leaks?
Of course I unsubscribe from subject in onStop() method of Activity.
Maybe there is a better solution to handle this kind of problem in Rxjava?

Any further answers will be appreciated :)

Title: Observable that emit items on demand

Body:
I want to create an Observable that will emit items on demand, that means I want a single subscribe to Observable and notify Observable that I need new item based on my request.

This is what I have done using PublishSubject:

public class RecognizeSubject {

PublishSubject<Bitmap> mSubject;

private Context mContext;
private FaceDetector mFaceDetecor;

public RecognizeSubject(Context mContext) {
    this.mContext = mContext;
    this.mSubject = PublishSubject.create();
}

public void detect(Bitmap btm){
    mSubject.onNext(btm);
}

public Flowable<SinglePhotoId> execute() {
    return mSubject.toFlowable(BackpressureStrategy.DROP)
            .observeOn(Schedulers.newThread())
            .map(bitmap1 -> recognize(bitmap1))
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(disposable -> initialize())
            .doFinally(() -> release());
}

private void initialize() {
    mFaceDetecor = new FaceDetector.Builder(mContext)
            .setTrackingEnabled(false)
            .setLandmarkType(FaceDetector.ALL_LANDMARKS)
            .build();
}

private void release() {
    if (mFaceDetecor != null)
        mFaceDetecor.release();
}

private SinglePhotoId recognize(Bitmap bitmap) {
    //SystemClock.sleep(3000);
   //make hard background work and return SinglePhotoId object
}

}

and here is a usage in Activity class:

private void takeSubjectSnap() {
    if (mSubject == null)
        mSubject = new RecognizeSubject(getBaseContext());

    if (mDisposable == null || mDisposable.isDisposed()) {
        mDisposable = mSubject.execute()
                .subscribe(this::handleDetectionSuccess,
                        this::handleDetectionError,
                        this::handleDetectionCompleted);
    }

    mSnapshotButton.setProgress(true);
    mSubject.detect(myVideoView.getBitmap());
}

So basically I subscribe to Flowable object and pass Bitmap object to my Subject class to proceed and return result via Flowable, is that solution right or can produce some memory leaks?

Is there any better solution to send an object to Observable to proceed and return result via a standard onNext() method?

Body:
OK, I have read your answer and changed my code a little, here is a diagram that illustrates what I want to achieve:

So my Subject class will process received data on background thread and emit processed items via onNext() method to their Observer. I made a simple Subject that receives Integer object and convert it to String object, here is the code:

public class MySubject {

private String TAG = "MySubject";

private PublishSubject<Integer> subject;
private final Observable<String> observable;

public MySubject() {
   Log.d(TAG, "---> MySubject() called");
   this.subject = PublishSubject.create();
   this.observable = subject
           .doOnSubscribe(disposable -> init())
           .doFinally(() -> relese()) //try do after terminate
           .observeOn(Schedulers.newThread())
           .map(this::myMap)
           .observeOn(AndroidSchedulers.mainThread());
}

private void init(){
   Log.d(TAG, "---> init() called");
}

private void relese(){
   Log.d(TAG, "---> relese() called");
}

private String myMap(Integer integer){
   Log.d(TAG, "---> myMap() called int: " + integer);
   SystemClock.sleep(3000);
   return " :) " + String.valueOf(integer);
}

public void decode(Integer integer){
   subject.onNext(integer);
}

public Observable<String> getObservable(){
   return observable;
}

}

And here is a usage in Activity class:

Disposable disposable = Disposables.disposed();
MySubject subject = new MySubject();

void onButton1() {

   if(disposable.isDisposed()){
       disposable = subject.getObservable()
               .subscribe(s -> {
                   Log.d(TAG, "---> onNext() called " + s);
               }, throwable -> {
                   Log.d(TAG, "---> onError() called " + throwable.getMessage());
               }, () -> {
                   Log.d(TAG, "---> onCompleted() called ");
               });
   }

   Random generator = new Random();
   int i = generator.nextInt(100) + 1;
   subject.decode(i);
}

Every time that method onButton1() is called I post new random int to subject object and after that I received processed data via onNext() method when it is finished.

Is that solution correct and doesn't cause any side effect or memory leaks?
Of course I unsubscribe from subject in onStop() method of Activity.
Maybe there is a better solution to handle this kind of problem in Rxjava?

Any further answers will be appreciated :)


来源: stackexchange

问:
How to convert a string to hyphen-conjoined words in JavaScript (& regex?)?
Let's say I have a string of text:

```<code>The quick brown fox jumped over 8 or 9 lazy dogs
</code>```

How would you convert this to lower case hyphen-conjoined words like this?

```<code>the-quick-brown-fox-jumped-over-8-or-9-lazy-dogs
</code>```

I assume it requires some kind of regex to convert it correctly?

答:
Use \s for a space character in a regular expression, add the g flag so it replaces all occurrences, and call toLowerCase() to make the string lowercase:

```<code>str.replace(/\s/g, "-").toLowerCase();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Let's say I have a string of text:

The quick brown fox jumped over 8 or 9 lazy dogs

How would you convert this to lower case hyphen-conjoined words like this?

the-quick-brown-fox-jumped-over-8-or-9-lazy-dogs

I assume it requires some kind of regex to convert it correctly?

Body:
Use \s for a space character in a regular expression, add the g flag so it replaces all occurrences, and call toLowerCase() to make the string lowercase:

str.replace(/\s/g, "-").toLowerCase();


问:
Large raster frequency table / counts
I try to calculate the frequency/count of pixel values of a raster in R using freq().
Create two example rasters for comparison:

```<code>library(raster)
RastSmall <- raster(nrow=70, ncol=70)
RastBig   <- raster(nrow=7000, ncol=7000)
set.seed(0)
RastSmall[] <- round(runif(1:ncell(r_hr), 1, 5))
RastBig[] <- round(runif(1:ncell(r_hr), 1, 5))
</code>```

Get the pixel count using freq()

```<code>freq(RastSmall)
value    count
[1,]     1  6540000
[2,]     2 12150000
[3,]     3 12140000
[4,]     4 11720000
[5,]     5  6450000
</code>```

However, it is a fairly large file and takes extremely long, i.e. up to hours. Is there a faster way in R?
Here the speed difference for a small and a large raster:

```<code>system.time(freq(RastSmall))
  user  system elapsed
  0.008   0.000   0.004
system.time(freq(RastBig))
  user  system elapsed
  40.484   0.964  41.445
</code>```

Is there a way to speed this up? Alternatively can this be done in the command line using something like gdal tools?

答:
I did exactly that last week, however I couldn't find other faster ways to do it in R.   I've tried to do it with the rqgis package by calling the r.report of GRASS.  It works but was slower than the R native function.  Maybe you'll have a better luck.  Here is my code with grass in case you want to try it:

```<code>library(RQGIS)
monqgis <- set_env("C:\\Mrnmicro\\Applic\\OSGeo4W")
find_algorithms(search_term = "report", qgis_env = monqgis)
get_usage(alg = "grass7:r.report", qgis_env = monqgis)
params <- get_args_man(alg = "grass7:r.report", qgis_env = monqgis)

get_usage(alg = "grass7:r.report", qgis_env = monqgis)

params$map <- classif
params$units <- 5
params$rawoutput <- "C:\\temp\\outputRQGIS_raw"
params$html <- "C:\\temp\\outputRQGIS"

system.time(asas <- run_qgis(alg = "grass7:r.report", params=params,load_output = params$OUTPUT, qgis_env = monqgis))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Large raster frequency table / counts

Body:
I try to calculate the frequency/count of pixel values of a raster in R using freq().
Create two example rasters for comparison:

library(raster)
RastSmall <- raster(nrow=70, ncol=70)
RastBig   <- raster(nrow=7000, ncol=7000)
set.seed(0)
RastSmall[] <- round(runif(1:ncell(r_hr), 1, 5))
RastBig[] <- round(runif(1:ncell(r_hr), 1, 5))

Get the pixel count using freq()

freq(RastSmall)
value    count
[1,]     1  6540000
[2,]     2 12150000
[3,]     3 12140000
[4,]     4 11720000
[5,]     5  6450000

However, it is a fairly large file and takes extremely long, i.e. up to hours. Is there a faster way in R?
Here the speed difference for a small and a large raster:

system.time(freq(RastSmall))
  user  system elapsed
  0.008   0.000   0.004
system.time(freq(RastBig))
  user  system elapsed
  40.484   0.964  41.445

Is there a way to speed this up? Alternatively can this be done in the command line using something like gdal tools?

Body:
I did exactly that last week, however I couldn't find other faster ways to do it in R.   I've tried to do it with the rqgis package by calling the r.report of GRASS.  It works but was slower than the R native function.  Maybe you'll have a better luck.  Here is my code with grass in case you want to try it:

library(RQGIS)
monqgis <- set_env("C:\\Mrnmicro\\Applic\\OSGeo4W")
find_algorithms(search_term = "report", qgis_env = monqgis)
get_usage(alg = "grass7:r.report", qgis_env = monqgis)
params <- get_args_man(alg = "grass7:r.report", qgis_env = monqgis)

get_usage(alg = "grass7:r.report", qgis_env = monqgis)

params$map <- classif
params$units <- 5
params$rawoutput <- "C:\\temp\\outputRQGIS_raw"
params$html <- "C:\\temp\\outputRQGIS"

system.time(asas <- run_qgis(alg = "grass7:r.report", params=params,load_output = params$OUTPUT, qgis_env = monqgis))


问:
angular2 - issue by using router
first of all I am a complete beginner at this kind of programming with nodejs, angular2 and typescript. Basically i start reading on https://angular.io/docs/ts/latest/guide/forms.html and https://angular.io/docs/ts/latest/guide/router.html#!#base-href to extend my application with new pages. I use mdl to use material components on my application.

 angular 2 seems to handly reloading and routing different so i get following issue:

I try to unterstand whats happening, can someone explain me what the difference between reloading and routing in angular2 and how I can fit the handling of routing to the behaviour of reloading?

Update #1:

index.html:

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Title</title>
  <script defer src="/assets/js/material.min.js"></script>
  <link rel="stylesheet" href="/assets/css/font-awesome.min.css">
  <link rel="stylesheet" href="/assets/css/material.min.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root><md-spinner></md-spinner></app-root>
</body>
</html>
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './pages/layout/app.component';
import { HomeComponent } from './pages/home/app.component';
import { LoginComponent } from './pages/myaccount/login.component';
import { NotFoundComponent } from './pages/error/404.component';
import { RegisterComponent } from './pages/myaccount/register.component';
import { RouterModule, Routes } from '@angular/router';
import { LoginService } from './service/LoginService';

const appRoutes: Routes = [
  {
      path: '',
      component: HomeComponent
  },
  { path: 'series', component: AppComponent },
  { path: 'login', component: LoginComponent },
  { path: 'register', component: RegisterComponent },
  { path: '**', component: NotFoundComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HomeComponent,
    RegisterComponent,
    NotFoundComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
    ],
  providers: [LoginService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

register.html:

```<code><div class="mdl-grid iv-padding" >
    <div class="mdl-layout-spacer"></div>
    <div class="mdl-cell mdl-cell--4-col">
      <div style="text-align:center;">
        <form (ngSubmit)="onSubmit()">
        <div class="iv-card-wide mdl-card mdl-shadow--2dp">
          <div class="mdl-card__title">
            <h2 class="mdl-card__title-text">Registrierung</h2>
          </div>
          <div class="mdl-card__supporting-text">
              <div class="text-field mdl-textfield mdl-js-textfield">
                <input class="mdl-textfield__input" required [(ngModel)]="model.username" name="username" type="text" id="username">
                <label class="mdl-textfield__label" for="username" >Username</label>
              </div>
              <br />
              <div class="text-field mdl-textfield mdl-js-textfield">
                <input class="mdl-textfield__input" [(ngModel)]="model.password" name="password" type="password" id="password">
                <label class="mdl-textfield__label" for="password">Password</label>
              </div>
              <br />
              <div class="text-field mdl-textfield mdl-js-textfield">
                <input class="mdl-textfield__input" [(ngModel)]="model.email" name="email" type="email" id="email">
                <label class="mdl-textfield__label" for="email">E-Mail</label>
              </div>
          </div>
          <div class="mdl-card__actions mdl-card--border">
            <button type="submit" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Registrieren</button>
          </div>
        </div>
        </form>
      </div>
    </div>
    <div class="mdl-layout-spacer"></div>
</div>
</code>```

RegisterComponent

```<code>import { Component } from '@angular/core';
import { User } from '../../objects/user';

@Component({
  selector: 'app-root',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})

export class RegisterComponent {
  model = new User(0, "", "", "");
  submitted = false;
  onSubmit() {
    console.log("PW" + this.model.password);
  }
}
</code>```

答:
Material Design Lite requires some extra work when you render the components dynamically. More information can be found in their docs

TLDR; You need to call componentHandler.upgradeElement after the elements have been injected into the DOM. An approach I've used in the past is described in the example below.

EDIT If you want a declarative solution this approach here seem like a pretty good one, but I have not used it myself.

I created a service that wraps the Material Lite componentHandler

```<code>import { Injectable } from '@angular/core';

export interface ComponentHandler {
    upgradeDom();

}

declare var componentHandler: ComponentHandler;

@Injectable()
export class MaterialService {
    handler: ComponentHandler;
    constructor() {
        this.handler = componentHandler;
    }

    // render on next tick
    render() {
        setTimeout(() => { this.handler.upgradeDom(); }, 0);
    }

}
</code>```

Then you call the service's render function after the component has injected the elements into the DOM.

This is a very contrived example but demonstrates "where" to call render

```<code>import { Component, OnInit } from '@angular/core';
import { DataService } from 'services/data.service';
import { MaterialService } from 'services/material.service';

@Component({
    selector: 'app-thing',
    templateUrl: `
       <ul>
            <li *ngFor="let item of data">
              {{data}}
            </li>
       </ul>
    `
})
export class ThingComponent implements OnInit {
    data: string[]
    constructor(
        private service: DataService,
        private material: MaterialService
    ) { }

    ngOnInit() {
        this.service.getData()
        .subscribe(data => {
            this.data = data;
            this.material.render();
        });
     }
}
</code>```

Title: angular2 - issue by using router

Body:
first of all I am a complete beginner at this kind of programming with nodejs, angular2 and typescript. Basically i start reading on https://angular.io/docs/ts/latest/guide/forms.html and https://angular.io/docs/ts/latest/guide/router.html#!#base-href to extend my application with new pages. I use mdl to use material components on my application.

 angular 2 seems to handly reloading and routing different so i get following issue:

I try to unterstand whats happening, can someone explain me what the difference between reloading and routing in angular2 and how I can fit the handling of routing to the behaviour of reloading?

Update #1:

index.html:

<!doctype html>

  <meta charset="utf-8">
  <title>Title</title>

  <link rel="stylesheet" href="/assets/css/font-awesome.min.css">
  <link rel="stylesheet" href="/assets/css/material.min.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root><md-spinner></md-spinner></app-root>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './pages/layout/app.component';
import { HomeComponent } from './pages/home/app.component';
import { LoginComponent } from './pages/myaccount/login.component';
import { NotFoundComponent } from './pages/error/404.component';
import { RegisterComponent } from './pages/myaccount/register.component';
import { RouterModule, Routes } from '@angular/router';
import { LoginService } from './service/LoginService';

const appRoutes: Routes = [
  {
      path: '',
      component: HomeComponent
  },
  { path: 'series', component: AppComponent },
  { path: 'login', component: LoginComponent },
  { path: 'register', component: RegisterComponent },
  { path: '**', component: NotFoundComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HomeComponent,
    RegisterComponent,
    NotFoundComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
    ],
  providers: [LoginService],
  bootstrap: [AppComponent]
})
export class AppModule { }

register.html:

        <form (ngSubmit)="onSubmit()">

Registrierung

                <input class="mdl-textfield__input" required [(ngModel)]="model.username" name="username" type="text" id="username">
                Username

                <input class="mdl-textfield__input" [(ngModel)]="model.password" name="password" type="password" id="password">
                Password

                <input class="mdl-textfield__input" [(ngModel)]="model.email" name="email" type="email" id="email">
                E-Mail

            <button type="submit" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">Registrieren</button>

        </form>

RegisterComponent

import { Component } from '@angular/core';
import { User } from '../../objects/user';

@Component({
  selector: 'app-root',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})

export class RegisterComponent {
  model = new User(0, "", "", "");
  submitted = false;
  onSubmit() {
    console.log("PW" + this.model.password);
  }
}

Body:
Material Design Lite requires some extra work when you render the components dynamically. More information can be found in their docs

TLDR; You need to call componentHandler.upgradeElement after the elements have been injected into the DOM. An approach I've used in the past is described in the example below.

EDIT If you want a declarative solution this approach here seem like a pretty good one, but I have not used it myself.

I created a service that wraps the Material Lite componentHandler

import { Injectable } from '@angular/core';

export interface ComponentHandler {
    upgradeDom();

}

declare var componentHandler: ComponentHandler;

@Injectable()
export class MaterialService {
    handler: ComponentHandler;
    constructor() {
        this.handler = componentHandler;
    }

    // render on next tick
    render() {
        setTimeout(() => { this.handler.upgradeDom(); }, 0);
    }

}

Then you call the service's render function after the component has injected the elements into the DOM.

This is a very contrived example but demonstrates "where" to call render

import { Component, OnInit } from '@angular/core';
import { DataService } from 'services/data.service';
import { MaterialService } from 'services/material.service';

@Component({
    selector: 'app-thing',
    templateUrl: `
       <ul>
            <li *ngFor="let item of data">
              {{data}}
            </li>
       </ul>
    `
})
export class ThingComponent implements OnInit {
    data: string[]
    constructor(
        private service: DataService,
        private material: MaterialService
    ) { }

    ngOnInit() {
        this.service.getData()
        .subscribe(data => {
            this.data = data;
            this.material.render();
        });
     }
}


问:
The difference between running a scala script directly vs through a scala shell
I ran into the "No TypeTag available for" error when running a simple script:

```<code>import scala.reflect.runtime.{universe => ru}
case class Person(name: String)
val classPerson = ru.typeOf[Person].typeSymbol.asClass
</code>```

The script is an example from Scala Reflection Doc. According to this post, the error is caused by the fact that the case class is not defined at the top level. I know scala automatically compiles a scala script into a class before running it, thus making the case class a internally defined class, but the same script would work if it is run in a scala shell. So what is the difference between running a scala script and running the same script through the scala shell?

答:
I'm not sure there is discrepancy between the Scala Shell and a Scala program in this case.  It still wouldn't work if the case class isn't defined "top-level" in the shell:

```<code>scala> import scala.reflect.runtime.{universe => ru}
import scala.reflect.runtime.{universe=>ru}

scala> case class Something(name: String)
defined class Something

scala> ru.typeOf[Something].typeSymbol.asClass
res1: reflect.runtime.universe.ClassSymbol = class Something

scala> { case class Something(name: String); ru.typeOf[Something].typeSymbol.asClass }

<console>:16: error: No TypeTag available for Something
    { case class Something(name: String); ru.typeOf[Something].typeSymbol.asClass }
                                                  ^
</code>```

[EDIT] Response to comments appended below:

It'll work in a program too as long as the case class is defined "top-level".  The following code will compile and output the class name:

```<code>import scala.reflect.runtime.{universe => ru}

case class Something(name: String)

object MyReflection extends App {
  println ("My case class: " + ru.typeOf[Something].typeSymbol.asClass)
}
</code>```

Body:
I ran into the "No TypeTag available for" error when running a simple script:

import scala.reflect.runtime.{universe => ru}
case class Person(name: String)
val classPerson = ru.typeOf[Person].typeSymbol.asClass

The script is an example from Scala Reflection Doc. According to this post, the error is caused by the fact that the case class is not defined at the top level. I know scala automatically compiles a scala script into a class before running it, thus making the case class a internally defined class, but the same script would work if it is run in a scala shell. So what is the difference between running a scala script and running the same script through the scala shell?

Body:
I'm not sure there is discrepancy between the Scala Shell and a Scala program in this case.  It still wouldn't work if the case class isn't defined "top-level" in the shell:

scala> import scala.reflect.runtime.{universe => ru}
import scala.reflect.runtime.{universe=>ru}

scala> case class Something(name: String)
defined class Something

scala> ru.typeOf[Something].typeSymbol.asClass
res1: reflect.runtime.universe.ClassSymbol = class Something

scala> { case class Something(name: String); ru.typeOf[Something].typeSymbol.asClass }

<console>:16: error: No TypeTag available for Something
    { case class Something(name: String); ru.typeOf[Something].typeSymbol.asClass }
                                                  ^

[EDIT] Response to comments appended below:

It'll work in a program too as long as the case class is defined "top-level".  The following code will compile and output the class name:

import scala.reflect.runtime.{universe => ru}

case class Something(name: String)

object MyReflection extends App {
  println ("My case class: " + ru.typeOf[Something].typeSymbol.asClass)
}


问:
Quiz displays wrong score
I am trying to build the quiz application with javascipt only but it gives me the wrong score. I first initialised correct variable with 0 and then wanted to increment the correct variable with 1 every time when the correct answer is selected but it shows the wrong score. I tried really hard to find any error but unable to find one. Please someone help me to fix this code and I would also appreciate if someone can specify why it is showing the wrong score.

var questions, question, pos = 0,
  ch1, ch2, ch3, cho, storeval, correct = 0;

questions = [
  ["What is 10 + 4", "12", "14", "16", "B"],
  ["What is 7 x 3", "21", "22", "23", "A"],
  ["What is 20 - 9", "15", "13", "11", "C"],
  ["What is 8/2", "5", "4", "2", "B"]
];

question = document.getElementById('question');

function loadQ() {

  ch1 = questions[pos][1];
  ch2 = questions[pos][2];
  ch3 = questions[pos][3];

  question.innerHTML = questions[pos][0] + "
";
  question.innerHTML += "<input type='radio' name='choices' value='A'>" + ch1 + "
";
  question.innerHTML += "<input type='radio' name='choices' value='B'>" + ch2 + "
";
  question.innerHTML += "<input type='radio' name='choices' value='C'>" + ch3 + "
";
}

function submitAnswer() {
  cho = document.getElementsByName('choices');

  for (var i = 0; i < cho.length; i++) {
    if (cho[i].checked) {
      storeval = cho[i].value;
    }
    if (storeval == questions[pos][4]) {
      correct++;
    }
  }
  pos++;

  if (pos < questions.length) {
    loadQ();
  } else {
    question.innerHTML = "Your Score is " + correct;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>Quiz</title>
</head>

<body onload="loadQ()">
  <div id="customize">
    <div id="question"></div>
    <input type="button" onclick="submitAnswer()" value="Submit">
  </div>
</body>

</html></code>```

答:
You have two independent if statements in submitAnswer. The second one checks whether storeval == questions[pos][4], but this could be an old value of storeval, because it doesn’t depend on the first if statement to change the value for the current question. Plus, it runs for every input with the potentially wrong value. They should be nested like this:

```<code>if (cho[i].checked) {
  storeval = cho[i].value;
  if (storeval == questions[pos][4]) {
    correct++;
  }
}
</code>```

Example

You can actually create live examples by modifying your loop code like this:

```<code>console.log("The loop is about to be entered. storeval is " + storeval + ".");
for (var i = 0; i < cho.length; i++) {
  console.log("The loop is running for answer " + cho[i].value + ". i is " + i + ".");
  if (cho[i].checked) {
    storeval = cho[i].value;
    console.log(cho[i].value + " is checked! Set storeval to " + storeval + ".");
  }
  if (storeval == questions[pos][4]) {
    correct++;
    console.log("storeval matches the expected question " + storeval + "! Update correct to " + correct + ".");
  }
}
</code>```

Messages beginning with “X is checked!” indicate that the first if statement is entered. Messages beginning with “storeval matches the expected question X!” indicate that the second if statement is entered.

If you pick the correct answer on the first question, you will get:

The loop is about to be entered. storeval is undefined.

  The loop is running for answer A. i is 0.

  The loop is running for answer B. i is 1.

  B is checked! Set storeval to B.

  storeval matches the expected question B! Update correct to 1.

  The loop is running for answer C. i is 2.

  storeval matches the expected question B! Update correct to 2.

If you then pick the correct answer on the second question, you will get:

The loop is about to be entered. storeval is B.

  The loop is running for answer A. i is 0.

  A is checked! Set storeval to A.

  storeval matches the expected question A! Update correct to 3.

  The loop is running for answer B. i is 1.

  storeval matches the expected question A! Update correct to 4.

  The loop is running for answer C. i is 2.

  storeval matches the expected question A! Update correct to 5.

Title: Quiz displays wrong score

Body:
I am trying to build the quiz application with javascipt only but it gives me the wrong score. I first initialised correct variable with 0 and then wanted to increment the correct variable with 1 every time when the correct answer is selected but it shows the wrong score. I tried really hard to find any error but unable to find one. Please someone help me to fix this code and I would also appreciate if someone can specify why it is showing the wrong score.

var questions, question, pos = 0,
  ch1, ch2, ch3, cho, storeval, correct = 0;

questions = [
  ["What is 10 + 4", "12", "14", "16", "B"],
  ["What is 7 x 3", "21", "22", "23", "A"],
  ["What is 20 - 9", "15", "13", "11", "C"],
  ["What is 8/2", "5", "4", "2", "B"]
];

question = document.getElementById('question');

function loadQ() {

  ch1 = questions[pos][1];
  ch2 = questions[pos][2];
  ch3 = questions[pos][3];

  question.innerHTML = questions[pos][0] + "
";
  question.innerHTML += "<input type='radio' name='choices' value='A'>" + ch1 + "
";
  question.innerHTML += "<input type='radio' name='choices' value='B'>" + ch2 + "
";
  question.innerHTML += "<input type='radio' name='choices' value='C'>" + ch3 + "
";
}

function submitAnswer() {
  cho = document.getElementsByName('choices');

  for (var i = 0; i < cho.length; i++) {
    if (cho[i].checked) {
      storeval = cho[i].value;
    }
    if (storeval == questions[pos][4]) {
      correct++;
    }
  }
  pos++;

  if (pos < questions.length) {
    loadQ();
  } else {
    question.innerHTML = "Your Score is " + correct;
  }
}

<!DOCTYPE html>

  <title>Quiz</title>

    <input type="button" onclick="submitAnswer()" value="Submit">

Body:
You have two independent if statements in submitAnswer. The second one checks whether storeval == questions[pos][4], but this could be an old value of storeval, because it doesn’t depend on the first if statement to change the value for the current question. Plus, it runs for every input with the potentially wrong value. They should be nested like this:

if (cho[i].checked) {
  storeval = cho[i].value;
  if (storeval == questions[pos][4]) {
    correct++;
  }
}

Example

You can actually create live examples by modifying your loop code like this:

console.log("The loop is about to be entered. storeval is " + storeval + ".");
for (var i = 0; i < cho.length; i++) {
  console.log("The loop is running for answer " + cho[i].value + ". i is " + i + ".");
  if (cho[i].checked) {
    storeval = cho[i].value;
    console.log(cho[i].value + " is checked! Set storeval to " + storeval + ".");
  }
  if (storeval == questions[pos][4]) {
    correct++;
    console.log("storeval matches the expected question " + storeval + "! Update correct to " + correct + ".");
  }
}

Messages beginning with “X is checked!” indicate that the first if statement is entered. Messages beginning with “storeval matches the expected question X!” indicate that the second if statement is entered.

If you pick the correct answer on the first question, you will get:

The loop is about to be entered. storeval is undefined.

  The loop is running for answer A. i is 0.

  The loop is running for answer B. i is 1.

  B is checked! Set storeval to B.

  storeval matches the expected question B! Update correct to 1.

  The loop is running for answer C. i is 2.

  storeval matches the expected question B! Update correct to 2.

If you then pick the correct answer on the second question, you will get:

The loop is about to be entered. storeval is B.

  The loop is running for answer A. i is 0.

  A is checked! Set storeval to A.

  storeval matches the expected question A! Update correct to 3.

  The loop is running for answer B. i is 1.

  storeval matches the expected question A! Update correct to 4.

  The loop is running for answer C. i is 2.

  storeval matches the expected question A! Update correct to 5.


问:
How to set a specific user on IIS Application
I have inherited some code that creates a couple of applications under IIS 7.0 using code similar to the following (tidied up for brevity)

```<code>DirectoryEntry iisServer = new DirectoryEntry("IIS://localhost/W3SVC/1");
DirectoryEntry folderRoot = iisServer.Children.Find("Root", "IIsWebVirtualDir");
DirectoryEntry newVirDir = folderRoot.Children.Add("MyNewVirtualDir", "IIsWebVirtualDir");

newVirDir.Properties["AccessRead"][0] = true;
newVirDir.Properties["AccessScript"][0] = true;
newVirDir.Properties["Path"].Insert(0, "C:\\MyVirtualDirStuff");
newVirDir.Properties["AccessExecute"][0] = true;
newVirDir.Properties["AppIsolated"].Value = 2; //"Medium (Pooled)"
newVirDir.Properties["DefaultDoc"][0] = "index.htm";
newVirDir.Invoke("AppCreate", true);
newVirDir.CommitChanges();
folderRoot.CommitChanges();
iisServer.CommitChanges();
</code>```

This all works correctly but now I have a need to specify that the Application runs under a specific account.  I can change this manually in IIS in the Connect As... dialog and specify the required domain username and password.

Unfortunately, I cannot for the life of me work out how to set this in the code.
I have tried setting the Username property in various ways but the Invoke("AppCreate") call always throws an Exception of some type dependent on what I've tried.  The following have all failed to work:

```<code>newVirDir.Username = "MYDOMAIN\\MyUser";
newVirDir.Properties["Username"][0] = "MYDOMAIN\\MyUser";
newVirDir.Properties["Username"].Insert(0, "MYDOMAIN\\MyUser");
</code>```

It must be easy - if only I knew how to do it!

Thanks in advance,
Chris

答:
Virtual directory Credential</p>

```<code>newVirDir.Properties["AuthFlags"].Value = 5;
newVirDir.Properties["UNCUsername"].Value = "MYDOMAIN\\MyUser";
newVirDir.Properties["UNCPassword"].Value = "password";
</code>```

Body:
I have inherited some code that creates a couple of applications under IIS 7.0 using code similar to the following (tidied up for brevity)

DirectoryEntry iisServer = new DirectoryEntry("IIS://localhost/W3SVC/1");
DirectoryEntry folderRoot = iisServer.Children.Find("Root", "IIsWebVirtualDir");
DirectoryEntry newVirDir = folderRoot.Children.Add("MyNewVirtualDir", "IIsWebVirtualDir");

newVirDir.Properties["AccessRead"][0] = true;
newVirDir.Properties["AccessScript"][0] = true;
newVirDir.Properties["Path"].Insert(0, "C:\\MyVirtualDirStuff");
newVirDir.Properties["AccessExecute"][0] = true;
newVirDir.Properties["AppIsolated"].Value = 2; //"Medium (Pooled)"
newVirDir.Properties["DefaultDoc"][0] = "index.htm";
newVirDir.Invoke("AppCreate", true);
newVirDir.CommitChanges();
folderRoot.CommitChanges();
iisServer.CommitChanges();

This all works correctly but now I have a need to specify that the Application runs under a specific account.  I can change this manually in IIS in the Connect As... dialog and specify the required domain username and password.

Unfortunately, I cannot for the life of me work out how to set this in the code.
I have tried setting the Username property in various ways but the Invoke("AppCreate") call always throws an Exception of some type dependent on what I've tried.  The following have all failed to work:

newVirDir.Username = "MYDOMAIN\\MyUser";
newVirDir.Properties["Username"][0] = "MYDOMAIN\\MyUser";
newVirDir.Properties["Username"].Insert(0, "MYDOMAIN\\MyUser");

It must be easy - if only I knew how to do it!

Thanks in advance,
Chris

Body:
Virtual directory Credential

newVirDir.Properties["AuthFlags"].Value = 5;
newVirDir.Properties["UNCUsername"].Value = "MYDOMAIN\\MyUser";
newVirDir.Properties["UNCPassword"].Value = "password";


问:
Error : java.util.ArrayList cannot be cast to java.lang.String
when am running my action i faced Error :
" java.util.ArrayList cannot be cast to java.lang.String "

and this is my code :

```<code> textField_1 = new JTextField();
       textField_1.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
           Object selected = list_1.getSelectedValue();
            Connection conn = null;
            PreparedStatement stmt = null;
            String a =null;
         try{

   conn=DriverManager.getConnection("jdbc:mysql://localhost/flyer","root","000");
   String query= " INSERT INTO flyer_item (discount)  SELECT price * ? FROM `item` WHERE item_name = `?` ";
   Statement st= conn.createStatement();

   java.sql.PreparedStatement ps = conn.prepareStatement(query);
                        ps.setString(1,a);
                        ps.setString(2,(String) selected);
                        ps.executeUpdate();
                        st.executeUpdate(query);

                    } catch (SQLException se){
                        System.out.println(se.getMessage());

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

Any help please ?

答:
Here Selected is an array-list and you are trying to convert it into string which is not possible:

```<code>ps.setString(2,(String) selected);
</code>```

What you should do?

```<code>ps.setString(2, selected.tostring());
</code>```

Body:
when am running my action i faced Error :
" java.util.ArrayList cannot be cast to java.lang.String "

and this is my code :

 textField_1 = new JTextField();
       textField_1.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
           Object selected = list_1.getSelectedValue();
            Connection conn = null;
            PreparedStatement stmt = null;
            String a =null;
         try{

   conn=DriverManager.getConnection("jdbc:mysql://localhost/flyer","root","000");
   String query= " INSERT INTO flyer_item (discount)  SELECT price * ? FROM `item` WHERE item_name = `?` ";
   Statement st= conn.createStatement();

   java.sql.PreparedStatement ps = conn.prepareStatement(query);
                        ps.setString(1,a);
                        ps.setString(2,(String) selected);
                        ps.executeUpdate();
                        st.executeUpdate(query);

                    } catch (SQLException se){
                        System.out.println(se.getMessage());

                    } }} );

Any help please ?

Body:
Here Selected is an array-list and you are trying to convert it into string which is not possible:

ps.setString(2,(String) selected);

What you should do?

ps.setString(2, selected.tostring());


问:
Removing NULL with COALESCE in Dynamic SQL
I have some dynamic SQL as part of a stored procedure I want to execute:

```<code>    SET @SQL_TXT = 'INSERT INTO ' +@ENTY_TABLE_NAME+
              '([ITEM_NAME]
               ,[ADD_DTT]
               ,[ADD_USR]
               ,[UPD_DTT]
               ,[UPD_USR]
               ,[ACTIVE_IND]
               ,[ITEM_PK])
         VALUES
               ('''+@UPD_VALUE+'''
          , CURRENT_TIMESTAMP
          , '''+@UPD_USR_DOM_NAME+''', CURRENT_TIMESTAMP,'''+@UPD_USR_DOM_NAME+''',''Y'','''+@ITEM_PK+''');
          SET @Id = SCOPE_IDENTITY();
          RETURN;'
</code>```

This runs fine, but ITEM_NAME can't be NULL so I want to ad a COALESE():

```<code>SET @SQL_TXT = 'INSERT INTO ' +@ENTY_TABLE_NAME+
          '(COALESCE([ITEM_NAME], '')
           ,[ADD_DTT]
           ,[ADD_USR]
           ,[UPD_DTT]
           ,[UPD_USR]
           ,[ACTIVE_IND]
           ,[ITEM_PK])
     VALUES
           ('''+@UPD_VALUE+'''
      , CURRENT_TIMESTAMP
      , '''+@UPD_USR_DOM_NAME+''', CURRENT_TIMESTAMP,'''+@UPD_USR_DOM_NAME+''',''Y'','''+@ITEM_PK+''');
      SET @Id = SCOPE_IDENTITY();
      RETURN;'
</code>```

But I am getting this error:

```<code>Incorrect syntax near the keyword 'COALESCE'.

Unclosed quotation mark after the character string ');

              SET @Id = SCOPE_IDENTITY();

              RETURN;'.

Incorrect syntax near '='.
</code>```

For the life of me I don't see where this ')' is. What am I doing wrong?

Edit: here is the exec

```<code>EXECUTE SP_executesql @SQL_TXT, N'@Id INTEGER OUTPUT', @Id OUTPUT
</code>```

答:
You can not put coalesce() around the column name destination of your insert, you use it around the value being inserted.

```<code>  SET @SQL_TXT = 'INSERT INTO ' +@ENTY_TABLE_NAME+
              '([ITEM_NAME]
               ,[ADD_DTT]
               ,[ADD_USR]
               ,[UPD_DTT]
               ,[UPD_USR]
               ,[ACTIVE_IND]
               ,[ITEM_PK])
         VALUES
               ('''+coalesce(@UPD_VALUE,'')+'''
          , CURRENT_TIMESTAMP
          , '''+@UPD_USR_DOM_NAME+''', CURRENT_TIMESTAMP,'''+@UPD_USR_DOM_NAME+''',''Y'','''+@ITEM_PK+''');
          SET @Id = SCOPE_IDENTITY();
          RETURN;'
</code>```

Note: @UPD_USR_DOM_NAME is inserted into two different columns. Not sure if that is intentional, just thought I would point it out.

You can also fully parameterize the rest of your values for use with sp_executesql instead of concatenating them like that. (Guessing at the data types of your parameters in this example)

```<code>declare @sql nvarchar(max);
declare @params nvarchar(max);
declare @id int;

set @sql = N'INSERT INTO ' +@ENTY_TABLE_NAME+'([ITEM_NAME] ,[ADD_DTT] ,[ADD_USR] ,[UPD_DTT] ,[UPD_USR] ,[ACTIVE_IND] ,[ITEM_PK])
      VALUES (coalesce(@UPD_VALUE,''), CURRENT_TIMESTAMP, @UPD_USR_DOM_NAME, CURRENT_TIMESTAMP,@UPD_USR_DOM_NAME,''Y'',@ITEM_PK);
      SET @Id = SCOPE_IDENTITY();
      RETURN;'

set @params = N'@UPD_VALUE varchar(32),@UPD_USR_DOM_NAME varchar(32), @ITEM_PK varchar(32), @Id INTEGER OUTPUT';

EXECUTE SP_executesql @sql, @params, @UPD_Value, @UPD_USER_DOM_NAME, @ITEM_PK, @Id = @Id OUTPUT;
</code>```

dynamic sql reference:

The curse and blessings of dynamic SQL - Erland Sommarskog

sp_executesql

Body:
I have some dynamic SQL as part of a stored procedure I want to execute:

    SET @SQL_TXT = 'INSERT INTO ' +@ENTY_TABLE_NAME+
              '([ITEM_NAME]
               ,[ADD_DTT]
               ,[ADD_USR]
               ,[UPD_DTT]
               ,[UPD_USR]
               ,[ACTIVE_IND]
               ,[ITEM_PK])
         VALUES
               ('''+@UPD_VALUE+'''
          , CURRENT_TIMESTAMP
          , '''+@UPD_USR_DOM_NAME+''', CURRENT_TIMESTAMP,'''+@UPD_USR_DOM_NAME+''',''Y'','''+@ITEM_PK+''');
          SET @Id = SCOPE_IDENTITY();
          RETURN;'

This runs fine, but ITEM_NAME can't be NULL so I want to ad a COALESE():

SET @SQL_TXT = 'INSERT INTO ' +@ENTY_TABLE_NAME+
          '(COALESCE([ITEM_NAME], '')
           ,[ADD_DTT]
           ,[ADD_USR]
           ,[UPD_DTT]
           ,[UPD_USR]
           ,[ACTIVE_IND]
           ,[ITEM_PK])
     VALUES
           ('''+@UPD_VALUE+'''
      , CURRENT_TIMESTAMP
      , '''+@UPD_USR_DOM_NAME+''', CURRENT_TIMESTAMP,'''+@UPD_USR_DOM_NAME+''',''Y'','''+@ITEM_PK+''');
      SET @Id = SCOPE_IDENTITY();
      RETURN;'

But I am getting this error:

Incorrect syntax near the keyword 'COALESCE'.

Unclosed quotation mark after the character string ');

              SET @Id = SCOPE_IDENTITY();

              RETURN;'.

Incorrect syntax near '='.

For the life of me I don't see where this ')' is. What am I doing wrong?

Edit: here is the exec

EXECUTE SP_executesql @SQL_TXT, N'@Id INTEGER OUTPUT', @Id OUTPUT

Body:
You can not put coalesce() around the column name destination of your insert, you use it around the value being inserted.

  SET @SQL_TXT = 'INSERT INTO ' +@ENTY_TABLE_NAME+
              '([ITEM_NAME]
               ,[ADD_DTT]
               ,[ADD_USR]
               ,[UPD_DTT]
               ,[UPD_USR]
               ,[ACTIVE_IND]
               ,[ITEM_PK])
         VALUES
               ('''+coalesce(@UPD_VALUE,'')+'''
          , CURRENT_TIMESTAMP
          , '''+@UPD_USR_DOM_NAME+''', CURRENT_TIMESTAMP,'''+@UPD_USR_DOM_NAME+''',''Y'','''+@ITEM_PK+''');
          SET @Id = SCOPE_IDENTITY();
          RETURN;'

Note: @UPD_USR_DOM_NAME is inserted into two different columns. Not sure if that is intentional, just thought I would point it out.

You can also fully parameterize the rest of your values for use with sp_executesql instead of concatenating them like that. (Guessing at the data types of your parameters in this example)

declare @sql nvarchar(max);
declare @params nvarchar(max);
declare @id int;

set @sql = N'INSERT INTO ' +@ENTY_TABLE_NAME+'([ITEM_NAME] ,[ADD_DTT] ,[ADD_USR] ,[UPD_DTT] ,[UPD_USR] ,[ACTIVE_IND] ,[ITEM_PK])
      VALUES (coalesce(@UPD_VALUE,''), CURRENT_TIMESTAMP, @UPD_USR_DOM_NAME, CURRENT_TIMESTAMP,@UPD_USR_DOM_NAME,''Y'',@ITEM_PK);
      SET @Id = SCOPE_IDENTITY();
      RETURN;'

set @params = N'@UPD_VALUE varchar(32),@UPD_USR_DOM_NAME varchar(32), @ITEM_PK varchar(32), @Id INTEGER OUTPUT';

EXECUTE SP_executesql @sql, @params, @UPD_Value, @UPD_USER_DOM_NAME, @ITEM_PK, @Id = @Id OUTPUT;

dynamic sql reference:

The curse and blessings of dynamic SQL - Erland Sommarskog

sp_executesql


问:
Javascript - Efficient way of defining a tree of images
Basically I have a folder full of images that branch out.

E.G:

```<code>Character
__male
____plain
______white
______brown
______black
____suit
______white
______brown
______black
__female
____plain
______white
______brown
______black
____dress
______white
______brown
______black
____bathingSuit
______white
______brown
______black
</code>```

I want to end up using the drawImage function like so:

```<code>var gender = "male",
    color = "white",
    clothing = "plain";

ctx.drawImage(character[gender][clothing][color], 0, 0, 100, 100);
</code>```

How would I go about doing this in a neat way that doesn't require 100 lines of code?

Also, the folder of images is ever so expanding. Is there a way where the code can automatically "go through folders" and add the images instead of manually adding it to the code?

答:
Encapsulate your logic inside a function, and use string concatenation when setting the correct image src. Assuming your Character folder is in the same directory as your HTML file, you can use:

// Placeholder variable
var ctx = { drawImage: Function.prototype }

var imageCache = {}

function getCharacterImage(options) {
  var src = ['Character', options.gender, options.clothing, options.color, options.action].join('/') + '.png'

  if (src in imageCache) return imageCache[src]

  var image = imageCache[src] = document.createElement('img')
  image.src = src
    return image
}

var image = getCharacterImage({
  gender: 'male',
  color: 'white',
  clothing: 'plain',
  action: 'walking'
})

console.log(image.src)

ctx.drawImage(image, 0, 0, 100, 100)```

Edit: If you would prefer to cache images that have already been created, you can create a map from srcs to images using dynamic object keys.

Body:
Basically I have a folder full of images that branch out.

E.G:

Character
__male
____plain
______white
______brown
______black
____suit
______white
______brown
______black
__female
____plain
______white
______brown
______black
____dress
______white
______brown
______black
____bathingSuit
______white
______brown
______black

I want to end up using the drawImage function like so:

var gender = "male",
    color = "white",
    clothing = "plain";

ctx.drawImage(character[gender][clothing][color], 0, 0, 100, 100);

How would I go about doing this in a neat way that doesn't require 100 lines of code?

Also, the folder of images is ever so expanding. Is there a way where the code can automatically "go through folders" and add the images instead of manually adding it to the code?

Body:
Encapsulate your logic inside a function, and use string concatenation when setting the correct image src. Assuming your Character folder is in the same directory as your HTML file, you can use:

// Placeholder variable
var ctx = { drawImage: Function.prototype }

var imageCache = {}

function getCharacterImage(options) {
  var src = ['Character', options.gender, options.clothing, options.color, options.action].join('/') + '.png'

  if (src in imageCache) return imageCache[src]

  var image = imageCache[src] = document.createElement('img')
  image.src = src
    return image
}

var image = getCharacterImage({
  gender: 'male',
  color: 'white',
  clothing: 'plain',
  action: 'walking'
})

console.log(image.src)

ctx.drawImage(image, 0, 0, 100, 100)

Edit: If you would prefer to cache images that have already been created, you can create a map from srcs to images using dynamic object keys.


问:
Change color of image mapping
How can i change the color of the mapping selection (area)?
This css: "area { background-color: red; }" does not work.

```<code><img id="map1" src="images/bg.png" usemap="#map1" />
    <map name="map1">
        <area shape="poly" onclick="openNav()" shape="poly" coords="902,516,936,496,940,535"/>
    </map>
</code>```

A hover would be nice, but just to reach it and change the background is a good start.

答:
Please check if the below code works:

```<code><area shape="poly" onclick="openNav()" class="poly" coords="902,516,936,496,940,535"/>
</code>```

In css , please make the changes:

```<code>.poly {
      backgroundColor = red;
}
</code>```

Just check if this works. I didn't run the code.

Title: Change color of image mapping

Body:
How can i change the color of the mapping selection (area)?
This css: "area { background-color: red; }" does not work.

    <map name="map1">
        <area shape="poly" onclick="openNav()" shape="poly" coords="902,516,936,496,940,535"/>
    </map>

A hover would be nice, but just to reach it and change the background is a good start.

Body:
Please check if the below code works:

<area shape="poly" onclick="openNav()" class="poly" coords="902,516,936,496,940,535"/>

In css , please make the changes:

.poly {
      backgroundColor = red;
}

Just check if this works. I didn't run the code.


问:
Can't set tag/attribute value using c# codebehind on aspx page
I have a custom .ascx control and would like to set one of it's properties using code.  In the .aspx I have this:

```<code><uc1:CustomContent ID="bunchOfContent" runat="server" contentPayload='<%# getRegionID() %>' />
</code>```

In the codebehind I have:

```<code>    public partial class Region : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
... things
        }

        public string getRegionID()
        {
            //return "region_" + Request["region"];
            return "thevalueIwant";
        }
</code>```

However, the value I want is not populated and the code is not invoked (breakpoints are not triggered).

What am I doing wrong?  I've tried various changes like changing the quotes from " to ' to no quotes at all.  Also I've used <%= instead of <%# but no luck.  Thanks!

答:
In the Page_Load method, you can do:

```<code>bunchOfContent.contentPayload = getRegionID();
</code>```

The reason why <%# ... %> did not work is because that's the form you use for databinding. In order for the code you put in there to be executed, you need to call the DataBind() method somewhere. And as for <%= ... %>, that's not suitable for setting a server control property, it simply is a short form of <% Response.Write(...) %>.

Body:
I have a custom .ascx control and would like to set one of it's properties using code.  In the .aspx I have this:

<uc1:CustomContent ID="bunchOfContent" runat="server" contentPayload='<%# getRegionID() %>' />

In the codebehind I have:

    public partial class Region : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
... things
        }

        public string getRegionID()
        {
            //return "region_" + Request["region"];
            return "thevalueIwant";
        }

However, the value I want is not populated and the code is not invoked (breakpoints are not triggered).

What am I doing wrong?  I've tried various changes like changing the quotes from " to ' to no quotes at all.  Also I've used <%= instead of <%# but no luck.  Thanks!

Body:
In the Page_Load method, you can do:

bunchOfContent.contentPayload = getRegionID();

The reason why <%# ... %> did not work is because that's the form you use for databinding. In order for the code you put in there to be executed, you need to call the DataBind() method somewhere. And as for <%= ... %>, that's not suitable for setting a server control property, it simply is a short form of <% Response.Write(...) %>.


问:
Unable to make clickable link in Swift 3
I want to have a clickable uitextview hyperlink in iOS Swift 3. My Code:</p>

```<code>private func setUpTextViews() {
  let attributedString = NSMutableAttributedString(string: "http://www.vitensenteret.no")
  attributedString.addAttribute(NSLinkAttributeName, value: "http//:www.vitensenteret.no", range: NSRange(location: 0, length: 19))

  hyperLink.attributedText = attributedString
  hyperLink.dataDetectorTypes = UIDataDetectorTypes.all
  phoneNumber.dataDetectorTypes = UIDataDetectorTypes.all
}

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in     characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
  UIApplication.shared.open(URL, options: [:])
  return false
}
</code>```

答:
Make sure you have enabled all below items inside storyboard to define on UITextView to act as link:

Uncheck editable,

Check Link for storyboard,

Make sure you have give delegate for UITextView to get call back for below delegate method:

```<code>func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool
{
return true;
}
</code>```

Also remove the ':' from above url given i.e., http://www.vitensenteret.no

Hope this will work for above issue.

Body:
I want to have a clickable uitextview hyperlink in iOS Swift 3. My Code:

private func setUpTextViews() {
  let attributedString = NSMutableAttributedString(string: "http://www.vitensenteret.no")
  attributedString.addAttribute(NSLinkAttributeName, value: "http//:www.vitensenteret.no", range: NSRange(location: 0, length: 19))

  hyperLink.attributedText = attributedString
  hyperLink.dataDetectorTypes = UIDataDetectorTypes.all
  phoneNumber.dataDetectorTypes = UIDataDetectorTypes.all
}

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in     characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
  UIApplication.shared.open(URL, options: [:])
  return false
}

Body:
Make sure you have enabled all below items inside storyboard to define on UITextView to act as link:

Uncheck editable,

Check Link for storyboard,

Make sure you have give delegate for UITextView to get call back for below delegate method:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool
{
return true;
}

Also remove the ':' from above url given i.e., http://www.vitensenteret.no

Hope this will work for above issue.


问:
Set userPassword to {CRYPT-SHA-512} in OpenLDAP programmaticaly remotely?
I'm trying to set a OpenLDAP userPassword to CRYPT-SHA-512 remotely. I would prefer to do this in PHP, but I'm open to other solutions that can be executed via PHP (e.g. python).

It's easy to set the userPassword to SHA1 remotely by setting the userPassword = '{SHA}'.base64_encode(sha1($password, true)).

How would you do this for CRYPT-SHA-512 password?

I would assume the checker would have to use the same crypt and number of rounds.

```<code><?php
  $rounds = 5000; //??
  $salt = random_seventeen_char();
  $userPassword = '{CRYPT}'.crypt($password, '$6$rounds='.$rounds.'$'.salt.'$');
?>
</code>```

I am able to do this through Apache Directory Studio without issues but need to be able to do it via a script.

答:
You cannot specify the rounds in OpenLDAP BINDPW. Here is the solution:</p>

```<code>function randomSalt( $length ) {
        $possible = '0123456789'.
                'abcdefghijklmnopqrstuvwxyz'.
                'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
                './';
        $str = '';
        // mt_srand((double)microtime() * 1000000);

        while (strlen($str) < $length)
                $str .= substr($possible, (rand() % strlen($possible)), 1);

        return $str;
}

$hashes['userPassword'] = '{CRYPT}'.crypt($this->pass, '$6$'.randomSalt(16).'$');
</code>```

Body:
I'm trying to set a OpenLDAP userPassword to CRYPT-SHA-512 remotely. I would prefer to do this in PHP, but I'm open to other solutions that can be executed via PHP (e.g. python).

It's easy to set the userPassword to SHA1 remotely by setting the userPassword = '{SHA}'.base64_encode(sha1($password, true)).

How would you do this for CRYPT-SHA-512 password?

I would assume the checker would have to use the same crypt and number of rounds.

<?php
  $rounds = 5000; //??
  $salt = random_seventeen_char();
  $userPassword = '{CRYPT}'.crypt($password, '$6$rounds='.$rounds.'$'.salt.'$');
?>

I am able to do this through Apache Directory Studio without issues but need to be able to do it via a script.

Body:
You cannot specify the rounds in OpenLDAP BINDPW. Here is the solution:

function randomSalt( $length ) {
        $possible = '0123456789'.
                'abcdefghijklmnopqrstuvwxyz'.
                'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
                './';
        $str = '';
        // mt_srand((double)microtime() * 1000000);

        while (strlen($str) < $length)
                $str .= substr($possible, (rand() % strlen($possible)), 1);

        return $str;
}

$hashes['userPassword'] = '{CRYPT}'.crypt($this->pass, '$6$'.randomSalt(16).'$');

ContentLicense: CC BY-SA 4.0


问:
.htaccess AddType json php with 1and1 hosting not working
I'm working with 1and1 hosting and i have this javascript code

```<code>    $.post('main.php',{data:'somedata'},function(e){
           if(e.response==10){
           //process info
    }
    });
</code>```

and in main.php i have this code

```<code><?php
header('Content-Type: application/json');
$response = array('response'=>10);
echo json_encode($response);
?>
</code>```

The problem here is that i receive a text/html response and i need a application/json response in my XAMPP local server works perfectly, the problem is that i need to add the json MIME Type but the 1and1 panel doesn't have that option, i know that i can parse that response in javascript, but i need it in JSON format for a Web Service purpose, i tried using .htaccess with this code

```<code>AddType application/json json php
</code>```

But doesn't work...

答: Consider using the longer $.ajax() form. That way you can specify return type. (dataType). PHP is only going to echo a string and that will not be treated like JSON until you receive it.

Body:
I'm working with 1and1 hosting and i have this javascript code

    $.post('main.php',{data:'somedata'},function(e){
           if(e.response==10){
           //process info
    }
    });

and in main.php i have this code

<?php
header('Content-Type: application/json');
$response = array('response'=>10);
echo json_encode($response);
?>

The problem here is that i receive a text/html response and i need a application/json response in my XAMPP local server works perfectly, the problem is that i need to add the json MIME Type but the 1and1 panel doesn't have that option, i know that i can parse that response in javascript, but i need it in JSON format for a Web Service purpose, i tried using .htaccess with this code

AddType application/json json php

But doesn't work...


问:
I need an implementation of java.time.LocalTime Converter
I'm using a LocalDate Converter, and now I need to use LocalTime also, Can anybody show me the code for the LocalTime JPA Converter, Thanks.</p>

```<code>@Converter(autoApply = true)
public class LocalDateDateConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate locDate) {
        return (locDate == null ? null : Date.valueOf(locDate));
    }

    @Override
    public LocalDate convertToEntityAttribute(Date sqlDate) {
        return (sqlDate == null ? null : sqlDate.toLocalDate());
    }
}
</code>```

答: I suggest you need to convert to and from java.sql.Time for the database. Look at the methods valueOf(LocalTime) and toLocalTime() in that class. Your code will be quite similar to the code you already have. Edit: I mean the code in the question; only after writing the answer I became aware that someone else had edited it in there.

Body:
I'm using a LocalDate Converter, and now I need to use LocalTime also, Can anybody show me the code for the LocalTime JPA Converter, Thanks.

@Converter(autoApply = true)
public class LocalDateDateConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate locDate) {
        return (locDate == null ? null : Date.valueOf(locDate));
    }

    @Override
    public LocalDate convertToEntityAttribute(Date sqlDate) {
        return (sqlDate == null ? null : sqlDate.toLocalDate());
    }
}


问:
Expected a colon error issues
Having a hard time figuring out why I am getting a expected a ';' after the function parseString.   </p>

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct Integer50
{
// a dynamically allocated array to hold a 50
// digit integer, stored in reverse order
int *digits;
} Integer50;

main() {
    Integer50 * parseString(char * str)
    { //error is on this colon
        return NULL;
    }
}
</code>```

答:
You cannot nest functions in C (though you can declare them inside a nested scope).

You will need to move:

```<code>Integer50 * parseString(char * str)
{ //error is on this colon
    return NULL;
}
</code>```

to the file scope.

Title: Expected a colon error issues

Body:
Having a hard time figuring out why I am getting a expected a ';' after the function parseString.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct Integer50
{
// a dynamically allocated array to hold a 50
// digit integer, stored in reverse order
int *digits;
} Integer50;

main() {
    Integer50 * parseString(char * str)
    { //error is on this colon
        return NULL;
    }
}

Body:
You cannot nest functions in C (though you can declare them inside a nested scope).

You will need to move:

Integer50 * parseString(char * str)
{ //error is on this colon
    return NULL;
}

to the file scope.


答:
Or this:
    "the quick brown fox jumps over the lazy dog".split(" ").join("-");</p>

Title: How to convert a string to hyphen-conjoined words in JavaScript (& regex?)?

Body:
Let's say I have a string of text:

The quick brown fox jumped over 8 or 9 lazy dogs

How would you convert this to lower case hyphen-conjoined words like this?

the-quick-brown-fox-jumped-over-8-or-9-lazy-dogs

I assume it requires some kind of regex to convert it correctly?


问:
BLE Universal sample app not working on windows 10 (IBM Lenovo Thinkpad L560)
I've used the windows universal apps found here to test the bluetooth low energy feature with a windows 10 (64bit) laptop. But I noticed that the same app doesn't work on certain laptops while working on certain other applications.

For example the BLE app worked correctly on a hp probook 450 G2 where it listened to heart rate monitoring BLE beacons. But the same app didn't receive any packets from the same beacon in another ibm lenovo thinkpad L560. (Both same OS, 64 bit)

This is the screenshot of a working app on the hp laptop.

This is the same app not-working on the ibm laptop

EDIT:
Both laptops shows bluetooth low energy support in the device manager.

Is this a known behavior? Has anyone already seen this kind of behavior?

(I can see few threads on windows mobile, but this is on windows laptops)

答:
Bluetooth LE, AKA Bluetooth 4.0, BLE and Bluetooth Smart is supported by most Operating Systems on mobile tablet and desktop,
 but the device needs a dedicated chip.

The hp Probook 450 G2 has Bluetooth 4.0 .

The IBM Thinkpad(latest model is from 2005) certainly has not.

Check the windows device manager to  see if Bluetooth devices have BLE capability(Bluetooth 4.0 or higher).


答:
area tags have to have an image associated with it. you cant just set the background-color to it.

You could have a plain image of the colour you want and place it on the href property of the area tag instead.

Title: Change color of image mapping


问:
00904. 00000 - "%s: invalid identifier"
Going crazy with this code.  Can Anybody put me on the right track?  I am using SQL Develope 3.1.07.  Thanks.

```<code>SELECT
    PHA.PO_HEADER_ID,
    PRLA.ATTRIBUTE1 As "REQUISITION_NUMBER",
    PHA.SEGMENT1 As PO_NUMBER,
    DECODE (nvl(REG.DOCUMENT_TYPE, '-'),
        'APW', 'Agreement for Performance of Work',
        'APWEMER', 'Agreement for Performance of Work - Emergency',
        'CONS', 'Consultant',
        'CONCEMER', 'Consultant - Emergency',
        'DFC', 'Direct Financial Contribution',
        'FELLOW', 'Fellowship',
        'GENEXT', 'General External Services',
        'IMPRESTCC', 'Imprest/Credit Card',
        'IS', 'Internal Services',
        'LOA', 'Letter of Agreement',
        'TSA', 'Technical Service Agreement') as DOCUMENT_TYPE,
   HAOU.NAME As BUDGET_CENTRE,
   PHA.CREATION_DATE As PO_CREATION_DATE,
   PHA.AUTHORIZATION_STATUS,
   PHA.APPROVED_DATE,
   PHA.COMMENTS,
   PHA.CLOSED_DATE,
   PHA.CLOSED_CODE,
   PDA.PO_DISTRIBUTION_ID,
   AIDA.INVOICE_ID,
   AIA.INVOICE_TYPE_LOOKUP_CODE AS INVOICE_TYPE,
   AIA.REMIT_TO_SUPPLIER_NAME AS SUPPLIER_NAME,
   AIA.REMIT_TO_SUPPLIER_ID AS SUPPLIER_ID,
   AIA.INVOICE_DATE, AIA.INVOICE_NUM,
   AIA.INVOICE_AMOUNT,
   AIA.INVOICE_CURRENCY_CODE AS INVOICE_CURRENCY,
   AIA.GL_DATE,
   AIA.PAYMENT_CURRENCY_CODE AS PAYMENT_CURRENCY,
   AIA.PAYMENT_CROSS_RATE_DATE AS PAYMENT_DATE,
   AIA.DESCRIPTION, AIA.EXCHANGE_DATE,
   AIA.EXCHANGE_RATE,
   AIA.BASE_AMOUNT AS FUNCTIONAL_CURRENCY_AMOUNT
FROM
   po_headers_all pha,
   po_distributions_all pda,
   ap_invoice_distributions_all aida,
   ap_invoices_all aia,
   po_requisition_lines_all prla,
   po_req_distributions_all prda,
   hr.hr_all_organization_units haou,
   pa.pa_projects_all ppa
LEFT JOIN
   xxwrp.xxwrp_service_reg_all reg
ON
   reg.po_header_id = pha.po_header_id
WHERE
   1=1
   AND pha.segment1 = '201251390'
   AND pda.req_distribution_id = prda.distribution_id
   AND prda.requisition_line_id = prla.requisition_line_id
   AND pha.po_header_id = pda.po_header_id
   AND pda.po_distribution_id = aida.po_distribution_id
   AND aida.invoice_id = aia.invoice_id
   AND pda.project_id = ppa.project_id
   AND haou.organization_id=ppa.carrying_out_organization_id
   AND pha.creation_date > aia.invoice_date
GROUP BY
   PHA.PO_HEADER_ID, PRLA.ATTRIBUTE1, PHA.SEGMENT1, REG.DOCUMENT_TYPE, HAOU.NAME, PHA.CREATION_DATE, PHA.AUTHORIZATION_STATUS, PHA.APPROVED_DATE, PHA.COMMENTS, PHA.CLOSED_DATE, PHA.CLOSED_CODE, PDA.PO_DISTRIBUTION_ID, AIDA.INVOICE_ID, AIA.INVOICE_TYPE_LOOKUP_CODE, AIA.REMIT_TO_SUPPLIER_NAME, AIA.REMIT_TO_SUPPLIER_ID, AIA.INVOICE_DATE, AIA.INVOICE_NUM, AIA.INVOICE_AMOUNT, AIA.INVOICE_CURRENCY_CODE, AIA.GL_DATE, AIA.PAYMENT_CURRENCY_CODE, AIA.PAYMENT_CROSS_RATE_DATE, AIA.DESCRIPTION, AIA.EXCHANGE_DATE, AIA.EXCHANGE_RATE, AIA.BASE_AMOUNT
</code>```

When I run it, it returns this error:

ORA-00904: "PHA"."PO_HEADER_ID": invalid identifier
  00904. 00000 -  "%s: invalid identifier"
  *Cause:

  *Action:
  Error at Line: 50 Column: 21

答:
The problem is your left join.  There is probably a column missing; the one you are joining on.

Here is more details on the error you're receiving:
https://www.techonthenet.com/oracle/errors/ora00904.php

Title: 00904. 00000 - "%s: invalid identifier"

Body:
Going crazy with this code.  Can Anybody put me on the right track?  I am using SQL Develope 3.1.07.  Thanks.

SELECT
    PHA.PO_HEADER_ID,
    PRLA.ATTRIBUTE1 As "REQUISITION_NUMBER",
    PHA.SEGMENT1 As PO_NUMBER,
    DECODE (nvl(REG.DOCUMENT_TYPE, '-'),
        'APW', 'Agreement for Performance of Work',
        'APWEMER', 'Agreement for Performance of Work - Emergency',
        'CONS', 'Consultant',
        'CONCEMER', 'Consultant - Emergency',
        'DFC', 'Direct Financial Contribution',
        'FELLOW', 'Fellowship',
        'GENEXT', 'General External Services',
        'IMPRESTCC', 'Imprest/Credit Card',
        'IS', 'Internal Services',
        'LOA', 'Letter of Agreement',
        'TSA', 'Technical Service Agreement') as DOCUMENT_TYPE,
   HAOU.NAME As BUDGET_CENTRE,
   PHA.CREATION_DATE As PO_CREATION_DATE,
   PHA.AUTHORIZATION_STATUS,
   PHA.APPROVED_DATE,
   PHA.COMMENTS,
   PHA.CLOSED_DATE,
   PHA.CLOSED_CODE,
   PDA.PO_DISTRIBUTION_ID,
   AIDA.INVOICE_ID,
   AIA.INVOICE_TYPE_LOOKUP_CODE AS INVOICE_TYPE,
   AIA.REMIT_TO_SUPPLIER_NAME AS SUPPLIER_NAME,
   AIA.REMIT_TO_SUPPLIER_ID AS SUPPLIER_ID,
   AIA.INVOICE_DATE, AIA.INVOICE_NUM,
   AIA.INVOICE_AMOUNT,
   AIA.INVOICE_CURRENCY_CODE AS INVOICE_CURRENCY,
   AIA.GL_DATE,
   AIA.PAYMENT_CURRENCY_CODE AS PAYMENT_CURRENCY,
   AIA.PAYMENT_CROSS_RATE_DATE AS PAYMENT_DATE,
   AIA.DESCRIPTION, AIA.EXCHANGE_DATE,
   AIA.EXCHANGE_RATE,
   AIA.BASE_AMOUNT AS FUNCTIONAL_CURRENCY_AMOUNT
FROM
   po_headers_all pha,
   po_distributions_all pda,
   ap_invoice_distributions_all aida,
   ap_invoices_all aia,
   po_requisition_lines_all prla,
   po_req_distributions_all prda,
   hr.hr_all_organization_units haou,
   pa.pa_projects_all ppa
LEFT JOIN
   xxwrp.xxwrp_service_reg_all reg
ON
   reg.po_header_id = pha.po_header_id
WHERE
   1=1
   AND pha.segment1 = '201251390'
   AND pda.req_distribution_id = prda.distribution_id
   AND prda.requisition_line_id = prla.requisition_line_id
   AND pha.po_header_id = pda.po_header_id
   AND pda.po_distribution_id = aida.po_distribution_id
   AND aida.invoice_id = aia.invoice_id
   AND pda.project_id = ppa.project_id
   AND haou.organization_id=ppa.carrying_out_organization_id
   AND pha.creation_date > aia.invoice_date
GROUP BY
   PHA.PO_HEADER_ID, PRLA.ATTRIBUTE1, PHA.SEGMENT1, REG.DOCUMENT_TYPE, HAOU.NAME, PHA.CREATION_DATE, PHA.AUTHORIZATION_STATUS, PHA.APPROVED_DATE, PHA.COMMENTS, PHA.CLOSED_DATE, PHA.CLOSED_CODE, PDA.PO_DISTRIBUTION_ID, AIDA.INVOICE_ID, AIA.INVOICE_TYPE_LOOKUP_CODE, AIA.REMIT_TO_SUPPLIER_NAME, AIA.REMIT_TO_SUPPLIER_ID, AIA.INVOICE_DATE, AIA.INVOICE_NUM, AIA.INVOICE_AMOUNT, AIA.INVOICE_CURRENCY_CODE, AIA.GL_DATE, AIA.PAYMENT_CURRENCY_CODE, AIA.PAYMENT_CROSS_RATE_DATE, AIA.DESCRIPTION, AIA.EXCHANGE_DATE, AIA.EXCHANGE_RATE, AIA.BASE_AMOUNT

When I run it, it returns this error:

ORA-00904: "PHA"."PO_HEADER_ID": invalid identifier
  00904. 00000 -  "%s: invalid identifier"
  *Cause:

  *Action:
  Error at Line: 50 Column: 21


问:
how to implement an onclick listener for a list view that links to a new fragment
So I have a listview that works, but I want to implement an onclick listener for this listview. I want the onclick listener to link to a new fragment so that another page is opened when I click on some index in the list. I have done some testing and have determined that the onclick listener as a whole does not work.

This is what I have so far:

```<code>package ca.queensu.engsoc.events;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class eventList extends Activity implements AdapterView.OnItemClickListener
{
public static final String KEY_NAME = "NAME_KEY";
ListView events;
String[] e;
mockData myBadData = new mockData();
@Override

protected void onCreate (Bundle savedInstanceState)
{
    //Fragment fragment_blank2=new SomeFragment();

    e = myBadData.getData();

    super.onCreate(savedInstanceState);

    setContentView(R.layout.event_list);

    events=(ListView) findViewById(R.id.dayList);

    ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,e);

    events.setAdapter(adapter);

    events.setOnItemClickListener(this);
}

@Override

public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    //TextView temp=(TextView) view;

    View temp=view;

    //final Toast toast = Toast.makeText(this, temp.getText() + "" + i, Toast.LENGTH_SHORT.show());

    temp.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Bundle bundle = new Bundle();

            bundle.putString(KEY_NAME,myBadData.getOneData(i));

            Fragment fr = new event_description();

            fr.setArguments(bundle);

            FragmentManager fm = getFragmentManager();

            FragmentTransaction fragmentTransaction = fm.beginTransaction();

            int contId = v.getId();

            fragmentTransaction.replace(contId, fr);

            fragmentTransaction.commit();

            Intent i=new Intent(eventList.this, fr.getClass());

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

}

What am I doing wrong?

答:
To do what you want first you need to declare a interface to use as callback between your adapter and your activity/fragment.

RecyclerItemCallback:

```<code>public interface RecyclerItemCallback {

    void onClick(int position);

}
</code>```

Then make your activity implement this interface: (

```<code>public class EventList extends Activity implements RecyclerItemCallback {

    ...

    @Override
    public void onClick(int position) {
        //Implement the method "Fragment getFragment(int position)" to find the Fragment you want based on the position
        YourFragment newFragment = getFragment(position);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (addToBackStack) {
            fragmentTransaction.addToBackStack(newFragment.getClass().getSimpleName());
        }
        fragmentTransaction.replace(R.id.content, newFragment).commitAllowingStateLoss();
    }
}
</code>```

Then in your adapter do this:

YourAdapter

```<code>public class YourAdapter extends RecyclerView.Adapter<YourAdapter.MyViewHolder> {

    private RecyclerItemCallback recyclerCallback;
    private ArrayList<YourObject> list;
    private Context context;
    private int lastPosition;

    public NewsAdapter(Context context, RecyclerItemCallback callback) {
        this.context = context;
        this.newsList = new ArrayList<>();
        this.recyclerCallback = callback;
    }
    ...

    class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView text1;
        ...
        private View.OnClickListener onRowClicked = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            recyclerCallback.onItemClick(getAdapterPosition());
        }
    };

    MyViewHolder(View itemView, int viewType) {
        super(itemView);
        this.viewType = viewType;
        ...
        itemView.setOnClickListener(onRowClicked);
    }
    ...
}
</code>```

Body:
So I have a listview that works, but I want to implement an onclick listener for this listview. I want the onclick listener to link to a new fragment so that another page is opened when I click on some index in the list. I have done some testing and have determined that the onclick listener as a whole does not work.

This is what I have so far:

package ca.queensu.engsoc.events;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class eventList extends Activity implements AdapterView.OnItemClickListener
{
public static final String KEY_NAME = "NAME_KEY";
ListView events;
String[] e;
mockData myBadData = new mockData();
@Override

protected void onCreate (Bundle savedInstanceState)
{
    //Fragment fragment_blank2=new SomeFragment();

    e = myBadData.getData();

    super.onCreate(savedInstanceState);

    setContentView(R.layout.event_list);

    events=(ListView) findViewById(R.id.dayList);

    ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,e);

    events.setAdapter(adapter);

    events.setOnItemClickListener(this);
}

@Override

public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
    //TextView temp=(TextView) view;

    View temp=view;

    //final Toast toast = Toast.makeText(this, temp.getText() + "" + i, Toast.LENGTH_SHORT.show());

    temp.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Bundle bundle = new Bundle();

            bundle.putString(KEY_NAME,myBadData.getOneData(i));

            Fragment fr = new event_description();

            fr.setArguments(bundle);

            FragmentManager fm = getFragmentManager();

            FragmentTransaction fragmentTransaction = fm.beginTransaction();

            int contId = v.getId();

            fragmentTransaction.replace(contId, fr);

            fragmentTransaction.commit();

            Intent i=new Intent(eventList.this, fr.getClass());

        }
    });
}

}

What am I doing wrong?

Body:
To do what you want first you need to declare a interface to use as callback between your adapter and your activity/fragment.

RecyclerItemCallback:

public interface RecyclerItemCallback {

    void onClick(int position);

}

Then make your activity implement this interface: (

public class EventList extends Activity implements RecyclerItemCallback {

    ...

    @Override
    public void onClick(int position) {
        //Implement the method "Fragment getFragment(int position)" to find the Fragment you want based on the position
        YourFragment newFragment = getFragment(position);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (addToBackStack) {
            fragmentTransaction.addToBackStack(newFragment.getClass().getSimpleName());
        }
        fragmentTransaction.replace(R.id.content, newFragment).commitAllowingStateLoss();
    }
}

Then in your adapter do this:

YourAdapter

public class YourAdapter extends RecyclerView.Adapter<YourAdapter.MyViewHolder> {

    private RecyclerItemCallback recyclerCallback;
    private ArrayList<YourObject> list;
    private Context context;
    private int lastPosition;

    public NewsAdapter(Context context, RecyclerItemCallback callback) {
        this.context = context;
        this.newsList = new ArrayList<>();
        this.recyclerCallback = callback;
    }
    ...

    class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView text1;
        ...
        private View.OnClickListener onRowClicked = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            recyclerCallback.onItemClick(getAdapterPosition());
        }
    };

    MyViewHolder(View itemView, int viewType) {
        super(itemView);
        this.viewType = viewType;
        ...
        itemView.setOnClickListener(onRowClicked);
    }
    ...
}


问:
Keeping only certain properties in a JavaScript object
I have an object.  I would like to modify the object (not clone it) by removing all properties except for certain specific properties. For instance, if I started with this object:

```<code>var myObj={
    p1:123,
    p2:321,
    p3:{p3_1:1231,p3_2:342},
    p4:'23423',
    //....
    p99:{p99_1:'sadf',p99_2:234},
    p100:3434
}
</code>```

and only want properties p1, p2, and p100, how can I obtain this object:

```<code>var myObj={
    p1:123,
    p2:321,
    p100:3434
}
</code>```

I understand how I could do this with brute force, but would like a more elegant solution.

答:
This was the first hit when googling 'js keep only certain keys' so might be worth an update.

The most 'elegant' solution might just be using underscore.js

```<code>_.pick(myObj, 'p1', 'p2', 'p100')
</code>```

Body:
I have an object.  I would like to modify the object (not clone it) by removing all properties except for certain specific properties. For instance, if I started with this object:

var myObj={
    p1:123,
    p2:321,
    p3:{p3_1:1231,p3_2:342},
    p4:'23423',
    //....
    p99:{p99_1:'sadf',p99_2:234},
    p100:3434
}

and only want properties p1, p2, and p100, how can I obtain this object:

var myObj={
    p1:123,
    p2:321,
    p100:3434
}

I understand how I could do this with brute force, but would like a more elegant solution.

Body:
This was the first hit when googling 'js keep only certain keys' so might be worth an update.

The most 'elegant' solution might just be using underscore.js

_.pick(myObj, 'p1', 'p2', 'p100')


问:
Using a Template Repeater in a Table tag
In my application I have noticed that my template repeater does not get called when inside of a table.  My goal is to use the repeater to complete the data and refresh it as needed.

Markup:

```<code><table>
    <tr>
        <th>Name</th>
        <th>Date Uploaded</th>
        <th>Default</th>
    </tr>
    <template id="themesRows" is="dom-repeat" items="{{themeList}}">
        <tr>
            <td>TEST {{item.name}}</td>
            <td>{{item.dateCreatedUtc}}</td>
            <td>
                <!--<input type="radio" name="default" value="{{item.id}}" selected="{{item.id == model.defaultThemeId}}" />-->
            </td>
            <td>{{index}}</td>
        </tr>
    </template>
</table>
</code>```

Dart:

```<code>class SampleB {
  String name = "";
  String dateCreatedUtc = "";
  int id = 0;
  SampleB(this.id, this.name, this.dateCreatedUtc);
}
</code>```

class MyPolymerElement extends PolymerElement{
     @property List themeList = [];
     MyPolymerElement.created() : super.created();
     attached(){}
   }

答:
When looking at design methodologies of Polymer being a modern version of HTML, coupled with Dart (originally tagged as the future of web programming). I had to do some sample tests.   After extracting it to its own spot, outside that of the table I did confirm that the data does in fact, repeat.  The issue comes from the table.

A table is an old way of listing out data.  It is the oldest but one of the most used concepts on the internet.  With this new age of computing and the leveraging of Design methodologies of Polymer we aren't actually suppose to use them at all.

Conceptually, there are more modern and entertaining ways to display information to users.  One of the most commonplace concepts is the idea all throughout Polymer, Cards.  You would define a card through css and html and repeat that, creating so many of the lists around the polymer websites.

I thought long and hard about this.  It seems that putting a template repeater inside of a table and a table>tbody pair would not carry out the render, instead it just rendered it as is. 1 row of empty strings underneath the header concepts.

So to get the correct answer to your explicit question, you could do something like this.

```<code><dom-module id="tableDesign">
  <template>
    <style>
      .table { display: table;}
      .row { display: table-row;}
      .header { font-weight:bold; display: table-cell; text-align:center;}
      .cell { display: table-cell;}
    </style>

    <div class="table">
      <div class="row">
        <div class="header">Name</div>
        <div class="header">Date Created</div>
        <div class="header">Default</div>
      </div>
      <template is="dom-repeat" items="{{themeList}}">
        <div class="row">
          <div class="cell">{{item.name}}</div>
          <div class="cell">{{item.dateCreatedUtc}}</div>
          <div class="cell">
            <!-- Insert Radio Here -->
          </div>
        </div>
      </template>
    </div>
  </template>
</dom-module>
</code>```

This will get your repeater to work, while leveraging a "table" without using thetable tag.

On a deeper level of understanding though, I think that looking at a more modern concept for displaying your rows of data should be looked into.  Developing a card or structure which fits with the modern concepts would allow you to effectively lever the modern tools you are trying to use.

Body:
In my application I have noticed that my template repeater does not get called when inside of a table.  My goal is to use the repeater to complete the data and refresh it as needed.

Markup:

        Name
        Date Uploaded
        Default

    <template id="themesRows" is="dom-repeat" items="{{themeList}}">

            TEST {{item.name}}
            {{item.dateCreatedUtc}}

            {{index}}

    </template>

Dart:

class SampleB {
  String name = "";
  String dateCreatedUtc = "";
  int id = 0;
  SampleB(this.id, this.name, this.dateCreatedUtc);
}

class MyPolymerElement extends PolymerElement{
     @property List themeList = [];
     MyPolymerElement.created() : super.created();
     attached(){}
   }

Body:
When looking at design methodologies of Polymer being a modern version of HTML, coupled with Dart (originally tagged as the future of web programming). I had to do some sample tests.   After extracting it to its own spot, outside that of the table I did confirm that the data does in fact, repeat.  The issue comes from the table.

A table is an old way of listing out data.  It is the oldest but one of the most used concepts on the internet.  With this new age of computing and the leveraging of Design methodologies of Polymer we aren't actually suppose to use them at all.

Conceptually, there are more modern and entertaining ways to display information to users.  One of the most commonplace concepts is the idea all throughout Polymer, Cards.  You would define a card through css and html and repeat that, creating so many of the lists around the polymer websites.

I thought long and hard about this.  It seems that putting a template repeater inside of a table and a table>tbody pair would not carry out the render, instead it just rendered it as is. 1 row of empty strings underneath the header concepts.

So to get the correct answer to your explicit question, you could do something like this.

<dom-module id="tableDesign">
  <template>
    <style>
      .table { display: table;}
      .row { display: table-row;}
      .header { font-weight:bold; display: table-cell; text-align:center;}
      .cell { display: table-cell;}
    </style>

    <div class="table">
      <div class="row">
        <div class="header">Name</div>
        <div class="header">Date Created</div>
        <div class="header">Default</div>
      </div>
      <template is="dom-repeat" items="{{themeList}}">
        <div class="row">
          <div class="cell">{{item.name}}</div>
          <div class="cell">{{item.dateCreatedUtc}}</div>
          <div class="cell">
            <!-- Insert Radio Here -->
          </div>
        </div>
      </template>
    </div>
  </template>
</dom-module>

This will get your repeater to work, while leveraging a "table" without using thetable tag.

On a deeper level of understanding though, I think that looking at a more modern concept for displaying your rows of data should be looked into.  Developing a card or structure which fits with the modern concepts would allow you to effectively lever the modern tools you are trying to use.