问:
How to get Response Headers upon HTTP Request?
I have the following code where I make a post request and I have set Authorization header with JWToken in my server. I wish to extract the JWToken from the response header and save it in local storage using port.
How to get hold of the Response? I see Metadata which has Headers in the Response type. ref - https://package.elm-lang.org/packages/elm/http/latest/Http#Response</p>

```<code>type Msg
  = EnteredEmail String
  | EnteredPassword String
  | SubmittedForm
  | RegistrationSuccess (Result Http.Error ())

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
  case msg of

    EnteredEmail email ->
      updateForm (\form -> { form | email = email }) model

    EnteredPassword password ->
      updateForm (\form -> { form | password = password }) model

    RegistrationSuccess _->
      -- TODO save JWT in local storage on successful registration
      (model, Cmd.none)

    SubmittedForm ->
      -- TODO validate the form
      (model, postCall model)

postCall : Model -> Cmd Msg
postCall model = Http.post {
          url = "http://localhost:9000/register",
          body = Http.jsonBody (
            Json.Encode.object[
              ("age", Json.Encode.int 30),
              ("email", Json.Encode.string model.form.email),
              ("password", Json.Encode.string model.form.password)
            ]
          ),
          expect = Http.expectWhatever RegistrationSuccess
        }
</code>```

答:
You can get to the Response and headers by using Http.expectStringResponse or Http.expectBytesResponse instead of Http.expectWhatever.

Here's an example that defines a convenience function expectJWT which will retrieve and return the Authorization header, or if it does not exist returns BadStatus 403. In postCall all that's changed is that Http.expectWhatever has been replaced with expectJWT:

```<code>expectJWT : (Result Http.Error String -> msg) -> Http.Expect msg
expectJWT toMsg =
    Http.expectStringResponse toMsg <|
        \response ->
            case response of
                Http.BadUrl_ url ->
                    Err (Http.BadUrl url)

                Http.Timeout_ ->
                    Err Http.Timeout

                Http.NetworkError_ ->
                    Err Http.NetworkError

                Http.BadStatus_ metadata body ->
                    Err (Http.BadStatus metadata.statusCode)

                Http.GoodStatus_ metadata body ->
                    metadata.headers
                        |> Dict.get "Authorization"
                        |> Result.fromMaybe (Http.BadStatus 403)

postCall : Model -> Cmd Msg
postCall model = Http.post {
          url = "http://localhost:9000/register",
          body = Http.jsonBody (
            Json.Encode.object[
              ("age", Json.Encode.int 30),
              ("email", Json.Encode.string model.form.email),
              ("password", Json.Encode.string model.form.password)
            ]
          ),
          expect =  expectJWT RegistrationSuccess
        }
</code>```

Body:
I have the following code where I make a post request and I have set Authorization header with JWToken in my server. I wish to extract the JWToken from the response header and save it in local storage using port.
How to get hold of the Response? I see Metadata which has Headers in the Response type. ref - https://package.elm-lang.org/packages/elm/http/latest/Http#Response

type Msg
  = EnteredEmail String
  | EnteredPassword String
  | SubmittedForm
  | RegistrationSuccess (Result Http.Error ())

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
  case msg of

    EnteredEmail email ->
      updateForm (\form -> { form | email = email }) model

    EnteredPassword password ->
      updateForm (\form -> { form | password = password }) model

    RegistrationSuccess _->
      -- TODO save JWT in local storage on successful registration
      (model, Cmd.none)

    SubmittedForm ->
      -- TODO validate the form
      (model, postCall model)

postCall : Model -> Cmd Msg
postCall model = Http.post {
          url = "http://localhost:9000/register",
          body = Http.jsonBody (
            Json.Encode.object[
              ("age", Json.Encode.int 30),
              ("email", Json.Encode.string model.form.email),
              ("password", Json.Encode.string model.form.password)
            ]
          ),
          expect = Http.expectWhatever RegistrationSuccess
        }

Body:
You can get to the Response and headers by using Http.expectStringResponse or Http.expectBytesResponse instead of Http.expectWhatever.

Here's an example that defines a convenience function expectJWT which will retrieve and return the Authorization header, or if it does not exist returns BadStatus 403. In postCall all that's changed is that Http.expectWhatever has been replaced with expectJWT:

expectJWT : (Result Http.Error String -> msg) -> Http.Expect msg
expectJWT toMsg =
    Http.expectStringResponse toMsg <|
        \response ->
            case response of
                Http.BadUrl_ url ->
                    Err (Http.BadUrl url)

                Http.Timeout_ ->
                    Err Http.Timeout

                Http.NetworkError_ ->
                    Err Http.NetworkError

                Http.BadStatus_ metadata body ->
                    Err (Http.BadStatus metadata.statusCode)

                Http.GoodStatus_ metadata body ->
                    metadata.headers
                        |> Dict.get "Authorization"
                        |> Result.fromMaybe (Http.BadStatus 403)

postCall : Model -> Cmd Msg
postCall model = Http.post {
          url = "http://localhost:9000/register",
          body = Http.jsonBody (
            Json.Encode.object[
              ("age", Json.Encode.int 30),
              ("email", Json.Encode.string model.form.email),
              ("password", Json.Encode.string model.form.password)
            ]
          ),
          expect =  expectJWT RegistrationSuccess
        }


来源: stackexchange

问:
Swift TabbarViewController action based on alert selection. shouldSelect and didSelect are not helping
I want to change the tab in tabbar based on an alert selection (Alert - Are you sure you want to leave this page. CASE - Yes - change the view as per tabbar selected.CASE - No - Don't do anything. Stay on same page(tabbar index).

I tried using tabbarcontrollerdelegate method didselect and shouldselect, but not able to have it working.

 func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

var decision : Bool?
let alert = UIAlertController(title: "You are in middle of a Quiz", message: "Do you want to end the Quiz in between !",         preferredStyle: UIAlertController.Style.alert)

alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: { _ in
            // do nothing.
            decision = false
        }))
        alert.addAction(UIAlertAction(title: "Yes",
                                      style: UIAlertAction.Style.default,
                                      handler: {(_: UIAlertAction!) in
                                        decision = true
            // go to clicked tabbar view
        }))
        self.present(alert, animated: true, completion: nil)

    return decision!

    }
```

This code is not working because before getting into alert selection, didselect returns bool (crashes in above case). What could be an alternate to solving this problem ie on tabbar click, the view should change only after user reconfirms that he wants to leave the current page (through an alert action).

答:
In shouldSelect viewController method check whether viewController is your destination view controller. If not return true, if yes present the alert and return false.

If No selected the alert, do nothing. If Yes selected, assign the destination view controller as selectedViewController in tabBarController

```<code>func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    if viewController is DestinationViewController {
        let alert = UIAlertController(title: "You are in middle of a Quiz", message: "Do you want to end the Quiz in between !",         preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "No", style: .default))
        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in
            tabBarController.selectedViewController = viewController
        }))
        self.present(alert, animated: true, completion: nil)
        return false
    }
    return true
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to change the tab in tabbar based on an alert selection (Alert - Are you sure you want to leave this page. CASE - Yes - change the view as per tabbar selected.CASE - No - Don't do anything. Stay on same page(tabbar index).

I tried using tabbarcontrollerdelegate method didselect and shouldselect, but not able to have it working.

 func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

var decision : Bool?
let alert = UIAlertController(title: "You are in middle of a Quiz", message: "Do you want to end the Quiz in between !",         preferredStyle: UIAlertController.Style.alert)

alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: { _ in
            // do nothing.
            decision = false
        }))
        alert.addAction(UIAlertAction(title: "Yes",
                                      style: UIAlertAction.Style.default,
                                      handler: {(_: UIAlertAction!) in
                                        decision = true
            // go to clicked tabbar view
        }))
        self.present(alert, animated: true, completion: nil)

    return decision!

    }

This code is not working because before getting into alert selection, didselect returns bool (crashes in above case). What could be an alternate to solving this problem ie on tabbar click, the view should change only after user reconfirms that he wants to leave the current page (through an alert action).

Body:
In shouldSelect viewController method check whether viewController is your destination view controller. If not return true, if yes present the alert and return false.

If No selected the alert, do nothing. If Yes selected, assign the destination view controller as selectedViewController in tabBarController

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    if viewController is DestinationViewController {
        let alert = UIAlertController(title: "You are in middle of a Quiz", message: "Do you want to end the Quiz in between !",         preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "No", style: .default))
        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in
            tabBarController.selectedViewController = viewController
        }))
        self.present(alert, animated: true, completion: nil)
        return false
    }
    return true
}


问:
Leaked Window but want to finish activity when user click on positive button
I already read this: Activity has leaked window that was originally added
and some other post also.

This is the exception line: E/WindowManager:private android.view.WindowLeaked:void ActivitysaveMessage() com.tekitsolutions.remindme.Activity.AddReminderActivity{
 has leaked window DecorView@87ebe2a[AddReminderActivity] that was originally addedString heremessage = "";
        atif android.view.ViewRootImpl.(ViewRootImpl.java:534!isEditReminder)
    {

Exception:

```<code>E/WindowManager:private android.view.WindowLeaked:void ActivitysaveMessage() com.tekitsolutions.remindme.Activity.AddReminderActivity{
 has leaked window DecorView@87ebe2a[AddReminderActivity] that was originally addedString heremessage = "";
        atif android.view.ViewRootImpl.<init>(ViewRootImpl.java:534!isEditReminder)
    {
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:346)
       message at= android.view.WindowManagerImplgetResources().addViewgetString(WindowManagerImplR.java:94string.reminder_added_successfully);
        at android.app.Dialog.show(Dialog.java:329)
} else {
      at android.app.AlertDialog$Builder.show(AlertDialog.java:1125)
       message at= com.tekitsolutions.remindme.Activity.AddReminderActivitygetResources().saveMessagegetString(AddReminderActivityR.java:1179string.reminder_update_successfully);
        at com.tekitsolutions.remindme.Activity.AddReminderActivity.onResponse(AddReminderActivity.java:1547)
   reminderId = tempReminderId;
   at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:71)
        atnew android.os.Handler.handleCallbackAlarmReceiver(Handler).java:873cancelAlarm(this, reminderId);
        at android.os.Handler.dispatchMessage(Handler.java:99)}

        at androidandroidx.osappcompat.Looperapp.loop(LooperAlertDialog.java:201)
     Builder alertDialogBuilder = atnew androidandroidx.appcompat.app.Activit
</code>```

My code:

```<code>private void saveMessage() {
        String message = "";
        if (!isEditReminder) {
            message = getResources().getString(R.string.reminder_added_successfully);
        } else {
            message = getResources().getString(R.string.reminder_update_successfully);
            reminderId = tempReminderId;
            new AlarmReceiver().cancelAlarm(this, reminderId);
        }

        androidx.appcompat.app.AlertDialog.Builder alertDialogBuilder = new androidx.appcompat.app.AlertDialog.Builder(this, R.style.dialogBoxStyle);
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setTitle("").setMessage(message).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = getIntent();
                showLog("ARA: "+ reminderId);
                intent.putExtra(REMINDER_ID, reminderId);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        androidx.appcompat.app.AlertDialog dialog = alertDialogBuilder.create();
        dialog.show();

    }
</code>```

答:
Because you are trying open a dialog after you exit an activity. In this case, the activity is being closed before the opening of the dialog</p>

```<code>// remove below line
 super.onBackPressed();
from your onBackPressed() method
</code>```

Body:
I already read this: Activity has leaked window that was originally added
and some other post also.

This is the exception line: E/WindowManager:private android.view.WindowLeaked:void ActivitysaveMessage() com.tekitsolutions.remindme.Activity.AddReminderActivity{
 has leaked window DecorView@87ebe2a[AddReminderActivity] that was originally addedString heremessage = "";
        atif android.view.ViewRootImpl.(ViewRootImpl.java:534!isEditReminder)
    {

Exception:

E/WindowManager:private android.view.WindowLeaked:void ActivitysaveMessage() com.tekitsolutions.remindme.Activity.AddReminderActivity{
 has leaked window DecorView@87ebe2a[AddReminderActivity] that was originally addedString heremessage = "";
        atif android.view.ViewRootImpl.<init>(ViewRootImpl.java:534!isEditReminder)
    {
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:346)
       message at= android.view.WindowManagerImplgetResources().addViewgetString(WindowManagerImplR.java:94string.reminder_added_successfully);
        at android.app.Dialog.show(Dialog.java:329)
} else {
      at android.app.AlertDialog$Builder.show(AlertDialog.java:1125)
       message at= com.tekitsolutions.remindme.Activity.AddReminderActivitygetResources().saveMessagegetString(AddReminderActivityR.java:1179string.reminder_update_successfully);
        at com.tekitsolutions.remindme.Activity.AddReminderActivity.onResponse(AddReminderActivity.java:1547)
   reminderId = tempReminderId;
   at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:71)
        atnew android.os.Handler.handleCallbackAlarmReceiver(Handler).java:873cancelAlarm(this, reminderId);
        at android.os.Handler.dispatchMessage(Handler.java:99)}

        at androidandroidx.osappcompat.Looperapp.loop(LooperAlertDialog.java:201)
     Builder alertDialogBuilder = atnew androidandroidx.appcompat.app.Activit

My code:

private void saveMessage() {
        String message = "";
        if (!isEditReminder) {
            message = getResources().getString(R.string.reminder_added_successfully);
        } else {
            message = getResources().getString(R.string.reminder_update_successfully);
            reminderId = tempReminderId;
            new AlarmReceiver().cancelAlarm(this, reminderId);
        }

        androidx.appcompat.app.AlertDialog.Builder alertDialogBuilder = new androidx.appcompat.app.AlertDialog.Builder(this, R.style.dialogBoxStyle);
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setTitle("").setMessage(message).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = getIntent();
                showLog("ARA: "+ reminderId);
                intent.putExtra(REMINDER_ID, reminderId);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        androidx.appcompat.app.AlertDialog dialog = alertDialogBuilder.create();
        dialog.show();

    }

Body:
Because you are trying open a dialog after you exit an activity. In this case, the activity is being closed before the opening of the dialog

// remove below line
 super.onBackPressed();
from your onBackPressed() method


问:
Angular form validation , access form control while iterating over it on HTML
I have a list of questions with answer options as radio button field. I'm getting these questions and answers from JSON file.so am iterating over it on HTML and assigning values to formControlName dynamically. My problem is how to validate while iterating over control values?

```<code>*ngIf="cricketForm.control.get('ques{{i}}').invalid"

*ngIf="cricketForm.control.get('ques{{i}}').invalid"
</code>```

this gives me an error. How to do it in the correct way?

https://stackblitz.com/edit/angular-yq4lyz-zt9b3h?file=app/form-field-overview-example.html
Right now validation is not working correctly

html file:

```<code><form [formGroup]="cricketForm">
  <div *ngFor = "let user of userJson; let i =index ">
    <div class="label1" for="NameId">{{user.question}}</div>
    <mat-radio-group formControlName="ques{{i+1}}" aria-label="Select an option">
      <div *ngFor = "let option of user.options; let j =index">
        <mat-radio-button  [value]=j>{{option}}</mat-radio-button>
      </div>
    </mat-radio-group>

  <div class="invalid-feedback" *ngIf="cricketForm.control.get('ques{{i}}').invalid" >This field is required</div>
  </div>
    <button (click)="onSubmit()">Submit</button>
    <button (click)="onReset()">Reset</button>
</form>
</code>```

ts file:

```<code>ngOnInit() {
    this.cricketForm = this.formBuilder.group({
      ques1: [null, [Validators.required]],
      ques2: [null, [Validators.required]],
      ques3: [null, [Validators.required]],
      ques4: [null, [Validators.required]]
    })
    this.userDataService.getJSON().subscribe(data => {
      console.log(data);
      this.userJson = data;
      this.options = data.options
    });
}
</code>```

Sample JSON Data:

```<code>[
{"question": "Who Was The First Indian To Hit A Test Century?", "options":["Lala Amarnath","Kapil Dev", "Sunil Gavaskar"],"ans":"Lala Amarnath"},
{"question":"Who Won The Inaugural Asia Cup Championship?","options":["Pakistan","Sri Lanka", "India"],"ans":"India"},
{"question":"Who Was Australia’s First Captain?","options":["F.S.Jackson"
,"D.W. Gregory", "Tony Lewis"],"ans":"D.W. Gregory"},
{"question":" When And Where Was The First Ranji Trophy Match Played?","options":["kolkata"
,"Mumbai", "Chennai"],"ans":"Chennai"}
]
</code>```

答:
You has a syntax error. Must be

```<code>*ngIf="cricketForm.get('ques'+(i+1)).invalid"
</code>```

See your forked stackblitz

NOTE: I think you must try rethinking your code using FormArrays. The way is so simple as

```<code><form formGroup="formArray">
  <div *ngFor = "let control of formArray.controls; let i =index ">
    <div class="label1" for="NameId">{{userJson[i].question}}</div>
    <mat-radio-group [formControl]="control" aria-label="Select an option">
      <div *ngFor = "let option of userJson[i].options; let j =index">
        <mat-radio-button  [value]=j>{{option}}</mat-radio-button>
      </div>
    </mat-radio-group>
  <div class="invalid-feedback" *ngIf="control.invalid" >This field is required</div>
  </div>
    <button (click)="onSubmit()">Submit</button>
    <button (click)="onReset()">Reset</button>

</form>
</code>```

See that, we iterate over formArray.controls and use i=index. To show the labels use userJson[i]

where:

```<code>this.formArray=new FormArray(
    this.userJson.map(
      ()=>new FormControl(null,Validators.required))
);
</code>```

Body:
I have a list of questions with answer options as radio button field. I'm getting these questions and answers from JSON file.so am iterating over it on HTML and assigning values to formControlName dynamically. My problem is how to validate while iterating over control values?

*ngIf="cricketForm.control.get('ques{{i}}').invalid"

*ngIf="cricketForm.control.get('ques{{i}}').invalid"

this gives me an error. How to do it in the correct way?

https://stackblitz.com/edit/angular-yq4lyz-zt9b3h?file=app/form-field-overview-example.html
Right now validation is not working correctly

html file:

<form [formGroup]="cricketForm">

{{user.question}}

    <mat-radio-group formControlName="ques{{i+1}}" aria-label="Select an option">

        <mat-radio-button  [value]=j>{{option}}</mat-radio-button>

    </mat-radio-group>

This field is required

    <button (click)="onSubmit()">Submit</button>
    <button (click)="onReset()">Reset</button>
</form>

ts file:

ngOnInit() {
    this.cricketForm = this.formBuilder.group({
      ques1: [null, [Validators.required]],
      ques2: [null, [Validators.required]],
      ques3: [null, [Validators.required]],
      ques4: [null, [Validators.required]]
    })
    this.userDataService.getJSON().subscribe(data => {
      console.log(data);
      this.userJson = data;
      this.options = data.options
    });
}

Sample JSON Data:

[
{"question": "Who Was The First Indian To Hit A Test Century?", "options":["Lala Amarnath","Kapil Dev", "Sunil Gavaskar"],"ans":"Lala Amarnath"},
{"question":"Who Won The Inaugural Asia Cup Championship?","options":["Pakistan","Sri Lanka", "India"],"ans":"India"},
{"question":"Who Was Australia’s First Captain?","options":["F.S.Jackson"
,"D.W. Gregory", "Tony Lewis"],"ans":"D.W. Gregory"},
{"question":" When And Where Was The First Ranji Trophy Match Played?","options":["kolkata"
,"Mumbai", "Chennai"],"ans":"Chennai"}
]

Body:
You has a syntax error. Must be

*ngIf="cricketForm.get('ques'+(i+1)).invalid"

See your forked stackblitz

NOTE: I think you must try rethinking your code using FormArrays. The way is so simple as

<form formGroup="formArray">
  <div *ngFor = "let control of formArray.controls; let i =index ">
    <div class="label1" for="NameId">{{userJson[i].question}}</div>
    <mat-radio-group [formControl]="control" aria-label="Select an option">
      <div *ngFor = "let option of userJson[i].options; let j =index">
        <mat-radio-button  [value]=j>{{option}}</mat-radio-button>
      </div>
    </mat-radio-group>
  <div class="invalid-feedback" *ngIf="control.invalid" >This field is required</div>
  </div>
    <button (click)="onSubmit()">Submit</button>
    <button (click)="onReset()">Reset</button>

</form>

See that, we iterate over formArray.controls and use i=index. To show the labels use userJson[i]

where:

this.formArray=new FormArray(
    this.userJson.map(
      ()=>new FormControl(null,Validators.required))
);


问:
How can I extract a subtree from my SVN repository into a new one?
We have a Subversion repository with one directory that is:

Not really in need of revision control beyond the capabilities of RCS

Not versioned in conjunction with anything else in the repository

Modified about six times as often as the rest of the repository

Although I know that high revision numbers aren't a problem, nonetheless I'd like to pull this one single directory out of my main repository and into a second, ideally new one.

What is the best process for that? If it makes a difference, the SVN repository is hosted on a (... checks... ) FreeBSD machine.

It's worth noting that while I need to retain the version history in the new repository, there's no need to obliterate the content in the old; it can just sit there, for all I care.

答:
You could use svnadmin dump and svnadmin load to create a new repository from the original one; then copy the directory that doesn't really fit into your scheme to a better location, then delete everything else. In the original repository you would simply delete the non-fitting directory. This keeps all history intact, and you end up with two repositories.

There is probably a way to subsequently clean both repositories from the then useless parts of the history (svndumpfilter), but since hard disc space is quite cheap I wouldn't think this necessary. Anyway, the SVN documentation has all the information about it.

OwnerDisplayName: Chris R

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Chris R

OwnerDisplayName: mghie

ContentLicense: CC BY-SA 2.5


问:
JPA How to get a property from a Arraylist of objects in a ManyToMany relation
Im struggling on how to get a attribute from a arraylist filled with objects. I want to find all the Dishes that belong to a certain Meal and filter those by the dishType and display them in a table in the view.

So I have written the method getDishNameByType but it will return null. Any help would be greatly appreciated!

Meal.Java

```<code>public class Meal {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToMany
    private Set<Dish> dishesList = new HashSet<>();

    public String getDishNameByType(String dishType) {
        for (Dish dish : dishesList) {
            if (dishType == dish.getDishType()) {
                return dish.getDishName();
            }
        }
        return null;
    }
}
</code>```

Dish.Java

```<code>public class Dish {

    @Id
    @GeneratedValue
    private Long id;

    private String dishName;

    private String dishType;

    @ManyToMany(mappedBy = "dishesList")
    private Set<Meal> mealsList = new HashSet<>();
</code>```

View.html

```<code><tr th:if="${mealPage.empty}">
    <td colspan="7" th:text="#{meals.list.table.empty}">No meals found</td>
</tr>
<tr th:each="meal : ${mealPage}">
    <td th:text="${meal.id}">1</td>
    <td th:each="dish : ${meal.dishesList}"
    th:text="${meal.getDishNameByType("Maincourse")}"></td>

</tr>
</code>```

答:
If you have two objects, obj1 and obj2, then obj1 == obj2 will be true if and only if the two objects are the very same.

```<code>String foo = "abc";
String bar = "abc";

boolean same = (foo == bar); //false
boolean similar = (foo.equals(bar)); //true
</code>```

So you will need to call equals:

```<code>public String getDishNameByType(String dishType) {
    for (Dish dish : dishesList) {
        if ((dishType.equals(dish.getDishType()))) {
            return dish.getDishName();
        }
    }
    return null;
}
</code>```

Body:
Im struggling on how to get a attribute from a arraylist filled with objects. I want to find all the Dishes that belong to a certain Meal and filter those by the dishType and display them in a table in the view.

So I have written the method getDishNameByType but it will return null. Any help would be greatly appreciated!

Meal.Java

public class Meal {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToMany
    private Set<Dish> dishesList = new HashSet<>();

    public String getDishNameByType(String dishType) {
        for (Dish dish : dishesList) {
            if (dishType == dish.getDishType()) {
                return dish.getDishName();
            }
        }
        return null;
    }
}

Dish.Java

public class Dish {

    @Id
    @GeneratedValue
    private Long id;

    private String dishName;

    private String dishType;

    @ManyToMany(mappedBy = "dishesList")
    private Set<Meal> mealsList = new HashSet<>();

View.html

    No meals found

    1

Body:
If you have two objects, obj1 and obj2, then obj1 == obj2 will be true if and only if the two objects are the very same.

String foo = "abc";
String bar = "abc";

boolean same = (foo == bar); //false
boolean similar = (foo.equals(bar)); //true

So you will need to call equals:

public String getDishNameByType(String dishType) {
    for (Dish dish : dishesList) {
        if ((dishType.equals(dish.getDishType()))) {
            return dish.getDishName();
        }
    }
    return null;
}


问:
" Kubernetes is starting ....." forever error on windows 10
I had a kubernetes single node cluster on my windows 10 machine. Due some errors I had to reinstall the Docker Desktop and since then kubernetes installation has failed while docker installed successfully. All attempts to resolve e.g. deleting the config file in .kube directory and complete reinstallation have failed. See attached pix for details. Installed docker version is Docker version 18.09.2, build 6247962. All search online efforts  do not yield a possible solution. I would appreciate pointers to a solution or walk-around.

答:
I would suggest you to check running Kubernetes components using command: docker ps -a --filter name=k8s as recommended by Nepomucen here.

Then, check the logs for each component using command:docker logs {container id from the previous command}.  You might some idea from the logs.

In my case, it was- x509: certificate is valid for docker-for-desktop, kubernetes, kubernetes.default, kubernetes.default.svc, kubernetes.default.svc.cluster.local, host.docker.internal, not vm.docker.internal

So, I tried the solution suggested in this link and it worked for me


问:
Can a finalizer be called on an object that is in the middle of a (native) call?
We're seeing a weird AddressSanitizer (clang/C++) "heap-use-after-free" violation that might relate to a finalizer corner case.

Let's say, a Java object OBJ has a handle to to a native resource X. A thread that created OBJ before, is now making a call on OBJ.method(), which calls into a (static) native method staticMethod(X), in which X is used.

Now, at more or less the same time, we're seeing a thread deleting the native resource X. We strongly assume that this triggered by the finalizer calling OBJ.finalize(), which does "delete X".

Is this a valid thing to do for a finalizer?

(OpenJDK 8)

答:
A safe way to do this seems to be using non-static native JNI methods.

In C/C++, a static JNI method signature looks something like this:

```<code>extern "C" JNIEXPORT jobject JNICALL
Java_com_example_MyClass_myMethod(JNIEnv* env, jclass type, jlong handle);
</code>```

Note the second parameter jclass type passing the JNI representation of a Java class.

A non-static JNI method, however, accepts the current Java instance object (this) instead and looks like this:

```<code>extern "C" JNIEXPORT jobject JNICALL
Java_com_example_MyClass_myMethod(JNIEnv* env, jobject thisObj, jlong handle);
</code>```

Background: The VM seems to optimize garbage collection quite aggressively. A thread still running a (non-static) method but calling only into a native static method does NOT prevent the object from being freed. If the JNI method is non-static however, this tells the VM that the Java object is still being referenced. Then, only once the the call returns this native reference to the object is cleared. Thus, no finalizer is allowed to run before that.

Body:
A safe way to do this seems to be using non-static native JNI methods.

In C/C++, a static JNI method signature looks something like this:

extern "C" JNIEXPORT jobject JNICALL
Java_com_example_MyClass_myMethod(JNIEnv* env, jclass type, jlong handle);

Note the second parameter jclass type passing the JNI representation of a Java class.

A non-static JNI method, however, accepts the current Java instance object (this) instead and looks like this:

extern "C" JNIEXPORT jobject JNICALL
Java_com_example_MyClass_myMethod(JNIEnv* env, jobject thisObj, jlong handle);

Background: The VM seems to optimize garbage collection quite aggressively. A thread still running a (non-static) method but calling only into a native static method does NOT prevent the object from being freed. If the JNI method is non-static however, this tells the VM that the Java object is still being referenced. Then, only once the the call returns this native reference to the object is cleared. Thus, no finalizer is allowed to run before that.


问:
Error: You have an error in your SQL syntax in select statement
I'm trying to get info only if o.status_id is equal to either 4 or 5, but I'm getting this error

```<code>Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the
right syntax to use near 'INNER JOIN order_items oi ON i.id = oi.item_id INNER JOIN orders o ON o.id =' at line 14
</code>```

this is my sql statement

```<code>$sql = '
SELECT
    i.*,
    o.*,
    oi.*,
    u.*,
    YEAR(o.sold_date) sold_date_Y4,
    MONTH(o.sold_date) sold_date_M4

FROM items i

WHERE o.status_id = 4 AND o.status_id = 5

INNER JOIN order_items oi ON i.id = oi.item_id
INNER JOIN orders o ON o.id = oi.order_id
INNER JOIN users u ON u.id = o.user_id
GROUP BY YEAR(o.sold_date), MONTH(o.sold_date), u.name, i.item
ORDER BY YEAR(o.sold_date), MONTH(o.sold_date), u.name, i.item

';
</code>```

From what I can see my MySQL version is 5.7.23

答:
The problem is that you have used WHERE before all your INNER JOIN

```<code>$sql = '
SELECT
    i.*,
    o.*,
    oi.*,
    u.*,
    YEAR(o.sold_date) sold_date_Y4,
    MONTH(o.sold_date) sold_date_M4

FROM items i

INNER JOIN order_items oi ON i.id = oi.item_id
INNER JOIN orders o ON o.id = oi.order_id
INNER JOIN users u ON u.id = o.user_id

WHERE o.status_id = 4 AND o.status_id = 5

GROUP BY YEAR(o.sold_date), MONTH(o.sold_date), u.name, i.item
ORDER BY YEAR(o.sold_date), MONTH(o.sold_date), u.name, i.item

';
</code>```

Body:
I'm trying to get info only if o.status_id is equal to either 4 or 5, but I'm getting this error

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the
right syntax to use near 'INNER JOIN order_items oi ON i.id = oi.item_id INNER JOIN orders o ON o.id =' at line 14

this is my sql statement

$sql = '
SELECT
    i.*,
    o.*,
    oi.*,
    u.*,
    YEAR(o.sold_date) sold_date_Y4,
    MONTH(o.sold_date) sold_date_M4

FROM items i

WHERE o.status_id = 4 AND o.status_id = 5

INNER JOIN order_items oi ON i.id = oi.item_id
INNER JOIN orders o ON o.id = oi.order_id
INNER JOIN users u ON u.id = o.user_id
GROUP BY YEAR(o.sold_date), MONTH(o.sold_date), u.name, i.item
ORDER BY YEAR(o.sold_date), MONTH(o.sold_date), u.name, i.item

';

From what I can see my MySQL version is 5.7.23

Body:
The problem is that you have used WHERE before all your INNER JOIN

$sql = '
SELECT
    i.*,
    o.*,
    oi.*,
    u.*,
    YEAR(o.sold_date) sold_date_Y4,
    MONTH(o.sold_date) sold_date_M4

FROM items i

INNER JOIN order_items oi ON i.id = oi.item_id
INNER JOIN orders o ON o.id = oi.order_id
INNER JOIN users u ON u.id = o.user_id

WHERE o.status_id = 4 AND o.status_id = 5

GROUP BY YEAR(o.sold_date), MONTH(o.sold_date), u.name, i.item
ORDER BY YEAR(o.sold_date), MONTH(o.sold_date), u.name, i.item

';


问:
Redefining ws in a grammar
According to the documentation, you can redefine the ws token in a grammar, this token is called automatically in some cases, such as this:

```<code>grammar Numbers { rule TOP { \d \d } };
my $result = Numbers.parse("3 \n 3");
say $result.perl
# OUTPUT: «Match.new(pos => 5, made => Any, from => 0, hash => Map.new(()), orig => "3 \n 3", list => ())␤»
</code>```

One of the advantages of redefining ws might be that it will not be thrown away. OK, I'll buy that and use for ws the exact same definition that is used internally:

```<code>grammar Numbers { rule TOP { \d \d }; regex ws { <!ww> \s* } };
my $result = Numbers.parse("3 \n 3");
say $result<ws> # OUTPUT: «Nil␤»
</code>```

Matching works, but $result is still dropped (redefining this to another token that does not use the default ws will work). So is ws dropped always?

Update This is probably related to this Rakudo bug

答:
Whitespace not being captured is nothing to do with the definition of ws, but rather to do with the way sigspace ("significant whitespace") works.

Sigspace, enabled by the :s modifier and on by default in a rule, inserts <.ws> according to its rules (which can be summarized as "after an atom"). This is a non-capturing call to the ws rule. Redefining ws has no impact on this, since it's a property of the rule calling ws, not of ws itself.

Indeed, if we write an explicit call to the default <ws>:

```<code>say "1 2" ~~ /\d <ws> \d/
</code>```

The it will capture, the output of the above program being:

```<code>｢1 2｣
 ws => ｢ ｣
</code>```

Title: Redefining ws in a grammar

Body:
According to the documentation, you can redefine the ws token in a grammar, this token is called automatically in some cases, such as this:

grammar Numbers { rule TOP { \d \d } };
my $result = Numbers.parse("3 \n 3");
say $result.perl
# OUTPUT: «Match.new(pos => 5, made => Any, from => 0, hash => Map.new(()), orig => "3 \n 3", list => ())␤»

One of the advantages of redefining ws might be that it will not be thrown away. OK, I'll buy that and use for ws the exact same definition that is used internally:

grammar Numbers { rule TOP { \d \d }; regex ws { <!ww> \s* } };
my $result = Numbers.parse("3 \n 3");
say $result<ws> # OUTPUT: «Nil␤»

Matching works, but $result is still dropped (redefining this to another token that does not use the default ws will work). So is ws dropped always?

Update This is probably related to this Rakudo bug

Body:
Whitespace not being captured is nothing to do with the definition of ws, but rather to do with the way sigspace ("significant whitespace") works.

Sigspace, enabled by the :s modifier and on by default in a rule, inserts <.ws> according to its rules (which can be summarized as "after an atom"). This is a non-capturing call to the ws rule. Redefining ws has no impact on this, since it's a property of the rule calling ws, not of ws itself.

Indeed, if we write an explicit call to the default <ws>:

say "1 2" ~~ /\d <ws> \d/

The it will capture, the output of the above program being:

｢1 2｣
 ws => ｢ ｣


问:
Whisper in Twilio -- Studio, TWIML and Functions
What I am trying to achieve is that I want to use the Whisper function in Twilio Studio.

Referencing this prior post Want to use Whisper in Twilio Studio the answer is that you cannot and it is advised to use TWIML to do this. This solution when used just using TWIML works fine. My question following on from this is that can you call TWIML from within Studio? It seems to me that you cannot but would be interested if someone can please clarify if this is the case.

Now, you can call functions from within Studio. So the next possible solution is that we write a function to use the whisper

Below is a template for call forwarding which works nicely to forward a number to using a function.

/**
 *  Call Forward Template
 *
 *  This Function will forward a call to another phone number. If the call isn't answered or the line is busy,
 *  the call is optionally forwarded to a specified URL. You can optionally restrict which calling phones
 *  will be forwarded.
 */

exports.handler = function(context, event, callback) {
  // set-up the variables that this Function will use to forward a phone call using TwiML

  // REQUIRED - you must set this
  let phoneNumber = event.PhoneNumber || "NUMBER TO FORWARD TO";
  // OPTIONAL
  let callerId =  event.CallerId || null;
  // OPTIONAL
  let timeout = event.Timeout || null;
  // OPTIONAL
  let allowedCallers = event.allowedCallers || [];

  // generate the TwiML to tell Twilio how to forward this call
  let twiml = new Twilio.twiml.VoiceResponse();

  let allowedThrough = true
  if (allowedCallers.length > 0) {
    if (allowedCallers.indexOf(event.From) === -1) {
      allowedThrough = false;
    }
  }

  let dialParams = {};
  if (callerId) {
    dialParams.callerId = callerId
  }
  if (timeout) {
    dialParams.timeout = timeout
  }

  if (allowedThrough) {
    twiml.dial(dialParams, phoneNumber);
  }
  else {
    twiml.say('Sorry, you are calling from a restricted number. Good bye.');
  }

  // return the TwiML
  callback(null, twiml);
};```
</div>
</div>
</p>

<p>The important parts of this are</p>

```// REQUIRED - you must set this
let phoneNumber = event.PhoneNumber || "NUMBER TO FORWARD TO";
```

<p>Which is easy as you just enter the number you wish to forward to.</p>

<p>And this which is the important bit in my opinion</p>

```if (allowedThrough) {
twiml.dial(dialParams, phoneNumber);
```

<p>So the question is, can we insert the whisper URL from the TWIML whisper in there. Something similar to the following.  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> twiml.dial({ url: 'https://handler.twilio.com/twiml/EH0b18ce0682059675bc39deca4e76e472' }, phoneNumber);</code>```

This doesn't work when I call this function from within Studio and I get the following error.

```<code>Msg "XML Validation warning"
line    "1"
parserMessage   " Attribute 'url' is not allowed to appear in element
'Dial'."
ErrorCode   "12200"
cols    "224"
LogLevel    "WARN"
url "https://olivine-okapi-1701.twil.io/fwd_whisper"
</code>```

This seems like hopefully just a syntax error. Not being a developer any help on this as to what is the correct syntax or whether or not this can even be done

答:
You can use this article for reference, Recording a Phone Call with Twilio - . You will follow the example provided under, Record a Two-way Call using the  TwiML Verb. So you would add the record attribute to the dialParams object:

dialParams.record = "record-from-ringing".

Body:
What I am trying to achieve is that I want to use the Whisper function in Twilio Studio.

Referencing this prior post Want to use Whisper in Twilio Studio the answer is that you cannot and it is advised to use TWIML to do this. This solution when used just using TWIML works fine. My question following on from this is that can you call TWIML from within Studio? It seems to me that you cannot but would be interested if someone can please clarify if this is the case.

Now, you can call functions from within Studio. So the next possible solution is that we write a function to use the whisper

Below is a template for call forwarding which works nicely to forward a number to using a function.

/**
 *  Call Forward Template
 *
 *  This Function will forward a call to another phone number. If the call isn't answered or the line is busy,
 *  the call is optionally forwarded to a specified URL. You can optionally restrict which calling phones
 *  will be forwarded.
 */

exports.handler = function(context, event, callback) {
  // set-up the variables that this Function will use to forward a phone call using TwiML

  // REQUIRED - you must set this
  let phoneNumber = event.PhoneNumber || "NUMBER TO FORWARD TO";
  // OPTIONAL
  let callerId =  event.CallerId || null;
  // OPTIONAL
  let timeout = event.Timeout || null;
  // OPTIONAL
  let allowedCallers = event.allowedCallers || [];

  // generate the TwiML to tell Twilio how to forward this call
  let twiml = new Twilio.twiml.VoiceResponse();

  let allowedThrough = true
  if (allowedCallers.length > 0) {
    if (allowedCallers.indexOf(event.From) === -1) {
      allowedThrough = false;
    }
  }

  let dialParams = {};
  if (callerId) {
    dialParams.callerId = callerId
  }
  if (timeout) {
    dialParams.timeout = timeout
  }

  if (allowedThrough) {
    twiml.dial(dialParams, phoneNumber);
  }
  else {
    twiml.say('Sorry, you are calling from a restricted number. Good bye.');
  }

  // return the TwiML
  callback(null, twiml);
};

The important parts of this are

// REQUIRED - you must set this
let phoneNumber = event.PhoneNumber || "NUMBER TO FORWARD TO";

Which is easy as you just enter the number you wish to forward to.

And this which is the important bit in my opinion

if (allowedThrough) {
twiml.dial(dialParams, phoneNumber);

So the question is, can we insert the whisper URL from the TWIML whisper in there. Something similar to the following.

 twiml.dial({ url: 'https://handler.twilio.com/twiml/EH0b18ce0682059675bc39deca4e76e472' }, phoneNumber);

This doesn't work when I call this function from within Studio and I get the following error.

Msg "XML Validation warning"
line    "1"
parserMessage   " Attribute 'url' is not allowed to appear in element
'Dial'."
ErrorCode   "12200"
cols    "224"
LogLevel    "WARN"
url "https://olivine-okapi-1701.twil.io/fwd_whisper"

This seems like hopefully just a syntax error. Not being a developer any help on this as to what is the correct syntax or whether or not this can even be done


问:
How to add module during build - Angular
I know how to write modules in angular. But how to actually add or remove a module during ng build, based on the supplied command line params, instead of adding it in the module dependencies directly? Kind of like multiple implementations for same interface and to decide the actual implementation during build. (similar to multi modules in java) Any suggestions or advices?</p>

答:
This question does not deserve down votes, as it is valid and applicable to Angular and angular cli provides a built-in method to do this. The feature is called file-replacements.

It's documented and explained extensively here. https://angular.io/guide/build


问:
Threadabortexception when calling showdialog in C#
I have an application that parses a large XML file and builds WPF UI controls based on that content. This task usually takes about 15 - 30 seconds. In order to inform the user about a running task, I display a simple intermediate progress dialog window, like:

Thread progressDialogThread = new Thread(() =>
{
    Window window = new Window
    {
        Content = new ProgressDialog(),
        Height = 100,
        Width = 150,
        WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen
    };
    window.ShowDialog();
});

progressDialogThread.SetApartmentState(ApartmentState.STA);
progressDialogThread.IsBackground = true;
progressDialogThread.Start();

buildUI();

progressDialogThread.Abort();
```

<p>This works, but I sometimes get a ThreadAbortException on <code>progressDialogThread.Start()</code>, when the XML should be parsed once again.</p>

<p>Does anyone know a better approach to "close" the progress dialog? </p>

<p>Since the controls have to be built on the main UI thread, I can not use the backgroundworker...</p>

<p>The progress dialog itself in XAML looks like:</p>

<pre class="lang-xml prettyprint-override"><code><UserControl x:Class="MyDialog.ProgressDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyDialog"
        mc:Ignorable="d"
        Background="{DynamicResource MaterialDesignPaper}"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        Height="100" Width="150">
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <Label HorizontalAlignment="Center">Please wait</Label>
        <ProgressBar
          Style="{StaticResource MaterialDesignCircularProgressBar}"
          Value="0"
          IsIndeterminate="True" Width="40" Height="41" Margin="55,0" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </StackPanel>
</UserControl>
</code>```

答:
Do not abort a thread, that should be avoided.

If you want to close a Window, you call Close on it.

Oh, it is created by another thread? Alright, that is why the Window has a Dispatcher, you use BeginInvoke and it will run the callback on that thread.

In fact, there is a chance you do not need to create the Window in another thread※. You can create it in the main thread and have a background thread interact with it via BeginInvoke.

※: If you have the main thread busy and want the Window in another thread so the main thread does not block it (or viceversa), you probably should be using a BackgroundWorker (as Caius Jard suggests) instead of having a UI thread busy.

Body:
I have an application that parses a large XML file and builds WPF UI controls based on that content. This task usually takes about 15 - 30 seconds. In order to inform the user about a running task, I display a simple intermediate progress dialog window, like:

Thread progressDialogThread = new Thread(() =>
{
    Window window = new Window
    {
        Content = new ProgressDialog(),
        Height = 100,
        Width = 150,
        WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen
    };
    window.ShowDialog();
});

progressDialogThread.SetApartmentState(ApartmentState.STA);
progressDialogThread.IsBackground = true;
progressDialogThread.Start();

buildUI();

progressDialogThread.Abort();

This works, but I sometimes get a ThreadAbortException on progressDialogThread.Start(), when the XML should be parsed once again.

Does anyone know a better approach to "close" the progress dialog?

Since the controls have to be built on the main UI thread, I can not use the backgroundworker...

The progress dialog itself in XAML looks like:

<UserControl x:Class="MyDialog.ProgressDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyDialog"
        mc:Ignorable="d"
        Background="{DynamicResource MaterialDesignPaper}"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        Height="100" Width="150">
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        Please wait
        <ProgressBar
          Style="{StaticResource MaterialDesignCircularProgressBar}"
          Value="0"
          IsIndeterminate="True" Width="40" Height="41" Margin="55,0" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </StackPanel>
</UserControl>


问:
how to check if there data range between 2 given dates?
I have start time and end time in my application. I now need to check if there is any time falling between those time in SQL Query.

How do I write the query.

Thanks

答:
I would recommend to not use between when comparing datetime. The result is often not what you want.

BETWEEN returns TRUE if the value of
  test_expression is greater than or
  equal to the value of begin_expression
  and less than or equal to the value of
  end_expression.

Test data for demo

```<code>declare @T table (dt datetime)

insert into @T values('2011-04-12T09:00:00')
insert into @T values('2011-04-12T10:00:00')
insert into @T values('2011-04-12T11:00:00')
insert into @T values('2011-04-12T12:00:00')
</code>```

Query using between

```<code>select *
from @T
where dt between '2011-04-12T10:00:00' and '2011-04-12T11:00:00'
</code>```

Result: 11:00 is included in the result.

```<code>dt
2011-04-12 10:00:00.000
2011-04-12 11:00:00.000
</code>```

Rewrite the query using >= and < instead.

```<code>select *
from @T
where
  dt >= '2011-04-12T10:00:00' and
  dt < '2011-04-12T11:00:00'
</code>```

Result

```<code>dt
2011-04-12 10:00:00.000
</code>```

The title of the question hints at that you want to check for overlapping date intervals. If that is the case you can have a look at this question How can I determine in SQL Server if a dateTime range overlaps another.

Body:
I would recommend to not use between when comparing datetime. The result is often not what you want.

BETWEEN returns TRUE if the value of
  test_expression is greater than or
  equal to the value of begin_expression
  and less than or equal to the value of
  end_expression.

Test data for demo

declare @T table (dt datetime)

insert into @T values('2011-04-12T09:00:00')
insert into @T values('2011-04-12T10:00:00')
insert into @T values('2011-04-12T11:00:00')
insert into @T values('2011-04-12T12:00:00')

Query using between

select *
from @T
where dt between '2011-04-12T10:00:00' and '2011-04-12T11:00:00'

Result: 11:00 is included in the result.

dt
2011-04-12 10:00:00.000
2011-04-12 11:00:00.000

Rewrite the query using >= and < instead.

select *
from @T
where
  dt >= '2011-04-12T10:00:00' and
  dt < '2011-04-12T11:00:00'

Result

dt
2011-04-12 10:00:00.000

The title of the question hints at that you want to check for overlapping date intervals. If that is the case you can have a look at this question How can I determine in SQL Server if a dateTime range overlaps another.


问:
Fatal error: Uncaught Error: Call to a member function bindValue()
I have a problem on SQL query which contains bindValue.
The error: Fatal error: Uncaught Error: Call to a member function bindValue() on bool (240).

But I can't see any problem in the codes. Help pls :/

```<code>$count = $db->query("SELECT * FROM songs WHERE title LIKE :search");
$count->bindValue(":search","%{$search}%",PDO::PARAM_STR); // (line:240)
$count->execute();
</code>```

答:
In order to use the function bindValue() you want to work with a prepared statement. So instead of calling query(), use prepare().

```<code>$count = $db->prepare("SELECT * FROM songs WHERE title LIKE :search");
$count->bindValue(":search","%{$search}%",PDO::PARAM_STR);
$count->execute();
</code>```

Body:
I have a problem on SQL query which contains bindValue.
The error: Fatal error: Uncaught Error: Call to a member function bindValue() on bool (240).

But I can't see any problem in the codes. Help pls :/

$count = $db->query("SELECT * FROM songs WHERE title LIKE :search");
$count->bindValue(":search","%{$search}%",PDO::PARAM_STR); // (line:240)
$count->execute();

Body:
In order to use the function bindValue() you want to work with a prepared statement. So instead of calling query(), use prepare().

$count = $db->prepare("SELECT * FROM songs WHERE title LIKE :search");
$count->bindValue(":search","%{$search}%",PDO::PARAM_STR);
$count->execute();


问:
how to get bottom error message from a nested exception using mockmvc
I am getting a nested exception like below for my Junit tests:

```<code> Caused by: com.exception.Test1RestException: operation failed for test1
at com.testController.tests(Test1Controller.java:123)
</code>```

............................

```<code>  Caused by: com.exception.Test2Exception: operation failed for test2
at com.testController.tests(Test2Controller.java:456)
</code>```

.............................

```<code> Caused by: com.exception.Test3RestException: operation failed for test3
at com.testController.tests(Test2Controller.java:789)
</code>```

I want to verify "operation failed for test3 " using mockmvc,used below

code for that

```<code>org.assertj.core.api.Assertions
        .assertThatThrownBy(() ->
 mockMvc.perform(fileUpload("/test/abc").file((MockMultipartFile) files))
              .andExpect(status().isOk()))
        .hasMessageContaining(operation failed for test3)
</code>```

But I am getting expected error message as "operation failed for
test1",any pointers to reach till bottom message here from my junit

答: it worked by using .hasStackTraceContaining(message) ,method call</p>

Body:
I am getting a nested exception like below for my Junit tests:

 Caused by: com.exception.Test1RestException: operation failed for test1
at com.testController.tests(Test1Controller.java:123)

............................

  Caused by: com.exception.Test2Exception: operation failed for test2
at com.testController.tests(Test2Controller.java:456)

.............................

 Caused by: com.exception.Test3RestException: operation failed for test3
at com.testController.tests(Test2Controller.java:789)

I want to verify "operation failed for test3 " using mockmvc,used below

code for that

org.assertj.core.api.Assertions
        .assertThatThrownBy(() ->
 mockMvc.perform(fileUpload("/test/abc").file((MockMultipartFile) files))
              .andExpect(status().isOk()))
        .hasMessageContaining(operation failed for test3)

But I am getting expected error message as "operation failed for
test1",any pointers to reach till bottom message here from my junit


问:
How to set Zookeeper IP address in ConsumerGroup instead of Kafka-Host IP address?
I have to set zookeeper IP address in ConsumerGroup instead of Kafka-Host IP address. Because I have set replication factor as 3 and 3 brokers were created. So, if one host fails then the another one can take over.

When I tried to put zookeeper IP address instead of Kafka-Host IP address in ConsumerGroup, it doesn't receive any messages which were sent from Producer API.

```<code>var kafka = require('kafka-node')
var ConsumerGroup = kafka.ConsumerGroup

function createConsumerGroup () {
  var options = {
    kafkaHost: '127.0.0.1:9092',
    batch: undefined,
    ssl: true,
    groupId: 'demoExample',
    protocol: ['roundrobin'],
    encoding: 'utf8',
    fromOffset: 'latest',
    commitOffsetsOnFirstJoin: true,
    outOfRangeOffset: 'earliest',
    onRebalance: (isAlreadyMember, callback) => { callback(); }
  }

  var consumerGroup = new ConsumerGroup(Object.assign({ id: 'demo-' + process.pid }, options), 'example')

  consumerGroup.on('message', function (message) {
    message.value = JSON.parse(message.value)
    console.log('Message Received')
  })
}
</code>```

I want that, if I pass zookeeper IP address in ConsumerGroup rather then Kafka-Host IP address, it should receive messages which were sent from Producer API on "example" topic. And if one broker fails then it should receive messages from another broker. As replication factor is set to 3 and 3 brokers were created.

答:
Okay, the problem was with the consumerGroup options object.

We have to pass zookeeper IP address in "host" key in options object instead of "kafkaHost" key. This solves the problem and receives all data sent by Producer API. And even automatically switch over to another replica set if one replica set fails.

```<code>var options = {
    kafkaHost: '127.0.0.1:9092',
    batch: undefined,
    ssl: true,
    groupId: 'demoExample',
    protocol: ['roundrobin'],
    encoding: 'utf8',
    fromOffset: 'latest',
    commitOffsetsOnFirstJoin: true,
    outOfRangeOffset: 'earliest',
    onRebalance: (isAlreadyMember, callback) => { callback(); }
  }
</code>```

The following block of code fix it.

```<code>var options = {
    host: '127.0.0.1:2181', // change in key & value
    batch: undefined,
    ssl: true,
    groupId: 'demoExample',
    protocol: ['roundrobin'],
    encoding: 'utf8',
    fromOffset: 'latest',
    commitOffsetsOnFirstJoin: true,
    outOfRangeOffset: 'earliest',
    onRebalance: (isAlreadyMember, callback) => { callback(); }
  }
</code>```

Thanks.

Body:
I have to set zookeeper IP address in ConsumerGroup instead of Kafka-Host IP address. Because I have set replication factor as 3 and 3 brokers were created. So, if one host fails then the another one can take over.

When I tried to put zookeeper IP address instead of Kafka-Host IP address in ConsumerGroup, it doesn't receive any messages which were sent from Producer API.

var kafka = require('kafka-node')
var ConsumerGroup = kafka.ConsumerGroup

function createConsumerGroup () {
  var options = {
    kafkaHost: '127.0.0.1:9092',
    batch: undefined,
    ssl: true,
    groupId: 'demoExample',
    protocol: ['roundrobin'],
    encoding: 'utf8',
    fromOffset: 'latest',
    commitOffsetsOnFirstJoin: true,
    outOfRangeOffset: 'earliest',
    onRebalance: (isAlreadyMember, callback) => { callback(); }
  }

  var consumerGroup = new ConsumerGroup(Object.assign({ id: 'demo-' + process.pid }, options), 'example')

  consumerGroup.on('message', function (message) {
    message.value = JSON.parse(message.value)
    console.log('Message Received')
  })
}

I want that, if I pass zookeeper IP address in ConsumerGroup rather then Kafka-Host IP address, it should receive messages which were sent from Producer API on "example" topic. And if one broker fails then it should receive messages from another broker. As replication factor is set to 3 and 3 brokers were created.

Body:
Okay, the problem was with the consumerGroup options object.

We have to pass zookeeper IP address in "host" key in options object instead of "kafkaHost" key. This solves the problem and receives all data sent by Producer API. And even automatically switch over to another replica set if one replica set fails.

var options = {
    kafkaHost: '127.0.0.1:9092',
    batch: undefined,
    ssl: true,
    groupId: 'demoExample',
    protocol: ['roundrobin'],
    encoding: 'utf8',
    fromOffset: 'latest',
    commitOffsetsOnFirstJoin: true,
    outOfRangeOffset: 'earliest',
    onRebalance: (isAlreadyMember, callback) => { callback(); }
  }

The following block of code fix it.

var options = {
    host: '127.0.0.1:2181', // change in key & value
    batch: undefined,
    ssl: true,
    groupId: 'demoExample',
    protocol: ['roundrobin'],
    encoding: 'utf8',
    fromOffset: 'latest',
    commitOffsetsOnFirstJoin: true,
    outOfRangeOffset: 'earliest',
    onRebalance: (isAlreadyMember, callback) => { callback(); }
  }

Thanks.


问:
Time measuring overhead in Java
When measuring elapsed time on a low level, I have the choice of using any of these:

```<code>System.currentTimeMillis();
System.nanoTime();
</code>```

Both methods are implemented native. Before digging into any C code, does anyone know if there is any substantial overhead calling one or the other? I mean, if I don't really care about the extra precision, which one would be expected to be less CPU time consuming?

N.B: I'm using the standard Java 1.6 JDK, but the question may be valid for any JRE...

答: At a theoretical level, for a VM that uses native threads, and sits on a modern preemptive operating system, the currentTimeMillis can be implemented to be read only once per timeslice. Presumably, nanoTime implementations would not sacrifice the precision. </p>

Title: Time measuring overhead in Java

Body:
When measuring elapsed time on a low level, I have the choice of using any of these:

System.currentTimeMillis();
System.nanoTime();

Both methods are implemented native. Before digging into any C code, does anyone know if there is any substantial overhead calling one or the other? I mean, if I don't really care about the extra precision, which one would be expected to be less CPU time consuming?

N.B: I'm using the standard Java 1.6 JDK, but the question may be valid for any JRE...


问:
How can I reference an environment variable from Node's .env file?
I have manually defined an environment variable in the shell, and I want to be able to reference this environment variable in a .env file in Node. Node's .env files don't seem to be able to support calling existing environment variables.

Example .env

```<code>testfilepath=$TEST_PATH/testfile
</code>```

Error:

```<code>npm start
Error: File does not exist at path: $TEST_PATH/testfile.
</code>```

How can I reference an existing environment variable in a Node .env file?

答:
dotenv doesn't support such functionality. You could use dotenv-expand on top of it to expand existing variables, though:

```<code>let dotenv = require('dotenv')
let dotenvExpand = require('dotenv-expand')

let myEnv = dotenv.config()
dotenvExpand(myEnv)
</code>```

Body:
I have manually defined an environment variable in the shell, and I want to be able to reference this environment variable in a .env file in Node. Node's .env files don't seem to be able to support calling existing environment variables.

Example .env

testfilepath=$TEST_PATH/testfile

Error:

npm start
Error: File does not exist at path: $TEST_PATH/testfile.

How can I reference an existing environment variable in a Node .env file?

Body:
dotenv doesn't support such functionality. You could use dotenv-expand on top of it to expand existing variables, though:

let dotenv = require('dotenv')
let dotenvExpand = require('dotenv-expand')

let myEnv = dotenv.config()
dotenvExpand(myEnv)


问:
How to correctly add the Runge error estimation rule to this example?
I have an algorithm for parallel computing a certain integral.
This solution gives very good time acceleration if you use multiple threads. And the more threads the faster the calculation.
I tested up to -N4 and the acceleration factor reached 8. Ie, the launch of the program on 4 cores is the calculation of the integral 8 times faster than the launch of this program on 1 core.
But I want to add a rule for estimating the error of Runge.
Since now, in order to increase the accuracy of the calculation of the integral, it is necessary to increase N. Which indicates how many parts we need to break our original segment.
How can i do this?

```<code>import Data.Time
import System.Environment
import Data.Massiv.Array as A

main = do
    begT <- getCurrentTime
    putStrLn $ show $ integrateA 100000 f 0.00005 10000
    endT <- getCurrentTime
    putStrLn $ init $ show $ diffUTCTime endT begT

f :: Double -> Double
f x = sin x * cos x*x*x

integrateA :: Int -> (Double -> Double) -> Double -> Double -> Double
integrateA n f a b =
 let step = (b - a) / fromIntegral n
  sz = size segments - 1
  segments = computeAs P $ A.map f (enumFromStepN Par a step (Sz (n + 1)))
  area y0 y1 = step * (y0 + y1) / 2
  areas = A.zipWith area (extract' 0 sz segments) (extract' 1 sz segments)
 in A.sum areas
</code>```

Examples of launches:

答:
You don't need to change anything in the already supplied integral estimator in order to add precision to it using Runge rule. Something like that, I think:

-- | Returns estimated integral up to a precision, or value estimated at max
-- number of steps
rungeRule ::
     Int -- ^ Maximum number of steps as an upper bound, to prevent unbounded computation
  -> Double -- ^ ε -- precision
  -> Int -- ^ Starting value of @n@
  -> Double -- ^ Θ -- ^ Either 1/3 for trapezoidal and midpoint or 1/15 for Simpson's
  -> (Int -> Double) -- ^ Integral estimator
  -> Either Double (Int, Double)
rungeRule nMax epsilon n0 theta integralEstimator =
  go (integralEstimator n0) (2 * n0)
  where
    go prevEstimate n
      | n >= nMax = Left prevEstimate
      | theta * abs (curEstimate - prevEstimate) < epsilon =
        Right (n, curEstimate)
      | otherwise = go curEstimate (2 * n)
      where
        curEstimate = integralEstimator n

trapezoidal ::
     Double -- ^ ε -- precision
  -> (Double -> Double) -- ^ f(x) - function to integrate
  -> Double -- ^ a - from
  -> Double -- ^ b - to
  -> Either Double (Int, Double)
trapezoidal epsilon f a b =
  rungeRule 100000 epsilon 10 (1 / 3) (\n -> integrateA n f a b)
```

<p>If we run it, we get promising results:</p>

```λ> trapezoidal 0.0005 (\x -> x * x) 10 20
Right (640,2333.333740234375)
λ> trapezoidal 0.00005 (\x -> x * x) 10 20
Right (2560,2333.3333587646484)
λ> trapezoidal 0.00000005 (\x -> x * x) 10 20
Right (81920,2333.3333333581686)
λ> trapezoidal 0.000000005 (\x -> x * x) 10 20
Left 2333.3333333581686
```

<p>Side note:</p>

<ul>
<li><p>Your function <code>f</code> the way you wrote it suggests that:</p>

<ul>
<li><p>you expect: <code>f x = (sin x) * (cos (x*x*x))</code> </p></li>
<li><p>where in reality it is: <code>f x = (sin x) * (cos x) * x * x</code></p></li>
</ul></li>
</ul>

<p><strong>Edit</strong>:</p>

<p>Solution presented above is general enough to work for all integral approximation rules. But there is some duplicate work happens at each iteration of Runge rule, in case of trapezoidal rule half of the elements are being recomputed each time, which I saw as a potential optimization. What comes next is a bit more advance usage of <code>massiv</code>, as such I am not gonna be able to elaborate on how it work, except the fact that the <code>segments</code> array passed around is used to access values computed at a previous step.</p>

<pre class="lang-hs prettyprint-override"><code>trapezoidalMemoized ::
     Int
  -> Array P Ix1 Double
  -> (Double -> Double)
  -> Double
  -> Double
  -> (Double, Array P Ix1 Double)
trapezoidalMemoized n prevSegments f a b =
  let step = (b - a) / fromIntegral n
      sz = size segments - 1
      curSegments =
        fmap f (enumFromStepN Seq (a + step) (2 * step) (Sz (n `div` 2)))
      segments =
        computeAs P $
        makeLoadArrayS (Sz (n + 1)) 0 $ \w -> do
          A.iforM_ prevSegments $ \i e -> w (i * 2) e
          A.iforM_ curSegments $ \i e -> w (i * 2 + 1) e
      area y0 y1 = step * (y0 + y1) / 2
      areas = A.zipWith area segments (extract' 1 sz segments)
   in (A.sum areas, segments)

trapezoidalRungeMemo ::
     Double -- ^ ε -- precision
  -> (Double -> Double) -- ^ f(x) - function to integrate
  -> Double -- ^ a - from
  -> Double -- ^ b - to
  -> Either Double (Int, Double)
trapezoidalRungeMemo epsilon f a b = go initEstimate initSegments 4
  where
    (initEstimate, initSegments) =
      trapezoidalMemoized 2 (A.fromList Seq [f a, f b]) f a b
    nMax = 131072 -- 2 ^ 17
    theta = 1 / 3
    go prevEstimate prevSegments n
      | n >= nMax = Left prevEstimate
      | theta * abs (curEstimate - prevEstimate) < epsilon =
        Right (n, curEstimate)
      | otherwise = go curEstimate curSegments (2 * n)
      where
        (curEstimate, curSegments) =
          trapezoidalMemoized n prevSegments f a b
</code>```

And making it parallelizable is even more involved:

-- Requires additional import: `Data.Massiv.Array.Unsafe`
trapezoidalMemoizedPar ::
     Int
  -> Array P Ix1 Double
  -> (Double -> Double)
  -> Double
  -> Double
  -> (Double, Array P Ix1 Double)
trapezoidalMemoizedPar n prevSegments f a b =
  let step = (b - a) / fromIntegral n
      sz = size segments - 1
      curSegments =
        fmap f (enumFromStepN Seq (a + step) (2 * step) (Sz (n `div` 2)))
      segments =
        computeAs P $
        unsafeMakeLoadArray Par (Sz (n + 1)) Nothing $ \scheduler _ w -> do
          splitLinearlyWith_
            scheduler
            (unSz (size prevSegments))
            (unsafeLinearIndex prevSegments) $ \i e -> w (i * 2) e
          splitLinearlyWith_
            scheduler
            (unSz (size curSegments))
            (unsafeLinearIndex curSegments) $ \i e -> w (i * 2 + 1) e
      area y0 y1 = step * (y0 + y1) / 2
      areas = A.zipWith area segments (extract' 1 sz segments)
   in (A.sum areas, segments)
```

Body:
I have an algorithm for parallel computing a certain integral.
This solution gives very good time acceleration if you use multiple threads. And the more threads the faster the calculation.
I tested up to -N4 and the acceleration factor reached 8. Ie, the launch of the program on 4 cores is the calculation of the integral 8 times faster than the launch of this program on 1 core.
But I want to add a rule for estimating the error of Runge.
Since now, in order to increase the accuracy of the calculation of the integral, it is necessary to increase N. Which indicates how many parts we need to break our original segment.
How can i do this?

import Data.Time
import System.Environment
import Data.Massiv.Array as A

main = do
    begT <- getCurrentTime
    putStrLn $ show $ integrateA 100000 f 0.00005 10000
    endT <- getCurrentTime
    putStrLn $ init $ show $ diffUTCTime endT begT

f :: Double -> Double
f x = sin x * cos x*x*x

integrateA :: Int -> (Double -> Double) -> Double -> Double -> Double
integrateA n f a b =
 let step = (b - a) / fromIntegral n
  sz = size segments - 1
  segments = computeAs P $ A.map f (enumFromStepN Par a step (Sz (n + 1)))
  area y0 y1 = step * (y0 + y1) / 2
  areas = A.zipWith area (extract' 0 sz segments) (extract' 1 sz segments)
 in A.sum areas

Examples of launches:

Body:
You don't need to change anything in the already supplied integral estimator in order to add precision to it using Runge rule. Something like that, I think:

-- | Returns estimated integral up to a precision, or value estimated at max
-- number of steps
rungeRule ::
     Int -- ^ Maximum number of steps as an upper bound, to prevent unbounded computation
  -> Double -- ^ ε -- precision
  -> Int -- ^ Starting value of @n@
  -> Double -- ^ Θ -- ^ Either 1/3 for trapezoidal and midpoint or 1/15 for Simpson's
  -> (Int -> Double) -- ^ Integral estimator
  -> Either Double (Int, Double)
rungeRule nMax epsilon n0 theta integralEstimator =
  go (integralEstimator n0) (2 * n0)
  where
    go prevEstimate n
      | n >= nMax = Left prevEstimate
      | theta * abs (curEstimate - prevEstimate) < epsilon =
        Right (n, curEstimate)
      | otherwise = go curEstimate (2 * n)
      where
        curEstimate = integralEstimator n

trapezoidal ::
     Double -- ^ ε -- precision
  -> (Double -> Double) -- ^ f(x) - function to integrate
  -> Double -- ^ a - from
  -> Double -- ^ b - to
  -> Either Double (Int, Double)
trapezoidal epsilon f a b =
  rungeRule 100000 epsilon 10 (1 / 3) (\n -> integrateA n f a b)

If we run it, we get promising results:

λ> trapezoidal 0.0005 (\x -> x * x) 10 20
Right (640,2333.333740234375)
λ> trapezoidal 0.00005 (\x -> x * x) 10 20
Right (2560,2333.3333587646484)
λ> trapezoidal 0.00000005 (\x -> x * x) 10 20
Right (81920,2333.3333333581686)
λ> trapezoidal 0.000000005 (\x -> x * x) 10 20
Left 2333.3333333581686

Side note:

Your function f the way you wrote it suggests that:

you expect: f x = (sin x) * (cos (x*x*x))

where in reality it is: f x = (sin x) * (cos x) * x * x

Edit:

Solution presented above is general enough to work for all integral approximation rules. But there is some duplicate work happens at each iteration of Runge rule, in case of trapezoidal rule half of the elements are being recomputed each time, which I saw as a potential optimization. What comes next is a bit more advance usage of massiv, as such I am not gonna be able to elaborate on how it work, except the fact that the segments array passed around is used to access values computed at a previous step.

trapezoidalMemoized ::
     Int
  -> Array P Ix1 Double
  -> (Double -> Double)
  -> Double
  -> Double
  -> (Double, Array P Ix1 Double)
trapezoidalMemoized n prevSegments f a b =
  let step = (b - a) / fromIntegral n
      sz = size segments - 1
      curSegments =
        fmap f (enumFromStepN Seq (a + step) (2 * step) (Sz (n `div` 2)))
      segments =
        computeAs P $
        makeLoadArrayS (Sz (n + 1)) 0 $ \w -> do
          A.iforM_ prevSegments $ \i e -> w (i * 2) e
          A.iforM_ curSegments $ \i e -> w (i * 2 + 1) e
      area y0 y1 = step * (y0 + y1) / 2
      areas = A.zipWith area segments (extract' 1 sz segments)
   in (A.sum areas, segments)

trapezoidalRungeMemo ::
     Double -- ^ ε -- precision
  -> (Double -> Double) -- ^ f(x) - function to integrate
  -> Double -- ^ a - from
  -> Double -- ^ b - to
  -> Either Double (Int, Double)
trapezoidalRungeMemo epsilon f a b = go initEstimate initSegments 4
  where
    (initEstimate, initSegments) =
      trapezoidalMemoized 2 (A.fromList Seq [f a, f b]) f a b
    nMax = 131072 -- 2 ^ 17
    theta = 1 / 3
    go prevEstimate prevSegments n
      | n >= nMax = Left prevEstimate
      | theta * abs (curEstimate - prevEstimate) < epsilon =
        Right (n, curEstimate)
      | otherwise = go curEstimate curSegments (2 * n)
      where
        (curEstimate, curSegments) =
          trapezoidalMemoized n prevSegments f a b

And making it parallelizable is even more involved:

-- Requires additional import: `Data.Massiv.Array.Unsafe`
trapezoidalMemoizedPar ::
     Int
  -> Array P Ix1 Double
  -> (Double -> Double)
  -> Double
  -> Double
  -> (Double, Array P Ix1 Double)
trapezoidalMemoizedPar n prevSegments f a b =
  let step = (b - a) / fromIntegral n
      sz = size segments - 1
      curSegments =
        fmap f (enumFromStepN Seq (a + step) (2 * step) (Sz (n `div` 2)))
      segments =
        computeAs P $
        unsafeMakeLoadArray Par (Sz (n + 1)) Nothing $ \scheduler _ w -> do
          splitLinearlyWith_
            scheduler
            (unSz (size prevSegments))
            (unsafeLinearIndex prevSegments) $ \i e -> w (i * 2) e
          splitLinearlyWith_
            scheduler
            (unSz (size curSegments))
            (unsafeLinearIndex curSegments) $ \i e -> w (i * 2 + 1) e
      area y0 y1 = step * (y0 + y1) / 2
      areas = A.zipWith area segments (extract' 1 sz segments)
   in (A.sum areas, segments)


问:
how to make webview not full size on screen
I would like to get my webview on iphone app, but it is making it full screen every time i add it. i added a webviewkit to most of the screen but the code seems to be over-riding this, i am not that good with code but just wondering can i change one thing on the code below to make it not full size

I added a webviewkit to some of the page but the code is overriding this somehow

```<code>import UIKit
import WebKit

class ViewController2: UIViewController, WKUIDelegate {

    @IBOutlet var webView: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        let myURL = URL(string:"https://weatheralertsireland.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
}
</code>```

can you please see what mistake I am making to make it fit in the webviewKit on the screen

答:
you have to provide frame to webview to get it sized according to your requirment and from your code just remove loadView method.</p>

```<code>let webView = WKWebView()
        let myURL = URL(string:"https://weatheralertsireland.com")
        let myRequest = URLRequest(url: myURL!)
        webView.frame = CGRect(x: 0, y: self.view.frame.size.height/2, width: self.view.frame.size.width, height: self.view.frame.size.height/2)
        self.view.addSubview(webView)
        webView.load(myRequest)
</code>```

Body:
I would like to get my webview on iphone app, but it is making it full screen every time i add it. i added a webviewkit to most of the screen but the code seems to be over-riding this, i am not that good with code but just wondering can i change one thing on the code below to make it not full size

I added a webviewkit to some of the page but the code is overriding this somehow

import UIKit
import WebKit

class ViewController2: UIViewController, WKUIDelegate {

    @IBOutlet var webView: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        let myURL = URL(string:"https://weatheralertsireland.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
}

can you please see what mistake I am making to make it fit in the webviewKit on the screen

Body:
you have to provide frame to webview to get it sized according to your requirment and from your code just remove loadView method.

let webView = WKWebView()
        let myURL = URL(string:"https://weatheralertsireland.com")
        let myRequest = URLRequest(url: myURL!)
        webView.frame = CGRect(x: 0, y: self.view.frame.size.height/2, width: self.view.frame.size.width, height: self.view.frame.size.height/2)
        self.view.addSubview(webView)
        webView.load(myRequest)


问:
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
This is the output of my Gradle console, I am unable to build my project

```<code>D:\Android Projects\....\app\src\main\res\layout\topic_view_header.xml
Error:error: resource attr/?? (aka -packagename- :attr/??) not found.
Error:error: resource attr/?? (aka -packagename-:attr/??) not found.
Error:error: resource attr/?? (aka -packagename-:attr/??) not found.
Error:resource attr/?? (aka -packagename-:attr/??) not found.
Error:resource attr/?? (aka -packagename-:attr/??) not found.
Error:resource attr/?? (aka -packagename-:attr/??) not found.
Error:failed linking file resources.
Error:java.util.concurrent.ExecutionException:
java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for
details
Error:Execution failed for task ':app:processDebugResources'.
> Failed to execute aapt
Information:BUILD FAILED in 27s
Information:11 errors
Information:0 warnings
</code>```

Android Studio 3.0 RC 2

答:
Most probably this happen because of some silly mistake in layout file

in my case case I have copied a textview from another project but the backgroundColor resource was not available in my current project

The thing that it was not showing the error at run time but gives above error while compile time.

You can find out where the exact error in your xml by following the process:

Click on the Gradle tab in right side of Android Studio -> Open the projects build directory as shown in below image -> Run the assembleDebug

-- The error will be shown like in below image

Body:
This is the output of my Gradle console, I am unable to build my project

D:\Android Projects\....\app\src\main\res\layout\topic_view_header.xml
Error:error: resource attr/?? (aka -packagename- :attr/??) not found.
Error:error: resource attr/?? (aka -packagename-:attr/??) not found.
Error:error: resource attr/?? (aka -packagename-:attr/??) not found.
Error:resource attr/?? (aka -packagename-:attr/??) not found.
Error:resource attr/?? (aka -packagename-:attr/??) not found.
Error:resource attr/?? (aka -packagename-:attr/??) not found.
Error:failed linking file resources.
Error:java.util.concurrent.ExecutionException:
java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException:
com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for
details
Error:Execution failed for task ':app:processDebugResources'.
> Failed to execute aapt
Information:BUILD FAILED in 27s
Information:11 errors
Information:0 warnings

Android Studio 3.0 RC 2


问:
Is there a way to put php inside of a IE conditional comments
I have a php section that loads jquery through wordpress from google's api. I dont want to load jquery on IE browsers. Long story short, it doesn't work for whatever reason (you can read through my other posted questions).

Or if this is not possible is there another way to NOT use this code when its an IE browser, maybe a php solution.

```<code><?php
    if( !is_admin()){
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2', true);
        wp_enqueue_script('jquery');
    }

?>
</code>```

Targets everything except IE (what i was trying to use, but it didnt work):

```<code><!--[if !IE]><!-->
<!--<![endif]-->
</code>```

答:
Short answer: no.

Long answer: IE conditional comments are client side, while PHP is server side, so it won't work.

Possible solution: http://php.net/manual/en/function.get-browser.php  (or according to one of the answers already posted, wordpress provides a $is_IE global)

Body:
I have a php section that loads jquery through wordpress from google's api. I dont want to load jquery on IE browsers. Long story short, it doesn't work for whatever reason (you can read through my other posted questions).

Or if this is not possible is there another way to NOT use this code when its an IE browser, maybe a php solution.

<?php
    if( !is_admin()){
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', false, '1.5.2', true);
        wp_enqueue_script('jquery');
    }

?>

Targets everything except IE (what i was trying to use, but it didnt work):


问:
How to show child records for only related parent in django Admin?
Model "Playbook" has related child objects "Activities"
Need to list_display "Activities" in django admin for each "playbook" object.
Currently list_display shows all activity objects for all playbook objects (parent object).

django v 1.10.x, python 3.5.x

Model.py

```<code>class PlayBook(TimeStampModel):
    name = models.CharField(max_length=200, unique=True)
    description = models.TextField(blank=True, help_text="Business purpose of the application")
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        ordering = ('name',)

    @property
    def short_description(self):
        return truncatechars(self.description, 35)

    def __str__(self):
        return "{}".format(self.name)

class Activity(TimeStampModel):

    minor = 'MINOR'
    normal = 'NORMAL'
    important = 'IMPORTANT'
    critical = 'CRITICAL'

    SEVERITY = (
        (minor, 'Minor'),
        (normal, 'Normal'),
        (important, 'Important'),
        (critical, 'Critical'),
    )

    low = 'LOW'
    high = 'HIGH'
    PRIORITY = (
            (low, 'Low'),
            (normal, 'Normal'),
            (high, 'High'),
            )

    new = 'New'
    in_progress = 'In_Progress'
    needs_info = 'Needs_Info'
    postponed = 'Postponed'
    closed = 'Closed'
    STATUS= (
            (new, 'New'),
            (in_progress, 'In_Progress'),
            (needs_info, 'Needs_Info'),
            (postponed, 'Postponed'),
            (closed, 'Closed'),

            )

    playbook = models.ForeignKey(PlayBook)
    subject = models.CharField(max_length=200, unique=True)
    description = models.TextField(blank=True, help_text="Business purpose of the application")
    manager = models.ForeignKey(User, on_delete=models.CASCADE)
    severity = models.CharField(max_length = 100, choices=SEVERITY, default=normal)
    priority = models.CharField(max_length = 100, choices=PRIORITY, default=normal)
    status = models.CharField(max_length = 100, choices=STATUS, default=new)

    def __str__(self):
        return "{}".format(self.subject)

    class Meta:
        ordering = ('severity',)
    @property
    def short_description(self):
        return truncatechars(self.description, 35)

class ReviewActivity(Activity):
    class Meta:
        proxy=True

    def __str__(self):
        return self.subject.upper()
</code>```

Admin.py

```<code>class ActivityAdmin(admin.TabularInline):
    list_display =['severity','priority', 'subject', 'status_colored','created','updated', 'short_description']

    def status_colored(self, obj):
        colors = {
            'Closed': '#DCE775',
            'Needs_Info': '#F8BBD0'  ,
            'In_Progress': '#FFCCBC',
            'New':'#81D4FA',
            'Postponed': '#CFD8DC'
        }
        return format_html(
            '<b style="background:{};">{}</b>',
            colors[obj.status],
            obj.status,
        )

class ActivityInline(admin.TabularInline):
    model = Activity
    extra = 1

class PlayBookAdmin(admin.ModelAdmin):

    inlines = [
            ActivityInline,
            ]

    list_display =['name','short_description','created', 'updated','owner',]

class ReviewActivityAdmin(admin.ModelAdmin):

    list_display =['severity','priority', 'subject', 'status_colored','created','updated', 'short_description']

    def status_colored(self, obj):
        colors = {
            'Closed': '#DCE775',
            'Needs_Info': '#F8BBD0'  ,
            'In_Progress': '#FFCCBC',
            'New':'#81D4FA',
            'Postponed': '#CFD8DC'
        }
        return format_html(
            '<b style="background:{};">{}</b>',
            colors[obj.status],
            obj.status,
        )

#admin.site.register(Activity, ActivityAdmin)
admin.site.register(PlayBook, PlayBookAdmin)
admin.site.register(ReviewActivity, ReviewActivityAdmin)
</code>```

Result:

I tried to use the proxy model. But it still displays all child records for all parents.

Playbook link displays the following:

playbook1 shows the tabular display

Problem:

Review Activity link displays all activity objects for all playbooks. Need to show activity object for a related playbook.not all playbooks*.
See(figure 4):

Link to github:

Link to source TaskMaster

答:
I just run into a similar situation this morning and this is how i solved it. I am going to use your example to explain.

I defined a new method called activities() in the PlayBook model like so:

```<code>class PlayBook(TimeStampModel):
    name = models.CharField(max_length=200, unique=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    def activities(self):
    qs = self.activity_set.all() # this gets all the child related objects
    for x in qs:
        result = x.subject # here i am just getting one of the fields from the Activities model
    return result
</code>```

so now in your admin.py you can set your list_diplay as follows

```<code>class PlayBookAdmin(admin.ModelAdmin):

    list_display =['activities',] # This will call the activities() method that your created in the models.py and display the result.
</code>```

Body:
Model "Playbook" has related child objects "Activities"
Need to list_display "Activities" in django admin for each "playbook" object.
Currently list_display shows all activity objects for all playbook objects (parent object).

django v 1.10.x, python 3.5.x

Model.py

class PlayBook(TimeStampModel):
    name = models.CharField(max_length=200, unique=True)
    description = models.TextField(blank=True, help_text="Business purpose of the application")
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        ordering = ('name',)

    @property
    def short_description(self):
        return truncatechars(self.description, 35)

    def __str__(self):
        return "{}".format(self.name)

class Activity(TimeStampModel):

    minor = 'MINOR'
    normal = 'NORMAL'
    important = 'IMPORTANT'
    critical = 'CRITICAL'

    SEVERITY = (
        (minor, 'Minor'),
        (normal, 'Normal'),
        (important, 'Important'),
        (critical, 'Critical'),
    )

    low = 'LOW'
    high = 'HIGH'
    PRIORITY = (
            (low, 'Low'),
            (normal, 'Normal'),
            (high, 'High'),
            )

    new = 'New'
    in_progress = 'In_Progress'
    needs_info = 'Needs_Info'
    postponed = 'Postponed'
    closed = 'Closed'
    STATUS= (
            (new, 'New'),
            (in_progress, 'In_Progress'),
            (needs_info, 'Needs_Info'),
            (postponed, 'Postponed'),
            (closed, 'Closed'),

            )

    playbook = models.ForeignKey(PlayBook)
    subject = models.CharField(max_length=200, unique=True)
    description = models.TextField(blank=True, help_text="Business purpose of the application")
    manager = models.ForeignKey(User, on_delete=models.CASCADE)
    severity = models.CharField(max_length = 100, choices=SEVERITY, default=normal)
    priority = models.CharField(max_length = 100, choices=PRIORITY, default=normal)
    status = models.CharField(max_length = 100, choices=STATUS, default=new)

    def __str__(self):
        return "{}".format(self.subject)

    class Meta:
        ordering = ('severity',)
    @property
    def short_description(self):
        return truncatechars(self.description, 35)

class ReviewActivity(Activity):
    class Meta:
        proxy=True

    def __str__(self):
        return self.subject.upper()

Admin.py

class ActivityAdmin(admin.TabularInline):
    list_display =['severity','priority', 'subject', 'status_colored','created','updated', 'short_description']

    def status_colored(self, obj):
        colors = {
            'Closed': '#DCE775',
            'Needs_Info': '#F8BBD0'  ,
            'In_Progress': '#FFCCBC',
            'New':'#81D4FA',
            'Postponed': '#CFD8DC'
        }
        return format_html(
            '{}',
            colors[obj.status],
            obj.status,
        )

class ActivityInline(admin.TabularInline):
    model = Activity
    extra = 1

class PlayBookAdmin(admin.ModelAdmin):

    inlines = [
            ActivityInline,
            ]

    list_display =['name','short_description','created', 'updated','owner',]

class ReviewActivityAdmin(admin.ModelAdmin):

    list_display =['severity','priority', 'subject', 'status_colored','created','updated', 'short_description']

    def status_colored(self, obj):
        colors = {
            'Closed': '#DCE775',
            'Needs_Info': '#F8BBD0'  ,
            'In_Progress': '#FFCCBC',
            'New':'#81D4FA',
            'Postponed': '#CFD8DC'
        }
        return format_html(
            '{}',
            colors[obj.status],
            obj.status,
        )

#admin.site.register(Activity, ActivityAdmin)
admin.site.register(PlayBook, PlayBookAdmin)
admin.site.register(ReviewActivity, ReviewActivityAdmin)

Result:

I tried to use the proxy model. But it still displays all child records for all parents.

Playbook link displays the following:

playbook1 shows the tabular display

Problem:

Review Activity link displays all activity objects for all playbooks. Need to show activity object for a related playbook.not all playbooks*.
See(figure 4):

Link to github:

Link to source TaskMaster

Body:
I just run into a similar situation this morning and this is how i solved it. I am going to use your example to explain.

I defined a new method called activities() in the PlayBook model like so:

class PlayBook(TimeStampModel):
    name = models.CharField(max_length=200, unique=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    def activities(self):
    qs = self.activity_set.all() # this gets all the child related objects
    for x in qs:
        result = x.subject # here i am just getting one of the fields from the Activities model
    return result

so now in your admin.py you can set your list_diplay as follows

class PlayBookAdmin(admin.ModelAdmin):

    list_display =['activities',] # This will call the activities() method that your created in the models.py and display the result.


问:
Azure Web Job running for two timezones, twice
I have given my Web Schedule for the azure web job as 000***. I uploaded this from PST Timezone. The web job runs at 12:00 AM UTC and again at 12:00 AM PST.
Why is it picking two time zones to run the job and how to ensure it only picks one timezone? Could some one please help.</p>

答: Try setting WEBSITE_TIME_ZONE application setting to a timezone string, e.g. Pacific Standard Time, on your app service/web app. And see if it runs properly or not.</p>


问:
ExecuteReader Timing Out
I'm trying to create a login page.

I get the users ID and password as parameters, and I want to access my database and compare them, but when I execute the query using ExecuteReader, the query always times out.

The database itself is very very small, only with about 5 or 6 users so it shouldn't be timing out......

```<code>SqlConnection cnn = null;
string connectionString = null;

connectionString = @"Data Source=DESKTOP-A5GR284\SQLEXPRESS;Initial Catalog=Chat_DB;Integrated Security=True";

cnn = new SqlConnection(connectionString);
cnn.Open();

SqlCommand cmd = new SqlCommand("SELECT * FROM Users", cnn);

SqlDataReader reader = cmd.ExecuteReader();

while (reader.HasRows)
{
    while (reader.Read())
    {
         Console.WriteLine("{0}", reader.GetString(1));
    }

    reader.NextResult();
}

cnn.Close();
</code>```

The reader will timeout before entering the 'while loop'

答:
According to MSDN, ExecuteReader()

Sends the CommandText to the Connection and builds a SqlDataReader.

Generally, if you get a timeout here, the problem is with the database connection. Looking at your code, I think the connection string in the connetionString is the problem. Check to see if it really is the connection string you're looking for. Also check for invisible characters in the same connection string.

Title: ExecuteReader Timing Out

Body:
I'm trying to create a login page.

I get the users ID and password as parameters, and I want to access my database and compare them, but when I execute the query using ExecuteReader, the query always times out.

The database itself is very very small, only with about 5 or 6 users so it shouldn't be timing out......

SqlConnection cnn = null;
string connectionString = null;

connectionString = @"Data Source=DESKTOP-A5GR284\SQLEXPRESS;Initial Catalog=Chat_DB;Integrated Security=True";

cnn = new SqlConnection(connectionString);
cnn.Open();

SqlCommand cmd = new SqlCommand("SELECT * FROM Users", cnn);

SqlDataReader reader = cmd.ExecuteReader();

while (reader.HasRows)
{
    while (reader.Read())
    {
         Console.WriteLine("{0}", reader.GetString(1));
    }

    reader.NextResult();
}

cnn.Close();

The reader will timeout before entering the 'while loop'