问:
Pass variables to second Map in RXJS
I have the following:

```<code>zip(this.baskets$.asObservable(), this.products$.asObservable()).
pipe(
  map(([baskets, products]) => /* get basket and product */),
  map(([basket, product]) => /* use basket and product in condition */)
);
</code>```

How to in first Map get the basket and product with given basketId and productId?

I know how to get them ... Something like:

```<code>let basket = baskets.find(x => x.id == data.basketId);

let product = products.find(x => x.id == data.productId);
</code>```

But how to pass and be able to use both in second map:

```<code>map(([basket, product]) => /* use basket and product in condition */)
</code>```

答:
You were almost there:

```<code>zip(this.baskets$,this.products$).pipe(
      map(([baskets,products]) => {
        const basket = baskets.find(bskt => bskt.id === this.data.basketId);
        const product = products.find(prdct => prdct.id === this.data.productId);
        return [basket,product];
      }),
      map(([basket,product]) => /*now use them here*/)
    )
</code>```

Of course they might be undefined in the second map if the ids were not found.

Title: Pass variables to second Map in RXJS

Body:
I have the following:

zip(this.baskets$.asObservable(), this.products$.asObservable()).
pipe(
  map(([baskets, products]) => /* get basket and product */),
  map(([basket, product]) => /* use basket and product in condition */)
);

How to in first Map get the basket and product with given basketId and productId?

I know how to get them ... Something like:

let basket = baskets.find(x => x.id == data.basketId);

let product = products.find(x => x.id == data.productId);

But how to pass and be able to use both in second map:

map(([basket, product]) => /* use basket and product in condition */)

Body:
You were almost there:

zip(this.baskets$,this.products$).pipe(
      map(([baskets,products]) => {
        const basket = baskets.find(bskt => bskt.id === this.data.basketId);
        const product = products.find(prdct => prdct.id === this.data.productId);
        return [basket,product];
      }),
      map(([basket,product]) => /*now use them here*/)
    )

Of course they might be undefined in the second map if the ids were not found.


来源: stackexchange

问:
copy specific folders under main folder
Think that I have a main-folder. Under main-folder there are my-folder-x type folders.
Under my-folder-x type folders there are both folders and some files.

```<code>-main-folder
 -my-folder-a
   -build-folder
   -demo-folder
   dummy.js
   dummy.css
   my.json
   -dummy-folder
 -my-folder-b
   -build-folder
   -demo-folder
   dummy.js
   dummy.css
   my.json
   -dummy-folder
 -my-folder-c
   -build-folder
   -demo-folder
   dummy.js
   dummy.css
   my.json
</code>```

I want to copy that folders with specific folder/files.So I want to copy that folders to copied-folder like this:

```<code>-copied-folder
  -my-folder-a
    -build-folder
    -demo-folder
  -my-folder-b
     -build-folder
     -demo-folder
  -my-folder-c
     -build-folder
     -demo-folder
</code>```

I need this to work on cross-platforms like Windows, Unix...

I'm trying ncp package.There is a filter option but I think it's for only filenames not folder.

https://github.com/AvianFlu/ncp

Any idea?

Note:I also need files and folders to be copied under build-folder and demo-folder. It can be folders or files under that two types of folders.

Note2: The project is using npm. For example I use rimraf npm package to delete folders.It's cross platform.Both work on Windows and Mac

https://www.npmjs.com/package/rimraf

答:
This find + cp should work with gnu utilities installed on Unix, Windows, Mac etc:

```<code>cd main-folder
find . \( -path '*/build-folder/*' -o -path '*/demo-folder/*' \) \
-exec cp --parents '{}' copied-folder \;
</code>```

GNU Utils on Windows

ContentLicense: CC BY-SA 4.0

Title: copy specific folders under main folder

Body:
Think that I have a main-folder. Under main-folder there are my-folder-x type folders.
Under my-folder-x type folders there are both folders and some files.

-main-folder
 -my-folder-a
   -build-folder
   -demo-folder
   dummy.js
   dummy.css
   my.json
   -dummy-folder
 -my-folder-b
   -build-folder
   -demo-folder
   dummy.js
   dummy.css
   my.json
   -dummy-folder
 -my-folder-c
   -build-folder
   -demo-folder
   dummy.js
   dummy.css
   my.json

I want to copy that folders with specific folder/files.So I want to copy that folders to copied-folder like this:

-copied-folder
  -my-folder-a
    -build-folder
    -demo-folder
  -my-folder-b
     -build-folder
     -demo-folder
  -my-folder-c
     -build-folder
     -demo-folder

I need this to work on cross-platforms like Windows, Unix...

I'm trying ncp package.There is a filter option but I think it's for only filenames not folder.

https://github.com/AvianFlu/ncp

Any idea?

Note:I also need files and folders to be copied under build-folder and demo-folder. It can be folders or files under that two types of folders.

Note2: The project is using npm. For example I use rimraf npm package to delete folders.It's cross platform.Both work on Windows and Mac

https://www.npmjs.com/package/rimraf

Body:
This find + cp should work with gnu utilities installed on Unix, Windows, Mac etc:

cd main-folder
find . \( -path '*/build-folder/*' -o -path '*/demo-folder/*' \) \
-exec cp --parents '{}' copied-folder \;

GNU Utils on Windows


问:
Warning for public method used just in class
Is there a way to make the IntelliJ Idea inspections or checkstyle to give you a warning when a public method is used only in the class where it is defined?

I had the impression that this was possible a while ago, but in the latest weeks I notice that this is not the case (anymore).

答:
In IntelliJ IDEA, it is one of the inspections. "Declaration access can be weaker".

In the Preferences dialog -> Editor -> Inspections -> Java -> Declaration redundancy -> Declaration access can be weaker.


问:
How do I prevent a component from rendering twice?
I want to initialize a component but it keeps rendering all the time.

According to the documentation I use React.memo but that doesn't prevent the component from rerendering: console.log("re-render") prints more than once. How do I make that component exactly static no matter what happens above in the tree?

```<code>const Canvas = React.memo((props) => {
    const context = useContext(Context);
    const width = "500%";
    const height = "500%";

    const count = useRef(0);

    useEffect(() => {
        context.initCanvas("c");
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []); //runs only once on mount

    console.log("re-render"); //outputs all the time when I cange something above in the tree.

    return (
        <>
            <canvas
                style={{border: "1px dashed black", margin: "10px"}}
                id="c"
                width={width}
                height={height}
            >
            </canvas>
        </>
    );
});
</code>```

答:
It looks like you are incrementing the count here:

```<code> Count: {count.current++}
</code>```

If you are only displaying a value you should not mutate it on the render.

You can handle this increment in other part of the code, maybe write a method that increment your counter and just apply it when its necessary. Other solution is to create a useEffect that will handle this counter.

In this case you are incrementing your value very time because you are making this operation on the render method.

Body:
I want to initialize a component but it keeps rendering all the time.

According to the documentation I use React.memo but that doesn't prevent the component from rerendering: console.log("re-render") prints more than once. How do I make that component exactly static no matter what happens above in the tree?

const Canvas = React.memo((props) => {
    const context = useContext(Context);
    const width = "500%";
    const height = "500%";

    const count = useRef(0);

    useEffect(() => {
        context.initCanvas("c");
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []); //runs only once on mount

    console.log("re-render"); //outputs all the time when I cange something above in the tree.

    return (
        <>
            <canvas
                style={{border: "1px dashed black", margin: "10px"}}
                id="c"
                width={width}
                height={height}
            >
            </canvas>
        </>
    );
});

Body:
It looks like you are incrementing the count here:

 Count: {count.current++}

If you are only displaying a value you should not mutate it on the render.

You can handle this increment in other part of the code, maybe write a method that increment your counter and just apply it when its necessary. Other solution is to create a useEffect that will handle this counter.

In this case you are incrementing your value very time because you are making this operation on the render method.


问:
Realm Database locale support
I am investigating the internationalisation of my Xamarin mobile application. We use Realm as the local storage.

Does anyone know the status of the locale support in Realm, or of any limitations in this regard.

Thanks in advance.

答:
I recommend you to use resx files for localization. This is the documentation link where you can find some samples.

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/localization/text?pivots=windows

other option could be using json files for each language that you want to support.

You can use IMarkupExtension to set the key in the xaml and with the IMarkupExtension class return the correct value depending your device language.

```<code>     Text="{locale:YourLocalizationMarkupExtension Name}"
</code>```

Title: Realm Database locale support

Body:
I recommend you to use resx files for localization. This is the documentation link where you can find some samples.

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/localization/text?pivots=windows

other option could be using json files for each language that you want to support.

You can use IMarkupExtension to set the key in the xaml and with the IMarkupExtension class return the correct value depending your device language.

     Text="{locale:YourLocalizationMarkupExtension Name}"


问:
Make React useEffect hook not run on initial render
According to the docs:

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

We can use the new useEffect() hook to simulate componentDidUpdate(), but it seems like useEffect() is being ran after every render, even the first time. How do I get it to not run on initial render?

As you can see in the example below, componentDidUpdateFunction is printed during the initial render but componentDidUpdateClass was not printed during the initial render.

function ComponentDidUpdateFunction() {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    console.log("componentDidUpdateFunction");
  });

  return (

componentDidUpdateFunction: {count} times

      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>

  );
}

class ComponentDidUpdateClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  componentDidUpdate() {
    console.log("componentDidUpdateClass");
  }

  render() {
    return (

componentDidUpdateClass: {this.state.count} times

        <button
          onClick={() => {
            this.setState({ count: this.state.count + 1 });
          }}
        >
          Click Me
        </button>

    );
  }
}

ReactDOM.render(

    <ComponentDidUpdateFunction />
    <ComponentDidUpdateClass />

,
  document.querySelector("#app")
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div></code>```

答:
@MehdiDehghani, your solution work perfectly fine, one addition you have to do is on unmount, reset the didMount.current value to false. When to try to use this custom hook somewhere else, you don't get cache value.

```<code>import React, { useEffect, useRef } from 'react';

const useDidMountEffect = (func, deps) => {
    const didMount = useRef(false);

    useEffect(() => {
        let unmount;
        if (didMount.current) unmount = func();
        else didMount.current = true;

        return () => {
            didMount.current = false;
            unmount && unmount();
        }
    }, deps);
}

export default useDidMountEffect;
</code>```

Body:
@MehdiDehghani, your solution work perfectly fine, one addition you have to do is on unmount, reset the didMount.current value to false. When to try to use this custom hook somewhere else, you don't get cache value.

import React, { useEffect, useRef } from 'react';

const useDidMountEffect = (func, deps) => {
    const didMount = useRef(false);

    useEffect(() => {
        let unmount;
        if (didMount.current) unmount = func();
        else didMount.current = true;

        return () => {
            didMount.current = false;
            unmount && unmount();
        }
    }, deps);
}

export default useDidMountEffect;


问:
How to know which user has been authenticated in Bot framework v4 using C#?
I have a bot made using framework v4 with c#. It has been authenticated using azure ad. List of user has been added in azure ad. once a user has been login, do we have any way to know which used has login.Can we know the name or email id of the user in bot.

I have followed this link for the authentication of bot with ad.

https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-authentication?view=azure-bot-service-4.0&tabs=csharp

The image shown in emulator:

The code

```<code>public class MainDialog : ComponentDialog
{
private readonly IBotServices _botServices;
protected readonly ILogger _logger;
private readonly UserState _userState;

private readonly string _connectionName;

private readonly IConfiguration _configuration;
public MainDialog(IConfiguration configuration,ILogger<MainDialog> logger, IBotServices botServices)
    : base(nameof(MainDialog))
{
    _configuration = configuration;
    _logger = logger;
    _botServices = botServices ?? throw new System.ArgumentNullException(nameof(botServices));
    _connectionName = configuration["ConnectionName"];

    AddDialog(new OAuthPrompt(
      nameof(OAuthPrompt),
      new OAuthPromptSettings
      {
          ConnectionName = configuration["ConnectionName"],
          Text = "Please Sign In",
          Title = "Sign In",
          Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
      }));

    AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));

    AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));
    AddDialog(new luisandqnamakerDialog(_botServices,_configuration,_logger));
    AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
    {
        PromptStepAsync,
        LoginStepAsync
    }));

    // The initial child Dialog to run.
    InitialDialogId = nameof(WaterfallDialog);
}

private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
    return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
}

private async Task<DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{

    // Get the token from the previous step. Note that we could also have gotten the
    // token directly from the prompt itself. There is an example of this in the next method.
    var tokenResponse = (TokenResponse)stepContext.Result;
    if (tokenResponse != null)
    {
        if (IsAuthCodeStep(stepContext.Context.Activity.Text))
        {
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("You are now logged in."), cancellationToken);
            return await stepContext.NextAsync();
        }
        else
        {
             await stepContext.PromptAsync(nameof(luisandqnamakerDialog), new PromptOptions { Prompt = MessageFactory.Text("Would you like to ask your question?") }, cancellationToken);
            return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
        }
    }

    await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

    return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
}

private bool IsAuthCodeStep(string code)
{
    if (string.IsNullOrEmpty(code) || !code.Length.Equals(6)) return false;
    if (!int.TryParse(code, out int result)) return false;
    if (result > 1) return true;
    return false;
}

protected override async Task<DialogTurnResult> OnBeginDialogAsync(DialogContext innerDc, object options, CancellationToken cancellationToken = default(CancellationToken))
{
    var result = await InterruptAsync(innerDc, cancellationToken);
    if (result != null)
    {
        return result;
    }

    return await base.OnBeginDialogAsync(innerDc, options, cancellationToken);
}

protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
{
    var result = await InterruptAsync(innerDc, cancellationToken);
    if (result != null)
    {
        return result;
    }

    return await base.OnContinueDialogAsync(innerDc, cancellationToken);
}

private async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
{
    if (innerDc.Context.Activity.Type == ActivityTypes.Message)
    {
        var text = innerDc.Context.Activity.Text.ToLowerInvariant();

        if (text == "logout")
        {
            // The bot adapter encapsulates the authentication processes.
            var botAdapter = (BotFrameworkAdapter)innerDc.Context.Adapter;
            await botAdapter.SignOutUserAsync(innerDc.Context, _connectionName, null, cancellationToken);
            await innerDc.Context.SendActivityAsync(MessageFactory.Text("You have been signed out."), cancellationToken);
            return await innerDc.CancelAllDialogsAsync(cancellationToken);
        }
    }

    return null;
}
}
</code>```

答:
You are following the correct documentation. If you take a look at the sample 24.bot-authentication-msgraph, the Bot Framework v4 bot authentication is using MS Graph sample. This sample utilizes the Graph API to retrieve the data about the user.Once you set up an AADv2 application and add the scopes, you can test the bot sample locally on the Emulator. Once you are logged in, if you type 'me', it will return back the user name.

Here is an example of how the sample works in the Emulator:

Hope this helps.

Body:
I have a bot made using framework v4 with c#. It has been authenticated using azure ad. List of user has been added in azure ad. once a user has been login, do we have any way to know which used has login.Can we know the name or email id of the user in bot.

I have followed this link for the authentication of bot with ad.

https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-authentication?view=azure-bot-service-4.0&tabs=csharp

The image shown in emulator:

The code

public class MainDialog : ComponentDialog
{
private readonly IBotServices _botServices;
protected readonly ILogger _logger;
private readonly UserState _userState;

private readonly string _connectionName;

private readonly IConfiguration _configuration;
public MainDialog(IConfiguration configuration,ILogger<MainDialog> logger, IBotServices botServices)
    : base(nameof(MainDialog))
{
    _configuration = configuration;
    _logger = logger;
    _botServices = botServices ?? throw new System.ArgumentNullException(nameof(botServices));
    _connectionName = configuration["ConnectionName"];

    AddDialog(new OAuthPrompt(
      nameof(OAuthPrompt),
      new OAuthPromptSettings
      {
          ConnectionName = configuration["ConnectionName"],
          Text = "Please Sign In",
          Title = "Sign In",
          Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
      }));

    AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));

    AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));
    AddDialog(new luisandqnamakerDialog(_botServices,_configuration,_logger));
    AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
    {
        PromptStepAsync,
        LoginStepAsync
    }));

    // The initial child Dialog to run.
    InitialDialogId = nameof(WaterfallDialog);
}

private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
    return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
}

private async Task<DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{

    // Get the token from the previous step. Note that we could also have gotten the
    // token directly from the prompt itself. There is an example of this in the next method.
    var tokenResponse = (TokenResponse)stepContext.Result;
    if (tokenResponse != null)
    {
        if (IsAuthCodeStep(stepContext.Context.Activity.Text))
        {
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("You are now logged in."), cancellationToken);
            return await stepContext.NextAsync();
        }
        else
        {
             await stepContext.PromptAsync(nameof(luisandqnamakerDialog), new PromptOptions { Prompt = MessageFactory.Text("Would you like to ask your question?") }, cancellationToken);
            return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
        }
    }

    await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

    return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
}

private bool IsAuthCodeStep(string code)
{
    if (string.IsNullOrEmpty(code) || !code.Length.Equals(6)) return false;
    if (!int.TryParse(code, out int result)) return false;
    if (result > 1) return true;
    return false;
}

protected override async Task<DialogTurnResult> OnBeginDialogAsync(DialogContext innerDc, object options, CancellationToken cancellationToken = default(CancellationToken))
{
    var result = await InterruptAsync(innerDc, cancellationToken);
    if (result != null)
    {
        return result;
    }

    return await base.OnBeginDialogAsync(innerDc, options, cancellationToken);
}

protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
{
    var result = await InterruptAsync(innerDc, cancellationToken);
    if (result != null)
    {
        return result;
    }

    return await base.OnContinueDialogAsync(innerDc, cancellationToken);
}

private async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
{
    if (innerDc.Context.Activity.Type == ActivityTypes.Message)
    {
        var text = innerDc.Context.Activity.Text.ToLowerInvariant();

        if (text == "logout")
        {
            // The bot adapter encapsulates the authentication processes.
            var botAdapter = (BotFrameworkAdapter)innerDc.Context.Adapter;
            await botAdapter.SignOutUserAsync(innerDc.Context, _connectionName, null, cancellationToken);
            await innerDc.Context.SendActivityAsync(MessageFactory.Text("You have been signed out."), cancellationToken);
            return await innerDc.CancelAllDialogsAsync(cancellationToken);
        }
    }

    return null;
}
}


问:
Autofac - Injecting Keyed service with NamedParameter into constructor
I have a Keyed service registered in Autofac that I would like to be injected via the constructor.
The service is registered

```<code>builder.Register((ctx, par) =>
{
    var namedParameter = par.Named<string>("myNamedParameter");
    ... configuration and instantiation ...
}).Keyed<IMyService>(myKey);
</code>```

and is currently being resolved explicitly

```<code>public class MyConsumer {
    private readonly IMyService _myService;

    //current
    public MyConsumer(ILifetimeScope scope) {
        _myService = _scope.ResolveKeyed<IMyService>(myKey, new NamedParameter("myNamedParameter", "parameterValue"));
    }

    //preferred
    public MyConsumer(IMyService myService) {
        _myService = myService;
    }
}
</code>```

However, I haven't been able to find a way to have said service injected during construction. Autofac's KeyFilterAttribute only accepts a key; it doesn't appear to allow for NamedParameters. Is this possible?

答:
NamedService is a specialized version of KeyedService where the key is of type String.

both

```<code>c.RegisterType<T>().Named<IT>("x");
c.RegisterType<T>().Keyed<IT>("x");
</code>```

are equivalent.

You can use

```<code>public MyConsumer([KeyFilter("x")]IMyService myService) {
    _myService = myService;
}
</code>```

and it will resolve the service named "x" of type IMyService

Body:
I have a Keyed service registered in Autofac that I would like to be injected via the constructor.
The service is registered

builder.Register((ctx, par) =>
{
    var namedParameter = par.Named<string>("myNamedParameter");
    ... configuration and instantiation ...
}).Keyed<IMyService>(myKey);

and is currently being resolved explicitly

public class MyConsumer {
    private readonly IMyService _myService;

    //current
    public MyConsumer(ILifetimeScope scope) {
        _myService = _scope.ResolveKeyed<IMyService>(myKey, new NamedParameter("myNamedParameter", "parameterValue"));
    }

    //preferred
    public MyConsumer(IMyService myService) {
        _myService = myService;
    }
}

However, I haven't been able to find a way to have said service injected during construction. Autofac's KeyFilterAttribute only accepts a key; it doesn't appear to allow for NamedParameters. Is this possible?

Body:
NamedService is a specialized version of KeyedService where the key is of type String.

both

c.RegisterType<T>().Named<IT>("x");
c.RegisterType<T>().Keyed<IT>("x");

are equivalent.

You can use

public MyConsumer([KeyFilter("x")]IMyService myService) {
    _myService = myService;
}

and it will resolve the service named "x" of type IMyService


问:
What is meant by NSXMLParserErrorDomain error 1549
I am trying to parse a xml document using NSXMLParser. Every time it result in  NSXMLParserErrorDomain error 1549. I cant find any documentation regarding that error code.

Any help.

-Shakthi

答:
This is probably a problem with resolving a DTD in the XML. Try disabling DTD downloading with this code:</p>

```<code>[parser setShouldResolveExternalEntities:NO]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is probably a problem with resolving a DTD in the XML. Try disabling DTD downloading with this code:

[parser setShouldResolveExternalEntities:NO]


问:
Filter dictionary on the basis of key value present in list
I have a dictionary D1 like this

and a list L1 like this

I want to have a dictionary like this (Filtering those key-value pairs whose key is present in the list )

So, I tried D1.Where(x => L1.Contains(x.Key)) but i got a dictionary of 2 rows with empry string in key and value.

Please advise.

答:
You can use some thing like this :

```<code>Dictionary<string, int> dictionary = new Dictionary<string, int> {{"A", 1}, {"B", 2}, {"C", 3}};

List<string> list = new List<string> {"A","B"};

var result = dictionary.Where(x => list.Contains(x.Key)).ToList();
</code>```

or

```<code>var result = dictionary.Where(x => list.Contains(x.Key)).ToDictionary(x=>x.Key,x=>x.Value);
</code>```

Body:
You can use some thing like this :

Dictionary<string, int> dictionary = new Dictionary<string, int> {{"A", 1}, {"B", 2}, {"C", 3}};

List<string> list = new List<string> {"A","B"};

var result = dictionary.Where(x => list.Contains(x.Key)).ToList();

or

var result = dictionary.Where(x => list.Contains(x.Key)).ToDictionary(x=>x.Key,x=>x.Value);


问:
Gstreamer does not work with other user than mendel
I have a google coral dev board. I want the gstreamer plugin to work with user other than default user mendel .I performed the following steps and ran into problem.

Installed the gstreamer using the following command.

sudo apt-get install -y gstreamer1.0-plugins-bad gstreamer1.0-plugins-good python3-gst-1.0 python3-gi

Then cloned the mendel user in the following script.

```<code>SRC=$1
DEST=$2

SRC_GROUPS=$(id -Gn ${SRC} | sed "s/${SRC} //g" | sed "s/ ${SRC}//g" | sed "s/ /,/g")
SRC_SHELL=$(awk -F : -v name=${SRC} '(name == $1) { print $7 }' /etc/passwd)

useradd --groups ${SRC_GROUPS} --shell ${SRC_SHELL} --create-home ${DEST}
passwd ${DEST}
</code>```

3. If we save the above file under the name clone-user.sh.
Then use the following command

  ./clone-user.sh mendel user2.

If we switch to the user created above using sudo su - user2 and run the command the gst-launch-1.0 videotestsrc ! waylandsink. Then gstreamer wont work.

Where as the command gst-launch-1.0 videotestsrc ! waylandsink works if we are using a default user. In my case it is mendel.

I have tried the  link. But it also doesnot work.

答:
You can get the new user's id with:

```<code>$ echo $UID
</code>```

copy the files from /run/user/1000 to the new user's id:

```<code>$ cp -r /run/user/1000 /run/user/$UID
</code>```

own it:

```<code>$ sudo chown username:username -R /run/user/$UID/*
</code>```

set XDG_RUNTIME_DIR:

```<code>$ export XDG_RUNTIME_DIR=/run/user/1000
</code>```

I'm able to do this and run the edgetpu_classify and gst-launch-1.0 with both mendel and root.

Body:
I have a google coral dev board. I want the gstreamer plugin to work with user other than default user mendel .I performed the following steps and ran into problem.

Installed the gstreamer using the following command.

sudo apt-get install -y gstreamer1.0-plugins-bad gstreamer1.0-plugins-good python3-gst-1.0 python3-gi

Then cloned the mendel user in the following script.

SRC=$1
DEST=$2

SRC_GROUPS=$(id -Gn ${SRC} | sed "s/${SRC} //g" | sed "s/ ${SRC}//g" | sed "s/ /,/g")
SRC_SHELL=$(awk -F : -v name=${SRC} '(name == $1) { print $7 }' /etc/passwd)

useradd --groups ${SRC_GROUPS} --shell ${SRC_SHELL} --create-home ${DEST}
passwd ${DEST}

3. If we save the above file under the name clone-user.sh.
Then use the following command

  ./clone-user.sh mendel user2.

If we switch to the user created above using sudo su - user2 and run the command the gst-launch-1.0 videotestsrc ! waylandsink. Then gstreamer wont work.

Where as the command gst-launch-1.0 videotestsrc ! waylandsink works if we are using a default user. In my case it is mendel.

I have tried the  link. But it also doesnot work.

Body:
You can get the new user's id with:

$ echo $UID

copy the files from /run/user/1000 to the new user's id:

$ cp -r /run/user/1000 /run/user/$UID

own it:

$ sudo chown username:username -R /run/user/$UID/*

set XDG_RUNTIME_DIR:

$ export XDG_RUNTIME_DIR=/run/user/1000

I'm able to do this and run the edgetpu_classify and gst-launch-1.0 with both mendel and root.


问:
SUM and SUMIF with an array argument
This works:

```<code>=SUM(SUMIF(A2:A9, {"Allen","James","Carol"} , F2:F9))
</code>```

This does NOT work :

```<code>=SUM(SUMIF(A2:A9, {G2,G3,G4} , F2:F9))
</code>```

G2, G3, G4 are cell addresses

I also tried this (This does NOT work as well):

Create a string in cell A15 which resolves to {"Allen","James","Carol"}

```<code>=SUM(SUMIF(A2:A9, {$A$15} , F2:F9))
</code>```

Any help greatly appreciated!!

答:
Use =SUM(SUMIF(A2:A9, G2:G4, F2:F9)).

Since this is an array formula, you may then have to confirm the formula with Ctrl+Shift+Enter, depending on your version of Excel,

Title: SUM and SUMIF with an array argument

Body:
This works:

=SUM(SUMIF(A2:A9, {"Allen","James","Carol"} , F2:F9))

This does NOT work :

=SUM(SUMIF(A2:A9, {G2,G3,G4} , F2:F9))

G2, G3, G4 are cell addresses

I also tried this (This does NOT work as well):

Create a string in cell A15 which resolves to {"Allen","James","Carol"}

=SUM(SUMIF(A2:A9, {$A$15} , F2:F9))

Any help greatly appreciated!!


问:
Ambiguous behaviour of strcmp()
Please note that I have checked the relevant questions to this title, but from my point of view they are not related to this question.

Initially I thought that program1 and program2 would give me the same result.

```<code>//Program 1

char *a = "abcd";
char *b = "efgh";
printf("%d", strcmp(a,b));

//Output: -4

</code>```

```<code>//Program 2
printf("%d", strcmp("abcd", "efgh"));

//Output: -1
</code>```

Only difference that I can spot is that in the program2 I have passed string literal, while in program I've passed char * as the argument of the strcmp() function.

Why there is a difference between the behaviour of these seemingly same program?

Platform: Linux mint
compiler: g++

Edit: Actually the program1 always prints the difference of ascii code of the first mismatched characters, but the program2 print -1 if the ascii code of the first mismatched character in string2 is greater than that of string1 and vice versa.

答:
This is your C code:

```<code>int x1()
{
  char *a = "abcd";
  char *b = "efgh";
  printf("%d", strcmp(a,b));
}

int x2()
{
  printf("%d", strcmp("abcd", "efgh"));
}
</code>```

And this is the generated assembly output for both functions:

```<code>.LC0:
        .string "abcd"
.LC1:
        .string "efgh"
.LC2:
        .string "%d"
x1:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 16
        mov     QWORD PTR [rbp-8], OFFSET FLAT:.LC0
        mov     QWORD PTR [rbp-16], OFFSET FLAT:.LC1
        mov     rdx, QWORD PTR [rbp-16]
        mov     rax, QWORD PTR [rbp-8]
        mov     rsi, rdx
        mov     rdi, rax
        call    strcmp              // the strcmp function is actually called
        mov     esi, eax
        mov     edi, OFFSET FLAT:.LC2
        mov     eax, 0
        call    printf
        nop
        leave
        ret

x2:
        push    rbp
        mov     rbp, rsp
        mov     esi, -1             // strcmp is never called, the compiler
                                    // knows what the result will be and it just
                                    // uses -1
        mov     edi, OFFSET FLAT:.LC2
        mov     eax, 0
        call    printf
        nop
        pop     rbp
        ret
</code>```

When the compiler sees strcmp("abcd", "efgh") it knows the result beforehand, because it knows that "abcd" comes before "efgh".

But if it sees strcmp(a,b) it does not know and hence generates code that actually calls strcmp.

With another compiler or with different compiler settings things could be different. You really shouldn't care about such details at least at a beginner's level.

Title: Ambiguous behaviour of strcmp()

Body:
Please note that I have checked the relevant questions to this title, but from my point of view they are not related to this question.

Initially I thought that program1 and program2 would give me the same result.

//Program 1

char *a = "abcd";
char *b = "efgh";
printf("%d", strcmp(a,b));

//Output: -4

//Program 2
printf("%d", strcmp("abcd", "efgh"));

//Output: -1

Only difference that I can spot is that in the program2 I have passed string literal, while in program I've passed char * as the argument of the strcmp() function.

Why there is a difference between the behaviour of these seemingly same program?

Platform: Linux mint
compiler: g++

Edit: Actually the program1 always prints the difference of ascii code of the first mismatched characters, but the program2 print -1 if the ascii code of the first mismatched character in string2 is greater than that of string1 and vice versa.

Body:
This is your C code:

int x1()
{
  char *a = "abcd";
  char *b = "efgh";
  printf("%d", strcmp(a,b));
}

int x2()
{
  printf("%d", strcmp("abcd", "efgh"));
}

And this is the generated assembly output for both functions:

.LC0:
        .string "abcd"
.LC1:
        .string "efgh"
.LC2:
        .string "%d"
x1:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 16
        mov     QWORD PTR [rbp-8], OFFSET FLAT:.LC0
        mov     QWORD PTR [rbp-16], OFFSET FLAT:.LC1
        mov     rdx, QWORD PTR [rbp-16]
        mov     rax, QWORD PTR [rbp-8]
        mov     rsi, rdx
        mov     rdi, rax
        call    strcmp              // the strcmp function is actually called
        mov     esi, eax
        mov     edi, OFFSET FLAT:.LC2
        mov     eax, 0
        call    printf
        nop
        leave
        ret

x2:
        push    rbp
        mov     rbp, rsp
        mov     esi, -1             // strcmp is never called, the compiler
                                    // knows what the result will be and it just
                                    // uses -1
        mov     edi, OFFSET FLAT:.LC2
        mov     eax, 0
        call    printf
        nop
        pop     rbp
        ret

When the compiler sees strcmp("abcd", "efgh") it knows the result beforehand, because it knows that "abcd" comes before "efgh".

But if it sees strcmp(a,b) it does not know and hence generates code that actually calls strcmp.

With another compiler or with different compiler settings things could be different. You really shouldn't care about such details at least at a beginner's level.


问:
I need to modify this shell script to match the parameters in between the two specified by user
I have this script and i need to modify it so that there are 2 inputs from the user. Then i need the script to return a list of numbers that are between the two.
The list of parameters is 5 10 6 12 5 18 10 4 19 21 5 12 18 22 For example: if the user inputs 12 and 20 we would have 5 matches (12, 18, 19, 12, 18).

```<code>#!/bin/bash
read –p “Enter the number you seek  “ NUM
for VALUE in $@; do
if [ $VALUE –eq $NUM ]; then COUNT=$((COUNT+1)); fi
Done
echo $NUM appeared $COUNT times
</code>```

I know how to add the second user input i am just stuck on how to get it to return the numbers in between.

答:
This will do :

```<code>#!/bin/bash

printf "Enter the number you seek : "
read  NUM
printf "Enter the second number you seek : "
read NUM2

echo "$@" | tr ' ' '\n' | sort -nr | awk -v "num=$NUM" -v "num2=$NUM2" '$1 >= num && $1 <= num2'
</code>```

Let me know if it helps!

Body:
I have this script and i need to modify it so that there are 2 inputs from the user. Then i need the script to return a list of numbers that are between the two.
The list of parameters is 5 10 6 12 5 18 10 4 19 21 5 12 18 22 For example: if the user inputs 12 and 20 we would have 5 matches (12, 18, 19, 12, 18).

#!/bin/bash
read –p “Enter the number you seek  “ NUM
for VALUE in $@; do
if [ $VALUE –eq $NUM ]; then COUNT=$((COUNT+1)); fi
Done
echo $NUM appeared $COUNT times

I know how to add the second user input i am just stuck on how to get it to return the numbers in between.

Body:
This will do :

#!/bin/bash

printf "Enter the number you seek : "
read  NUM
printf "Enter the second number you seek : "
read NUM2

echo "$@" | tr ' ' '\n' | sort -nr | awk -v "num=$NUM" -v "num2=$NUM2" '$1 >= num && $1 <= num2'

Let me know if it helps!


问:
Silverlight Error "Layout Cycle Detected Layout could not complete" when using custom control
I'm building a custom control in Silverlight by deriving from ContentControl and doing some special formatting to put a dropshadow behind the contents.

I've nearly got it working but have recently ran into a bizarre error.  It works fine if it contains anything besides a Border, or a Grid/Stackpanel/etc that does not have an explicitly defined height and width.

I get a JavaScript error in IE, and the text says:

Runtime Error 4008...  Layout Cycle Detected... Layout Could Not Complete.

If I specify a height and width on the contained grid/stackpanel/etc it works fine.

There is a ton on the web about this error when too many textboxes are used (over 250), but I'm able to reproduce my error with a single button in a grid.

I have no textboxes at all on the page.  The error has to do with a detected infinite loop. I set a few breakpoints in the code and it seems that the "SizeChanged" event is getting called a lot during rendering, and each time the height/width increments by 10.

I'm assuming that setting a default height/width causes it to skip this incrementing of the number, but I have no idea why this error is happening.

Has anyone ran into this or have any ideas?

答: I had the same problem and what i did was put all the layout updates (size changes) in a "invoke" delegate en invoked later, it stops crashing but you there is a good change it's stuck in a loop</p>

OwnerDisplayName: Matthew Timbs

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Matthew Timbs


问:
Django referencing foreignkeys on updates
I asked this question before, it got closed because I didn't provide sufficient information to the situation. This is the edit.

I'm running Django and running into this problem. I'm trying to create or update an entry in my MySQL table. One of the keys is, however, a foreignKey. (I know how to create table entries with foreignKeys, but my approach doesn't work) As per Django reference for doing the recommended way is to set the new table entry as default value.

Which I did:

item = {}
for entry in params:
    if entry not in ['_state', 'timestamp', 'rule_case', 'session_key']:
        item[entry] = params[entry]

        if entry == 'code':
            item[entry] = Demo_user_sessions.objects.get(session=session_key)

obj, created = Demo_user_sessions.objects.update_or_create(session=session_key, defaults=item)
```

<p>This I extended by looking for the special key and replacing the content with the link to the referenced table. The one by the foreignKey.</p>

<p>Here my model for the entry that I am trying to make.</p>

<pre class="lang-py prettyprint-override"><code>class Demo_user_sessions(models.Model):
    session_key = models.CharField(primary_key=True, max_length=8)
    timestamp = models.DateTimeField(auto_now_add=True)
    code = models.ForeignKey('HS_Code', on_delete=models.CASCADE, null=True)
    # ... some other

    class Meta:
        ordering = ['timestamp']

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

Here my current error message when doing:

Traceback (most recent call last):
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/Mantaray/main/views.py", line 111, in api_user_session
    obj, created = Demo_user_sessions.objects.update_or_create(session=params['session_key'], defaults=item)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/query.py", line 584, in update_or_create
    setattr(obj, k, v() if callable(v) else v)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 215, in __set__
    'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/base.py", line 518, in __repr__
    return '<%s: %s>' % (self.__class__.__name__, self)
TypeError: __str__ returned non-string (type Demo_user_sessions)
```

I kinda get the problem of the error message. I just don't know what to change or what to do differently.

答:
So there are two issues, 1) __str__ must return a string representation of the instance. 2) item["code"] must be an instance of HS_Code or you could do item["code_id"] = some_integer_id_representing_the_HS_Code.

So something like:

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

And:

```<code>if entry == 'code':
    item[entry] = HS_Code.objects.get(some_lookup=some_value)
</code>```

Body:
I asked this question before, it got closed because I didn't provide sufficient information to the situation. This is the edit.

I'm running Django and running into this problem. I'm trying to create or update an entry in my MySQL table. One of the keys is, however, a foreignKey. (I know how to create table entries with foreignKeys, but my approach doesn't work) As per Django reference for doing the recommended way is to set the new table entry as default value.

Which I did:

item = {}
for entry in params:
    if entry not in ['_state', 'timestamp', 'rule_case', 'session_key']:
        item[entry] = params[entry]

        if entry == 'code':
            item[entry] = Demo_user_sessions.objects.get(session=session_key)

obj, created = Demo_user_sessions.objects.update_or_create(session=session_key, defaults=item)

This I extended by looking for the special key and replacing the content with the link to the referenced table. The one by the foreignKey.

Here my model for the entry that I am trying to make.

class Demo_user_sessions(models.Model):
    session_key = models.CharField(primary_key=True, max_length=8)
    timestamp = models.DateTimeField(auto_now_add=True)
    code = models.ForeignKey('HS_Code', on_delete=models.CASCADE, null=True)
    # ... some other

    class Meta:
        ordering = ['timestamp']

    def __str__(self):
        return self

Here my current error message when doing:

Traceback (most recent call last):
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/Mantaray/main/views.py", line 111, in api_user_session
    obj, created = Demo_user_sessions.objects.update_or_create(session=params['session_key'], defaults=item)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/query.py", line 584, in update_or_create
    setattr(obj, k, v() if callable(v) else v)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 215, in __set__
    'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/base.py", line 518, in __repr__
    return '<%s: %s>' % (self.__class__.__name__, self)
TypeError: __str__ returned non-string (type Demo_user_sessions)

I kinda get the problem of the error message. I just don't know what to change or what to do differently.

Body:
So there are two issues, 1) __str__ must return a string representation of the instance. 2) item["code"] must be an instance of HS_Code or you could do item["code_id"] = some_integer_id_representing_the_HS_Code.

So something like:

def __str__(self):
    return self.session_key

And:

if entry == 'code':
    item[entry] = HS_Code.objects.get(some_lookup=some_value)


问:
How to mock File in javascript?
I'm developing some small project to exercise my TDD skills. The project consists of an audio player which has the ability to drag'n'drop files in a playlist. I'm using Jasmine as a testing framework. The problem I faced is that I can't mock javascript files to test my file upload functionality. I tried to create a File like this:

```<code>new File(new Blob(), "name");
</code>```

but Chrome does not allow creating files manually. File's constructor is illegal to use. I found a solution with grunt.js which consists of returning some files from grunt, but I don't really wanna use server-side for such a small test project. Is there any workaround for this problem?

答:
Here's how I create a dummy pdf file to use with pdf.js

Create a base64 string of your file. I use base64 command in my shell.

```<code>base64 < src/mockData/dummy.pdf
#outputs something like: VEhJUyBJUyBUSEUgQU5TV0VSCg==
</code>```

Copy this string into your source code.

```<code>const dataBase64 = "VEhJUyBJUyBUSEUgQU5TV0VSCg==";
//note this not a pdf, but for demo purposes because a pdf file is too big
</code>```

Decode the base64 and create a file

```<code>const arrayBuffer = Uint8Array.from(window.atob(dataBase64), c => c.charCodeAt(0));
const file = new File([arrayBuffer], "dummy.pdf", {type: 'application/pdf'});
</code>```

Title: How to mock File in javascript?

Body:
I'm developing some small project to exercise my TDD skills. The project consists of an audio player which has the ability to drag'n'drop files in a playlist. I'm using Jasmine as a testing framework. The problem I faced is that I can't mock javascript files to test my file upload functionality. I tried to create a File like this:

new File(new Blob(), "name");

but Chrome does not allow creating files manually. File's constructor is illegal to use. I found a solution with grunt.js which consists of returning some files from grunt, but I don't really wanna use server-side for such a small test project. Is there any workaround for this problem?

Body:
Here's how I create a dummy pdf file to use with pdf.js

Create a base64 string of your file. I use base64 command in my shell.

base64 < src/mockData/dummy.pdf
#outputs something like: VEhJUyBJUyBUSEUgQU5TV0VSCg==

Copy this string into your source code.

const dataBase64 = "VEhJUyBJUyBUSEUgQU5TV0VSCg==";
//note this not a pdf, but for demo purposes because a pdf file is too big

Decode the base64 and create a file

const arrayBuffer = Uint8Array.from(window.atob(dataBase64), c => c.charCodeAt(0));
const file = new File([arrayBuffer], "dummy.pdf", {type: 'application/pdf'});


问:
How to customise the Admin panel in Keystone JS? (Or: how do the custom admin pages in Keystone JS demo-project/blog work?)
We are looking to use KeystoneJS in a large project and we want to be able to customise the Admin panel.  There's a nice example of how to do it here, and I've been reviewing this PR to the project.  Although the example looks as if it would work for us, I don't understand the logic behind it, that is, what we would need to implement to make it work, what the possibilities and constraints are.

Is it the case that when you use the Keystone NextJS app (which is good for us), if you add a folder /admin/pages the Keystone app will look there and use those custom admin pages instead of the regular ones?  I'm assuming we have full access to the rest of the app, the controllers, the DB from these pages as well....

I also noticed that JedWatson notes in https://github.com/keystonejs/keystone/pull/1019 that

Note this lacks SSR support, and I didn't put as much effort into the examples, but it's otherwise (I think) identical in functionality.

Does it lack SSR support just for the admin part, or does adding custom admin pages somehow affect SSR support in the rest of the app? (SSR is the reason we're using next)

Thanks for any info.

答:
There are two api for custom pages, one is pages option in the admin-ui app constructor and 2nd is part of hooks api in keystone constructor.

pages: this one is legacy and only adds custom pages, it does not overwrite the existing list pages in admin-ui it only hides them if not properly configured. usually the Dashboard is visible and all lists are listed there.

hooks: this is new and expected to add more customization options, unfortunately my PRs are stale and they are not the spec keystone core team would want to add. this also does not removes any pages.

admin ui runs as react app built or loaded using webpack config. that is why there is no ssr support. even though the example use a custom admin directory but that not loaded by nextjs component, it is loaded dynamically using webpack server mounting the admin-ui react app

if you really want to have ssr, you can use some learning from closed PRs which were used as POC long ago. but that would be overkill as the admin-ui has many more updates after that.

hooks/pages have access to core limited set of access, there are some access based on React context, provider and consumer hooks. You can use react-apollo hooks as there is already provider wrapped at root of react context. you can also make use of react router hooks, they are upgraded to latest version. it has no access to server side context or controller. (not sure what you meant by controller)


问:
remove a remote branch (push origin ':' ) with gitpython
I cannot find a way to perform a commend equivalent to:

git push origin :branchName

A command that delete a remote branch, can gitpython perform this using git push?

Thanks

答:
```<code>import git
git.Git(local_path).clone(remote_path)
repo = git.Repo(local_path)
remote = repo.remote(name='origin')
branch_attribute = repo.remotes.origin.fetch()
for branch in branch_attribute:
    rm_prefix_origin = branch.name.split('/')
    rm_prefix_origin .remove('origin')
    branch_name = '/'.join(rm_prefix_origin )
    remote.push(refspec=(':' + branch_name))
</code>```


问:
Resolve AvoidLiteralsInIfCondition in interface default method
The PMD rule AvoidLiteralsInIfCondition flags a problem whenever a literal (e.g. 7, 10) is used in a condition (e.g. if (x > 7)).  In a class, I typically solve this by creating a private static final to hold the value.  However, if the literal is used in an interface's default method, I cannot create a private static final in the interface.  How do I fix the AvoidLiteralsInIfCondition?

I know I could use // NOPMD or @SuppressWarnings but that does not fix the problem.  I do not benefit from clearer code by using a private static final.

Here is some code that demonstrates the problem.

```<code>public interface UTF8Length
{
   default int getUTF8Length(char value)
   {
      if (value <= 0x007F)  // PMD flags a problem with 0x007F
         return 1;

      if (value <= 0x07FF)  // PMD flags a problem with 0x07FF
         return 2;

      return 3;
   }
}
</code>```

答:
As proposed in the OP comments, you could externalize your constants to an external class:

```<code>public class ConstantHelper {
    public static final int TWO_BYTE_MAX_CP = 0x7FF;
}
</code>```

Then in your interface's default method you could do this without offending PMD:

```<code>if (value <= ConstantHelper.TWO_BYTE_MAX_CP) { // No PMD issue with this.
    return 2;
}
</code>```

That's probably fine for your example, but there are a couple of guiding principles:

Externalizing a constant to a constants class is not a good approach if that constant is only an implementation detail for your interface, and is unlikely to ever be used by any other classes or interfaces. Creating a new constants class solely to remove a PMD warning is a questionable approach.

Externalizing a constant to a constants class is not a good approach if the value might change in the future, because that change might also impact other classes. In this case it looks like you are referring to Unicode values that will almost certainly never change, so that is not an issue here.

An alternative approach is to have a local declarations within your default method, and use those:

```<code>default int getUTF8Length(char value) {

    final int oneByteMaxCP = 0x007F; // PMD flags AvoidFinalLocalVariables

    if (value <= oneByteMaxCP) {
        return 1;
    }

    final int twoByteMaxCP = 0x007FF; // PMD flags AvoidFinalLocalVariables

    if (value <= twoByteMaxCP) {
        return 2;
    }

    return 3;
}
</code>```

If you do that you will offend PMD in a different way ("AvoidFinalLocalVariable: Avoid using final local variables, turn them into fields") but the advantages are:

You don't need an external class.

I find the code slightly clearer, though that is personal taste.

Those local declarations are self documenting, and - unlike comments - they must be correct for the code to work properly.

Those local declarations are completely private. This might not be a benefit for your specific example, but it is easy to imagine other scenarios where you want to use constants in a default method, and not share them with anyone else.

So if the constant values you want to externalize don't violate the two principles described above then create a constants class. Otherwise, declare your constants locally, and accept that you will get AvoidFinalLocalVariable warnings from PMD, because writing clear, clean and maintainable code is more important than removing PMD warnings.

Body:
The PMD rule AvoidLiteralsInIfCondition flags a problem whenever a literal (e.g. 7, 10) is used in a condition (e.g. if (x > 7)).  In a class, I typically solve this by creating a private static final to hold the value.  However, if the literal is used in an interface's default method, I cannot create a private static final in the interface.  How do I fix the AvoidLiteralsInIfCondition?

I know I could use // NOPMD or @SuppressWarnings but that does not fix the problem.  I do not benefit from clearer code by using a private static final.

Here is some code that demonstrates the problem.

public interface UTF8Length
{
   default int getUTF8Length(char value)
   {
      if (value <= 0x007F)  // PMD flags a problem with 0x007F
         return 1;

      if (value <= 0x07FF)  // PMD flags a problem with 0x07FF
         return 2;

      return 3;
   }
}

Body:
As proposed in the OP comments, you could externalize your constants to an external class:

public class ConstantHelper {
    public static final int TWO_BYTE_MAX_CP = 0x7FF;
}

Then in your interface's default method you could do this without offending PMD:

if (value <= ConstantHelper.TWO_BYTE_MAX_CP) { // No PMD issue with this.
    return 2;
}

That's probably fine for your example, but there are a couple of guiding principles:

Externalizing a constant to a constants class is not a good approach if that constant is only an implementation detail for your interface, and is unlikely to ever be used by any other classes or interfaces. Creating a new constants class solely to remove a PMD warning is a questionable approach.

Externalizing a constant to a constants class is not a good approach if the value might change in the future, because that change might also impact other classes. In this case it looks like you are referring to Unicode values that will almost certainly never change, so that is not an issue here.

An alternative approach is to have a local declarations within your default method, and use those:

default int getUTF8Length(char value) {

    final int oneByteMaxCP = 0x007F; // PMD flags AvoidFinalLocalVariables

    if (value <= oneByteMaxCP) {
        return 1;
    }

    final int twoByteMaxCP = 0x007FF; // PMD flags AvoidFinalLocalVariables

    if (value <= twoByteMaxCP) {
        return 2;
    }

    return 3;
}

If you do that you will offend PMD in a different way ("AvoidFinalLocalVariable: Avoid using final local variables, turn them into fields") but the advantages are:

You don't need an external class.

I find the code slightly clearer, though that is personal taste.

Those local declarations are self documenting, and - unlike comments - they must be correct for the code to work properly.

Those local declarations are completely private. This might not be a benefit for your specific example, but it is easy to imagine other scenarios where you want to use constants in a default method, and not share them with anyone else.

So if the constant values you want to externalize don't violate the two principles described above then create a constants class. Otherwise, declare your constants locally, and accept that you will get AvoidFinalLocalVariable warnings from PMD, because writing clear, clean and maintainable code is more important than removing PMD warnings.


问:
Getting value of all fields of objects in a loop
I have class with 12 fields. Is there any way in kotlin to get values of all of them in a loop? I know I can get lists of all fields in a class but I don't know if I can read values from it. </p>

答:
You can use reflection MyClass::class.memberProperties to get all properties. Each property has a method get to extract the value from a suitable object:

```<code>val myObject = MyClass(...)
for (prop in MyClass::class.memberProperties) {
    println(prop.get(myObject))
}
</code>```

Body:
You can use reflection MyClass::class.memberProperties to get all properties. Each property has a method get to extract the value from a suitable object:

val myObject = MyClass(...)
for (prop in MyClass::class.memberProperties) {
    println(prop.get(myObject))
}


问:
updating sql server database using c# in asp.net
There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?</p>

```<code>protected void Page_Load(object sender, EventArgs e) {
    rno.Text = Request.QueryString["rno"];//rno is a textbox

    string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
    SqlConnection cnn = new SqlConnection(connectionString);
    cnn.Open();

    String sql = "select fname from table1 where rno = @rno";

    SqlCommand command = new SqlCommand(sql, cnn);
    command.Parameters.AddWithValue("@rno", rno.Text.Trim());
    SqlDataReader reader = command.ExecuteReader();
    if (reader.Read()) {
        fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
    }
    reader.Close();
    command.Dispose();
    cnn.Close();

    fName.ReadOnly = true;
}

protected void modify_Click(object sender, EventArgs e) {

    fName.ReadOnly = false;
}

protected void savechanges_Click(object sender, EventArgs e) {
    string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
    SqlConnection cnn = new SqlConnection(connectionString);
    cnn.Open();

    String sql = "update table1 set fname=@fname where rno = @rno";

    SqlCommand command = new SqlCommand(sql, cnn);
    command.Parameters.AddWithValue("@fname", sfname);
    command.Parameters.AddWithValue("@rno", rno.Text.Trim());

    command.ExecuteNonQuery();
    command.Dispose();
    cnn.Close();
    fName.ReadOnly = true;
}
</code>```

答: After searching for a while, I found out that this code was executing perfectly. The only problem was that everything was inside the page_Load() method and thus the page was reloading everytime I updated the database and thus removing the small window to edit the textboxes. The appropriate solution was to associate this code with some button event rather than with the page_Load() event.</p>

Body:
There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?

protected void Page_Load(object sender, EventArgs e) {
    rno.Text = Request.QueryString["rno"];//rno is a textbox

    string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
    SqlConnection cnn = new SqlConnection(connectionString);
    cnn.Open();

    String sql = "select fname from table1 where rno = @rno";

    SqlCommand command = new SqlCommand(sql, cnn);
    command.Parameters.AddWithValue("@rno", rno.Text.Trim());
    SqlDataReader reader = command.ExecuteReader();
    if (reader.Read()) {
        fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
    }
    reader.Close();
    command.Dispose();
    cnn.Close();

    fName.ReadOnly = true;
}

protected void modify_Click(object sender, EventArgs e) {

    fName.ReadOnly = false;
}

protected void savechanges_Click(object sender, EventArgs e) {
    string connectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
    SqlConnection cnn = new SqlConnection(connectionString);
    cnn.Open();

    String sql = "update table1 set fname=@fname where rno = @rno";

    SqlCommand command = new SqlCommand(sql, cnn);
    command.Parameters.AddWithValue("@fname", sfname);
    command.Parameters.AddWithValue("@rno", rno.Text.Trim());

    command.ExecuteNonQuery();
    command.Dispose();
    cnn.Close();
    fName.ReadOnly = true;
}


问:
Switch statement in Javascript with variable comparison
I've found a great count up timer on-line, but I need a timer that will show time till a certain date, and once that date-time has past, it'll show how long it's been since that date-time.

I've tried to add a switch statement, but I get all zero's.

The statement has to change depending on if the count to/from date has passed.

Here's the entire webpage

```<code>    <html>
    <head>
 <title>Orders with Approvals Received</title>
<meta http-equiv="refresh" content="150">
<script>
/*
 * Basic Count Up from Date and Time
 * Author: @mrwigster / https://guwii.com/bytes/count-date-time-javascript/
 */
window.onload = function() {
  // Month Day, Year Hour:Minute:Second, id-of-element-container
  countUpFromTime("Feb 6, 2020 15:00:00", 'countup1'); // ****** Change this line!
};
function countUpFromTime(countFrom, id) {
  countFrom = new Date(countFrom).getTime();
  var now = new Date(),
      countFrom = new Date(countFrom),

      timeDifference = now < countup1 ? (countFrom - now): (now - countFrom);
  //  timeDifference = (now - countFrom); // Count Up
   //  timeDifference = (countFrom - now); //Count Down

    var secondsInADay = 60 * 60 * 1000 * 24,
      secondsInAHour = 60 * 60 * 1000;

  days = Math.floor(timeDifference / (secondsInADay) * 1);
  hours = Math.floor((timeDifference % (secondsInADay)) / (secondsInAHour) * 1);
  mins = Math.floor(((timeDifference % (secondsInADay)) % (secondsInAHour)) / (60 * 1000) * 1);
  secs = Math.floor((((timeDifference % (secondsInADay)) % (secondsInAHour)) % (60 * 1000)) / 1000 * 1);

  var idEl = document.getElementById(id);
  idEl.getElementsByClassName('days')[0].innerHTML = days;
  idEl.getElementsByClassName('hours')[0].innerHTML = hours;
  idEl.getElementsByClassName('minutes')[0].innerHTML = mins;
  idEl.getElementsByClassName('seconds')[0].innerHTML = secs;

  clearTimeout(countUpFromTime.interval);
  countUpFromTime.interval = setTimeout(function(){ countUpFromTime(countFrom, id); }, 1000);
}

</script>
<style>
body {margin:0;
width: 322px;
height: 192px;
}
.caption
    {
        background-color:BLUE;
        color:white;
        font-family: "Times New Roman", Times, serif;
        font-size: 20px;
        border-style:solid;
        border-width:1px;
        border-color:white;
        text-align:center;
    }
.countup {
  text-align: center;
  margin-bottom: 0px;
}
.countup .timeel {
  display: inline-block;
  padding: 9px;
  background: #151515;
  margin: 0;
  color: white;
  margin-left: 0px;
  border-radius: 5px 0 0 5px;
}
.countup span[class*="timeRef"] {
  border-radius: 0 10px 10px 0;
  margin-left: 0;
  background: #e8c152;
  color: black;
}

</style>
    </head>
<body>
   <thead>
    <div class="caption">
    <caption>1_Arthur20 Ended</caption>
    </div>
    </thead>
   <tbody>
<div class="countup" id="countup1">
  <span class="timeel days">00</span>
  <span class="timeel timeRefDays">D</span>
  <span class="timeel hours">00</span>
  <span class="timeel timeRefHours">H</span>
  <span class="timeel minutes">00</span>
  <span class="timeel timeRefMinutes">M</span>
  <span class="timeel seconds">00</span>
  <span class="timeel timeRefSeconds">S</span>
</div>
<div class="countup" id="countup1">
  <span class="timeel days">2</span>
  <span class="timeel timeRefDays">Open</span>
  <span class="timeel hours">502</span>
 <span class="timeel timeRefHours">Total</span>
</div>
</tbody>
</table>
</html>
</code>```

I'd appreciate any help that you could give.
Thanks,

Edit: I added the line as palash suggested, but one the time has passed it gives me an extra 1 day, 1 hour, 1 minute. So when it's counting down it works great, once it hits all zeros, I get the extra time on the count up. I thought it might be because of timezone, but if I substitute the count up code it works fine. Not certain what's going on with it.

Thanks to everyone that commented.

答:
As was mentioned, make sure you have no closing brackets inside your case blocks, only at the end of the switch statement.

```<code>switch (true) {
  case now <= countUpFromTime:
    timeDifference = (countFrom - now);
    break;
  case now > countUpFromTime:
    timeDifference = (now - countFrom);
    break;
  default:
    break;
</code>```

Body:
I've found a great count up timer on-line, but I need a timer that will show time till a certain date, and once that date-time has past, it'll show how long it's been since that date-time.

I've tried to add a switch statement, but I get all zero's.

The statement has to change depending on if the count to/from date has passed.

Here's the entire webpage

 <title>Orders with Approvals Received</title>
<meta http-equiv="refresh" content="150">

1_Arthur20 Ended

  00
  D
  00
  H
  00
  M
  00
  S

  2
  Open
  502
 Total

I'd appreciate any help that you could give.
Thanks,

Edit: I added the line as palash suggested, but one the time has passed it gives me an extra 1 day, 1 hour, 1 minute. So when it's counting down it works great, once it hits all zeros, I get the extra time on the count up. I thought it might be because of timezone, but if I substitute the count up code it works fine. Not certain what's going on with it.

Thanks to everyone that commented.

Body:
As was mentioned, make sure you have no closing brackets inside your case blocks, only at the end of the switch statement.

switch (true) {
  case now <= countUpFromTime:
    timeDifference = (countFrom - now);
    break;
  case now > countUpFromTime:
    timeDifference = (now - countFrom);
    break;
  default:
    break;


答:
Instead of a switch statement in this scenario, you can use conditional (ternary) operator here like:

```<code>timeDifference = now <= countUpFromTime ? (countFrom - now) : (now - countFrom);
</code>```

Title: Switch statement in Javascript with variable comparison

Body:
Instead of a switch statement in this scenario, you can use conditional (ternary) operator here like:

timeDifference = now <= countUpFromTime ? (countFrom - now) : (now - countFrom);


问:
Can't free linked list in objective-C iPhone dev
I'm writing an application for iPhone, that uses a linked list to keep track of a set of points. I've used linked lists time and time again successfully in other C programs, but I've never used a linked list on iPhone, and my 'freeList' function is crashing.

```<code>pointNode * temp;

pointTrain = lPoints->next;
while (pointTrain) {
    temp = pointTrain->next;
    free(pointTrain);
    pointTrain = temp;
}
</code>```

This is how I'm freeing my list, 'lPoints' is the head, and is always allocated during runtime. This code is executed before any more nodes are added, but it seems to still execute even though "pointTrain" is NULL, which SHOULD make it skip the while loop. Unfortunately, the loop is still executed, and the program crashes on free(pointTrain)

Is there something I'm just not seeing?

Points are added like so within a loop:

```<code>pointTrain->x = onPx / trueWidth;
pointTrain->y = onPx % trueWidth;
pointTrain->next = (pointNode*)malloc(sizeof(pointNode));
pointTrain = pointTrain->next;
</code>```

答:
A wise man once said, "I'd rather ride a horse the direction it's going."

Don't roll your own struct when there's a perfectly good NSMutableArray class you could be using. Linear iteration of an array is cheap and easy, and the class comes with its own memory management hooks, and all you have to do is USE them.

This is something I see a lot with C and C++ devs who pop over to Objective-C. The next project on my plate is to un-fubar a project that a VERY senior C++ guy spent the last six months on. Looking at the code, it's plain that he spent almost all of that time arguing with the framework. He's practically built his own framework at this point.

Body:
I'm writing an application for iPhone, that uses a linked list to keep track of a set of points. I've used linked lists time and time again successfully in other C programs, but I've never used a linked list on iPhone, and my 'freeList' function is crashing.

pointNode * temp;

pointTrain = lPoints->next;
while (pointTrain) {
    temp = pointTrain->next;
    free(pointTrain);
    pointTrain = temp;
}

This is how I'm freeing my list, 'lPoints' is the head, and is always allocated during runtime. This code is executed before any more nodes are added, but it seems to still execute even though "pointTrain" is NULL, which SHOULD make it skip the while loop. Unfortunately, the loop is still executed, and the program crashes on free(pointTrain)

Is there something I'm just not seeing?

Points are added like so within a loop:

pointTrain->x = onPx / trueWidth;
pointTrain->y = onPx % trueWidth;
pointTrain->next = (pointNode*)malloc(sizeof(pointNode));
pointTrain = pointTrain->next;


问:
Is Google Cloud Datastore available in terraform?
I plan to use terraform to setup a Google Cloud Datastore, however I cannot find any in the documentation. Is this resource available in terraform?</p>

答:
Ali was right. There is a module available. But for some reason, its not updated into official terraform documentation.

I noticed following line:

These variables must be set in the module block when using this
  module.


答: I believe (would need to see (and interpret) machine code) one version works without calling code in the library (as if you wrote printf("%d", -1);).

Title: Ambiguous behaviour of strcmp()


问:
In App Purchase Crash - [[SKPaymentQueue defaultQueue] addPayment:payment];
I am getting a crash with the following error message:

[FilterPurchase respondsToSelector:]: message sent to deallocated instance 0x1edacba0

This occurs on this line:

```<code> [[SKPaymentQueue defaultQueue] addPayment:payment];
</code>```

The problem occurs when I load the In App Purchase View, then remove the view from superview and then re-open it and click to make a purchase.

Has anyone got any ideas on how I could correct this issue. Don't know if the above is enough information to correct the issue.

Don't know if this has anything to do with it but it is called on each load.

```<code>[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
</code>```

Thanks

答: One of reasons of the crash can be insertion of SKPayment with empty productIdentifier.

Body:
I am getting a crash with the following error message:

[FilterPurchase respondsToSelector:]: message sent to deallocated instance 0x1edacba0

This occurs on this line:

 [[SKPaymentQueue defaultQueue] addPayment:payment];

The problem occurs when I load the In App Purchase View, then remove the view from superview and then re-open it and click to make a purchase.

Has anyone got any ideas on how I could correct this issue. Don't know if the above is enough information to correct the issue.

Don't know if this has anything to do with it but it is called on each load.

[[SKPaymentQueue defaultQueue] addTransactionObserver:self];

Thanks


问:
crystal report free edition in which version of MS Visual Studio
which edition of MS Visual Studio contains free redistributable edition of Crystal Reports? Also, is CR included in latest versions of Visual Studio? </p>

答: You can distribute Crystal Reports made with Visual Studio Professional at no extra cost above what you pay for Visual Studio. As mentioned you do need to have, at least, the Professional SKU and Crystal Reports is available in the last three editions of Visual Studio Pro(2005, 2008, and 2010).</p>


问:
How can I change button class and fontawesome icon based on my database value 0 or 1 in laravel using jquery ajax?
I have column status in database with boolean value 0 and 1. 0 means user is shown and 1 means user is hidden.

This is my button

```<code> <button class="btn btn-info btn-sm btn_show" type="button" id="btn_show" data-value="{{$user->status}}" data-id="{{$user->id}}"><i
                                            class="fa fa-eye"></i>
                                </button>
</code>```

My Controller

```<code> public function userhideandshow($id)
{
    $user = User::find($id);
    if ($user->status == 0) {
        $user->status = 1;
    } else {
        $user->status = 0;
    }
    $user->save();

    return response()->json(['success']);
}
</code>```

Ajax Call

```<code>$(function () {
        $(".btn_show").click(function () {
            let status = $(this).data('value');
            console.log(value);
            let id = $(this).data('id');
            $.ajax({
                url: "/user/" + id,
                method: "POST",
                data: {'id': id, 'status': value},
                dataType: "json",
                success: function (data) {
                    console.log(value);
                    if (value == 0) {
                        $("button.btn_show").find("i").removeClass("fa fa-eye").addClass("fa fa-eye-slash");
                    } else {
                        $("button.btn_show").find("i").removeClass("fa fa-eye-slash").addClass("fa fa-eye");
                    }
                },
            });
        });
    });
</code>```

When I click on button I want to change its class and icon based on my database value. If value is 0, then button is primary and icon is fa fa-eye and if 1 then fa fa-eye slash and button info. Database value is changing but how do I change button based on value. Thanks in advance.

My need is this

 @if($user->status == 0)
    <button type="button" id="btn_show" data-value="{{ $user->status }}" data-id="{{$user->id}}" class="btn btn-primary btn-sm btn_show">
        </button>
  @else
    <button type="button" id="btn_show" data-value="{{$user->status}}" data-id="{{$user->id}}" class="btn btn-info btn-sm btn_show">
        </button>
@endif```

答:
You need to set class to current clicked button, so try this

```<code>$(".btn_show").click(function () {
    let this_button = $(this);
    let this_button_icon = $(this).find("i"); // Add this to have current button icon instance
    let status = $(this).data('value');
    console.log(value);
    let id = $(this).data('id');
    $.ajax({
        url: "/user/" + id,
        method: "POST",
        data: {'id': id, 'status': value},
        dataType: "json",
        success: function (data) {
        console.log(value);
        // set class to icon
        if (value == 0) {
        this_button_icon.removeClass("fa fa-eye").addClass("fa fa-eye-slash");
        this_button.attr('data-user-id', 1);
        } else {
            this_button_icon.removeClass("fa fa-eye-slash").addClass("fa fa-eye");
            this_button.attr('data-user-id', 0);
        }
    },
});
</code>```

EDITED: Try this

```<code><button type="button" id="btn_show{{$user->id}}" data-value="{{$user->status}}" data-id="{{$user->id}}" class="btn btn-sm btn_show {{$user->status ? 'btn-info' : 'btn-primary'}}"><i
                class="fa {{$user->status ? 'fa-eye-slash' : 'fa-eye'}}"></i>
    </button>
</code>```

Body:
I have column status in database with boolean value 0 and 1. 0 means user is shown and 1 means user is hidden.

This is my button

 <button class="btn btn-info btn-sm btn_show" type="button" id="btn_show" data-value="{{$user->status}}" data-id="{{$user->id}}">
                                </button>

My Controller

 public function userhideandshow($id)
{
    $user = User::find($id);
    if ($user->status == 0) {
        $user->status = 1;
    } else {
        $user->status = 0;
    }
    $user->save();

    return response()->json(['success']);
}

Ajax Call

$(function () {
        $(".btn_show").click(function () {
            let status = $(this).data('value');
            console.log(value);
            let id = $(this).data('id');
            $.ajax({
                url: "/user/" + id,
                method: "POST",
                data: {'id': id, 'status': value},
                dataType: "json",
                success: function (data) {
                    console.log(value);
                    if (value == 0) {
                        $("button.btn_show").find("i").removeClass("fa fa-eye").addClass("fa fa-eye-slash");
                    } else {
                        $("button.btn_show").find("i").removeClass("fa fa-eye-slash").addClass("fa fa-eye");
                    }
                },
            });
        });
    });

When I click on button I want to change its class and icon based on my database value. If value is 0, then button is primary and icon is fa fa-eye and if 1 then fa fa-eye slash and button info. Database value is changing but how do I change button based on value. Thanks in advance.

My need is this

 @if($user->status == 0)
    <button type="button" id="btn_show" data-value="{{ $user->status }}" data-id="{{$user->id}}" class="btn btn-primary btn-sm btn_show">
        </button>
  @else
    <button type="button" id="btn_show" data-value="{{$user->status}}" data-id="{{$user->id}}" class="btn btn-info btn-sm btn_show">
        </button>
@endif

Body:
You need to set class to current clicked button, so try this

$(".btn_show").click(function () {
    let this_button = $(this);
    let this_button_icon = $(this).find("i"); // Add this to have current button icon instance
    let status = $(this).data('value');
    console.log(value);
    let id = $(this).data('id');
    $.ajax({
        url: "/user/" + id,
        method: "POST",
        data: {'id': id, 'status': value},
        dataType: "json",
        success: function (data) {
        console.log(value);
        // set class to icon
        if (value == 0) {
        this_button_icon.removeClass("fa fa-eye").addClass("fa fa-eye-slash");
        this_button.attr('data-user-id', 1);
        } else {
            this_button_icon.removeClass("fa fa-eye-slash").addClass("fa fa-eye");
            this_button.attr('data-user-id', 0);
        }
    },
});

EDITED: Try this

<button type="button" id="btn_show{{$user->id}}" data-value="{{$user->status}}" data-id="{{$user->id}}" class="btn btn-sm btn_show {{$user->status ? 'btn-info' : 'btn-primary'}}"><i
                class="fa {{$user->status ? 'fa-eye-slash' : 'fa-eye'}}"></i>
    </button>


问:
Using window.location.origin in angular library configuration using AOT
When I pass window.location.origin in the forRoot({...}) configuration object argument of my angular library and compile using AOT, it's value is just null. Is there a way to pass it's value to my angular library with AOT enabled?

After some googling I'm thinking perhaps an injection token needs to be set with WINDOW and then consumed on the library side but I'd like to avoid this if possible. I can also just hard code the origin but that is quite limiting. Would like a sort of set it and forget it approach hence why I carved out a feature into a library.

My Library is set up as follows.

```<code>export class AppConfig {
  origin: string;
}

...

export const APP_CONFIG_TOKEN = new InjectionToken<AppConfig>('APP_CONFIG_TOKEN');

...

@NgModule()
export class MyLibrary {
  public static forRoot(config: AppConfig) {
    return {
      ngModule: MyLibrary,
      providers: [
        {
          provide: APP_CONFIG_TOKEN,
          useValue: config
        }
      ]
    };
  }

</code>```

I'm consuming the value of the token in a service within the library

```<code>@Injectable()
export class MyService {
  constructor(@Inject(APP_CONFIG_TOKEN) private config: AppConfig) { }

  myOrigin(): string {
    return this.config.origin; // expecting it to return a value like `http://localhost:4200` but it returns `null`
  }
}
</code>```

and I'm importing the library in my AppModule like so

```<code>@NgModule({
  imports: [
    MyLibrary.forRoot({
      origin: window.location.origin // with AOT, this seems to be null
    })
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
AOT builds parts of the app so that the client has to do less computing.
Try looking at this issue

https://github.com/angular/angular-cli/issues/10957

Body:
When I pass window.location.origin in the forRoot({...}) configuration object argument of my angular library and compile using AOT, it's value is just null. Is there a way to pass it's value to my angular library with AOT enabled?

After some googling I'm thinking perhaps an injection token needs to be set with WINDOW and then consumed on the library side but I'd like to avoid this if possible. I can also just hard code the origin but that is quite limiting. Would like a sort of set it and forget it approach hence why I carved out a feature into a library.

My Library is set up as follows.

export class AppConfig {
  origin: string;
}

...

export const APP_CONFIG_TOKEN = new InjectionToken<AppConfig>('APP_CONFIG_TOKEN');

...

@NgModule()
export class MyLibrary {
  public static forRoot(config: AppConfig) {
    return {
      ngModule: MyLibrary,
      providers: [
        {
          provide: APP_CONFIG_TOKEN,
          useValue: config
        }
      ]
    };
  }

I'm consuming the value of the token in a service within the library

@Injectable()
export class MyService {
  constructor(@Inject(APP_CONFIG_TOKEN) private config: AppConfig) { }

  myOrigin(): string {
    return this.config.origin; // expecting it to return a value like `http://localhost:4200` but it returns `null`
  }
}

and I'm importing the library in my AppModule like so

@NgModule({
  imports: [
    MyLibrary.forRoot({
      origin: window.location.origin // with AOT, this seems to be null
    })
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
Evaluate random function for each row
I have the following sql:

SELECT SERIES.TIME AS TIME
FROM GENERATE_SERIES(
             CAST('now' AS TIMESTAMP) - cast('1 month' AS INTERVAL),
             CAST('now' AS TIMESTAMP),
             CAST('1 day' AS INTERVAL)
         ) AS SERIES (TIME)
         CROSS JOIN
         (SELECT * FROM GENERATE_SERIES(1, (floor(random() * 10)::int))) as RANDOM_TABLE
```

<p>This should generate a series of dates with an interval of one hour in it. What I now try to get is each day to be randomly fanned out. I have noticed that in the above sql statement <code>random()</code> is only evaluated once even though it is in a subquery.</p>

<p>Now without the <code>CROSS JOIN</code> I get:</p>

```| 2019-02-13 |
| 2019-02-14 |
| 2019-02-15 |
```

<p>and with the <code>CROSS JOIN</code> I now get for example:</p>

```| 2019-02-13 |
| 2019-02-13 |
| 2019-02-13 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-15 |
| 2019-02-15 |
| 2019-02-15 |
```

<p>What I would like to have is a random number each time I fan out. E.g.:</p>

```| 2019-02-13 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-15 |
| 2019-02-15 |
| 2019-02-15 |
```

How do I need to modify my query to achieve that?

答:
The problem is premature optimization.  Postgres "forgets" that random() is volatile and should be called each time.

Here is a fix:

```<code>SELECT SERIES.TIME AS TIME
FROM (SELECT s.time, (floor(random() * 10)::int) as num
      FROM GENERATE_SERIES(now() - interval '1 month' , now(), interval '1 day') s(time)
         ) AS SERIES (TIME)
         CROSS JOIN LATERAL
         GENERATE_SERIES(1, num) as RANDOM_TABLE
</code>```

And a db<>fiddle.

Note that I made some substitutions that seem more "Postgres-like" -- using now(), interval and so on for date arithmetic rather than converting strings.

Title: Evaluate random function for each row

Body:
I have the following sql:

SELECT SERIES.TIME AS TIME
FROM GENERATE_SERIES(
             CAST('now' AS TIMESTAMP) - cast('1 month' AS INTERVAL),
             CAST('now' AS TIMESTAMP),
             CAST('1 day' AS INTERVAL)
         ) AS SERIES (TIME)
         CROSS JOIN
         (SELECT * FROM GENERATE_SERIES(1, (floor(random() * 10)::int))) as RANDOM_TABLE

This should generate a series of dates with an interval of one hour in it. What I now try to get is each day to be randomly fanned out. I have noticed that in the above sql statement random() is only evaluated once even though it is in a subquery.

Now without the CROSS JOIN I get:

| 2019-02-13 |
| 2019-02-14 |
| 2019-02-15 |

and with the CROSS JOIN I now get for example:

| 2019-02-13 |
| 2019-02-13 |
| 2019-02-13 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-15 |
| 2019-02-15 |
| 2019-02-15 |

What I would like to have is a random number each time I fan out. E.g.:

| 2019-02-13 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-15 |
| 2019-02-15 |
| 2019-02-15 |

How do I need to modify my query to achieve that?

Body:
The problem is premature optimization.  Postgres "forgets" that random() is volatile and should be called each time.

Here is a fix:

SELECT SERIES.TIME AS TIME
FROM (SELECT s.time, (floor(random() * 10)::int) as num
      FROM GENERATE_SERIES(now() - interval '1 month' , now(), interval '1 day') s(time)
         ) AS SERIES (TIME)
         CROSS JOIN LATERAL
         GENERATE_SERIES(1, num) as RANDOM_TABLE

And a db<>fiddle.

Note that I made some substitutions that seem more "Postgres-like" -- using now(), interval and so on for date arithmetic rather than converting strings.


问:
Warning: array_merge(): Argument #1 Error message in Wordpress using WooCommerce
I realize there's quite a few of these questions answered and all are unique in their own way. Above is the error message that appeared over this weekend and I can't find a solution for the life of me. I mange to open up the file in Siteground's File Manager and here are the lines in question. What can I do to fix this error?

Warning: array_merge(): Argument #1 is not an array in /home/customer/www/myapx.shop/public_html/wp-content/plugins/elementor/includes/base/controls-stack.php on line 1184

Codebase

```<code>            if ( 'repeater' === $control_obj->get_type() ) {
        foreach ( $settings[ $control_name ] as & $field ) {
            $field = $this->parse_dynamic_settings( $field, $control['fields'], $field );
        }

        continue;
    }

    $dynamic_settings = $control_obj->get_settings( 'dynamic' );

    if ( ! empty( $control['dynamic'] ) ) {
        $dynamic_settings = array_merge( $dynamic_settings, $control['dynamic'] );
    }

    if ( empty( $dynamic_settings ) || ! isset( $all_settings[ Manager::DYNAMIC_SETTING_KEY ][ $control_name ] ) ) {
        continue;
    }
</code>```

Any help or guidance would be appreciated.

P.S. Go easy on me not very technical.

答:
I am having the same issue and it seems to be from the current update of the Elementor plugin. See this post:

https://wordpress.org/support/topic/error-with-new-update-2-9-2/

In my case, there was a conflict with an Add on for elementor, I reverted to version 2.8.5 of the plugin and the error is gone.

Body:
I realize there's quite a few of these questions answered and all are unique in their own way. Above is the error message that appeared over this weekend and I can't find a solution for the life of me. I mange to open up the file in Siteground's File Manager and here are the lines in question. What can I do to fix this error?

Warning: array_merge(): Argument #1 is not an array in /home/customer/www/myapx.shop/public_html/wp-content/plugins/elementor/includes/base/controls-stack.php on line 1184

Codebase

            if ( 'repeater' === $control_obj->get_type() ) {
        foreach ( $settings[ $control_name ] as & $field ) {
            $field = $this->parse_dynamic_settings( $field, $control['fields'], $field );
        }

        continue;
    }

    $dynamic_settings = $control_obj->get_settings( 'dynamic' );

    if ( ! empty( $control['dynamic'] ) ) {
        $dynamic_settings = array_merge( $dynamic_settings, $control['dynamic'] );
    }

    if ( empty( $dynamic_settings ) || ! isset( $all_settings[ Manager::DYNAMIC_SETTING_KEY ][ $control_name ] ) ) {
        continue;
    }

Any help or guidance would be appreciated.

P.S. Go easy on me not very technical.