问:
About Form Validation
Where I am going wrong? Validation is not working. It is printing false on validation.Whereas text form field printing okay whereas validation is printing false.</p>

```<code>Form(
      key: _formKey,
      child: Column(children: <Widget>[
        TextFormField(validator: (val) {
          if (val.length == 6) {
            print('okay');
          } else {
            print('error');
          }
        }),
        TextFormField(

            validator: (val) => val.length == 6 ? 'Okay' : 'dsfj'),
        RaisedButton(
            child: Text('test'),
            onPressed: () {
              if (_formKey.currentState.validate()) {
                print('true');
              } else {
                print('false');
              }
            })
      ]),
    ),
</code>```

答:
Basically I am returning string in validator even if condition validates.Hence (_formKey.currentState.validate()) is returning false in both cases even text form fields validate or not.
So, try to return null if your condition fulfill to avoid such problems.

```<code>TextFormField(validator: (val) => val.length < 6 ? 'Password is too short' : null),
</code>```

Like this.
Thanks

Title: About Form Validation

Body:
Where I am going wrong? Validation is not working. It is printing false on validation.Whereas text form field printing okay whereas validation is printing false.

Form(
      key: _formKey,
      child: Column(children: <Widget>[
        TextFormField(validator: (val) {
          if (val.length == 6) {
            print('okay');
          } else {
            print('error');
          }
        }),
        TextFormField(

            validator: (val) => val.length == 6 ? 'Okay' : 'dsfj'),
        RaisedButton(
            child: Text('test'),
            onPressed: () {
              if (_formKey.currentState.validate()) {
                print('true');
              } else {
                print('false');
              }
            })
      ]),
    ),

Body:
Basically I am returning string in validator even if condition validates.Hence (_formKey.currentState.validate()) is returning false in both cases even text form fields validate or not.
So, try to return null if your condition fulfill to avoid such problems.

TextFormField(validator: (val) => val.length < 6 ? 'Password is too short' : null),

Like this.
Thanks


来源: stackexchange

问:
How to show a loading spinner while waiting on an observable getting data from a service in Angular
I have set up an observable service that helps me persist data, but I need a way to show a loading spinner while the data is waiting to come from the observable.

My service:

```<code>imports [...]

import { Observable, BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class OrganisationsService {
  private organisations$ = new BehaviorSubject<Organisation[]>([
    {
      [...]
    }
  ]);

  constructor(private http: HttpClient) {
    this.http
      .get(
        environment.apicall
      )
      .subscribe((data) => this.organisations$.next(data['organisations']));
  }

  getList(): Observable<Organisation[]> {
    return this.organisations$.asObservable();
  }
</code>```

Here's my component:

```<code>    imports ...

    import UIkit from 'uikit';
    import { Observable } from 'rxjs';

    @Component({
      selector: 'app-organisationlist',
      templateUrl: './organisationlist.component.html',
      styleUrls: ['./organisationlist.component.css']
    })
    export class OrganisationlistComponent implements OnInit {

      public loading = true;

      public organisations$: Observable<Organisation[]>;

      constructor(public organisationsService: OrganisationsService) {}

      ngOnInit() {
        this.getData().then(() => {
          this.loading = false;
        });
      }

      async getData() {
        this.organisations$ = this.organisationsService.getList();
      }
}
</code>```

Here's my layout (uses Uikit):

```<code>  <div *ngIf="loading" uk-spinner></div>
  <div>
    <ul class="uk-list">
      <li *ngFor="let organisation of organisations$ | async">
        {{ organisation.name }}
      </li>
    </ul>
  </div>
</code>```

Obviously, the getData function, although declared async, is not actually async and returns immediately. So this.loading is 'false' OnInit, and therefore it doesn't show.

There are plenty of answers around that show how this might work when the subscription happens in the component, but because this is shared data in a service, I can't find a way to wait on the data before setting this.loading to false.

Many thanks.

答:
Complementary my comment using the nils' operator. I like this solution because is "transparent", see that a call is simply,e.g.

```<code>return this.httpClient.get('.....').pipe(
      indicate(this.loading$))
</code>```

Moreover, You can use with any observable, not only call http. Using rxjs operators for, e.g. make severals http call using forkJoin, or use switchMap to make two calls you has only a pipe, don't overload the calls and don't cause a flick

The operator as

```<code>export const prepare = <T>(callback: () => void) => {
    return (source: Observable<T>): Observable<T> =>
        defer(() => {
            callback();
            return source;
        });
};

export const indicate = <T>(indicator: Subject<boolean>) => {
    let alive = true;
    return (source: Observable<T>): Observable<T> =>
        source.pipe(
            prepare(() =>
                timer(500)
                    .pipe(
                        takeWhile(() => alive),
                        take(1)
                    )
                    .subscribe(() => {
                        indicator.next(true);
                    })
            ),
            finalize(() => {
                alive = false;
                indicator.next(false);
            })
        );
};

export const toClass = <T>(ClassType: { new(): T }) => (
    source: Observable<T>
) => source.pipe(map(val => Object.assign(new ClassType(), val)));
</code>```

I put a timer because I don't want the "loading" is showed if the call not spend more than 500 miliseconds

A service like

```<code>export class DataService {

  loading$ = new Subject<boolean>()

  getData():Observable<any>
  {
    //one call, I simulate a simple response
    //in general will be like this.httpClient.get(....)
    const observable=of('New Data in'+new Date()).pipe(delay(1000))

    return observable.pipe(
      indicate(this.loading$))
  }
}
</code>```

I has, e.g. in our app.component

```<code><button (click)="loadData()">load</button>
{{data}}
<div *ngIf="(dataService.loading$ | async)">
    loading...
</div>
</code>```

And the function loadData

```<code>export class AppComponent  {
  data:any
  //don't forget declare as public
  constructor(public dataService:DataService){}
  loadData()
  {
    this.dataService.getData().subscribe(res=>{
      this.data=res
    })
  }
}
</code>```

Update
Well, I make that $loading belongs to the service, but you can make that $loading belongs to the component and use the pipe in the component

```<code>  loading$ = new Subject<boolean>()
  loadData2()
  {
    this.data="";
    this.dataService.getData2().pipe(
      indicate(this.loading$))
      .subscribe(res=>{
      this.data=res
    })
  }

<div *ngIf="(loading$ | async)">
    loading...
</div>
</code>```

You can see in this stackblitz

ContentLicense: CC BY-SA 4.0

Body:
I have set up an observable service that helps me persist data, but I need a way to show a loading spinner while the data is waiting to come from the observable.

My service:

imports [...]

import { Observable, BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class OrganisationsService {
  private organisations$ = new BehaviorSubject<Organisation[]>([
    {
      [...]
    }
  ]);

  constructor(private http: HttpClient) {
    this.http
      .get(
        environment.apicall
      )
      .subscribe((data) => this.organisations$.next(data['organisations']));
  }

  getList(): Observable<Organisation[]> {
    return this.organisations$.asObservable();
  }

Here's my component:

    imports ...

    import UIkit from 'uikit';
    import { Observable } from 'rxjs';

    @Component({
      selector: 'app-organisationlist',
      templateUrl: './organisationlist.component.html',
      styleUrls: ['./organisationlist.component.css']
    })
    export class OrganisationlistComponent implements OnInit {

      public loading = true;

      public organisations$: Observable<Organisation[]>;

      constructor(public organisationsService: OrganisationsService) {}

      ngOnInit() {
        this.getData().then(() => {
          this.loading = false;
        });
      }

      async getData() {
        this.organisations$ = this.organisationsService.getList();
      }
}

Here's my layout (uses Uikit):

        {{ organisation.name }}

Obviously, the getData function, although declared async, is not actually async and returns immediately. So this.loading is 'false' OnInit, and therefore it doesn't show.

There are plenty of answers around that show how this might work when the subscription happens in the component, but because this is shared data in a service, I can't find a way to wait on the data before setting this.loading to false.

Many thanks.

Body:
Complementary my comment using the nils' operator. I like this solution because is "transparent", see that a call is simply,e.g.

return this.httpClient.get('.....').pipe(
      indicate(this.loading$))

Moreover, You can use with any observable, not only call http. Using rxjs operators for, e.g. make severals http call using forkJoin, or use switchMap to make two calls you has only a pipe, don't overload the calls and don't cause a flick

The operator as

export const prepare = <T>(callback: () => void) => {
    return (source: Observable<T>): Observable<T> =>
        defer(() => {
            callback();
            return source;
        });
};

export const indicate = <T>(indicator: Subject<boolean>) => {
    let alive = true;
    return (source: Observable<T>): Observable<T> =>
        source.pipe(
            prepare(() =>
                timer(500)
                    .pipe(
                        takeWhile(() => alive),
                        take(1)
                    )
                    .subscribe(() => {
                        indicator.next(true);
                    })
            ),
            finalize(() => {
                alive = false;
                indicator.next(false);
            })
        );
};

export const toClass = <T>(ClassType: { new(): T }) => (
    source: Observable<T>
) => source.pipe(map(val => Object.assign(new ClassType(), val)));

I put a timer because I don't want the "loading" is showed if the call not spend more than 500 miliseconds

A service like

export class DataService {

  loading$ = new Subject<boolean>()

  getData():Observable<any>
  {
    //one call, I simulate a simple response
    //in general will be like this.httpClient.get(....)
    const observable=of('New Data in'+new Date()).pipe(delay(1000))

    return observable.pipe(
      indicate(this.loading$))
  }
}

I has, e.g. in our app.component

<button (click)="loadData()">load</button>
{{data}}
<div *ngIf="(dataService.loading$ | async)">
    loading...
</div>

And the function loadData

export class AppComponent  {
  data:any
  //don't forget declare as public
  constructor(public dataService:DataService){}
  loadData()
  {
    this.dataService.getData().subscribe(res=>{
      this.data=res
    })
  }
}

Update
Well, I make that $loading belongs to the service, but you can make that $loading belongs to the component and use the pipe in the component

  loading$ = new Subject<boolean>()
  loadData2()
  {
    this.data="";
    this.dataService.getData2().pipe(
      indicate(this.loading$))
      .subscribe(res=>{
      this.data=res
    })
  }

<div *ngIf="(loading$ | async)">
    loading...
</div>

You can see in this stackblitz


问:
Wordpress Category Image in Categories response using Advanced Custom Fields returning null
I am trying to add a category image field category image in categories response using Advanced Custom Field.

But the field is returning null, here is my code.

```<code>function addCategoryImage(){
    register_rest_field('category', 'categoryImage', array(
        'taxonomy' => 'category',
        'get_callback' => function() {
            $category = get_the_category();
            return get_field('category_image', 'category_' . $category_id);
        }

    ));
};

add_action('rest_api_init', 'addCategoryImage');
</code>```

答:
The get_field('category_image', 'category_' . $category_id); function will not return anything if the category_id is null, so try to return $category and check if dose return anything or not, if it does, you still need to get the term_id if the post can have more than a category then you need to specify the term slug to get the id.

General advice: when dealing with API or internal function always print out all the variables you're using to check if they have any value in the first place. Don't write a full code and do the final test because f there is an issue it's going to be hard to find out where is the cause.

Check more details here:
https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/

Body:
I am trying to add a category image field category image in categories response using Advanced Custom Field.

But the field is returning null, here is my code.

function addCategoryImage(){
    register_rest_field('category', 'categoryImage', array(
        'taxonomy' => 'category',
        'get_callback' => function() {
            $category = get_the_category();
            return get_field('category_image', 'category_' . $category_id);
        }

    ));
};

add_action('rest_api_init', 'addCategoryImage');


问:
GraphQL Clojure: Getting the GQL query fields
I'm using lacinia library for my GraphQL Clojure server.

For this simple schema:

```<code>input QueryConfig {
  startDate: String!
  endDate: String!
}

type MyData{
  x: Float!
  y: Float!
  z: Float!
}

schema {
    query: Query
}

type Query {
  myQuery(config:QueryConfig) : [MyData]
}
</code>```

I'm posting the following query:

```<code>{
  myQuery(config:{startDate:"2020-01-01",endDate:"2020-01-01"}){
    x
  }
}
</code>```

In my resolver code, I would like to know what fields were asked (x in the example above), So I won't over fetch results from my DB and retrieve only the x values.

In the resolver code the context contains :graphql-query key which contains the entire query. However, parsing the query text seems awkward.

```<code>(defn my-resolver
  [context args value]
  ;TODO find out what fields were asked and fetch from DB
  )
</code>```

What would be the right way of getting the query fields?

答:
Lacinia does allow you to preview nested selections:

A field resolver can “preview” what fields will be selected below it
  in the selections tree. This is a tool frequently used to optimize
  data retrieval operations.

Example code from docs:

(require
  '[com.walmartlabs.lacinia.executor :as executor])

(defn resolve-hero
  [context args _]
  (if (executor/selects-field? context :character/friends)
    (fetch-hero-with-friends args)
    (fetch-hero args)))
```

Body:
I'm using lacinia library for my GraphQL Clojure server.

For this simple schema:

input QueryConfig {
  startDate: String!
  endDate: String!
}

type MyData{
  x: Float!
  y: Float!
  z: Float!
}

schema {
    query: Query
}

type Query {
  myQuery(config:QueryConfig) : [MyData]
}

I'm posting the following query:

{
  myQuery(config:{startDate:"2020-01-01",endDate:"2020-01-01"}){
    x
  }
}

In my resolver code, I would like to know what fields were asked (x in the example above), So I won't over fetch results from my DB and retrieve only the x values.

In the resolver code the context contains :graphql-query key which contains the entire query. However, parsing the query text seems awkward.

(defn my-resolver
  [context args value]
  ;TODO find out what fields were asked and fetch from DB
  )

What would be the right way of getting the query fields?


问:
How to make selecteditem text red and bold on trigger (in combobox)
I faced the problem: if I choose item from my combobox and its property .IsNotCorrect is true then make this selecteditem text red and bold and all other items in combobox are black. This is my attempt of doing this but nothing happens:</p>

```<code><ComboBox x:Name="REASON_ID" DisplayMemberPath="Name" IsReadOnly="True" IsEditable="True"
    SelectedItem="{Binding SelectedReason, Mode=TwoWay,
    UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem Content="{DynamicResource lang_Common_SelectItem}"
                          IsEnabled="False"/>
            <CollectionContainer
                 Collection="{Binding Source={StaticResource StaticReasons}}"/>

            <Style TargetType="{x:Type ComboBoxItem}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=SelectedItem.IsNotCorrect, ElementName=REASON_ID}" Value="True">
                        <Setter Property="Foreground" Value="Red" />
                        <Setter Property="FontWeight" Value="Bold" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>

        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>
</code>```

答:
If you want, that all items in drop down list, which IsNotCorrect are bold and red, then remove your Style from displayed collection and put it to the ComboBox.Resources. The binding should also be adjusted:

```<code><ComboBox.Resources>
    <Style TargetType="{x:Type ComboBoxItem}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsNotCorrect}" Value="True">
                <Setter Property="Foreground" Value="Red" />
                <Setter Property="FontWeight" Value="Bold" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ComboBox.Resources>
</code>```

If you want to change the representation in text field, then you have to modify the ControlTemplate of ComboBox.

copy the default ControlTemplate of ComboBox see ComboBox Styles
and
Templates
e.g. to the Resources of element, which contains your ComboBox.

Change the
</Style>
```

Body:
I faced the problem: if I choose item from my combobox and its property .IsNotCorrect is true then make this selecteditem text red and bold and all other items in combobox are black. This is my attempt of doing this but nothing happens:

<ComboBox x:Name="REASON_ID" DisplayMemberPath="Name" IsReadOnly="True" IsEditable="True"
    SelectedItem="{Binding SelectedReason, Mode=TwoWay,
    UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}">
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem Content="{DynamicResource lang_Common_SelectItem}"
                          IsEnabled="False"/>
            <CollectionContainer
                 Collection="{Binding Source={StaticResource StaticReasons}}"/>

            </Style>

        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

Body:
If you want, that all items in drop down list, which IsNotCorrect are bold and red, then remove your Style from displayed collection and put it to the ComboBox.Resources. The binding should also be adjusted:

<ComboBox.Resources>
    <Style TargetType="{x:Type ComboBoxItem}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsNotCorrect}" Value="True">
                <Setter Property="Foreground" Value="Red" />
                <Setter Property="FontWeight" Value="Bold" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ComboBox.Resources>

If you want to change the representation in text field, then you have to modify the ControlTemplate of ComboBox.

copy the default ControlTemplate of ComboBox see ComboBox Styles
and
Templates
e.g. to the Resources of element, which contains your ComboBox.

Change the <Style x:Key="{x:Type ComboBox}" to the <Style
x:Key="UsrDefinedStyle"in the copied code.

Find TextBox with name PART_EditableTextBox and remove Style="{x:Null}" in the copied code.

Set style of your ComboBox to the Style="{StaticResource UsrDefinedStyle}"

Put to the Resources of your ComboBox:

<Style TargetType="{x:Type TextBox}" BasedOn="{x:Null}">
   <Style.Triggers>
      <DataTrigger Binding="{Binding SelectedItem.IsNotCorrect, RelativeSource={RelativeSource AncestorType=ComboBox}}" Value="True">
          <Setter Property="Foreground" Value="Red" />
          <Setter Property="FontWeight" Value="Bold" />
      </DataTrigger>
   </Style.Triggers>
</Style>


问:
Use C dll in windows phone 7
A simple but fundamental question :

Is it possible to use a dll devlopped in C, in my WP7 project ?

How can I do that ?

Thanks.

答:
It is actually possible, as long as you can activate the COM Bridge and be able to register the DLL with the OS. This is not a well-documented capability and it will pretty much get the application rejected from the Marketplace (since it is not one of the officially supported features), but you can certainly do it "just for fun".

Here is what Chris Walshie has to say about it:

http://blog.walshie.me/2010/11/12/windows-phone-7-native-apps-the-missing-link

Yes, it will involve a lot more work, but it was already found that a lot of OEMs are bundling their applications with native DLLs, and that pattern can be successfully used in third-party applications as well (looking at what XDA guys do).

ContentLicense: CC BY-SA 3.0

Title: Use C dll in windows phone 7


问:
How to apply basic authentication in WCF?
I'm implementing a WcfClientFactory

```<code>public class WcfClientFactory : IDisposable
{
    internal const string WildcardConfigurationName = "*";

    //We track all channels created by this instance so they can be destroyed
    private readonly List<WeakReference<IDisposable>> _disposableItems = new List<WeakReference<IDisposable>>();

    public T CreateClient<T>(string configurationName = WildcardConfigurationName, string address=null)
    {
        var factory = new ChannelFactory<T>(configurationName);
        if (!string.IsNullOrWhiteSpace(address))
        {
            factory.Endpoint.Address = new EndpointAddress(address);
        }
        var channel = factory.CreateChannel();
        var clientChannel = (IClientChannel)channel;

        clientChannel.Open();
        _disposableItems.Add(new WeakReference<IDisposable>(clientChannel,false));
        return channel;
    }

    void IDisposable.Dispose()
    {
        //No finalizer is implemented as there are no directly held scarce resources.
        //Presumably the finalizers of items in disposableItems will handle their own teardown
        //if it comes down to it.
        foreach (var reference in _disposableItems)
        {
            IDisposable disposable;
            if (reference.TryGetTarget(out disposable))
            {
                disposable.Dispose();
            }
        }
    }
}
</code>```

So I can create a WCF clientChannel

```<code>var client = _wcfClientFactory.CreateClient<ICrmService>(address);
</code>```

It works fine if the WCF does not have any authentication. Now, we want to add authentication to this factory. How can I do it? I tried below code

```<code>public T CreateClientWithBasicAuthentication<T>(string address)
{
    WSHttpBinding myBinding = new WSHttpBinding();
    myBinding.Security.Mode = SecurityMode.Transport;
    myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

    var factory = new ChannelFactory<T>(myBinding, new EndpointAddress(address));
    var channel = factory.CreateChannel();
    var clientChannel = (IClientChannel)channel;

    ////CrmServiceClient csc = (CrmServiceClient)channel;
    ////csc.ClientCredentials.UserName.UserName = _UserName;
    ////csc.ClientCredentials.UserName.Password = _Password;

    clientChannel.Open();
    _disposableItems.Add(new WeakReference<IDisposable>(clientChannel, false));

    return channel;
}
</code>```

But it generates exception and asks for UserName and Password. How can I set the password and username?

The variable factory has a member of Credential, but it is get only. That's why I think it has to be a way to set credential before call CreateChannel

Thanks

答:
There may be a problem with the description here, your idea is right, here we can set the client authentication credentials.

```<code>var factory = new ChannelFactory<T>(myBinding, new EndpointAddress(address));
            //for HttpClientCredentialType.Basic
            factory.Credentials.UserName.UserName = "administrator";
            factory.Credentials.UserName.Password = "abcd1234!";
            //for window credentials
            //factory.Credentials.Windows.ClientCredential.UserName = "adminsitrator";
            //factory.Credentials.Windows.ClientCredential.Password = "abcd1234!";
            var channel = factory.CreateChannel();
</code>```

Besides, please note that the binding type that the channel factory uses should be consistent with the binding type on the server-side.

Feel free to let me know if the problem still exists.

Body:
I'm implementing a WcfClientFactory

public class WcfClientFactory : IDisposable
{
    internal const string WildcardConfigurationName = "*";

    //We track all channels created by this instance so they can be destroyed
    private readonly List<WeakReference<IDisposable>> _disposableItems = new List<WeakReference<IDisposable>>();

    public T CreateClient<T>(string configurationName = WildcardConfigurationName, string address=null)
    {
        var factory = new ChannelFactory<T>(configurationName);
        if (!string.IsNullOrWhiteSpace(address))
        {
            factory.Endpoint.Address = new EndpointAddress(address);
        }
        var channel = factory.CreateChannel();
        var clientChannel = (IClientChannel)channel;

        clientChannel.Open();
        _disposableItems.Add(new WeakReference<IDisposable>(clientChannel,false));
        return channel;
    }

    void IDisposable.Dispose()
    {
        //No finalizer is implemented as there are no directly held scarce resources.
        //Presumably the finalizers of items in disposableItems will handle their own teardown
        //if it comes down to it.
        foreach (var reference in _disposableItems)
        {
            IDisposable disposable;
            if (reference.TryGetTarget(out disposable))
            {
                disposable.Dispose();
            }
        }
    }
}

So I can create a WCF clientChannel

var client = _wcfClientFactory.CreateClient<ICrmService>(address);

It works fine if the WCF does not have any authentication. Now, we want to add authentication to this factory. How can I do it? I tried below code

public T CreateClientWithBasicAuthentication<T>(string address)
{
    WSHttpBinding myBinding = new WSHttpBinding();
    myBinding.Security.Mode = SecurityMode.Transport;
    myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

    var factory = new ChannelFactory<T>(myBinding, new EndpointAddress(address));
    var channel = factory.CreateChannel();
    var clientChannel = (IClientChannel)channel;

    ////CrmServiceClient csc = (CrmServiceClient)channel;
    ////csc.ClientCredentials.UserName.UserName = _UserName;
    ////csc.ClientCredentials.UserName.Password = _Password;

    clientChannel.Open();
    _disposableItems.Add(new WeakReference<IDisposable>(clientChannel, false));

    return channel;
}

But it generates exception and asks for UserName and Password. How can I set the password and username?

The variable factory has a member of Credential, but it is get only. That's why I think it has to be a way to set credential before call CreateChannel

Thanks

Body:
There may be a problem with the description here, your idea is right, here we can set the client authentication credentials.

var factory = new ChannelFactory<T>(myBinding, new EndpointAddress(address));
            //for HttpClientCredentialType.Basic
            factory.Credentials.UserName.UserName = "administrator";
            factory.Credentials.UserName.Password = "abcd1234!";
            //for window credentials
            //factory.Credentials.Windows.ClientCredential.UserName = "adminsitrator";
            //factory.Credentials.Windows.ClientCredential.Password = "abcd1234!";
            var channel = factory.CreateChannel();

Besides, please note that the binding type that the channel factory uses should be consistent with the binding type on the server-side.

Feel free to let me know if the problem still exists.


问:
Fatal error: Call to a member function prepare() on null
I am trying to access a list of categories and their contents. I have a class called Categories. I keep getting this error. The weird thing is that I've used this same exact code in two other places so far with no problems. All I did here was reuse the code and change all the variables.

```<code>Fatal error: Call to a member function prepare() on null
</code>```

Here is the code to my class:

```<code>    <?php

class Category {
    public function fetch_all() {
        global $pdo;

        $query = $pdo->prepare("SELECT * FROM dd_cat");
        $query->execute();

        return $query->fetchAll();
    }

    public function fetch_data($cat_id) {
        global $pdo;

        $query = $pdo->prepare("SELECT * FROM dd_cat WHERE cat_id = ?");
        $query->bindValue(1, $cat_id);
        $query->execute();

        return $query->fetch();
    }
}

?>
</code>```

And here is the code I am trying to call:

```<code><?php
session_start();
//Add session_start to top of each page//
require_once('includes/config.php');
require_once('includes/header.php');
include_once('includes/category.php');

?>
<link rel="stylesheet" href="css/dd.css">
    <div id="menu">
        <a class="item" href="drop_index.php">Home</a> -
        <a class="item" href="create_topic.php">Create a topic</a> -
        <a class="item" href="create_cat.php">Create a category</a>
        <div id="userbar">
<?php
    if( $user->is_logged_in() )
    {
        echo 'Hello ' . $_SESSION['user_name'] . '. Not you? <a href="logout.php">Sign out</a>';
    }
    else
    {
        echo '<a href="login.php">Sign in</a> or <a href="index.php">create an account</a>.';
    }
?>
        </div>
    </div>

<?php

$category = new Category;
$categories = $category->fetch_all();

?>
    <div id ="wrapper">
        <h1>Categories</h1>
        <section>
            <ul>
                <?php foreach ($categories as $category) { ?>
                    <li><a href="category.php?id=<?php echo $category['cat_id']; ?>">
                        <?php echo $category['cat_title']; ?></a>
                    </li>
                <?php } ?>
            </ul>
        </section>
    </div>
<?php
require_once('includes/footer.php');
?>
</code>```

答:
@delato468 comment must be listed as a solution as it worked for me.

In addition to defining the parameter, the user must pass it too at the time of calling the function

```<code>fetch_data(PDO $pdo, $cat_id)
</code>```

Body:
I am trying to access a list of categories and their contents. I have a class called Categories. I keep getting this error. The weird thing is that I've used this same exact code in two other places so far with no problems. All I did here was reuse the code and change all the variables.

Fatal error: Call to a member function prepare() on null

Here is the code to my class:

    <?php

class Category {
    public function fetch_all() {
        global $pdo;

        $query = $pdo->prepare("SELECT * FROM dd_cat");
        $query->execute();

        return $query->fetchAll();
    }

    public function fetch_data($cat_id) {
        global $pdo;

        $query = $pdo->prepare("SELECT * FROM dd_cat WHERE cat_id = ?");
        $query->bindValue(1, $cat_id);
        $query->execute();

        return $query->fetch();
    }
}

?>

And here is the code I am trying to call:

<?php
session_start();
//Add session_start to top of each page//
require_once('includes/config.php');
require_once('includes/header.php');
include_once('includes/category.php');

?>
<link rel="stylesheet" href="css/dd.css">

        Home -
        Create a topic -
        Create a category

<?php
    if( $user->is_logged_in() )
    {
        echo 'Hello ' . $_SESSION['user_name'] . '. Not you? Sign out';
    }
    else
    {
        echo 'Sign in or create an account.';
    }
?>

<?php

$category = new Category;
$categories = $category->fetch_all();

?>

Categories

                <?php foreach ($categories as $category) { ?>

<a href="category.php?id=<?php echo $category['cat_id']; ?>">
                        <?php echo $category['cat_title']; ?>

                <?php } ?>

<?php
require_once('includes/footer.php');
?>

Body:
@delato468 comment must be listed as a solution as it worked for me.

In addition to defining the parameter, the user must pass it too at the time of calling the function

fetch_data(PDO $pdo, $cat_id)


问:
Jupyter Notebook Widgets: How to make "Filter As You Type" Textbox?
I'm trying to make a "filter as you type" textbox widget in my Jupyter Notebook in which if I write M it displays all players with "M"...if I type O after the M it displays players with "MO" in their name  (e.g. MOHAMED SALAH AND MO SALAH) and so on. The code below works quite well. The ONLY problem I'm having is that it keeps appending to the cell result...so if I write 3 letters it displays 3 tables. I want to clear the previous output so that I'd always have the latest result only. How can I do that?

```<code>import pandas as pd, IPython.display, ipywidgets as widgets
out = widgets.Output()
display(out)

df = pd.DataFrame ({'PLAYER':['MOHAMED SALAH', 'MESSI', 'MO SALAH', 'RONALDO']})
display(df)

textbox = widgets.Text(value='', description='Player:')
display(textbox)

def display_result(value):
    value = str(value['new']).upper()
    if "{" not in value:
        print(value)
        result = df[(df['PLAYER'].str.contains(value))]
        if result.shape[0]>0: display(result)

textbox.observe(display_result)
</code>```

Output:

答:
You are just missing a call to out.clear_output() in your function!

import pandas as pd, IPython.display, ipywidgets as widgets
out = widgets.Output()
display(out)

df = pd.DataFrame ({'PLAYER':['MOHAMED SALAH', 'MESSI', 'MO SALAH', 'RONALDO']})

textbox = widgets.Text(value='', description='Player:')
display(textbox)

def display_result(value):
    value = str(value['new']).upper()
    if "{" not in value:
        result = df[(df['PLAYER'].str.contains(value))]
        out.clear_output()
        if result.shape[0]>0:
            with out:
                display(result)

textbox.observe(display_result)
```

Body:
I'm trying to make a "filter as you type" textbox widget in my Jupyter Notebook in which if I write M it displays all players with "M"...if I type O after the M it displays players with "MO" in their name  (e.g. MOHAMED SALAH AND MO SALAH) and so on. The code below works quite well. The ONLY problem I'm having is that it keeps appending to the cell result...so if I write 3 letters it displays 3 tables. I want to clear the previous output so that I'd always have the latest result only. How can I do that?

import pandas as pd, IPython.display, ipywidgets as widgets
out = widgets.Output()
display(out)

df = pd.DataFrame ({'PLAYER':['MOHAMED SALAH', 'MESSI', 'MO SALAH', 'RONALDO']})
display(df)

textbox = widgets.Text(value='', description='Player:')
display(textbox)

def display_result(value):
    value = str(value['new']).upper()
    if "{" not in value:
        print(value)
        result = df[(df['PLAYER'].str.contains(value))]
        if result.shape[0]>0: display(result)

textbox.observe(display_result)

Output:


问:
Laravel Develoyment on AWS EC2 server
This is the virtualhost configuration.  This is not working. please help me

    ServerName example.com
    DocumentRoot /var/www/html/blog/public

    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>

    <Directory /var/www/html/blog/>
            AllowOverride All
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
```

答:
most common case after deployment is proper permissions. storage and bootstrap should have writeable permissions.

if the problem not about permissions then check the logs of laravel
storage/logs/laravel.log

Title: Laravel Develoyment on AWS EC2 server


问:
navLinks.forEach is not a function
I am making a Responsive Navigation bar and i don't know what is the problem in the function. it should work because the navLinks is defined. So can anyone tell me what is the problem here?

const navSlide = () => {
  const burger = document.querySelector('.burger');
  const nav = document.querySelector('.nav-links');
  const navLinks = document.querySelector('.nav-links li');
  //Toggle Nav
  burger.addEventListener('click', () => {
    nav.classList.toggle('nav-active');
  });
  //Animate Links
  navLinks.forEach((link, index) => {
    link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7}s`;
  });
}

navSlide();
```

答:
The querySelector() method returns the first element within the document that matches the specified selector, or group of selectors whereas querySelectorAll() method returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

Since you want to retrieve all li elements and not just the first li element found inside the .nav-links element, just replace querySelector() with querySelectorAll() in your navLinks variable like this:

```<code>const navLinks = document.querySelectorAll('.nav-links li');
</code>```

Title: navLinks.forEach is not a function

Body:
The querySelector() method returns the first element within the document that matches the specified selector, or group of selectors whereas querySelectorAll() method returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

Since you want to retrieve all li elements and not just the first li element found inside the .nav-links element, just replace querySelector() with querySelectorAll() in your navLinks variable like this:

const navLinks = document.querySelectorAll('.nav-links li');


问:
Is there a way to track my app's search ranking on Apple App Store?
I want to programmatically track my app's search ranking on Apple's app store. Is there any API or website to do this, outside of the 'App Store' app on my iPhone?</p>

答:
You can use the google advance search option like

site:itunes.apple.com/us/ "requires iOS 9 or later"

and then scrape the response.


问:
Windows Forms Separator Control
Where in VS2010 can I find a horizontal separator control, as can be found in Outlook settings (screenshots below)?

https://jira.atlassian.com/secure/attachment/14933/outlook+settings.jpg
http://www.keithfimreite.com/Images/OutlookSettings3.gif

Note: VB.NET preferred, but C# answers okay.

答:
It's not actually included in the standard set of controls (pretty sure it used to be back in the day!) but you can easily create your own or cheat by using a GroupBox with no text and a height of 1px.

UserControl to provide the same thing: (Not written by me, source: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/0d4b986e-3ed0-4933-a15d-4b42e02005a7/)

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

    public LineSeparator()
    {
        InitializeComponent();
        this.Paint += new PaintEventHandler(LineSeparator_Paint);
        this.MaximumSize = new Size(2000, 2);
        this.MinimumSize = new Size(0, 2);
        this.Width = 350;
    }

    private void LineSeparator_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        g.DrawLine(Pens.DarkGray, new Point(0, 0), new Point(this.Width, 0));
        g.DrawLine(Pens.White, new Point(0, 1), new Point(this.Width, 1));
    }
}
</code>```

Title: Windows Forms Separator Control

Body:
It's not actually included in the standard set of controls (pretty sure it used to be back in the day!) but you can easily create your own or cheat by using a GroupBox with no text and a height of 1px.

UserControl to provide the same thing: (Not written by me, source: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/0d4b986e-3ed0-4933-a15d-4b42e02005a7/)

public partial class LineSeparator:UserControl
{

    public LineSeparator()
    {
        InitializeComponent();
        this.Paint += new PaintEventHandler(LineSeparator_Paint);
        this.MaximumSize = new Size(2000, 2);
        this.MinimumSize = new Size(0, 2);
        this.Width = 350;
    }

    private void LineSeparator_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        g.DrawLine(Pens.DarkGray, new Point(0, 0), new Point(this.Width, 0));
        g.DrawLine(Pens.White, new Point(0, 1), new Point(this.Width, 1));
    }
}


问:
Angular how to add 2 values?
I am adding 2 values but not getting the expected result.

For example 1 + 1 = 2 but i am getting 11

My code

```<code>this.newpoint = this.data.point + 1;
console.log(this.newpoint);
</code>```

this.data.point value is 0 but its in string maybe this is the problem ?

答:
var num = 1;
var newpoint = Number(num) + 1;
alert(newpoint);```

TRY THIS

Title: Angular how to add 2 values?

Body:
I am adding 2 values but not getting the expected result.

For example 1 + 1 = 2 but i am getting 11

My code

this.newpoint = this.data.point + 1;
console.log(this.newpoint);

this.data.point value is 0 but its in string maybe this is the problem ?

Body:
var num = 1;
var newpoint = Number(num) + 1;
alert(newpoint);

TRY THIS


问:
how to pass basic authentication in api call in react native using asynch await fetch
i want to call the basic authentication rest api in the react native.how to pass basic authentication headers.getting error - unhandled promise rejection - cant find base64 variable</p>

```<code>  getDataFromAPI=async()=>
{

  var headers = new Headers();
  headers.append("Authorization", "Basic " + base64.encode("admin:admin@123"));
  const endpoint='url'
  const res=await fetch (endpoint,{headers:headers})
  const data=await res.json()
  this.setState({items:data})
}
  _renderItem=({item,index})=>{
    let{cardText,card,cardImage}= styles
return  (
  <TouchableOpacity style={card}>
          <Text style={cardText}>{item.id} Reactor Status:  {item.ph}</Text>
  </TouchableOpacity>
)
}
</code>```

答:
installed
npm i -S base-64
and imported
import {decode as atob, encode as btoa} from 'base-64'

and i got the response from the basic authentication rest api in react native code

```<code>getDataFromAPI=async()=>
{

  var headers = new Headers();
  headers.append("Authorization", "Basic " + btoa("admin:admin@123"));
  const endpoint='url'
  const res=await fetch (endpoint,{headers:headers})
  const data=await res.json()
  this.setState({items:data})
}
</code>```

Body:
i want to call the basic authentication rest api in the react native.how to pass basic authentication headers.getting error - unhandled promise rejection - cant find base64 variable

  getDataFromAPI=async()=>
{

  var headers = new Headers();
  headers.append("Authorization", "Basic " + base64.encode("admin:admin@123"));
  const endpoint='url'
  const res=await fetch (endpoint,{headers:headers})
  const data=await res.json()
  this.setState({items:data})
}
  _renderItem=({item,index})=>{
    let{cardText,card,cardImage}= styles
return  (
  <TouchableOpacity style={card}>
          <Text style={cardText}>{item.id} Reactor Status:  {item.ph}</Text>
  </TouchableOpacity>
)
}

Body:
installed
npm i -S base-64
and imported
import {decode as atob, encode as btoa} from 'base-64'

and i got the response from the basic authentication rest api in react native code

getDataFromAPI=async()=>
{

  var headers = new Headers();
  headers.append("Authorization", "Basic " + btoa("admin:admin@123"));
  const endpoint='url'
  const res=await fetch (endpoint,{headers:headers})
  const data=await res.json()
  this.setState({items:data})
}


问:
what would be the possible approach to go : SQS or SNS?

I am going to make the rails application which integrates the Amazon's cloud services.

I have explore amazon's SNS service which gives the facility of public subscription which i don't want to do. I want to notify only particular subscriber.
For example if I have 5 subscriber in one topic then the notification should be goes to particular  subscriber.

I have also explored amazon's SQS in which i have to write a poller which monitor the queue for message. SQS has also a lock mechanism but the problem is that it is distributed so there would be a chance of getting same message from another copy of queue for process.

I want to know that what would be the possible approach to go.

答:
SQS sounds like what you want.

You can run multiple "worker" processes that compete over messages in the queue.  Each message is only consumed once.  The logic behind the "lock" / timeout that you mention is as follows: if one of your workers were to die after downloading a message, but before processing it, then you want that message to eventually time out and be re-downloaded for processing on another node.

Yes, SQS is built on a polling model.  For example, I have a number of use cases in which I use a minutely cron job to poll for new messages in the queue and take action on any messages found.  This pattern is stupid simple to build and works wonders for a bunch of use cases -- a handy little "client" script that pushes a message into the queue, and the cron activated script that will process that message within a minute or so.

If your message pattern is extremely sparse -- eg, only a few messages a day -- it may seem wasteful to poll constantly while the queue is empty.  It hardly matters.

My original calculation was that a minutely cron job would cost $0.04 (now $0.02) per month.  Since then, SQS added a "Long-Polling" feature that lets you achieve sub-second latency on processing new messages by sending 1 "long-poll" message every 20 seconds to poll an idle queue.  Plus, they dropped the price 50%.  So per month, that's 131k messages (~$0.06), a little bit more expensive, but with near realtime request processing.

Keep in mind that a minutely cron job I described only costs ~$0.04 / month in request load (30d*24h*60m * 1c / 10k msgs).  So at a minutely clip, cost shouldn't really be a concern here.  Even polling every second, the price rises only to $2.59 / mo, not exactly a bank buster.

However, it is possible to avoid frequent polling using a webservice that takes an SNS HTTP message.  Such an architecture would work as follows: client pushes message to SNS, which pushes message to SQS and routes an HTTP request to your webservice, triggering it to drain the queue.  You'd still want to poll the queue hourly or daily, just in case an HTTP request was dropped.  In the end though, I'm not sure I can think of any scenario which really justifies such complexity.  I'd much rather pay $0.04 a month to have a dirt simple cron job polling my queue.


问:
Recycler view showing single item
I am facing a strange error where recyclerview is showing only a single item. Below is code for my recyclerview adapter :

```<code>public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

List<chat> chats;
String username;
final int My=0,Their=1;

public ChatAdapter(List<chat> chats) {
    this.chats = chats;
    this.username = PushApp.getApp().getSPF().getStringData(Constants.ANAME);
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    RecyclerView.ViewHolder viewHolder;
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());

    switch (viewType) {
        case My:
            View v1 = inflater.inflate(R.layout.my_chat_child, parent, false);
            viewHolder = new MyChatHolder(v1);
            break;
        case Their:
            View v2 = inflater.inflate(R.layout.their_chat_child, parent, false);
            viewHolder = new TheirMessageHolder(v2);
            break;
        default:
            View v = inflater.inflate(R.layout.my_chat_child, parent, false);
            viewHolder = new MyChatHolder(v);
            break;
    }

    return viewHolder;

}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    switch (holder.getItemViewType()) {
        case My:
            MyChatHolder myChatHolder = (MyChatHolder) holder;
            myChatHolder.setMyMessage(chats.get(position).getMessage());
            break;

        case Their:
            TheirMessageHolder theirMessageHolder = (TheirMessageHolder) holder;
            theirMessageHolder.setTheirChat(chats.get(position).getFrom(), chats.get(position).getMessage());
            break;
    }
}

@Override
public int getItemViewType(int position) {
    if(username.equalsIgnoreCase(chats.get(position).getFrom()))
        return My;
    return Their;
}

@Override
public int getItemCount() {
    return chats.size();
}}
</code>```

I have already used this code in other app and its working perfectly. I have checked the chats data which is also perfect.

Here's link to git repo layout files:
layout files

答:
content_main.xml as follows

```<code>android:layout_width="match_parent"
android:layout_height="match_parent"
</code>```

IN row_list.xml file make following changes

```<code>android:layout_width="match_parent"
android:layout_height="wrap_content"
</code>```

I make above changes it runs.

Title: Recycler view showing single item

Body:
I am facing a strange error where recyclerview is showing only a single item. Below is code for my recyclerview adapter :

public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

List<chat> chats;
String username;
final int My=0,Their=1;

public ChatAdapter(List<chat> chats) {
    this.chats = chats;
    this.username = PushApp.getApp().getSPF().getStringData(Constants.ANAME);
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    RecyclerView.ViewHolder viewHolder;
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());

    switch (viewType) {
        case My:
            View v1 = inflater.inflate(R.layout.my_chat_child, parent, false);
            viewHolder = new MyChatHolder(v1);
            break;
        case Their:
            View v2 = inflater.inflate(R.layout.their_chat_child, parent, false);
            viewHolder = new TheirMessageHolder(v2);
            break;
        default:
            View v = inflater.inflate(R.layout.my_chat_child, parent, false);
            viewHolder = new MyChatHolder(v);
            break;
    }

    return viewHolder;

}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    switch (holder.getItemViewType()) {
        case My:
            MyChatHolder myChatHolder = (MyChatHolder) holder;
            myChatHolder.setMyMessage(chats.get(position).getMessage());
            break;

        case Their:
            TheirMessageHolder theirMessageHolder = (TheirMessageHolder) holder;
            theirMessageHolder.setTheirChat(chats.get(position).getFrom(), chats.get(position).getMessage());
            break;
    }
}

@Override
public int getItemViewType(int position) {
    if(username.equalsIgnoreCase(chats.get(position).getFrom()))
        return My;
    return Their;
}

@Override
public int getItemCount() {
    return chats.size();
}}

I have already used this code in other app and its working perfectly. I have checked the chats data which is also perfect.

Here's link to git repo layout files:
layout files

Body:
content_main.xml as follows

android:layout_width="match_parent"
android:layout_height="match_parent"

IN row_list.xml file make following changes

android:layout_width="match_parent"
android:layout_height="wrap_content"

I make above changes it runs.


问:
How to produce an array with values in a specific shape?
I would like to create an array with values that range from 0.0 to 1.0 as shown here:
weighting matrix

Basically, the left and top edges should remain close to 1.0 but slowly decay to 0.5 in the corners.
The bottom and right edges should remain close to 0.0
The middle region should be mostly 0.5, and the values should be decaying diagonally from 1.0 to 0.0.

This is what I've tried but it doesn't give me exactly what I would like.

```<code>import numpy as np
import matplotlib.pyplot as plt

def sigmoid(x):
  y = np.zeros(len(x))
  for i in range(len(x)):
    y[i] = 1 / (1 + math.exp(-x[i]))
  return y

sigmoid_ = sigmoid(np.linspace(20, 2.5, 30))
temp1 = np.repeat(sigmoid_.reshape((1,len(sigmoid_))), repeats=10, axis=0)
sigmoid_ = sigmoid(np.linspace(6, 3, 10))
temp2 = np.repeat(sigmoid_.reshape((len(sigmoid_),1)), repeats=30, axis=1)
alpha1 = temp1 + temp2

sigmoid_ = sigmoid(np.linspace(-2.5, -20, 30))
temp1 = np.repeat(sigmoid_.reshape((1,len(sigmoid_))), repeats=10, axis=0)
sigmoid_ = sigmoid(np.linspace(-3, -6, 10))
temp2 = np.repeat(sigmoid_.reshape((len(sigmoid_),1)), repeats=30, axis=1)
alpha2 = temp1 + temp2

alpha = alpha1 + alpha2
alpha = alpha - np.min(alpha)
alpha = alpha / np.max(alpha)

plt.matshow(alpha)
</code>```

Which gives me this: results

Can someone help me?

答:
This is the simplest function I can think of:

```<code>tune_me = 101
x = np.linspace(0, 1, tune_me)
y = np.linspace(0, 1, tune_me)
xv, yv = np.meshgrid(x, y)
sig = 1/(1 + np.exp(tune_me - xv - yv))

plt.matshow(sig)
</code>```

But if you want something specific, you should probably figure out your math (maybe on the math stack exchange) before you try to implement it.

Body:
I would like to create an array with values that range from 0.0 to 1.0 as shown here:
weighting matrix

Basically, the left and top edges should remain close to 1.0 but slowly decay to 0.5 in the corners.
The bottom and right edges should remain close to 0.0
The middle region should be mostly 0.5, and the values should be decaying diagonally from 1.0 to 0.0.

This is what I've tried but it doesn't give me exactly what I would like.

import numpy as np
import matplotlib.pyplot as plt

def sigmoid(x):
  y = np.zeros(len(x))
  for i in range(len(x)):
    y[i] = 1 / (1 + math.exp(-x[i]))
  return y

sigmoid_ = sigmoid(np.linspace(20, 2.5, 30))
temp1 = np.repeat(sigmoid_.reshape((1,len(sigmoid_))), repeats=10, axis=0)
sigmoid_ = sigmoid(np.linspace(6, 3, 10))
temp2 = np.repeat(sigmoid_.reshape((len(sigmoid_),1)), repeats=30, axis=1)
alpha1 = temp1 + temp2

sigmoid_ = sigmoid(np.linspace(-2.5, -20, 30))
temp1 = np.repeat(sigmoid_.reshape((1,len(sigmoid_))), repeats=10, axis=0)
sigmoid_ = sigmoid(np.linspace(-3, -6, 10))
temp2 = np.repeat(sigmoid_.reshape((len(sigmoid_),1)), repeats=30, axis=1)
alpha2 = temp1 + temp2

alpha = alpha1 + alpha2
alpha = alpha - np.min(alpha)
alpha = alpha / np.max(alpha)

plt.matshow(alpha)

Which gives me this: results

Can someone help me?

Body:
This is the simplest function I can think of:

tune_me = 101
x = np.linspace(0, 1, tune_me)
y = np.linspace(0, 1, tune_me)
xv, yv = np.meshgrid(x, y)
sig = 1/(1 + np.exp(tune_me - xv - yv))

plt.matshow(sig)

But if you want something specific, you should probably figure out your math (maybe on the math stack exchange) before you try to implement it.


问:
3D plot of x1 and x2 versus z, where z is defined as z = x1^2 + 0.1*x1 in R
Heres my code:

```<code>x1 = seq(from=0,to=1,length.out=10)
x2 = seq(from=0,to=1,length.out=10)
x1x2 = expand.grid(x1,x2)

z = (x1)^2+0.1*(x1)

z = length(length(x1x2))
x1x2z = data.frame(x1x2,z)
x1x2z

colnames(xyz) = c("x1=","x2","z")
head(x1x2z,3)
plot_ly(x1x2z,x1=~x,x2=~x2,z=~z,color="red")
</code>```

I am getting the error:

```<code>No trace type specified:
  Based on info supplied, a 'scatter3d' trace seems appropriate.
  Read more about this trace type -> https://plot.ly/r/reference/#scatter3d
Error: Tibble columns must have consistent lengths, only values of length one are recycled:
* Length 10: Column `x`
* Length 100: Columns `y`, `z`
</code>```

答:
First of all you have to tidy up in the code from above.
Some naming was not correct in the example, which made the debbuging a bit trickier than necessary.

The main issue with the code was not to set the type of plot you wanted.
this can be done with the type argument of plot_ly. You can use this function in the following way with the use of add trace

```<code>plot_ly(x1x2z, type="scatter3d", mode="markers") %>% add_trace(
x = x1x2z$x1,
y = x1x2z$x2,
z = x1x2z$z,
marker = list(  color = 'rgb(17, 157, 255)',
  size = 20,
  line = list(
    color = 'rgb(231, 99, 250)',
    width = 2
  )
  ))
</code>```

output image for the data in the question and the ploting function above

Body:
Heres my code:

x1 = seq(from=0,to=1,length.out=10)
x2 = seq(from=0,to=1,length.out=10)
x1x2 = expand.grid(x1,x2)

z = (x1)^2+0.1*(x1)

z = length(length(x1x2))
x1x2z = data.frame(x1x2,z)
x1x2z

colnames(xyz) = c("x1=","x2","z")
head(x1x2z,3)
plot_ly(x1x2z,x1=~x,x2=~x2,z=~z,color="red")

I am getting the error:

No trace type specified:
  Based on info supplied, a 'scatter3d' trace seems appropriate.
  Read more about this trace type -> https://plot.ly/r/reference/#scatter3d
Error: Tibble columns must have consistent lengths, only values of length one are recycled:
* Length 10: Column `x`
* Length 100: Columns `y`, `z`

Body:
First of all you have to tidy up in the code from above.
Some naming was not correct in the example, which made the debbuging a bit trickier than necessary.

The main issue with the code was not to set the type of plot you wanted.
this can be done with the type argument of plot_ly. You can use this function in the following way with the use of add trace

plot_ly(x1x2z, type="scatter3d", mode="markers") %>% add_trace(
x = x1x2z$x1,
y = x1x2z$x2,
z = x1x2z$z,
marker = list(  color = 'rgb(17, 157, 255)',
  size = 20,
  line = list(
    color = 'rgb(231, 99, 250)',
    width = 2
  )
  ))

output image for the data in the question and the ploting function above


问:
Does an interface by default extend Object?
If you define a interface like below

```<code>interface I1{

}
</code>```

The in any code section you can write like

```<code>I1 i1;
i1.equals(null);
</code>```

Then from where the equals method come, is the interface also extends the super class Object ?, if that true how an interface can extends a class?

Suppose let the interface extends the super class Object , then if you see why the collection interface like Set thave define the  equals() and hashCode() method ?. All the class extends the Object class so if you define any abstract method in a interface which present in Object class then who implement the interface they no need to implements those method. Like in below code

```<code>interface I1{
String toString();
}

class A implements I1{

}
</code>```

Here the class A no need to implements the method toString() as it's present in Object class.
Then what is the objective  of defining those method in collection interface as they can't force there implementation class to implement those method.

答:
A Java Interface does not extend the java.lang.Object class but instances of objects that implement the interface extend the Object class otherwise if Java Interfaces allowed to extend the java.lang.Object class then Java would support multiple inheritance of which it does not in its language specification.

Consider the scenario below:

```<code>interface MyInterface
{
   // interface methods here
}
MyClass extend java.lang.Object implements MyInterface
{
   // override methods or interface method implementations
}
</code>```

Now if MyInterface extends java.lang.Object class then that would mean the MyClass would also be extending the MyInterface interface by construction creating multiple inheritance. So makes sense that Java interfaces do not extend the java.lang.Object class as this would create chaos due to multiple inheritance.

Body:
If you define a interface like below

interface I1{

}

The in any code section you can write like

I1 i1;
i1.equals(null);

Then from where the equals method come, is the interface also extends the super class Object ?, if that true how an interface can extends a class?

Suppose let the interface extends the super class Object , then if you see why the collection interface like Set thave define the  equals() and hashCode() method ?. All the class extends the Object class so if you define any abstract method in a interface which present in Object class then who implement the interface they no need to implements those method. Like in below code

interface I1{
String toString();
}

class A implements I1{

}

Here the class A no need to implements the method toString() as it's present in Object class.
Then what is the objective  of defining those method in collection interface as they can't force there implementation class to implement those method.

Body:
A Java Interface does not extend the java.lang.Object class but instances of objects that implement the interface extend the Object class otherwise if Java Interfaces allowed to extend the java.lang.Object class then Java would support multiple inheritance of which it does not in its language specification.

Consider the scenario below:

interface MyInterface
{
   // interface methods here
}
MyClass extend java.lang.Object implements MyInterface
{
   // override methods or interface method implementations
}

Now if MyInterface extends java.lang.Object class then that would mean the MyClass would also be extending the MyInterface interface by construction creating multiple inheritance. So makes sense that Java interfaces do not extend the java.lang.Object class as this would create chaos due to multiple inheritance.


问:
How to add a additional menu beside a select option? (react)
I found a greate select lib for react (react-select), but it not supported for nested select options, so I want to know how to add an additional menu beside a select option? it's kind of like the bookmark collection.

here I have a demo :
enter link description here

答:
I have found a solution , antd - cascader menu. it 100% matched my reuirment.
here is the link : https://ant.design/components/cascader/</p>


问:
How to replace NA with set of values
I have the following data frame:

```<code>library(dplyr)
library(tibble)

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df
</code>```

It looks like this:

```<code># A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA
</code>```

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

```<code>  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2
</code>```

How can I achieve that?

答:
Another option :

```<code>transform(df, score = pmin(max(score, na.rm = TRUE) +
                      cumsum(is.na(score)), score, na.rm = TRUE))

#  source score
#1      a    10
#2      b     5
#3      c    11
#4      d     3
#5      e    12
</code>```

If you want to do this in dplyr

```<code>library(dplyr)
df %>% mutate(score = pmin(max(score, na.rm = TRUE) +
                      cumsum(is.na(score)), score, na.rm = TRUE))
</code>```

Title: How to replace NA with set of values

Body:
I have the following data frame:

library(dplyr)
library(tibble)

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df

It looks like this:

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2

How can I achieve that?

Body:
Another option :

transform(df, score = pmin(max(score, na.rm = TRUE) +
                      cumsum(is.na(score)), score, na.rm = TRUE))

#  source score
#1      a    10
#2      b     5
#3      c    11
#4      d     3
#5      e    12

If you want to do this in dplyr

library(dplyr)
df %>% mutate(score = pmin(max(score, na.rm = TRUE) +
                      cumsum(is.na(score)), score, na.rm = TRUE))


问:
Issue with creating an Azure Function "No job functions found" error
What I am trying to achieve is that, I want to be able to create an Azure Function that would upload a video to YouTube using the YouTube API. example:https://developers.google.com/youtube/v3/docs/videos/insert . After creating the azure function, I then want to use that function inside my Azure logic app. Here is the code for the Azure function(uploded video):

```<code>using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

namespace Google.Apis.YouTube.Samples
    {
        /// <summary>
        /// YouTube Data API v3 sample: upload a video.
        /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
        /// See https://developers.google.com/api-client-library/dotnet/get_started
        /// </summary>
        public class UploadVideo
        {
            [STAThread]
            static void Main(string[] args)
            {
                Console.WriteLine("YouTube Data API: Upload Video");
                Console.WriteLine("==============================");

                try
                {
                    new UploadVideo().Run().Wait();
                }
                catch (AggregateException ex)
                {
                    foreach (var e in ex.InnerExceptions)
                    {
                        Console.WriteLine("Error: " + e.Message);
                    }
                }

                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }

            private async Task Run()
            {
                UserCredential credential;
                using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows an application to upload files to the
                        // authenticated user's YouTube channel, but doesn't allow other types of access.
                        new[] { YouTubeService.Scope.YoutubeUpload },
                        "user",
                        CancellationToken.None
                    );
                }

                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
                });

                var video = new Video();
                video.Snippet = new VideoSnippet();
                video.Snippet.Title = "Default Video Title";
                video.Snippet.Description = "Default Video Description";
                video.Snippet.Tags = new string[] { "tag1", "tag2" };
                video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
                video.Status = new VideoStatus();
                video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
                var filePath = @"/Users/sean/Desktop/audio/test1.mp4"; // Replace with path to actual movie file.

                using (var fileStream = new FileStream(filePath, FileMode.Open))
                {
                    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                    videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                    videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                    await videosInsertRequest.UploadAsync();
                }
            }

            void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
            {
                switch (progress.Status)
                {
                    case UploadStatus.Uploading:
                        Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                        break;

                    case UploadStatus.Failed:
                        Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                        break;
                }
            }

            void videosInsertRequest_ResponseReceived(Video video)
            {
                Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
            }
        }
    }
</code>```

When I run this code, I am not seeing the expected outcome like this: https://developers.google.com/youtube/v3/docs/videos#resource . Instead, I am getting an error :

No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

I have made all my methods public. I am not sure what I am missing.

答:
It looks like the wrong template was used when you tried to create an Azure Function, so it created a Console App instead. Right now you're missing Azure Functions specific Nuget packages and I think your project also lacks some Azure Function specific files such as the host.json.

Can you try following these instructions when using Visual Studio:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-your-first-function-visual-studio

Or these instructions when using VS Code:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-first-function-vs-code?pivots=programming-language-csharp

This way you'll end up with a proper structure of a Function App, including the correct dependencies.

Body:
What I am trying to achieve is that, I want to be able to create an Azure Function that would upload a video to YouTube using the YouTube API. example:https://developers.google.com/youtube/v3/docs/videos/insert . After creating the azure function, I then want to use that function inside my Azure logic app. Here is the code for the Azure function(uploded video):

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

namespace Google.Apis.YouTube.Samples
    {
        ///
        /// YouTube Data API v3 sample: upload a video.
        /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
        /// See https://developers.google.com/api-client-library/dotnet/get_started
        ///
        public class UploadVideo
        {
            [STAThread]
            static void Main(string[] args)
            {
                Console.WriteLine("YouTube Data API: Upload Video");
                Console.WriteLine("==============================");

                try
                {
                    new UploadVideo().Run().Wait();
                }
                catch (AggregateException ex)
                {
                    foreach (var e in ex.InnerExceptions)
                    {
                        Console.WriteLine("Error: " + e.Message);
                    }
                }

                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }

            private async Task Run()
            {
                UserCredential credential;
                using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows an application to upload files to the
                        // authenticated user's YouTube channel, but doesn't allow other types of access.
                        new[] { YouTubeService.Scope.YoutubeUpload },
                        "user",
                        CancellationToken.None
                    );
                }

                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
                });

                var video = new Video();
                video.Snippet = new VideoSnippet();
                video.Snippet.Title = "Default Video Title";
                video.Snippet.Description = "Default Video Description";
                video.Snippet.Tags = new string[] { "tag1", "tag2" };
                video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
                video.Status = new VideoStatus();
                video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
                var filePath = @"/Users/sean/Desktop/audio/test1.mp4"; // Replace with path to actual movie file.

                using (var fileStream = new FileStream(filePath, FileMode.Open))
                {
                    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                    videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                    videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                    await videosInsertRequest.UploadAsync();
                }
            }

            void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
            {
                switch (progress.Status)
                {
                    case UploadStatus.Uploading:
                        Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                        break;

                    case UploadStatus.Failed:
                        Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                        break;
                }
            }

            void videosInsertRequest_ResponseReceived(Video video)
            {
                Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
            }
        }
    }

When I run this code, I am not seeing the expected outcome like this: https://developers.google.com/youtube/v3/docs/videos#resource . Instead, I am getting an error :

No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

I have made all my methods public. I am not sure what I am missing.


问:
How to put image to the relevant folder if the percentage is below 50 from Python
```<code> # loop over the indexes of the high confidence class labels
                for (i, j) in enumerate(idxs):
                    label1 = mlb.classes_[j]  # Label
                    label2 = "{:.2f}%".format(proba[j] * 100)  # Percentage
                    label3 = "{}: {:.2f}%".format(mlb.classes_[j], proba[j] * 100)  # Label and Percentage

                    # accuracy = label2[0][i] * 100
                    text = cv2.putText(output, label3, (10, (i * 30) + 25),
                                       cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 100, 0),

                    pat = os.path.split(imagePath)
                    print(pat[0])
                    print(pat[1])

                if label1 == "Looking Straight" and label2 >= str(50):
                    path = "D:/Icorve Project/Learn Neural Networks/Categorical/Looking Straight/{}"
                    print(path.format(pat[1]))
                    cv2.imwrite(path.format(pat[1]), output)

                else:
                    path = "D:/Icorve Project/Learn Neural Networks/Categorical/Looking Away/{}"
</code>```

In here there are three classes. For ex:
     1. Looking Straight

```<code>for an example if i take Looking straight one the label is printing on on the image saying "Looking straight" : 98.25%  its working perfectly. But i want to put below 50 percentage images to another folder. How to do it ???
Label1 = Class name
label2 = Percentage
label 3 = Class name + percentage
</code>```

: GeForce GTX 1050 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1)
WARNING:tensorflow:Error in loading the saved optimizer state. As a result, your model is starting with a freshly initialized optimizer.
[INFO] classifying image...
examples
data_248000_249000.h5_922.png
D:/Icorve Project/Learn Neural Networks/Categorical/Looking Straight/data_248000_249000.h5_922.png
(531, 413)
(531, 413, 3)
(180, 140, 1)

答:
I suppose that the first if is inside the for loop.

Then, you could use:

```<code>proba[j] >= 0.5
</code>```

Instead of

```<code>label2 >= str(50)
</code>```

Body:
 # loop over the indexes of the high confidence class labels
                for (i, j) in enumerate(idxs):
                    label1 = mlb.classes_[j]  # Label
                    label2 = "{:.2f}%".format(proba[j] * 100)  # Percentage
                    label3 = "{}: {:.2f}%".format(mlb.classes_[j], proba[j] * 100)  # Label and Percentage

                    # accuracy = label2[0][i] * 100
                    text = cv2.putText(output, label3, (10, (i * 30) + 25),
                                       cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 100, 0),

                    pat = os.path.split(imagePath)
                    print(pat[0])
                    print(pat[1])

                if label1 == "Looking Straight" and label2 >= str(50):
                    path = "D:/Icorve Project/Learn Neural Networks/Categorical/Looking Straight/{}"
                    print(path.format(pat[1]))
                    cv2.imwrite(path.format(pat[1]), output)

                else:
                    path = "D:/Icorve Project/Learn Neural Networks/Categorical/Looking Away/{}"

In here there are three classes. For ex:
     1. Looking Straight

for an example if i take Looking straight one the label is printing on on the image saying "Looking straight" : 98.25%  its working perfectly. But i want to put below 50 percentage images to another folder. How to do it ???
Label1 = Class name
label2 = Percentage
label 3 = Class name + percentage

: GeForce GTX 1050 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1)
WARNING:tensorflow:Error in loading the saved optimizer state. As a result, your model is starting with a freshly initialized optimizer.
[INFO] classifying image...
examples
data_248000_249000.h5_922.png
D:/Icorve Project/Learn Neural Networks/Categorical/Looking Straight/data_248000_249000.h5_922.png
(531, 413)
(531, 413, 3)
(180, 140, 1)

Body:
I suppose that the first if is inside the for loop.

Then, you could use:

proba[j] >= 0.5

Instead of

label2 >= str(50)


问:
Convert float to String and String to float in Java
How could I convert from float to string or string to float?

In my case I need to make the assertion between 2 values string (value that I have got from table) and float value that I have calculated.

```<code>String valueFromTable = "25";
Float valueCalculated =25.0;
</code>```

I tried from float to string:

```<code>String sSelectivityRate = String.valueOf(valueCalculated);
</code>```

but the assertion fails

答:
There are three ways to convert float to String.

"" + f

Float.toString(f)

String.valueOf(f)

There are two ways Convert String to float

Float.valueOf(str)

Float.parseFloat(str);

Example:-

```<code>public class Test {

    public static void main(String[] args) {
        System.out.println("convert FloatToString " + convertFloatToString(34.0f));

        System.out.println("convert FloatToStr Using Float Method " + convertFloatToStrUsingFloatMethod(23.0f));

        System.out.println("convert FloatToStr Using String Method " + convertFloatToStrUsingFloatMethod(233.0f));

        float f = Float.valueOf("23.00");
    }

    public static String convertFloatToString(float f) {
        return "" + f;
    }

    public static String convertFloatToStrUsingFloatMethod(float f) {
        return Float.toString(f);
    }

    public static String convertFloatToStrUsingStringMethod(float f) {
        return String.valueOf(f);
    }

}
</code>```

Body:
How could I convert from float to string or string to float?

In my case I need to make the assertion between 2 values string (value that I have got from table) and float value that I have calculated.

String valueFromTable = "25";
Float valueCalculated =25.0;

I tried from float to string:

String sSelectivityRate = String.valueOf(valueCalculated);

but the assertion fails

Body:
There are three ways to convert float to String.

"" + f

Float.toString(f)

String.valueOf(f)

There are two ways Convert String to float

Float.valueOf(str)

Float.parseFloat(str);

Example:-

public class Test {

    public static void main(String[] args) {
        System.out.println("convert FloatToString " + convertFloatToString(34.0f));

        System.out.println("convert FloatToStr Using Float Method " + convertFloatToStrUsingFloatMethod(23.0f));

        System.out.println("convert FloatToStr Using String Method " + convertFloatToStrUsingFloatMethod(233.0f));

        float f = Float.valueOf("23.00");
    }

    public static String convertFloatToString(float f) {
        return "" + f;
    }

    public static String convertFloatToStrUsingFloatMethod(float f) {
        return Float.toString(f);
    }

    public static String convertFloatToStrUsingStringMethod(float f) {
        return String.valueOf(f);
    }

}


问:
How can i redirect unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei) using .htaccess?
There is a issue of unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei)

How can I redirect its to main root?

My .htaccess not working, I'm using below code in .htaccess:-

```<code>RewriteEngine On
ErrorDocument 404 /example.com
</code>```

答:
use Complete url of your site. Like this

ErrorDocument 404 https://www.yourdomain.com/example.php

Body:
There is a issue of unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei)

How can I redirect its to main root?

My .htaccess not working, I'm using below code in .htaccess:-

RewriteEngine On
ErrorDocument 404 /example.com


问:
How To Configure openam SAML2 service provider to use NameID Format unspecified
currently, we use openAM version 13.0.0 as a service provider for SAML2 SSO.

How To Configure openAM SAML2 service provider to use NameID Format unspecified?

Edit :
I faced the following issue :

ERROR: spAssertionConsumer.jsp: SSO failed. com.sun.identity.saml2.common.SAML2Exception: No local user being mapped. at com.sun.identity.saml2.profile.SPACSUtils.processResponse(SPACSUtils.java:1225)

答: Given you use spSSOInit.jsp to trigger SP-initiated SSO flow, you can specify the NameID format to be sent (NameIDPolicy element in SAML AuthNRequest) by using request parameter NameIDFormat. If it's supported by the SP and IdP, it will be used. If you do not specify this request parameter, OpenAM tries to find the first NameID format that is supported by both entities. If the IDP does not specify anything, the first NameID format of the hosted SP is used.


问:
Can't get react app working in IE11: Invalid prop `children` supplied to `Provider`
I have a react app I need to add IE11 support to. It's running, but there is an error which makes the app not usable.

The console complains that the prop type is incorrect (which other browser does not complain about):

```<code>Invalid prop `children` supplied to `ModalProvider`
</code>```

I suspect that the issue is Symbol is not being (properly) polyfilled, since when I log the props.children object, it says something about Symbol and undefined, and there are many other issues on StackOverflow describing Symbol, IE11 and polyfill. See screenshot below:

I have tried a lot of different solutions described, but can't remove this error, and therefore get the app to work properly. Do you have any ideas?

The project

First off, the project is two separate react projects, where one (simple react-scripts app that just displays the imported/linked component, lets call it A) links to the other (complex exported module, lets call it B). So I'm not entirely sure which one of them that should be polyfilled, or both.

Webpack.config.js for B:

```<code>var path = require('path')

module.exports = {
  entry: {
    maps: './src/index.js'
  },
  output: {
    path: __dirname + '/dist',
    filename: 'index.js',
    library: 'Map',
    libraryTarget: 'umd'
  },
  module: {
    rules: [
      {
        test: /\.[s]?css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
              localIdentName: '[local]--[sha1:hash:hex:4]'
            }
          },
          'sass-loader'
        ],
        include: /\.module\.[s]?css$/
      },
      {
        test: /\.[s]?css$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
        exclude: /\.module\.[s]?css$/
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
      {
        test: /\.svg$/,
        use: ['@svgr/webpack']
      },
      {
        test: /\.(jpe?g|png)$/i,
        loader: 'file-loader?name=/public/icons/[name].[ext]'
      }
    ]
  },
  resolve: {
    modules: [
      path.resolve(__dirname, 'src'),
      path.resolve(__dirname, 'node_modules')
    ],
    extensions: ['.js', '.jsx']
  },
  externals: {
    // Use external version of React
    react: 'react',
    'react-dom': 'react-dom'
  },
  // NOTE: @claus added options to fix files not being watched
  watchOptions: {
    aggregateTimeout: 300,
    poll: 1000
  }
}
</code>```

package.json browserlist for B:

```<code>"browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all",
      "ie 11"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version",
      "ie 11"
    ]
  }
</code>```

.babelrc for B:

```<code>{
  "presets": [
    ["@babel/preset-env"],
    "@babel/preset-react"],
  "plugins": ["@babel/plugin-proposal-object-rest-spread"]
}
</code>```

答:
Have you followed the below steps to support react app in IE 11?

Install the package: npm install react-app-polyfill.

Add import 'react-app-polyfill/ie11'; import 'react-app-polyfill/stable'; at the first line in src/index.js.

Add ie 11 in packge.json like this:

You can restart your app and it will work in IE11.

And I think you should polyfill both react projects to make both of them compatible with IE 11. If the error still persists, it could be better if you provide a minimal, reproducible sample so that we can test on our sides.

Body:
I have a react app I need to add IE11 support to. It's running, but there is an error which makes the app not usable.

The console complains that the prop type is incorrect (which other browser does not complain about):

Invalid prop `children` supplied to `ModalProvider`

I suspect that the issue is Symbol is not being (properly) polyfilled, since when I log the props.children object, it says something about Symbol and undefined, and there are many other issues on StackOverflow describing Symbol, IE11 and polyfill. See screenshot below:

I have tried a lot of different solutions described, but can't remove this error, and therefore get the app to work properly. Do you have any ideas?

The project

First off, the project is two separate react projects, where one (simple react-scripts app that just displays the imported/linked component, lets call it A) links to the other (complex exported module, lets call it B). So I'm not entirely sure which one of them that should be polyfilled, or both.

Webpack.config.js for B:

var path = require('path')

module.exports = {
  entry: {
    maps: './src/index.js'
  },
  output: {
    path: __dirname + '/dist',
    filename: 'index.js',
    library: 'Map',
    libraryTarget: 'umd'
  },
  module: {
    rules: [
      {
        test: /\.[s]?css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
              localIdentName: '[local]--[sha1:hash:hex:4]'
            }
          },
          'sass-loader'
        ],
        include: /\.module\.[s]?css$/
      },
      {
        test: /\.[s]?css$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
        exclude: /\.module\.[s]?css$/
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
      {
        test: /\.svg$/,
        use: ['@svgr/webpack']
      },
      {
        test: /\.(jpe?g|png)$/i,
        loader: 'file-loader?name=/public/icons/[name].[ext]'
      }
    ]
  },
  resolve: {
    modules: [
      path.resolve(__dirname, 'src'),
      path.resolve(__dirname, 'node_modules')
    ],
    extensions: ['.js', '.jsx']
  },
  externals: {
    // Use external version of React
    react: 'react',
    'react-dom': 'react-dom'
  },
  // NOTE: @claus added options to fix files not being watched
  watchOptions: {
    aggregateTimeout: 300,
    poll: 1000
  }
}

package.json browserlist for B:

"browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all",
      "ie 11"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version",
      "ie 11"
    ]
  }

.babelrc for B:

{
  "presets": [
    ["@babel/preset-env"],
    "@babel/preset-react"],
  "plugins": ["@babel/plugin-proposal-object-rest-spread"]
}


问:
Android BottomSheet: How can I know if user is dragging up or down the bottomsheet?
I have an app with bottomsheet opened upto 90% of the screen height. How can I know if the user is dragging up/down the bottomsheet. I read we can use onSlide() but the offset values are NaN and sometimes outright weird, so it seems kinda unreliable. Any help is appreciated. Thanks in advance.</p>

答:
You can add a BottomSheetCallback to know the status and the direction.

Something like:

```<code>    BottomSheetBehavior<...> bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetLayout);

    bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {

      @Override public void onStateChanged(@NonNull View bottomSheet, int newState) {
        if (newState == BottomSheetBehavior.STATE_DRAGGING){
            // Dragging state
        }
      }

      @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) {
        // The new offset of this bottom sheet within [-1,1] range.
        // Offset increasesas this bottom sheet is moving upward.
        // From 0 to 1 the sheet is between collapsed and expanded states and
        // From -1 to 0 it is between hidden and collapsed states.
      }
    });
</code>```

Body:
You can add a BottomSheetCallback to know the status and the direction.

Something like:

    BottomSheetBehavior<...> bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetLayout);

    bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {

      @Override public void onStateChanged(@NonNull View bottomSheet, int newState) {
        if (newState == BottomSheetBehavior.STATE_DRAGGING){
            // Dragging state
        }
      }

      @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) {
        // The new offset of this bottom sheet within [-1,1] range.
        // Offset increasesas this bottom sheet is moving upward.
        // From 0 to 1 the sheet is between collapsed and expanded states and
        // From -1 to 0 it is between hidden and collapsed states.
      }
    });


问:
Formatting x-axis labels as time values in Chart.js
Using chart.js I would like to reformat my bottom chart labels into MM DD format (ie. Feb 2)
How do I get chart.js to recognize the data as dates and convert it?
It comes in like this from my csv file:
2020-02-06

Here is my chart.js coding but it doesn't seem to work.

```<code>    data: {
            labels: dollar.years,
            datasets: [
              {label: 'Cdn dollar in cents',
                data: dollar.vals,
                fill: false,
                borderColor: '#4BD0B0',
                pointRadius: 0,
                borderWidth: 8
              }
                      ]
                },

          options: {
          legend:{
          display:false,
          usePointStyle: true,

          labels: {
          boxwidth:10,
          rotation:90
                    }
                  },

          scales: {

          yAxes: [{
          gridLines:{
          display:true
                    },

          ticks: {
          min: .74,
          max: .76,
          stepSize: .025,
                }
                }],

          xAxes: [{
          gridLines:{
          display:true
                },
          ticks: {
          labelOffset: 1,
                },
                  }],
                  }
                  }
        });
      }
</code>```

答:
All you need is to define your xAxis as a time cartesian axis with a 'day' unit.

The default display format of 'day' is 'MMM D' (for instance 'Feb 2').

```<code>options: {
    ...
    scales: {
        xAxes: [{
            type: 'time',
            time: {
                unit: 'day',
                tooltipFormat: 'MMM DD'
            }
            ...
        }]
    }
    ...
}
</code>```

Please have a look at the following runnable code snippet:

new Chart(document.getElementById('myChart'), {
  type: 'line',
  data: {
    labels: ['2020-02-06', '2020-02-07', '2020-02-08', '2020-02-09', '2020-02-10', '2020-02-11', '2020-02-12'],
    datasets: [{
      label: 'My Dataset',
      data: [0.758, 0.756, 0.755, 0.754, 0.753, 0.758, 0.76],
      fill: false,
      backgroundColor: 'green',
      borderColor: 'green'
    }]
  },
  options: {
    responsive: true,
    title: {
      display: false
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          min: .74,
          max: .76,
          stepSize: .005
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          unit: 'day',
          tooltipFormat: 'MMM DD'
        }
      }],
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="80"></canvas></code>```

Body:
Using chart.js I would like to reformat my bottom chart labels into MM DD format (ie. Feb 2)
How do I get chart.js to recognize the data as dates and convert it?
It comes in like this from my csv file:
2020-02-06

Here is my chart.js coding but it doesn't seem to work.

    data: {
            labels: dollar.years,
            datasets: [
              {label: 'Cdn dollar in cents',
                data: dollar.vals,
                fill: false,
                borderColor: '#4BD0B0',
                pointRadius: 0,
                borderWidth: 8
              }
                      ]
                },

          options: {
          legend:{
          display:false,
          usePointStyle: true,

          labels: {
          boxwidth:10,
          rotation:90
                    }
                  },

          scales: {

          yAxes: [{
          gridLines:{
          display:true
                    },

          ticks: {
          min: .74,
          max: .76,
          stepSize: .025,
                }
                }],

          xAxes: [{
          gridLines:{
          display:true
                },
          ticks: {
          labelOffset: 1,
                },
                  }],
                  }
                  }
        });
      }

Body:
All you need is to define your xAxis as a time cartesian axis with a 'day' unit.

The default display format of 'day' is 'MMM D' (for instance 'Feb 2').

options: {
    ...
    scales: {
        xAxes: [{
            type: 'time',
            time: {
                unit: 'day',
                tooltipFormat: 'MMM DD'
            }
            ...
        }]
    }
    ...
}

Please have a look at the following runnable code snippet:

new Chart(document.getElementById('myChart'), {
  type: 'line',
  data: {
    labels: ['2020-02-06', '2020-02-07', '2020-02-08', '2020-02-09', '2020-02-10', '2020-02-11', '2020-02-12'],
    datasets: [{
      label: 'My Dataset',
      data: [0.758, 0.756, 0.755, 0.754, 0.753, 0.758, 0.76],
      fill: false,
      backgroundColor: 'green',
      borderColor: 'green'
    }]
  },
  options: {
    responsive: true,
    title: {
      display: false
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          min: .74,
          max: .76,
          stepSize: .005
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          unit: 'day',
          tooltipFormat: 'MMM DD'
        }
      }],
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="80"></canvas>