问:
Show Loading Spinner with Axios and React (possible Redux)
My objective is show a loading spinner when a http request is called. I want to do this globally, It means, when any component call some api, is automatic to show teh spinner, preferably, with no aditional code to control the spinner.

I'm using react and axios. I know about the axios' interceptors.

My actual strucuture:

<Component App>
    <Component A />
    <Component B />
    <Loading Component>
</Component App>
```

<p>I don't know is It possible in react, but I Tried to make a general class to implement a base informations about the service, for example, baseUrl and the http interceptor. So, when a need to call a API service, I create a specialized class using the general class and concentred all api methods from that concept there, and, then, use the base class to call the axios method get,post,etc. So, the interceptor appears and show the spinner before the request and hide after the request.</p>

<p>The idea is a component call the specialized class to call a API and show the spinner until the request is running.</p>

<p>I think to use redux to make the state be global, but I don't know if It possible to implement in a class (API Class Base and Specialized API Class)</p>

<p>My questions:
- Is It possible use this architeture?
- If yes, how to implement and use redux with this?
- IIs that right to use class or is better use a component to implement a base service class and the specialized class?</p>

<p>App component:</p>

<pre class="lang-php prettyprint-override"><code>class App extends Component {

  constructor(props) {
      super(props);

      this.state = {
          rows: []
      };
  }

  componentDidMount() {
var service = new specializedService();

     var response =

 specializedService.someAPIMethod(1).then((res) => {
           this.setState({
               rows: res.data
           });
     });
}

render() {
return (
        <div className="App">
                <Component A rows={this.state.rows} />
                <Component B rows={this.state.rows}/>
                <Loading />
        </div>
    );
  }
</code>```

specializedService:

```<code>import serviceBase from "./serviceBase";

class specializedService {

    someAPIMethod(id) {
        return serviceBase.get('someMethod/' + id);
    };

}
</code>```

serviceBase:

```<code>import axios from "axios";

const serviceBase = () => {

    const api = axios.create({
        baseURL: 'https://xxxxx.xxxxx.com/xxxxxx/'
    });

    api.interceptors.request.use(async (config) => {
        try{
            // In this moment, show the spinner
            // showLoading();
        }
        catch(e)
        {
            alert('Error request' + e);
        }

        return config;
    });

    api.interceptors.response.use(async (config) => {
        try {
            // In this moment, hide the spinner
            // hideLoading();
        }
        catch(e)
        {
            alert('Error response' + e);
        }

        return config;
    });

    return api;
};

export default serviceBase;
</code>```

I made a simple sample to illustrate the situation, but I don't connect the redux
https://repl.it/@DiegoFerreira1/LoadingSpinnerApp

答:
I think the best way to achieve that would be using redux. you can have a "request status" reducer of some sort, and a value in your store that indicates whether a request is being sent.

Pseudo-code:

const sendRequest = async (req) {
  dispatch({type: "REQUEST_SENT"});
  const res = await axios.get(req);
  dispatch({type: "REQUEST_SUCCEEDED", payload: res});
}
```

And depending on the action you switch the value of your request status in your store, re-rendering your components.

Body:
My objective is show a loading spinner when a http request is called. I want to do this globally, It means, when any component call some api, is automatic to show teh spinner, preferably, with no aditional code to control the spinner.

I'm using react and axios. I know about the axios' interceptors.

My actual strucuture:

<Component App>
    <Component A />
    <Component B />
    <Loading Component>
</Component App>

I don't know is It possible in react, but I Tried to make a general class to implement a base informations about the service, for example, baseUrl and the http interceptor. So, when a need to call a API service, I create a specialized class using the general class and concentred all api methods from that concept there, and, then, use the base class to call the axios method get,post,etc. So, the interceptor appears and show the spinner before the request and hide after the request.

The idea is a component call the specialized class to call a API and show the spinner until the request is running.

I think to use redux to make the state be global, but I don't know if It possible to implement in a class (API Class Base and Specialized API Class)

My questions:
- Is It possible use this architeture?
- If yes, how to implement and use redux with this?
- IIs that right to use class or is better use a component to implement a base service class and the specialized class?

App component:

class App extends Component {

  constructor(props) {
      super(props);

      this.state = {
          rows: []
      };
  }

  componentDidMount() {
var service = new specializedService();

     var response =

 specializedService.someAPIMethod(1).then((res) => {
           this.setState({
               rows: res.data
           });
     });
}

render() {
return (

                <Component A rows={this.state.rows} />
                <Component B rows={this.state.rows}/>
                <Loading />

    );
  }

specializedService:

import serviceBase from "./serviceBase";

class specializedService {

    someAPIMethod(id) {
        return serviceBase.get('someMethod/' + id);
    };

}

serviceBase:

import axios from "axios";

const serviceBase = () => {

    const api = axios.create({
        baseURL: 'https://xxxxx.xxxxx.com/xxxxxx/'
    });

    api.interceptors.request.use(async (config) => {
        try{
            // In this moment, show the spinner
            // showLoading();
        }
        catch(e)
        {
            alert('Error request' + e);
        }

        return config;
    });

    api.interceptors.response.use(async (config) => {
        try {
            // In this moment, hide the spinner
            // hideLoading();
        }
        catch(e)
        {
            alert('Error response' + e);
        }

        return config;
    });

    return api;
};

export default serviceBase;

I made a simple sample to illustrate the situation, but I don't connect the redux
https://repl.it/@DiegoFerreira1/LoadingSpinnerApp

Body:
I think the best way to achieve that would be using redux. you can have a "request status" reducer of some sort, and a value in your store that indicates whether a request is being sent.

Pseudo-code:

const sendRequest = async (req) {
  dispatch({type: "REQUEST_SENT"});
  const res = await axios.get(req);
  dispatch({type: "REQUEST_SUCCEEDED", payload: res});
}

And depending on the action you switch the value of your request status in your store, re-rendering your components.


来源: stackexchange

问:
Specifically increase an ID value depending on A Foreign Key
I have two database tables; one named Mould, other one named MeasResult.
Mould table has MID as Primary key and MeasResult table has a Foreign Key named MoldID that references MID.
I am logging measurement to MeasResult table using this Foreign key.
MeasResult table also has a MeasID column that keeps track of measurement insert count. For every measurement i am logging 50 rows of data.
What i need to is that i need to increase this MeasID value by 1 every time a new measurement is logged with minding MoldID (Foreign Key in the table).

My current code doesn't mind the Foreign Key, it is just increases MeasResult value by one for every measurement log.

```<code>using (LinqDataClassesDataContext dataContext = new
LinqDataClassesDataContext())
            {
                var measid = dataContext.MeasResults.Select(a =>
a.MeasId).Where(p => p != null).Max() + 1;

                string id = ""; string plane = ""; int pos = 0; int dist = 0; double apert = 0;

                id = comboBMouldID.SelectedValue.ToString();
                plane = comboBSurface.SelectedItem.ToString();
                pos = Convert.ToInt32(txtTravelPos.Text);

                for (int i = 0; i < daGridMeas.Rows.Count - 1; i++)
                {
                    dist = Convert.ToInt32(daGridMeas.Rows[i].Cells[0].Value.ToString());
                    apert = Convert.ToDouble(daGridMeas.Rows[i].Cells[1].Value.ToString());

                    var st = new MeasResult();
                    {
                        st.MoldID = id;
                        st.Plane = plane;
                        st.Postn = pos;
                        st.Distnc = dist;
                        st.Apert = apert;
                        st.MeasId = measid;
                        st.Date = DateTime.Now;
                    };

                    dataContext.MeasResults.InsertOnSubmit(st);
                    dataContext.SubmitChanges();
                }
</code>```

How can i change the code so it would increase MeasID by 1 for every measurement taken for specific MoldID?

答:
Then it should be pretty simple based on your answer.

Calculate the existing number of records with this MoldID:

```<code>var NumberOfPreviousMeasurements = dataContext.MeasResults.Where(m => m.MoldId == comboMouldID.SelectedValue.ToString()).Count();
</code>```

And then assign this value as the MeasId of the new record.
Shouldn't this suffice?

ContentLicense: CC BY-SA 4.0

Body:
I have two database tables; one named Mould, other one named MeasResult.
Mould table has MID as Primary key and MeasResult table has a Foreign Key named MoldID that references MID.
I am logging measurement to MeasResult table using this Foreign key.
MeasResult table also has a MeasID column that keeps track of measurement insert count. For every measurement i am logging 50 rows of data.
What i need to is that i need to increase this MeasID value by 1 every time a new measurement is logged with minding MoldID (Foreign Key in the table).

My current code doesn't mind the Foreign Key, it is just increases MeasResult value by one for every measurement log.

using (LinqDataClassesDataContext dataContext = new
LinqDataClassesDataContext())
            {
                var measid = dataContext.MeasResults.Select(a =>
a.MeasId).Where(p => p != null).Max() + 1;

                string id = ""; string plane = ""; int pos = 0; int dist = 0; double apert = 0;

                id = comboBMouldID.SelectedValue.ToString();
                plane = comboBSurface.SelectedItem.ToString();
                pos = Convert.ToInt32(txtTravelPos.Text);

                for (int i = 0; i < daGridMeas.Rows.Count - 1; i++)
                {
                    dist = Convert.ToInt32(daGridMeas.Rows[i].Cells[0].Value.ToString());
                    apert = Convert.ToDouble(daGridMeas.Rows[i].Cells[1].Value.ToString());

                    var st = new MeasResult();
                    {
                        st.MoldID = id;
                        st.Plane = plane;
                        st.Postn = pos;
                        st.Distnc = dist;
                        st.Apert = apert;
                        st.MeasId = measid;
                        st.Date = DateTime.Now;
                    };

                    dataContext.MeasResults.InsertOnSubmit(st);
                    dataContext.SubmitChanges();
                }

How can i change the code so it would increase MeasID by 1 for every measurement taken for specific MoldID?

Body:
Then it should be pretty simple based on your answer.

Calculate the existing number of records with this MoldID:

var NumberOfPreviousMeasurements = dataContext.MeasResults.Where(m => m.MoldId == comboMouldID.SelectedValue.ToString()).Count();

And then assign this value as the MeasId of the new record.
Shouldn't this suffice?


问:
Disabling a button based on value in a UITextField only works once (RxSwift)
I'm trying to get to grips with RxCocoa and have experienced an unusual bug relating to some dynamic UI behaviour I'm trying to implement.

I have a UITextField that's used for user input. The button which adds the input to a Realm database is bound to an RxSwift Action. This works absolutely fine.

Initially, I disabled the button until there was text of at least 1 character in length in the UITextField - the code of this works fine. The bug in my code arose when I then added a subscription to the Action's executionObservables parameter that should clear the UITextField after the button is pressed.

Expected behaviour:

No text (initial state) > button disabled

Text entered > button enabled

Text entered and button pressed > text field cleared and button disabled

Actual behaviour:

No text  (initial state) > button disabled

Text entered > button enabled

Text entered and button pressed > text field cleared BUT button remains enabled

Adding debug() indicates that the binding to the UITextField that disables the button is disposed but I can't figure out why as the UIViewController and its associated view model should still be in scope. Can anyone point me in the right direction?

Code snippet:

```<code>func bindViewModel() {
    // populate table
    viewModel.output.sectionedObservations
        .drive(tableView.rx.items(dataSource: dataSource))
        .disposed(by: disposeBag)

    // only allow enable button when there is text in the textfield
    observationTextField.rx.text
        .debug()
        .map { $0!.count > 0 }
        .bind(to: addObservationButton.rx.isEnabled)
        .disposed(by: disposeBag)

// clear textfield once Action triggered by button press has completed
viewModel.addObservation.executionObservables
    .subscribe({ [unowned self] _ in
        self.observationTextField.rx.text.onNext("")
})
.disposed(by: disposeBag)

// add Observation to Realm using Action provided by the view model
addObservationButton.rx.tap
    .withLatestFrom(observationTextField.rx.text.orEmpty)
    .take(1)
    .bind(to: viewModel.addObservation.inputs)
    .disposed(by: disposeBag)
}
</code>```

答:
I think there is a little misunderstanding about how ControlProperty trait behaves. Let's take a look at specific behavior which is Programmatic value changes won't be reported

This Observable observationTextField.rx.text after subscription will not emit event for both:

self.observationTextField.rx.text.onNext("")

or

self.observationTextField.text = ""

I have 2 suggestion for your code:

1) Do the job manually:

viewModel.addObservation.executionObservables
    .subscribe({ [unowned self] _ in
        self.observationTextField = ""
        self.addObservationButton.isEnabled = false
})
.disposed(by: disposeBag)
```

<p>2) Add one more Observable and subscription:</p>

<pre class="lang-swift prettyprint-override"><code>//a
    viewModel.addObservation.executionObservables
      .map { _ in return "" }
      .bind(to: observationTextField.rx.text)
      .disposed(by: disposeBag)

    viewModel.addObservation.executionObservables
      .map { _ in return false }
      .bind(to: addObservationButton.rx.isEnabled)
      .disposed(by: disposeBag)
</code>```

//b
    let executionObservables = viewModel.addObservation
      .executionObservables
      .share()

    executionObservables
      .map { _ in return "" }
      .bind(to: observationTextField.rx.text)
      .disposed(by: disposeBag)

    executionObservables
      .map { _ in return false }
      .bind(to: addObservationButton.rx.isEnabled)
      .disposed(by: disposeBag)
```

Not sure how Action is implemented, to prevent job done twice maybe you have to share resources.

Body:
I'm trying to get to grips with RxCocoa and have experienced an unusual bug relating to some dynamic UI behaviour I'm trying to implement.

I have a UITextField that's used for user input. The button which adds the input to a Realm database is bound to an RxSwift Action. This works absolutely fine.

Initially, I disabled the button until there was text of at least 1 character in length in the UITextField - the code of this works fine. The bug in my code arose when I then added a subscription to the Action's executionObservables parameter that should clear the UITextField after the button is pressed.

Expected behaviour:

No text (initial state) > button disabled

Text entered > button enabled

Text entered and button pressed > text field cleared and button disabled

Actual behaviour:

No text  (initial state) > button disabled

Text entered > button enabled

Text entered and button pressed > text field cleared BUT button remains enabled

Adding debug() indicates that the binding to the UITextField that disables the button is disposed but I can't figure out why as the UIViewController and its associated view model should still be in scope. Can anyone point me in the right direction?

Code snippet:

func bindViewModel() {
    // populate table
    viewModel.output.sectionedObservations
        .drive(tableView.rx.items(dataSource: dataSource))
        .disposed(by: disposeBag)

    // only allow enable button when there is text in the textfield
    observationTextField.rx.text
        .debug()
        .map { $0!.count > 0 }
        .bind(to: addObservationButton.rx.isEnabled)
        .disposed(by: disposeBag)

// clear textfield once Action triggered by button press has completed
viewModel.addObservation.executionObservables
    .subscribe({ [unowned self] _ in
        self.observationTextField.rx.text.onNext("")
})
.disposed(by: disposeBag)

// add Observation to Realm using Action provided by the view model
addObservationButton.rx.tap
    .withLatestFrom(observationTextField.rx.text.orEmpty)
    .take(1)
    .bind(to: viewModel.addObservation.inputs)
    .disposed(by: disposeBag)
}

Body:
I think there is a little misunderstanding about how ControlProperty trait behaves. Let's take a look at specific behavior which is Programmatic value changes won't be reported

This Observable observationTextField.rx.text after subscription will not emit event for both:

self.observationTextField.rx.text.onNext("")

or

self.observationTextField.text = ""

I have 2 suggestion for your code:

1) Do the job manually:

viewModel.addObservation.executionObservables
    .subscribe({ [unowned self] _ in
        self.observationTextField = ""
        self.addObservationButton.isEnabled = false
})
.disposed(by: disposeBag)

2) Add one more Observable and subscription:

//a
    viewModel.addObservation.executionObservables
      .map { _ in return "" }
      .bind(to: observationTextField.rx.text)
      .disposed(by: disposeBag)

    viewModel.addObservation.executionObservables
      .map { _ in return false }
      .bind(to: addObservationButton.rx.isEnabled)
      .disposed(by: disposeBag)

//b
    let executionObservables = viewModel.addObservation
      .executionObservables
      .share()

    executionObservables
      .map { _ in return "" }
      .bind(to: observationTextField.rx.text)
      .disposed(by: disposeBag)

    executionObservables
      .map { _ in return false }
      .bind(to: addObservationButton.rx.isEnabled)
      .disposed(by: disposeBag)

Not sure how Action is implemented, to prevent job done twice maybe you have to share resources.


问:
CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error
I just upgraded from Angular 2 rc4 to rc6 and having troubles doing so.

I see the following error on my console:

```<code>Unhandled Promise rejection: Template parse errors:
'cl-header' is not a known element:
1. If 'cl-header' is an Angular component, then verify that it is part of this module.
2. If 'cl-header' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("<main>
    [ERROR ->]<cl-header>Loading Header...</cl-header>
    <div class="container-fluid">
      <cl-feedbackcontai"): AppComponent@1:4
</code>```

Here is my Header Component:

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

// own service
import { AuthenticationService } from '../../../services/authentication/authentication.service.ts';

import '../../../../../public/css/styles.css';

@Component({
  selector: 'cl-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent { // more code here... }
</code>```

Here is my Header Module:

```<code>import { NgModule, CUSTOM_ELEMENTS_SCHEMA }      from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule }      from '@angular/common';
import { FormsModule }      from '@angular/forms';

import { HeaderComponent }  from './../../../components/util_components/header/header.component.ts';

@NgModule({
    declarations: [ HeaderComponent ],
    bootstrap:    [ HeaderComponent ],
    imports: [ RouterModule, CommonModule, FormsModule ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class HeaderModule { }
</code>```

I created a wrapper module called util module which imports the HeaderModule:

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

import {HeaderModule} from "./header/header.module";
// ...

@NgModule({
    declarations: [ ],
    bootstrap:    [ ],
    imports: [ HeaderModule]
})
export class UtilModule { }
</code>```

Which is finally imported by the AppModule:

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

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

import {UtilModule} from "./modules/util_modules/util.module";
import {RoutingModule} from "./modules/routing_modules/routing.module";

@NgModule({
    bootstrap: [AppComponent],
    declarations: [AppComponent],
    imports: [BrowserModule, UtilModule, RoutingModule]
})
export class AppModule { }
</code>```

To my understanding I am following the instructions of the error message using the SCHEMA to surpress the error. But it seems not to work.
What am I doing wrong?
(I hope its nothing obvious I just don't see at the moment. Been spending the past 6 hours upgrading to this version...)

答:
With components containing Angular Material, a similar error came up with my unit tests. As per @Dan Stirling-Talbert's answer above, added this to my component .spec file and the error was cleared from my unit tests.

```<code>Import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'
</code>```

Then add the schema in the generated beforeEach() statement:

```<code>beforeEach(asyn(() => {
    declarations: [ AboutComponent ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
}));
</code>```

My Karma error was:
If 'mat-panel-title' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

ContentLicense: CC BY-SA 3.0

Body:
I just upgraded from Angular 2 rc4 to rc6 and having troubles doing so.

I see the following error on my console:

Unhandled Promise rejection: Template parse errors:
'cl-header' is not a known element:
1. If 'cl-header' is an Angular component, then verify that it is part of this module.
2. If 'cl-header' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("
    [ERROR ->]<cl-header>Loading Header...</cl-header>

      <cl-feedbackcontai"): AppComponent@1:4

Here is my Header Component:

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

// own service
import { AuthenticationService } from '../../../services/authentication/authentication.service.ts';

import '../../../../../public/css/styles.css';

@Component({
  selector: 'cl-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent { // more code here... }

Here is my Header Module:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA }      from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule }      from '@angular/common';
import { FormsModule }      from '@angular/forms';

import { HeaderComponent }  from './../../../components/util_components/header/header.component.ts';

@NgModule({
    declarations: [ HeaderComponent ],
    bootstrap:    [ HeaderComponent ],
    imports: [ RouterModule, CommonModule, FormsModule ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class HeaderModule { }

I created a wrapper module called util module which imports the HeaderModule:

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

import {HeaderModule} from "./header/header.module";
// ...

@NgModule({
    declarations: [ ],
    bootstrap:    [ ],
    imports: [ HeaderModule]
})
export class UtilModule { }

Which is finally imported by the AppModule:

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

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

import {UtilModule} from "./modules/util_modules/util.module";
import {RoutingModule} from "./modules/routing_modules/routing.module";

@NgModule({
    bootstrap: [AppComponent],
    declarations: [AppComponent],
    imports: [BrowserModule, UtilModule, RoutingModule]
})
export class AppModule { }

To my understanding I am following the instructions of the error message using the SCHEMA to surpress the error. But it seems not to work.
What am I doing wrong?
(I hope its nothing obvious I just don't see at the moment. Been spending the past 6 hours upgrading to this version...)

Body:
With components containing Angular Material, a similar error came up with my unit tests. As per @Dan Stirling-Talbert's answer above, added this to my component .spec file and the error was cleared from my unit tests.

Import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'

Then add the schema in the generated beforeEach() statement:

beforeEach(asyn(() => {
    declarations: [ AboutComponent ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
}));

My Karma error was:
If 'mat-panel-title' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.


问:
Making a column of boolean values based on two conditions in pandas dataframe
I'm trying to makea column of boolean values based on if one column has the word 'hazard' and does not contain the word 'roof' (thus I get all non-roof hazards).

I'm using the below code and I'm getting an error:

```<code>labels['h_count2'] = labels[(labels['Description'].str.contains('Hazard')) & (labels['Description'].str.contains('Roof'))]
</code>```

This is the traceback:

```<code>---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2656             try:
-> 2657                 return self._engine.get_loc(key)
   2658             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'h_count2'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\managers.py in set(self, item, value)
   1052         try:
-> 1053             loc = self.items.get_loc(item)
   1054         except KeyError:

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2658             except KeyError:
-> 2659                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2660         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'h_count2'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-46-51360ea6f27f> in <module>
      1 labels['h_count'] = labels['Description'].str.contains('Roof Hazard')
      2 labels['b_count'] = labels['Description'].str.contains('Brush')
----> 3 labels['h_count2'] = labels[(labels['Description'].str.contains('Hazard')) & (labels['Description'].str.contains('Roof'))]
      4
      5 def target(row):

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
   3368         else:
   3369             # set column
-> 3370             self._set_item(key, value)
   3371
   3372     def _setitem_slice(self, key, value):

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
   3444         self._ensure_valid_index(value)
   3445         value = self._sanitize_column(key, value)
-> 3446         NDFrame._set_item(self, key, value)
   3447
   3448         # check if we are modifying a copy

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\generic.py in _set_item(self, key, value)
   3170
   3171     def _set_item(self, key, value):
-> 3172         self._data.set(key, value)
   3173         self._clear_item_cache()
   3174

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\managers.py in set(self, item, value)
   1054         except KeyError:
   1055             # This item wasn't present, just insert at end
-> 1056             self.insert(len(self.items), item, value)
   1057             return
   1058

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\managers.py in insert(self, loc, item, value, allow_duplicates)
   1156
   1157         block = make_block(values=value, ndim=self.ndim,
-> 1158                            placement=slice(loc, loc + 1))
   1159
   1160         for blkno, count in _fast_count_smallints(self._blknos[loc:]):

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\blocks.py in make_block(values, placement, klass, ndim, dtype, fastpath)
   3093         values = DatetimeArray._simple_new(values, dtype=dtype)
   3094
-> 3095     return klass(values, ndim=ndim, placement=placement)
   3096
   3097

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\blocks.py in __init__(self, values, placement, ndim)
   2629
   2630         super(ObjectBlock, self).__init__(values, ndim=ndim,
-> 2631                                           placement=placement)
   2632
   2633     @property

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\blocks.py in __init__(self, values, placement, ndim)
     85             raise ValueError(
     86                 'Wrong number of items passed {val}, placement implies '
---> 87                 '{mgr}'.format(val=len(self.values), mgr=len(self.mgr_locs)))
     88
     89     def _check_ndim(self, values, ndim):

ValueError: Wrong number of items passed 5, placement implies 1
</code>```

What am i doing wrong?

答:
```<code>labels = pd.DataFrame({'Description': ['Hazard Roof test', 'test', 'Hazard is not', 'test2']})

labels['h_count2'] = (labels['Description'].str.upper().str.contains('HAZARD')) & ~(labels['Description'].str.upper().str.contains('ROOF'))

</code>```

```<code>    Description        h_count2
0   Hazard Roof test    False
1   test                False
2   Hazard is not       True
3   test2               False

</code>```

Body:
I'm trying to makea column of boolean values based on if one column has the word 'hazard' and does not contain the word 'roof' (thus I get all non-roof hazards).

I'm using the below code and I'm getting an error:

labels['h_count2'] = labels[(labels['Description'].str.contains('Hazard')) & (labels['Description'].str.contains('Roof'))]

This is the traceback:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2656             try:
-> 2657                 return self._engine.get_loc(key)
   2658             except KeyError:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'h_count2'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\managers.py in set(self, item, value)
   1052         try:
-> 1053             loc = self.items.get_loc(item)
   1054         except KeyError:

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2658             except KeyError:
-> 2659                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2660         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'h_count2'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-46-51360ea6f27f> in <module>
      1 labels['h_count'] = labels['Description'].str.contains('Roof Hazard')
      2 labels['b_count'] = labels['Description'].str.contains('Brush')
----> 3 labels['h_count2'] = labels[(labels['Description'].str.contains('Hazard')) & (labels['Description'].str.contains('Roof'))]
      4
      5 def target(row):

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
   3368         else:
   3369             # set column
-> 3370             self._set_item(key, value)
   3371
   3372     def _setitem_slice(self, key, value):

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
   3444         self._ensure_valid_index(value)
   3445         value = self._sanitize_column(key, value)
-> 3446         NDFrame._set_item(self, key, value)
   3447
   3448         # check if we are modifying a copy

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\generic.py in _set_item(self, key, value)
   3170
   3171     def _set_item(self, key, value):
-> 3172         self._data.set(key, value)
   3173         self._clear_item_cache()
   3174

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\managers.py in set(self, item, value)
   1054         except KeyError:
   1055             # This item wasn't present, just insert at end
-> 1056             self.insert(len(self.items), item, value)
   1057             return
   1058

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\managers.py in insert(self, loc, item, value, allow_duplicates)
   1156
   1157         block = make_block(values=value, ndim=self.ndim,
-> 1158                            placement=slice(loc, loc + 1))
   1159
   1160         for blkno, count in _fast_count_smallints(self._blknos[loc:]):

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\blocks.py in make_block(values, placement, klass, ndim, dtype, fastpath)
   3093         values = DatetimeArray._simple_new(values, dtype=dtype)
   3094
-> 3095     return klass(values, ndim=ndim, placement=placement)
   3096
   3097

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\blocks.py in __init__(self, values, placement, ndim)
   2629
   2630         super(ObjectBlock, self).__init__(values, ndim=ndim,
-> 2631                                           placement=placement)
   2632
   2633     @property

C:\ProgramData\Anaconda3\envs\tensorflowenvironment\lib\site-packages\pandas\core\internals\blocks.py in __init__(self, values, placement, ndim)
     85             raise ValueError(
     86                 'Wrong number of items passed {val}, placement implies '
---> 87                 '{mgr}'.format(val=len(self.values), mgr=len(self.mgr_locs)))
     88
     89     def _check_ndim(self, values, ndim):

ValueError: Wrong number of items passed 5, placement implies 1

What am i doing wrong?

Body:
labels = pd.DataFrame({'Description': ['Hazard Roof test', 'test', 'Hazard is not', 'test2']})

labels['h_count2'] = (labels['Description'].str.upper().str.contains('HAZARD')) & ~(labels['Description'].str.upper().str.contains('ROOF'))

    Description        h_count2
0   Hazard Roof test    False
1   test                False
2   Hazard is not       True
3   test2               False


问:
How to pass multiple arguments to a test case in CumulusCI test automation framework?
Problem statement:

Unable to pass multiple variable values to my test case using CumulusCI command:

```<code>`cci task run robot...
</code>```

I am referring this section for building my command: https://cumulusci.readthedocs.io/en/latest/tasks.html#id49

If I have to pass just one variable in the same way as above, say for eg. just LocalOrRemote, then the code works perfectly fine, so it appears that this has to do something with the way I am passing multiple variables.

My test automation tech stack is Robot Framework, CumulusCI, Selenium

Sample Code:

```<code>*** Settings ***
Resource  C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot
Suite Setup  Run Keywords  Suite Setup KW1  AND  Suite Setup OS And Browser  ${LocalOrRemote}  ${Browser}

*** Test Cases ***
Verify whether I am able to set environment and browser
    [Tags]  LocalEdge
    [Documentation]  This test should run on the local edge browser
    Keyword X
    Keyword Y

*** Keywords ***
Suite Setup KW1
    do something
Suite Setup OS And Browser
    [Arguments]  ${LocalOrRemote}  ${Browser}
    Log Many  ${LocalOrRemote}  ${Browser}
    run keyword if  '${LocalOrRemote}'=='Local'  Setup Local Browser  ${Browser}
    ...  ELSE IF  '${LocalOrRemote}'=='Remote'  Setup Remote Browser  ${Browser}
    ...  ELSE  FAIL  "Incorrect environment value passed! Please refer the instructions in README for running the test suite"
</code>```

Command I am using to invoke my test:

```<code>cci task run robot -o suites mypath/MyTestFile.robot -o include LocalEdge -o vars LocalOrRemote:Local,Browser:edge
</code>```

Issue I am facing:

The value of ${Browser} is not received as edge but defaulted to chrome, which means the command is not able to pass on my desired value to the TC.

```<code>KEYWORD BuiltIn . Log Many ${LocalOrRemote}, ${Browser}
Documentation:
Logs the given messages as separate entries using the INFO level.
Start / End / Elapsed:  20190522 16:36:53.877 / 20190522 16:36:53.878 / 00:00:00.001
16:36:53.877    INFO    Local
16:36:53.877    INFO    chrome
</code>```

答:
How to pass multiple arguments to a test case in CumulusCI test automation framework?

The way you are doing it is the correct way: -o vars var1:value1,var2:value2

Here's a really simple example:

```<code>*** Test cases ***
Example
    Should be equal  ${LocalOrRemote}  Local
    Should be equal  ${Browser}        edge
</code>```

Save that to a file and then run it with the robot task like this:

```<code>cci task run robot -o vars LocalOrRemote:Local,Browser:edge -o suites example.robot
</code>```

You will see that the variables are initialized properly. If the wrong browser is opening up, one of your libraries must be changing the value of the ${Browser} variable without you realizing it.

Body:
Problem statement:

Unable to pass multiple variable values to my test case using CumulusCI command:

`cci task run robot...

I am referring this section for building my command: https://cumulusci.readthedocs.io/en/latest/tasks.html#id49

If I have to pass just one variable in the same way as above, say for eg. just LocalOrRemote, then the code works perfectly fine, so it appears that this has to do something with the way I am passing multiple variables.

My test automation tech stack is Robot Framework, CumulusCI, Selenium

Sample Code:

*** Settings ***
Resource  C:/Dev/myproject/robotframework/EnvironmentSetupFile.robot
Suite Setup  Run Keywords  Suite Setup KW1  AND  Suite Setup OS And Browser  ${LocalOrRemote}  ${Browser}

*** Test Cases ***
Verify whether I am able to set environment and browser
    [Tags]  LocalEdge
    [Documentation]  This test should run on the local edge browser
    Keyword X
    Keyword Y

*** Keywords ***
Suite Setup KW1
    do something
Suite Setup OS And Browser
    [Arguments]  ${LocalOrRemote}  ${Browser}
    Log Many  ${LocalOrRemote}  ${Browser}
    run keyword if  '${LocalOrRemote}'=='Local'  Setup Local Browser  ${Browser}
    ...  ELSE IF  '${LocalOrRemote}'=='Remote'  Setup Remote Browser  ${Browser}
    ...  ELSE  FAIL  "Incorrect environment value passed! Please refer the instructions in README for running the test suite"

Command I am using to invoke my test:

cci task run robot -o suites mypath/MyTestFile.robot -o include LocalEdge -o vars LocalOrRemote:Local,Browser:edge

Issue I am facing:

The value of ${Browser} is not received as edge but defaulted to chrome, which means the command is not able to pass on my desired value to the TC.

KEYWORD BuiltIn . Log Many ${LocalOrRemote}, ${Browser}
Documentation:
Logs the given messages as separate entries using the INFO level.
Start / End / Elapsed:  20190522 16:36:53.877 / 20190522 16:36:53.878 / 00:00:00.001
16:36:53.877    INFO    Local
16:36:53.877    INFO    chrome

Body:
How to pass multiple arguments to a test case in CumulusCI test automation framework?

The way you are doing it is the correct way: -o vars var1:value1,var2:value2

Here's a really simple example:

*** Test cases ***
Example
    Should be equal  ${LocalOrRemote}  Local
    Should be equal  ${Browser}        edge

Save that to a file and then run it with the robot task like this:

cci task run robot -o vars LocalOrRemote:Local,Browser:edge -o suites example.robot

You will see that the variables are initialized properly. If the wrong browser is opening up, one of your libraries must be changing the value of the ${Browser} variable without you realizing it.


问:
need help connecting to mysql database
0

hi need to connect to a mysql server i have set up on godaddy.com

my code is

```<code>var dbcon : IDbConnection; //port is 3303
var connectionString : String = "Server=xxxxx.xx.xx.x; Uid=lxxxx; Pwd=xxxx; Database=lxxx;";

dbcon = new SqlConnection(connectionString);
dbcon.Open();
</code>```

however my connection is rejected, i suspect i need to put in a port number.can anyone tell me how would i specify a port number in my connection string?? thx

答: The SQLConnection class is used to connect to SQL Server. To connect to MySQL, you have to use the MySQL .NET Connector.  When using the MySQL Connector, you should be using the class MySQLConnection.  The connection string options reference should be able to help you get all the options correct.  When using the MySQL connector, you don't need to specify the port unless you are using something other than the default, which is 3306.</p>

Title: need help connecting to mysql database

Body:
0

hi need to connect to a mysql server i have set up on godaddy.com

my code is

var dbcon : IDbConnection; //port is 3303
var connectionString : String = "Server=xxxxx.xx.xx.x; Uid=lxxxx; Pwd=xxxx; Database=lxxx;";

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

however my connection is rejected, i suspect i need to put in a port number.can anyone tell me how would i specify a port number in my connection string?? thx


问:
Django Swagger Rest API, tryit now function when api is on different server to ui
I am trying to document our Django Rest API using Django Swagger Rest API where our API is on different server to UI

Trying to change the TryIt now URL for the curl request as the API is on a different server to the UI

I have tried setting url in get_swagger_view, but this appends ui url before this url
I have tried changing base_path in SWAGGER settings but nothing works

答:
Assuming that you tried absolute url and it didn't work, another way to do that is customize the generator instead of using get_swagger_view function. You can change whatever you need, for instance:

```<code>from rest_framework import response, schemas
from rest_framework.decorators import api_view, renderer_classes
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer

class CustomRenderer(OpenAPIRenderer):
    def get_customizations(self):
        data = super().get_customizations()
        data['host'] = 'yourdomain.com/path'
        return data

@api_view()
@renderer_classes([SwaggerUIRenderer, CustomRenderer])
def swagger_view(request):
    generator = schemas.SchemaGenerator(title='Your title')
    return response.Response(generator.get_schema(request=request))
</code>```

Don't forget to configure this function in your urls.py:

```<code>urlpatterns = [
    url(r'docs^$', swagger_view)
]
</code>```

Body:
Assuming that you tried absolute url and it didn't work, another way to do that is customize the generator instead of using get_swagger_view function. You can change whatever you need, for instance:

from rest_framework import response, schemas
from rest_framework.decorators import api_view, renderer_classes
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer

class CustomRenderer(OpenAPIRenderer):
    def get_customizations(self):
        data = super().get_customizations()
        data['host'] = 'yourdomain.com/path'
        return data

@api_view()
@renderer_classes([SwaggerUIRenderer, CustomRenderer])
def swagger_view(request):
    generator = schemas.SchemaGenerator(title='Your title')
    return response.Response(generator.get_schema(request=request))

Don't forget to configure this function in your urls.py:

urlpatterns = [
    url(r'docs^$', swagger_view)
]


问:
how to create a function that gives a prime number + bool value?
I'm struggling since yesterday with this, how to create a function that has a list of prime numbers and returns "prime number + true/false"
ex:

2 true
3 true
4 false
5 true

it's in Swift 5, first func called primecheck is working great, the problem is in the second one PrimeList

```<code>func primecheck (numbers:Int) -> Bool{

    var prime = true

    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }
    if numbers > 2{
        for i in 2...numbers - 1{
            if numbers % i == 0 {
                prime = false

            }

        }
    }
    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }

    if numbers < 0{
        prime = false
    }
    return prime
}

func PrimeList(maxP:Int) -> [(num1:Int, num2:Bool)] {

    var primes: [(num1:Int, num2:Bool)] = []

    for i in 1...maxP {

        if primecheck(numbers:i){
            print(i)
            primes[i - 1] = (i, true)

        } else {
            primes[i - 1] = (i, false)
        }
    }
  //  isPrime[0] = true
  //  isPrime[1] = true

    return primes
}

print(PrimeList(maxP:20))
</code>```

expected output:

```<code>print(primeList(maxP:20))
// 2 true
// 3 true

// 4 false
...
// 20 false
</code>```

but always appears this error:

Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

答:
Your program is crashing because you can't index into an empty array in Swift.  You should use append to add items to your array.

Instead of creating the array by appending items though, this is an ideal place to use map:

```<code>func primeList(maxP: Int) -> [(num1: Int, num2: Bool)] {
    return (1...maxP).map { ($0, primecheck(numbers: $0)) }
}
</code>```

Explanation:

map creates an array.  In this case, it takes each item from the range (1...maxP) and converts it using the provided closure into a tuple of the original value and the result of calling primecheck with that value.  The result is the desired array with the pairing of the values with bools indicating if they are prime.

Your primecheck function can be cleaned up by using guard to immediately return false for numbers not greater than 1.  You can immediately return false if you find a number that evenly divides the input, otherwise return true if none are found.

```<code>func primecheck (numbers:Int) -> Bool {
    guard numbers > 1 else { return false }

    for i in 2..<numbers {
        if numbers % i == 0 {
            return false
        }
    }

    return true
}
</code>```

Notes:

You can further optimize primecheck by abandoning the check for a divisor when i * i > numbers.  Add guard i * i <= numbers else { return true } at the top of the for loop.  Alternatively, make the upper end of your divisor range be Int(sqrt(Double(numbers))).

2...numbers - 1 has been rewritten as 2..<numbers.

Function names should start with a lowercase letter.

Body:
I'm struggling since yesterday with this, how to create a function that has a list of prime numbers and returns "prime number + true/false"
ex:

2 true
3 true
4 false
5 true

it's in Swift 5, first func called primecheck is working great, the problem is in the second one PrimeList

func primecheck (numbers:Int) -> Bool{

    var prime = true

    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }
    if numbers > 2{
        for i in 2...numbers - 1{
            if numbers % i == 0 {
                prime = false

            }

        }
    }
    if numbers == 1 || numbers == 0 || numbers == 2{
        prime = true

    }

    if numbers < 0{
        prime = false
    }
    return prime
}

func PrimeList(maxP:Int) -> [(num1:Int, num2:Bool)] {

    var primes: [(num1:Int, num2:Bool)] = []

    for i in 1...maxP {

        if primecheck(numbers:i){
            print(i)
            primes[i - 1] = (i, true)

        } else {
            primes[i - 1] = (i, false)
        }
    }
  //  isPrime[0] = true
  //  isPrime[1] = true

    return primes
}

print(PrimeList(maxP:20))

expected output:

print(primeList(maxP:20))
// 2 true
// 3 true

// 4 false
...
// 20 false

but always appears this error:

Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

Body:
Your program is crashing because you can't index into an empty array in Swift.  You should use append to add items to your array.

Instead of creating the array by appending items though, this is an ideal place to use map:

func primeList(maxP: Int) -> [(num1: Int, num2: Bool)] {
    return (1...maxP).map { ($0, primecheck(numbers: $0)) }
}

Explanation:

map creates an array.  In this case, it takes each item from the range (1...maxP) and converts it using the provided closure into a tuple of the original value and the result of calling primecheck with that value.  The result is the desired array with the pairing of the values with bools indicating if they are prime.

Your primecheck function can be cleaned up by using guard to immediately return false for numbers not greater than 1.  You can immediately return false if you find a number that evenly divides the input, otherwise return true if none are found.

func primecheck (numbers:Int) -> Bool {
    guard numbers > 1 else { return false }

    for i in 2..<numbers {
        if numbers % i == 0 {
            return false
        }
    }

    return true
}

Notes:

You can further optimize primecheck by abandoning the check for a divisor when i * i > numbers.  Add guard i * i <= numbers else { return true } at the top of the for loop.  Alternatively, make the upper end of your divisor range be Int(sqrt(Double(numbers))).

2...numbers - 1 has been rewritten as 2..<numbers.

Function names should start with a lowercase letter.


问:
Subpages not showing up as children in mainnavigation (Typo3)
I have several pages with subpages in my pagetree as shown below.

My pagetree with subpages

However, the links to the subpages do not seem to be clickable.

I have implemented my navigation in Fluid, as per the code below (which is in the default.html file in the Layouts folder):

```<code><nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="{rl}">Company Name</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
            <f:for each="{mainnavigation}" as="mainnavigationItem">
                <f:if condition="{mainnavigationItem.children}">
                    <f:then>
                        <li class="nav-item {f:if(condition: mainnavigationItem.active, then:'active')} dropdown">
                            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                {mainnavigationItem.title}
                            </a>
                            <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                                <f:for each="{mainnavigationItem.children}" as="child">
                                    <a class="dropdown-item" href="{child.link}" target="{child.target}" title="{child.title}">{child.title}</a>
                                </f:for>
                            </div>
                        </li>
                    </f:then>
                    <f:else>
                        <li class="nav-item {f:if(condition: mainnavigationItem.active, then:'active')}">
                            <a class="nav-link" href="{mainnavigationItem.link}" target="{mainnavigationItem.target}" title="{mainnavigationItem.title}">{mainnavigationItem.title} <span class="sr-only">(current)</span></a>
                        </li>
                    </f:else>
                </f:if>
            </f:for>
        </ul>
    </div>
</nav>
</code>```

And the mainnavigation variable is defined in the configuration of my extension in setup.typoscript as shown below. Note that levels is set to 2, in order to render the subpages.

```<code>  dataProcessing {
            10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
            10 {
                references.fieldName = media
            }
            20 = TYPO3\CMS\Frontend\DataProcessing\MenuProcessor
            20 {
                levels = 2
                includeSpacer = 1
                as = mainnavigation
            }
        }
</code>```

As you can see in the picture below, an arrow is added for the subpages. When I click this arrow or the page title, nothing happens however.

The menu with dropdowns

Additionally I am getting this error in the webconsole:

```<code>Uncaught TypeError: Cannot read property 'fn' of undefined
at util.js:55
at bootstrap.min.js:6
at bootstrap.min.js:6
</code>```

Which refers to:

```<code>$.fn.emulateTransitionEnd = transitionEndEmulator
</code>```

答:
You have a syntax error in your html code.

Your code:

```<code><a class="dropdown-item" href="{child.link}" target="{child.target}" title="{child.title}>{child.title}</a>
</code>```

Should be:

```<code><a class="dropdown-item" href="{child.link}" target="{child.target}" title="{child.title}">{child.title}</a>
</code>```

Missing " after {child.title}, so the  is not closed correctly.

Body:
I have several pages with subpages in my pagetree as shown below.

My pagetree with subpages

However, the links to the subpages do not seem to be clickable.

I have implemented my navigation in Fluid, as per the code below (which is in the default.html file in the Layouts folder):

    Company Name
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

            <f:for each="{mainnavigation}" as="mainnavigationItem">
                <f:if condition="{mainnavigationItem.children}">
                    <f:then>

                                {mainnavigationItem.title}

                                <f:for each="{mainnavigationItem.children}" as="child">
                                    {child.title}
                                </f:for>

                    </f:then>
                    <f:else>

                            {mainnavigationItem.title} (current)

                    </f:else>
                </f:if>
            </f:for>

And the mainnavigation variable is defined in the configuration of my extension in setup.typoscript as shown below. Note that levels is set to 2, in order to render the subpages.

  dataProcessing {
            10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
            10 {
                references.fieldName = media
            }
            20 = TYPO3\CMS\Frontend\DataProcessing\MenuProcessor
            20 {
                levels = 2
                includeSpacer = 1
                as = mainnavigation
            }
        }

As you can see in the picture below, an arrow is added for the subpages. When I click this arrow or the page title, nothing happens however.

The menu with dropdowns

Additionally I am getting this error in the webconsole:

Uncaught TypeError: Cannot read property 'fn' of undefined
at util.js:55
at bootstrap.min.js:6
at bootstrap.min.js:6

Which refers to:

$.fn.emulateTransitionEnd = transitionEndEmulator

Body:
You have a syntax error in your html code.

Your code:

<a class="dropdown-item" href="{child.link}" target="{child.target}" title="{child.title}>{child.title}</a>

Should be:

<a class="dropdown-item" href="{child.link}" target="{child.target}" title="{child.title}">{child.title}</a>

Missing " after {child.title}, so the  is not closed correctly.


问:
Add image to set property without saving it in VB.net
I have developed the code to generated outlook emails from stats data. Stuck at a problem where storing an image is required in the PC as it is needed for replacing the image in HTML outlook body to complete report.
outlook part is achieved via
Imports EAGetMail
Imports EASendMail
Imports Microsoft.Office.Interop.Outlook
Have tried mentioning the image differently have tried input stream also. None of it work while the
Dim attach = OutlookMessage.Attachments.Add property is only accepting a path and not an image.

```<code>Dim captcha2 As Bitmap
 If System.IO.File.Exists("C:\output\Sa7e839.jpg") Then
            System.IO.File.Delete("C:\output\Sa7e839.jpg")
        End If

        captcha2.Save("C:\output\Sa7e839.jpg")

Dim attach = OutlookMessage.Attachments.Add("C:\output\Sa7e839.jpg") ' temp saved file. deletes on rerun of app
attach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "backlog") ' setting property
oMail.HtmlBody = oMail.HtmlBody.Replace("cid:image003.png@01D2B201.94F4FA80", "cid:backlog") ' replacing HTML
</code>```

Expected Result: The image should not need to be saved and then attach as the path the image should moved directly from code to the outlook body mail.

答:
You cannot embed images directly into HTML body - Outlook (which uses Word to render HTML messages) does not support base64 encoded images embedded into the HTML body - they must be added as attachments and referenced by the content id.

And attachments in OOM can only be added from the file system. If you want to create an attachment bypassing the file system, you'd need to use Extended MAPI (C++ or Delphi) or Redemption (any language).

Body:
I have developed the code to generated outlook emails from stats data. Stuck at a problem where storing an image is required in the PC as it is needed for replacing the image in HTML outlook body to complete report.
outlook part is achieved via
Imports EAGetMail
Imports EASendMail
Imports Microsoft.Office.Interop.Outlook
Have tried mentioning the image differently have tried input stream also. None of it work while the
Dim attach = OutlookMessage.Attachments.Add property is only accepting a path and not an image.

Dim captcha2 As Bitmap
 If System.IO.File.Exists("C:\output\Sa7e839.jpg") Then
            System.IO.File.Delete("C:\output\Sa7e839.jpg")
        End If

        captcha2.Save("C:\output\Sa7e839.jpg")

Dim attach = OutlookMessage.Attachments.Add("C:\output\Sa7e839.jpg") ' temp saved file. deletes on rerun of app
attach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "backlog") ' setting property
oMail.HtmlBody = oMail.HtmlBody.Replace("cid:image003.png@01D2B201.94F4FA80", "cid:backlog") ' replacing HTML

Expected Result: The image should not need to be saved and then attach as the path the image should moved directly from code to the outlook body mail.


问:
ValueError: No 'serving_default' in the SavedModel's SignatureDefs. Possible values are 'name_of_my_model'
I am trying to quantize a Tensorflow SavedModel using the following command line:

```<code>tflite_convert \
  --output_file=/tmp/foo.tflite \
  --saved_model_dir=/tmp/saved_model
</code>```

But I get the following Error:

```<code>ValueError: No 'serving_default' in the SavedModel's SignatureDefs. Possible values are 'my model name'
</code>```

I already checked, a signature_def_map was defined when exporting the model.

The command:

```<code>saved_model_cli show --dir /tmp/mobilenet/1 --tag_set serve
</code>```

returns

```<code>The given SavedModel MetaGraphDef contains SignatureDefs with the following keys:
SignatureDef key: 'name_of_my_model'
</code>```

and:

```<code>The given SavedModel SignatureDef contains the following input(s):
  inputs['is_training'] tensor_info:
      dtype: DT_BOOL
      shape: ()
      name: is_training:0
  inputs['question1_embedding'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 35, 300)
      name: question1_embedding:0
  inputs['question2_embedding'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 35, 300)
      name: question2_embedding:0
The given SavedModel SignatureDef contains the following output(s):
  outputs['prediction'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 1)
      name: prediction:0
Method name is: tensorflow/serving/predict
</code>```

答:
You should be able to use the saved_model_signature_key to specify the signature name when converting

```<code>tflite_convert \
         --output_file=/tmp/foo.tflite \
         --saved_model_dir=/tmp/saved_model \
         --saved_model_signature_key='my model name'
</code>```

Body:
I am trying to quantize a Tensorflow SavedModel using the following command line:

tflite_convert \
  --output_file=/tmp/foo.tflite \
  --saved_model_dir=/tmp/saved_model

But I get the following Error:

ValueError: No 'serving_default' in the SavedModel's SignatureDefs. Possible values are 'my model name'

I already checked, a signature_def_map was defined when exporting the model.

The command:

saved_model_cli show --dir /tmp/mobilenet/1 --tag_set serve

returns

The given SavedModel MetaGraphDef contains SignatureDefs with the following keys:
SignatureDef key: 'name_of_my_model'

and:

The given SavedModel SignatureDef contains the following input(s):
  inputs['is_training'] tensor_info:
      dtype: DT_BOOL
      shape: ()
      name: is_training:0
  inputs['question1_embedding'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 35, 300)
      name: question1_embedding:0
  inputs['question2_embedding'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 35, 300)
      name: question2_embedding:0
The given SavedModel SignatureDef contains the following output(s):
  outputs['prediction'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 1)
      name: prediction:0
Method name is: tensorflow/serving/predict

Body:
You should be able to use the saved_model_signature_key to specify the signature name when converting

tflite_convert \
         --output_file=/tmp/foo.tflite \
         --saved_model_dir=/tmp/saved_model \
         --saved_model_signature_key='my model name'


问:
Downloading file programmatically with HTTP authentication
I want to download a file (e.g. http://rapidpich.ir/d/555864) programmatically using php. However, when I attempt to follow the link in my web browser, I'm asked for a username and password.

How can I provide these credentials in PHP and retrieve the file?

答:
Usually to grab a file you'd write something like:

```<code>$file_contents = file_get_contents("http://url.to/file");
</code>```

You may do something other than store into a variable, or you may use a different function.

If the file is protected by HTTP authentication, you can usually specify the credentials in the URI:

```<code>$file_contents = file_get_contents("http://username:password@url.to/file");
</code>```

Hope this helps.

Body:
Usually to grab a file you'd write something like:

$file_contents = file_get_contents("http://url.to/file");

You may do something other than store into a variable, or you may use a different function.

If the file is protected by HTTP authentication, you can usually specify the credentials in the URI:

$file_contents = file_get_contents("http://username:password@url.to/file");

Hope this helps.


答:
labels:

```<code>   A  Description
0  1        Roof
1  2       Hazard
2  3  Roof Hazard

labels['h_count2'] = labels.Description.str.contains('Hazard') & ~labels.Description.str.contains('Roof')
</code>```

Results in

```<code>   A  Description  h_count2
0  1        Roof      False
1  2       Hazard      True
2  3  Roof Hazard     False
</code>```

Title: Making a column of boolean values based on two conditions in pandas dataframe

Body:
labels:

   A  Description
0  1        Roof
1  2       Hazard
2  3  Roof Hazard

labels['h_count2'] = labels.Description.str.contains('Hazard') & ~labels.Description.str.contains('Roof')

Results in

   A  Description  h_count2
0  1        Roof      False
1  2       Hazard      True
2  3  Roof Hazard     False


问:
How to remove columns based on a specific row with 0?
I have the data frame that looks like below:

```<code>Genes     Sample1    Sample2   Sample3   Sample4
A1BG         14         59        11        31
A2M           0        7708       7306       0
A2ML1        64         71       1317       3406
A4GALT      142          0       1195       700
AAAS        1821       1233        0        959
</code>```

I wanted to remove the columns based on a row (Gene: A2M) with 0. So, if any of the samples with 0 for the row A2M should be removed. And the output should look like below:

```<code>Genes     Sample2   Sample3
A1BG         59        11
A2M         7708       7306
A2ML1        71       1317
A4GALT        0       1195
AAAS        1233        0
</code>```

Body:
I have the data frame that looks like below:

Genes     Sample1    Sample2   Sample3   Sample4
A1BG         14         59        11        31
A2M           0        7708       7306       0
A2ML1        64         71       1317       3406
A4GALT      142          0       1195       700
AAAS        1821       1233        0        959

I wanted to remove the columns based on a row (Gene: A2M) with 0. So, if any of the samples with 0 for the row A2M should be removed. And the output should look like below:

Genes     Sample2   Sample3
A1BG         59        11
A2M         7708       7306
A2ML1        71       1317
A4GALT        0       1195
AAAS        1233        0

Body:
An option using tidyverse

library(tidyverse)
df1 %>%
   filter(Genes == "A2M") %>%
   select_if(~is.numeric(.x) & .x != 0) %>%
   names %>%
   select(df1, .)
#  Sample2 Sample3
#1      59      11
#2    7708    7306
#3      71    1317
#4       0    1195
#5    1233       0

data

df1 <- structure(list(Genes = c("A1BG", "A2M", "A2ML1", "A4GALT", "AAAS"
), Sample1 = c(14L, 0L, 64L, 142L, 1821L), Sample2 = c(59L, 7708L,
71L, 0L, 1233L), Sample3 = c(11L, 7306L, 1317L, 1195L, 0L), Sample4 = c(31L,
0L, 3406L, 700L, 959L)), class = "data.frame", row.names = c(NA,
-5L))


问:
Twitter Bootstrap Modal stop Youtube video
I'm very new to javascript and trying to use Twitter bootstrap to get a good looking website up and running quickly.  I know this has something to do with jquery, but I'm not sure how to stop my video when I push the close button or the close icon. </p>

<p>Can someone explain how I can get my video to stop playing because even when I close the window, I can still hear it in the background.  </p>

```<code><!-- Button to trigger modal -->
    <a href="#myModal" role="button" class="btn" data-toggle="modal"><img src="img/play.png"></a>

<!-- Modal -->
  <div id="myModal" class="modal hide fade" tabindex="-1" role=labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria>×</button>
      <h3 id="myModalLabel">I am the header</h3>
    </div>
    <div class="modal-body">
      <p><iframe width="100%" height="315" src="http:com/embed/662KGcqjT5Q" frameborder="0" allowfullscreen></iframe></p>
    </div>
    <div class="modal-footer">
      <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    </div>
  </div>
</code>```

答:
7 years after, we still need to solve this.

We found a best way to fix it (Inspired by RobCalvert123 answer)

```<code>  jQuery(".modal-backdrop, .modal.open .close,.modal.open .btn").live("click", function() {
         // Get iframe opened
         var iframe_open = jQuery('.modal.open');
         // Get src from opened iframe
         var src = iframe_open.attr('src');
         // replace src by src to stop it that's the tips
        iframe_open.attr("src", src);
});
</code>```

Body:
I'm very new to javascript and trying to use Twitter bootstrap to get a good looking website up and running quickly.  I know this has something to do with jquery, but I'm not sure how to stop my video when I push the close button or the close icon.

Can someone explain how I can get my video to stop playing because even when I close the window, I can still hear it in the background.

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

I am the header

      <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>

Body:
7 years after, we still need to solve this.

We found a best way to fix it (Inspired by RobCalvert123 answer)

  jQuery(".modal-backdrop, .modal.open .close,.modal.open .btn").live("click", function() {
         // Get iframe opened
         var iframe_open = jQuery('.modal.open');
         // Get src from opened iframe
         var src = iframe_open.attr('src');
         // replace src by src to stop it that's the tips
        iframe_open.attr("src", src);
});


问:
Customizing Ant Design theme
Im following the official docs but it is not working for me. I installed the less, less-loader and customize-cra and then I added config-overrides.js go the root directory of React app. The config-overrides.js looks like this:

```<code>import { addLessLoader, fixBabelImports, override } from 'customize-cra'

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: {
      '@primary-color': '#1DA57A',
      '@link-color': '#1DA57A',
      '@success-color': '#1DA57A',
      '@warning-color': '#1DA57A',
      '@error-color': '#1DA57A'
    }
  })
)
</code>```

The colors in the app are still default Ant Design colors. What am I missing, please?

Thank you.

答:
The documentation on antd/antd-mobile is incorrect.  You need to perform the fixBabelImports as follows:

// config-overrides.js
const {
    override,
    disableEsLint,
    addLessLoader,
    fixBabelImports
} = require('customize-cra');

module.exports = override(
    fixBabelImports('antd-mobile', {
            libraryDirectory: 'es',
            libraryName: 'antd-mobile',
            style: true
    }),
    fixBabelImports('antd', {
        libraryDirectory: 'es',
        libraryName: 'antd',
        style: true
    }),
    disableEsLint(),
    addLessLoader({
        javascriptEnabled: true
    })
);```

Title: Customizing Ant Design theme

Body:
Im following the official docs but it is not working for me. I installed the less, less-loader and customize-cra and then I added config-overrides.js go the root directory of React app. The config-overrides.js looks like this:

import { addLessLoader, fixBabelImports, override } from 'customize-cra'

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: {
      '@primary-color': '#1DA57A',
      '@link-color': '#1DA57A',
      '@success-color': '#1DA57A',
      '@warning-color': '#1DA57A',
      '@error-color': '#1DA57A'
    }
  })
)

The colors in the app are still default Ant Design colors. What am I missing, please?

Thank you.


问:
Store and retrieve UIColor from Core Data using swift 5
The answers to the following questions are partially depreciated: Storing UIColor object in Core Data and Best way to save and retrieve UIColors to Core Data.

1) 'unarchiveObject(with:)' was deprecated in iOS 12.0: Use +unarchivedObjectOfClass:fromData:error: instead

2) 'archivedData(withRootObject:)' was deprecated in iOS 12.0: Use +archivedDataWithRootObject:requiringSecureCoding:error: instead

```<code>extension UIColor
{
   class func color(withData data:Data) -> UIColor
   { return NSKeyedUnarchiver.unarchiveObject(with: data) as! UIColor }

   func encode() -> Data
   { return NSKeyedArchiver.archivedData(withRootObject: self) }
}
</code>```

Trying to follow the compiler instructions and documentation, I can't get rid of errors. Could someone please clarify the correct equivalent for the above extension methods in Swift 5?

答:
Try the following for Swift 5

```<code>extension UIColor {

     class func color(data:Data) -> UIColor? {
          return try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? UIColor
     }

     func encode() -> Data? {
          return try? NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false)
     }
}
</code>```

Body:
The answers to the following questions are partially depreciated: Storing UIColor object in Core Data and Best way to save and retrieve UIColors to Core Data.

1) 'unarchiveObject(with:)' was deprecated in iOS 12.0: Use +unarchivedObjectOfClass:fromData:error: instead

2) 'archivedData(withRootObject:)' was deprecated in iOS 12.0: Use +archivedDataWithRootObject:requiringSecureCoding:error: instead

extension UIColor
{
   class func color(withData data:Data) -> UIColor
   { return NSKeyedUnarchiver.unarchiveObject(with: data) as! UIColor }

   func encode() -> Data
   { return NSKeyedArchiver.archivedData(withRootObject: self) }
}

Trying to follow the compiler instructions and documentation, I can't get rid of errors. Could someone please clarify the correct equivalent for the above extension methods in Swift 5?

Body:
Try the following for Swift 5

extension UIColor {

     class func color(data:Data) -> UIColor? {
          return try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? UIColor
     }

     func encode() -> Data? {
          return try? NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: false)
     }
}


问:
I've been stuck on this issue for days Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
I am trying to complete a project for class and after asking some of my peers who couldn't figure out the problem I'd like to ask for help.

I've had a read of some of the similar questions that have been asked but I haven't been able to figure out the problem just using those sources.

```<code>private void products_lstValueChanged(javax.swing.event.ListSelectionEvent evt) {
    //whenever this event is triggered update the selected product to be whichever one is highlighted in the list
    //get the selected Value from the list - returned as an OBJECT
    Object selectedObject = (Object)products_lst.getSelectedValue();

    //cast the object to an animal and set as selectedAnimal value
    selectedProduct = (Product)selectedObject;

    updateQuantity();
    }

    private void updateQuantity()
    {
        int stockLevel =selectedProduct.getStockLevel();

        Order latest = currentCustomer.findLatestOrder();

        for(Map.Entry<Integer, OrderLine> oEntry : latest.getOrderLines().entrySet())
        {
            if(oEntry.getValue().getProduct().getProductId() == selectedProduct.getProductId())
            {
                stockLevel-=oEntry.getValue().getQuantity();
            }

        }

        if(selectedProduct != null)
        {
            quantity_cmb.removeAllItems();

            for(int i = 1; i<=stockLevel;i++)
            {
                quantity_cmb.addItem(""+i);
            }
        }
   }
</code>```

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
      at Views.ViewProducts.updateQuantity(ViewProducts.java:233)
      at Views.ViewProducts.products_lstValueChanged(ViewProducts.java:228)

答:
So looking at the exception trace, the exception appears to happen five (233-228) lines after the call to products_lstValueChanged in updateQuantity.

That line is:

```<code>    int stockLevel =selectedProduct.getStockLevel();
</code>```

So selectedProduct is null. This implies products_lst.getSelectedValue() returned null.

So it seems that this code was called when no item was selected. Possibly it had just been deselected. You need to handle that case.

Body:
I am trying to complete a project for class and after asking some of my peers who couldn't figure out the problem I'd like to ask for help.

I've had a read of some of the similar questions that have been asked but I haven't been able to figure out the problem just using those sources.

private void products_lstValueChanged(javax.swing.event.ListSelectionEvent evt) {
    //whenever this event is triggered update the selected product to be whichever one is highlighted in the list
    //get the selected Value from the list - returned as an OBJECT
    Object selectedObject = (Object)products_lst.getSelectedValue();

    //cast the object to an animal and set as selectedAnimal value
    selectedProduct = (Product)selectedObject;

    updateQuantity();
    }

    private void updateQuantity()
    {
        int stockLevel =selectedProduct.getStockLevel();

        Order latest = currentCustomer.findLatestOrder();

        for(Map.Entry<Integer, OrderLine> oEntry : latest.getOrderLines().entrySet())
        {
            if(oEntry.getValue().getProduct().getProductId() == selectedProduct.getProductId())
            {
                stockLevel-=oEntry.getValue().getQuantity();
            }

        }

        if(selectedProduct != null)
        {
            quantity_cmb.removeAllItems();

            for(int i = 1; i<=stockLevel;i++)
            {
                quantity_cmb.addItem(""+i);
            }
        }
   }

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
      at Views.ViewProducts.updateQuantity(ViewProducts.java:233)
      at Views.ViewProducts.products_lstValueChanged(ViewProducts.java:228)

Body:
So looking at the exception trace, the exception appears to happen five (233-228) lines after the call to products_lstValueChanged in updateQuantity.

That line is:

    int stockLevel =selectedProduct.getStockLevel();

So selectedProduct is null. This implies products_lst.getSelectedValue() returned null.

So it seems that this code was called when no item was selected. Possibly it had just been deselected. You need to handle that case.


问:
WPF style overwritten when content applied to UserControl
I have a UserContol for a hyperlink.  I need to dynamically set the content of the button to a database value.

I have looked at this link [1]:Custom button user control style overwritten when content is set and it seems I have most everything from that post.  But I get errors when I try to set the content in the user control.  I am not a WPF programmer so any help in small words would be appreciated.

USER CONTROL

`

```<code><UserControl x:Class="DDC.Controls.LinkButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800"
             x:Name="UserControl">

    <UserControl.Resources>
        <Style x:Key="LinkButtonStyle"    TargetType="{x:Type Button}">
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlLightLightBrushKey}}"/>
            <Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
            <Setter Property="BorderBrush" Value="{StaticResource ButtonNormalBorder}"/>
            <Setter Property="Cursor" Value="Hand" />
            <Setter Property="Padding" Value="5,0,0,0" />
            <Setter Property="ToolTip" Value="Click to Follow Link" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                                                <ContentPresenter

                                  VerticalAlignment="Top">
                            <ContentPresenter.Resources>
                                <Style TargetType="{x:Type TextBlock}">
                                    <Setter Property="TextDecorations" Value="Underline" />
                                    <Setter Property="TextWrapping" Value="Wrap"/>
                                </Style>
                            </ContentPresenter.Resources>
                        </ContentPresenter>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="Foreground" Value="LightGray" />
                </Trigger>
            </Style.Triggers>
        </Style>

    </UserControl.Resources>

    <Grid>
        <Button Name ="btnLinkAddress"
                Style="{DynamicResource LinkButtonStyle}"
                Content="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type LinkButton}}}"
                Width="Auto"
                Height="Auto"
                UseLayoutRounding="True"
                Click="LinkButton_Click" >
        </Button>
    </Grid>
</UserControl>
</code>```

C# Class

```<code>public partial class LinkButton : UserControl
    {

        public new static   DependencyProperty ContentProperty =
           DependencyProperty.Register("Content", typeof(object), typeof(LinkButton));

        public new object Content
        {
            get { return (string)GetValue(ContentProperty); }
            set { SetValue(ContentProperty, value); }
        }

        private void LinkButton_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            TextBlock tb = (TextBlock)btn.Content;
            Uri uri = new System.Uri(tb.Text);
           // Uri uri = new System.Uri(btn.Content.ToString());

            Process.Start(new ProcessStartInfo(uri.AbsoluteUri));
            e.Handled = true;
        }
        public LinkButton()
        {
            InitializeComponent();
        }
</code>```

ERRORS

I get these errors when trying to set the content in the user control

```<code>Content="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type LinkButton}}}"`
</code>```

LinkButton is not supported in a Windows Presentation Foundation (WPF) project.

```<code>Content="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
</code>```

Logical tree depth exceeded while traversing the tree. This could indicate a cycle in the tree.

答:
Rename the property to something else than Content:

```<code>public partial class LinkButton : UserControl
{
    public static DependencyProperty ButtonContentProperty =
       DependencyProperty.Register("ButtonContent", typeof(object), typeof(LinkButton));

    public object ButtonContent
    {
        get { return (string)GetValue(ButtonContentProperty); }
        set { SetValue(ButtonContentProperty, value); }
    }

    private void LinkButton_Click(object sender, RoutedEventArgs e)
    {
        ...
    }
    public LinkButton()
    {
        InitializeComponent();
    }
}
</code>```

...and bind to it like this:

```<code><Button Name ="btnLinkAddress"
        Style="{DynamicResource LinkButtonStyle}"
        Content="{Binding Path=ButtonContent, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
        Width="Auto"
        Height="Auto"
        UseLayoutRounding="True"
        Click="LinkButton_Click" >
</code>```

If you want to set the AncestorType to LinkButton, you should define a namespace mapping:

```<code><Button xmlns:local="clr-namespace:DDC.Controls"
        Name ="btnLinkAddress"
        Style="{DynamicResource LinkButtonStyle}"
        Content="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type local:LinkButton}}}"
        Width="Auto"
        Height="Auto"
        UseLayoutRounding="True"
        Click="LinkButton_Click" >
</code>```

Body:
I have a UserContol for a hyperlink.  I need to dynamically set the content of the button to a database value.

I have looked at this link [1]:Custom button user control style overwritten when content is set and it seems I have most everything from that post.  But I get errors when I try to set the content in the user control.  I am not a WPF programmer so any help in small words would be appreciated.

USER CONTROL

`

<UserControl x:Class="DDC.Controls.LinkButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800"
             x:Name="UserControl">

    <UserControl.Resources>

                            </ContentPresenter.Resources>
                        </ContentPresenter>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

        </Style>

    </UserControl.Resources>

    <Grid>
        <Button Name ="btnLinkAddress"
                Style="{DynamicResource LinkButtonStyle}"
                Content="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type LinkButton}}}"
                Width="Auto"
                Height="Auto"
                UseLayoutRounding="True"
                Click="LinkButton_Click" >
        </Button>
    </Grid>
</UserControl>

C# Class

public partial class LinkButton : UserControl
    {

        public new static   DependencyProperty ContentProperty =
           DependencyProperty.Register("Content", typeof(object), typeof(LinkButton));

        public new object Content
        {
            get { return (string)GetValue(ContentProperty); }
            set { SetValue(ContentProperty, value); }
        }

        private void LinkButton_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            TextBlock tb = (TextBlock)btn.Content;
            Uri uri = new System.Uri(tb.Text);
           // Uri uri = new System.Uri(btn.Content.ToString());

            Process.Start(new ProcessStartInfo(uri.AbsoluteUri));
            e.Handled = true;
        }
        public LinkButton()
        {
            InitializeComponent();
        }

ERRORS

I get these errors when trying to set the content in the user control

Content="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type LinkButton}}}"`

LinkButton is not supported in a Windows Presentation Foundation (WPF) project.

Content="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"

Logical tree depth exceeded while traversing the tree. This could indicate a cycle in the tree.

Body:
Rename the property to something else than Content:

public partial class LinkButton : UserControl
{
    public static DependencyProperty ButtonContentProperty =
       DependencyProperty.Register("ButtonContent", typeof(object), typeof(LinkButton));

    public object ButtonContent
    {
        get { return (string)GetValue(ButtonContentProperty); }
        set { SetValue(ButtonContentProperty, value); }
    }

    private void LinkButton_Click(object sender, RoutedEventArgs e)
    {
        ...
    }
    public LinkButton()
    {
        InitializeComponent();
    }
}

...and bind to it like this:

<Button Name ="btnLinkAddress"
        Style="{DynamicResource LinkButtonStyle}"
        Content="{Binding Path=ButtonContent, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
        Width="Auto"
        Height="Auto"
        UseLayoutRounding="True"
        Click="LinkButton_Click" >

If you want to set the AncestorType to LinkButton, you should define a namespace mapping:

<Button xmlns:local="clr-namespace:DDC.Controls"
        Name ="btnLinkAddress"
        Style="{DynamicResource LinkButtonStyle}"
        Content="{Binding Path=Content, RelativeSource={RelativeSource AncestorType={x:Type local:LinkButton}}}"
        Width="Auto"
        Height="Auto"
        UseLayoutRounding="True"
        Click="LinkButton_Click" >