问:
How to delete the message users have reacted to
Trying to delete the original user command the bot reply after the bot is reacted to. For some reason, it only works every other time and when it does work it relays a DiscordAPIError: Unknown Message error

const isValidCommand = (message, cmdName) => message.content.toLowerCase().startsWith(PREFIX + cmdName)
client.on('message', function(message) {
  if (message.author.bot) return;
  if (isValidCommand(message, "banker"))
    message.reply("Bankers are on the way to get your cash. Please be patient as Bankers are busy individuals as well. If there is a major delay you are welcome to use !HeadBanker.      Bankers Please React With Money Bag When Sent/Sending!").then(r_msg =>
      r_msg.react(''))
  if (isValidCommand(message, "banker"))
    message.channel.send("<@&717082379470110885> Banker Cash Needed")
    .then(msg => {
      msg.delete({
        timeout: 0100
      })
    })
  if (isValidCommand(message, "headbanker"))
    message.reply("I see you have pinged Head Banker. If its between 14:00TCT and 5:00TCT you should get a response within a minute or two max. If no response in five minutes you have permission to ping again.").then(r_msg =>
      r_msg.react(''))
  if (isValidCommand(message, "headbanker"))
    message.channel.send("<@&716843712092569640> Cash Needed")
    .then(msg => {
      msg.delete({
          timeout: 0100
        })
        .catch(console.log);
    })

  client.on('messageReactionAdd', (reaction, user) => {
    let limit = 2;
    if (reaction.emoji.name == '' && reaction.count >= limit) reaction.message.delete()
      .catch(console.log);
    if (reaction.emoji.name == '' && reaction.count >= limit) message.delete()
      .catch(console.log);
  });
})
```

答:
I think that's caused by the fact that you've declared your messageReactionAdd listener inside your message listener: that means that every time you get a new message your client will add a new handler, and so it will try to delete the same message multiple time, resulting in an "unknown message" error from the API.

Instead of adding a listener for the reactions on your client, you should try creating a reaction collector using either Message.awaitReactions() or Message.createReactionCollector(). Here's an example:

const isValidCommand = (message, cmdName) => message.content.toLowerCase().startsWith(PREFIX + cmdName)

client.on('message', function(message) {
  if (message.author.bot) return;
  if (isValidCommand(message, "banker")) { // Use single if statements where possible
    message.reply("Bankers are on the way to get your cash. Please be patient as Bankers are busy individuals as well. If there is a major delay you are welcome to use !HeadBanker.      Bankers Please React With Money Bag When Sent/Sending!").then(r_msg =>
      r_msg.react(''))
    message.channel.send("<@&717082379470110885> Banker Cash Needed")
      .then(msg => {
        msg.delete({ timeout: 0100 })
      })
  }
  if (isValidCommand(message, "headbanker")) {
    message.reply("I see you have pinged Head Banker. If its between 14:00TCT and 5:00TCT you should get a response within a minute or two max. If no response in five minutes you have permission to ping again.").then(r_msg =>
      r_msg.react(''))
    message.channel.send("<@&716843712092569640> Cash Needed")
      .then(msg => {
        msg.delete({ timeout: 0100 })
          .catch(console.log);
      })
  }

  message.awaitReactions(r => r.emoji.name == '', { max: 2 }).then(collected => {
    if (collected.size >= 2)
      message.delete()
  })
})
```

Also, it's good practice not to repeat if statements, you should merge them wherever you can.

Body:
I think that's caused by the fact that you've declared your messageReactionAdd listener inside your message listener: that means that every time you get a new message your client will add a new handler, and so it will try to delete the same message multiple time, resulting in an "unknown message" error from the API.

Instead of adding a listener for the reactions on your client, you should try creating a reaction collector using either Message.awaitReactions() or Message.createReactionCollector(). Here's an example:

const isValidCommand = (message, cmdName) => message.content.toLowerCase().startsWith(PREFIX + cmdName)

client.on('message', function(message) {
  if (message.author.bot) return;
  if (isValidCommand(message, "banker")) { // Use single if statements where possible
    message.reply("Bankers are on the way to get your cash. Please be patient as Bankers are busy individuals as well. If there is a major delay you are welcome to use !HeadBanker.      Bankers Please React With Money Bag When Sent/Sending!").then(r_msg =>
      r_msg.react(''))
    message.channel.send("<@&717082379470110885> Banker Cash Needed")
      .then(msg => {
        msg.delete({ timeout: 0100 })
      })
  }
  if (isValidCommand(message, "headbanker")) {
    message.reply("I see you have pinged Head Banker. If its between 14:00TCT and 5:00TCT you should get a response within a minute or two max. If no response in five minutes you have permission to ping again.").then(r_msg =>
      r_msg.react(''))
    message.channel.send("<@&716843712092569640> Cash Needed")
      .then(msg => {
        msg.delete({ timeout: 0100 })
          .catch(console.log);
      })
  }

  message.awaitReactions(r => r.emoji.name == '', { max: 2 }).then(collected => {
    if (collected.size >= 2)
      message.delete()
  })
})

Also, it's good practice not to repeat if statements, you should merge them wherever you can.


来源: stackexchange

问:
Correct way to compare two objects extending Comparable
I'm new to generics and having trouble figuring out how to properly compare two Comparable objects.

```<code>private int getSortPos(int dir, Comparable d1, Comparable d2) {
    if (d1 == null && d2 != null)
    {
        return dir * -1;
    }
    else if (d1 != null && d2 == null)
    {
        return dir;
    }
    else if (d1 == null)
    {
        return 0;
    }
    else
    {
        return dir * d1.compareTo(d2);
    }
}
</code>```

I'm using this code to compare both String and Date objects, both extending Comparable. I'm using sonar in IntelliJ and it tells me: "Provide the parametrized type for this generic" referring to the function parameters. The code works as intended but have "Major code smell". What would be the correct way of doing this?

答:
```<code>private <T extends Comparable<T>> int getSortPos(int dir, T d1, T d2) {
    if (d1 == null && d2 != null)
    {
        return dir * -1;
    }
    else if (d1 != null && d2 == null)
    {
        return dir;
    }
    else if (d1 == null)
    {
        return 0;
    }
    else
    {
        return dir * d1.compareTo(d2);
    }
}
</code>```

Doing it this way solved my problem. Is there an even better solution?

ContentLicense: CC BY-SA 4.0

Body:
I'm new to generics and having trouble figuring out how to properly compare two Comparable objects.

private int getSortPos(int dir, Comparable d1, Comparable d2) {
    if (d1 == null && d2 != null)
    {
        return dir * -1;
    }
    else if (d1 != null && d2 == null)
    {
        return dir;
    }
    else if (d1 == null)
    {
        return 0;
    }
    else
    {
        return dir * d1.compareTo(d2);
    }
}

I'm using this code to compare both String and Date objects, both extending Comparable. I'm using sonar in IntelliJ and it tells me: "Provide the parametrized type for this generic" referring to the function parameters. The code works as intended but have "Major code smell". What would be the correct way of doing this?

Body:
private <T extends Comparable<T>> int getSortPos(int dir, T d1, T d2) {
    if (d1 == null && d2 != null)
    {
        return dir * -1;
    }
    else if (d1 != null && d2 == null)
    {
        return dir;
    }
    else if (d1 == null)
    {
        return 0;
    }
    else
    {
        return dir * d1.compareTo(d2);
    }
}

Doing it this way solved my problem. Is there an even better solution?


问:
How to show a triangle image in an html tree
I am trying to use this tree:
https://www.w3schools.com/howto/howto_js_treeview.asp
Can someone tell me what part of the code shows the triangle image being shown with every expandable li? I would like to reduce the size of it, but I cant figure out where it is coming from.</p>

答:
Styles:

.caret {
  cursor: pointer;
  -webkit-user-select: none; /* Safari 3.1+ */
  -moz-user-select: none; /* Firefox 2+ */
  -ms-user-select: none; /* IE 10+ */
  user-select: none;
}

.caret::before {
  content: "\25B6"; //Unicode for the triangle
  color: black;
  display: inline-block;
  margin-right: 6px;
}

.caret-down::before { //Adding this class rotates the element to point down
  -ms-transform: rotate(90deg); /* IE 9 */
  -webkit-transform: rotate(90deg); /* Safari */'
  transform: rotate(90deg);
}
```

<p>and usage:</p>

<pre class="lang-html prettyprint-override"><code><span class="caret">Beverages</span>
</code>```

Body:
Styles:

.caret {
  cursor: pointer;
  -webkit-user-select: none; /* Safari 3.1+ */
  -moz-user-select: none; /* Firefox 2+ */
  -ms-user-select: none; /* IE 10+ */
  user-select: none;
}

.caret::before {
  content: "\25B6"; //Unicode for the triangle
  color: black;
  display: inline-block;
  margin-right: 6px;
}

.caret-down::before { //Adding this class rotates the element to point down
  -ms-transform: rotate(90deg); /* IE 9 */
  -webkit-transform: rotate(90deg); /* Safari */'
  transform: rotate(90deg);
}

and usage:

<span class="caret">Beverages</span>


问:
I can't create Question in python manage.py shell.(Django)
in models.py i have created class Question and then i want to create Question in models.py shell i am getting an error

models.py

```<code>from django.db import models, migrations

class Question(models.Model):
    author = models.CharField(max_length = 20)
    title = models.CharField(max_length = 30)
    body = models.TextField(null = True, blank = True)
    rating = 0
    category = models.CharField(max_length = 10)

class Migration(migrations.Migration):
    initial = True
    dependencies = []

    operations = [
        migrations.CreateModel (
            name = 'question',
            fields = [
                ('id', models.AutoField(auto_created=True,
                primary_key=True, serialize=False, verbose_name='ID')),
                ('author', models.CharField(max_length=20)),
                ('title', models.CharField(max_length = 30)),
                ('body', models.TextField(null = True, blank = True)),
                ('rating', 0),
                ('category', models.CharField(max_length = 10)),
            ],
        ),
    ]
</code>```

shell

```<code>>>> from f.models import Queston
>>> first_question =  first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body, category = 'some_category')

 File "<console>", line 1
    first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body, category = 'some_category')
</code>```

答: Are you Python 2 or 3? If you are Python 2, do this: raw_input(' '). If you are Python 3, do this: input(' ').

Body:
in models.py i have created class Question and then i want to create Question in models.py shell i am getting an error

models.py

from django.db import models, migrations

class Question(models.Model):
    author = models.CharField(max_length = 20)
    title = models.CharField(max_length = 30)
    body = models.TextField(null = True, blank = True)
    rating = 0
    category = models.CharField(max_length = 10)

class Migration(migrations.Migration):
    initial = True
    dependencies = []

    operations = [
        migrations.CreateModel (
            name = 'question',
            fields = [
                ('id', models.AutoField(auto_created=True,
                primary_key=True, serialize=False, verbose_name='ID')),
                ('author', models.CharField(max_length=20)),
                ('title', models.CharField(max_length = 30)),
                ('body', models.TextField(null = True, blank = True)),
                ('rating', 0),
                ('category', models.CharField(max_length = 10)),
            ],
        ),
    ]

shell

>>> from f.models import Queston
>>> first_question =  first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body, category = 'some_category')

 File "<console>", line 1
    first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body, category = 'some_category')


问:
How to properly use a lambda expression with the scipy.derivative method?
I have written the following function to calculate the probability that a single reaction in a system of reaction fires and stores the output of the function, the probability of each reaction in the system firing, as an array:

```<code>def propensity_calc(LHS, popul_num, stoch_rate):
    propensity = np.zeros(len(LHS))
    for row in range(len(LHS)):
            a = stoch_rate[row]
            for i in range(len(popul_num)):
                if (popul_num[i] >= LHS[row, i]):
                    binom_rxn = binom(popul_num[i], LHS[row, i])
                    a = a*binom_rxn
                else:
                    a = 0
                    break
            propensity[row] = a
    return propensity
</code>```

The inputs for this function are 3 arrays popul_num has the discrete number of molecules of each reactant, LHS is a 2D array with the ratios between each molecule species for each reaction in the system and stoch_rate is the rate of each reaction.

I now want to call the propensity_calc function with the scipy.misc.derivative method in a different function to calculate the partial derivative: bji(x) = daj(x)/xi, where aj(x) is the result from the above propensity_calc function and xi is the corresponding elements of the popul_num array.

This is what I've got written so far:

```<code>from scipy.misc import derivative
from scipy import optimize

def time_step_calc(popul_num, state_change_array, a0):
    # equation 22:
    expctd_net_change = a0*state_change_array
    print("expected net change:\n", expctd_net_change)
    # equation 24 partial differentiation:
    for x in range(len(popul_num)):
        part_propensity_diff = derivative(lambda LHS, popul_num, stoch_rate: propensity_calc, popul_num[x])    <-- Error here with the number of arguments passed to lambda
    # equation 26:
    t_step = epsi*a0 / sum(expctd_net_change*part_propensity_diff)
    delta_t = optimize.fmin(t_step, 0.00012)
    print("calculated delta_t:\n", delta_t)
    return delta_t
</code>```

To pass the propensity_calc function to scipy.derviative I've tried to use a lambda function but I get the following error:

```<code>File "C:\Users\Mike\AppData\Local\Programs\Python\Python38-32\lib\site-packages\scipy\misc\common.py", line 119, in derivative
val += weights[k]*func(x0+(k-ho)*dx,*args)
TypeError: <lambda>() missing 2 required positional arguments: 'popul_num' and 'stoch_rate'
</code>```

I've read the lambda documentation but I still don't understand where I'm going wrong, any suggestions as to how I can fix this error and do the partial differentiation?

Cheers

答:
Generally, Scipy will only pass one argument to the lambda function, so it is only passing the value of LHS. Look at the example in scipy documentation:

```<code>from scipy.misc import derivative
def f(x):
    return x**3 + x**2

derivative(func=f, x0=1.0, dx=1e-6)
4.9999999999217337
</code>```

Here, 4.99 is the derivative of f on x=1 when moving x by 1e-6. Say that f has two variables:

```<code>def f(x, y):
    return x**3 + y**2
</code>```

If you want the partial derivative with respect to y, then you'd need a wrapper function for scipy to understand which variable to change. This would look like:

```<code>def wrapper(y):
    return f(x, y)
</code>```

And of course, now you need a value for x

```<code>x = 1
derivative(wrapper, 2)
4.0
</code>```

Body:
I have written the following function to calculate the probability that a single reaction in a system of reaction fires and stores the output of the function, the probability of each reaction in the system firing, as an array:

def propensity_calc(LHS, popul_num, stoch_rate):
    propensity = np.zeros(len(LHS))
    for row in range(len(LHS)):
            a = stoch_rate[row]
            for i in range(len(popul_num)):
                if (popul_num[i] >= LHS[row, i]):
                    binom_rxn = binom(popul_num[i], LHS[row, i])
                    a = a*binom_rxn
                else:
                    a = 0
                    break
            propensity[row] = a
    return propensity

The inputs for this function are 3 arrays popul_num has the discrete number of molecules of each reactant, LHS is a 2D array with the ratios between each molecule species for each reaction in the system and stoch_rate is the rate of each reaction.

I now want to call the propensity_calc function with the scipy.misc.derivative method in a different function to calculate the partial derivative: bji(x) = daj(x)/xi, where aj(x) is the result from the above propensity_calc function and xi is the corresponding elements of the popul_num array.

This is what I've got written so far:

from scipy.misc import derivative
from scipy import optimize

def time_step_calc(popul_num, state_change_array, a0):
    # equation 22:
    expctd_net_change = a0*state_change_array
    print("expected net change:\n", expctd_net_change)
    # equation 24 partial differentiation:
    for x in range(len(popul_num)):
        part_propensity_diff = derivative(lambda LHS, popul_num, stoch_rate: propensity_calc, popul_num[x])    <-- Error here with the number of arguments passed to lambda
    # equation 26:
    t_step = epsi*a0 / sum(expctd_net_change*part_propensity_diff)
    delta_t = optimize.fmin(t_step, 0.00012)
    print("calculated delta_t:\n", delta_t)
    return delta_t

To pass the propensity_calc function to scipy.derviative I've tried to use a lambda function but I get the following error:

File "C:\Users\Mike\AppData\Local\Programs\Python\Python38-32\lib\site-packages\scipy\misc\common.py", line 119, in derivative
val += weights[k]*func(x0+(k-ho)*dx,*args)
TypeError: <lambda>() missing 2 required positional arguments: 'popul_num' and 'stoch_rate'

I've read the lambda documentation but I still don't understand where I'm going wrong, any suggestions as to how I can fix this error and do the partial differentiation?

Cheers

Body:
Generally, Scipy will only pass one argument to the lambda function, so it is only passing the value of LHS. Look at the example in scipy documentation:

from scipy.misc import derivative
def f(x):
    return x**3 + x**2

derivative(func=f, x0=1.0, dx=1e-6)
4.9999999999217337

Here, 4.99 is the derivative of f on x=1 when moving x by 1e-6. Say that f has two variables:

def f(x, y):
    return x**3 + y**2

If you want the partial derivative with respect to y, then you'd need a wrapper function for scipy to understand which variable to change. This would look like:

def wrapper(y):
    return f(x, y)

And of course, now you need a value for x

x = 1
derivative(wrapper, 2)
4.0


问:
Flex 4: LineSeries AnimateColor not working
This is a fairly simple question I would think.
here is the code (I cut it down for an easy read)

```<code>    <fx:Declarations>
    <s:AnimateColor id="rw"
                    target="{targetRatioCol}"
                    colorFrom="0x000000"
                    colorTo="0xFFFFFF"
                    colorPropertyName="color"
                    duration="5000"
                    repeatCount="0"
                    repeatBehavior="reverse"
                    />

</fx:Declarations>
....

            <mx:LineSeries id="targetRatio" displayName="Target" xField="Month" creationComplete="rw.play();" yField="targetRatio" verticalAxis="{v2}"
                       >
            <mx:lineStroke>
                <mx:SolidColorStroke id="targetRatioCol"   color="0xFFFFFF" weight="4"  />
            </mx:lineStroke>
        </mx:LineSeries>
</code>```

the chart shows the line but the animation doesn't work.
My question is why isn't this working?

Thanks in advance
Nat

答: I don't think that the Chart redraws when the animation is played.  Charts are a very strange beast.  If I were you, I'd create an item renderer for the line which has the animation within it so that you'd only redraw the line.</p>

ContentLicense: CC BY-SA 3.0

Body:
This is a fairly simple question I would think.
here is the code (I cut it down for an easy read)

    <fx:Declarations>
    <s:AnimateColor id="rw"
                    target="{targetRatioCol}"
                    colorFrom="0x000000"
                    colorTo="0xFFFFFF"
                    colorPropertyName="color"
                    duration="5000"
                    repeatCount="0"
                    repeatBehavior="reverse"
                    />

</fx:Declarations>
....

            <mx:LineSeries id="targetRatio" displayName="Target" xField="Month" creationComplete="rw.play();" yField="targetRatio" verticalAxis="{v2}"
                       >
            <mx:lineStroke>
                <mx:SolidColorStroke id="targetRatioCol"   color="0xFFFFFF" weight="4"  />
            </mx:lineStroke>
        </mx:LineSeries>

the chart shows the line but the animation doesn't work.
My question is why isn't this working?

Thanks in advance
Nat


问:
Blazor server side - redirecting if unauthenticated before the page starts loading
Might be trying to solve this the wrong way, but here's the situation.

I have a component designed to redirect to login if the user trying to access it isn't authenticated, and display not found if they aren't authorized for the page requested.

```<code><AuthorizeViewWithPermissions RequiredPermission="RequiredPermission">
    <Authorized>
        @ChildContent
    </Authorized>
    <NotAuthenticated>
        <LoginRedirect />
    </NotAuthenticated>
    <NotAuthorized>
        <NotFoundRedirect />
    </NotAuthorized>
</AuthorizeViewWithPermissions>

@code {
    [Parameter] public RenderFragment ChildContent { get; set; }

    [Parameter] public Permissions RequiredPermission { get; set; }

    protected override void OnInitialized()
    {

    }
}
</code>```

LoginRedirect is this:

```<code>    public class LoginRedirect : ComponentBase
    {
        [Inject] protected NavigationManager NavigationManager { get; set; }

        protected override void OnInitialized()
        {
            NavigationManager.NavigateTo("/Login", true);
        }
    }
</code>```

internals of AuthorizeViewWithPermissions:

```<code>    /// <summary>
    /// Largely borrowed from the original AuthorizeView, but cut up a bit to use custom permissions and cut out a lot of stuff that isn't needed.
    /// </summary>
    public class AuthorizeViewWithPermissions : ComponentBase
    {
        private AuthenticationState _currentAuthenticationState;

        private bool _isAuthorized;

        private bool _isAuthenticated;

        /// <summary>
        /// The permission type required to display the content
        /// </summary>
        [Parameter] public Permissions RequiredPermission { get; set; }

        /// <summary>
        /// The content that will be displayed if the user is authorized.
        /// </summary>
        [Parameter] public RenderFragment<AuthenticationState> ChildContent { get; set; }

        /// <summary>
        /// The content that will be displayed if the user is not authorized.
        /// </summary>
        [Parameter] public RenderFragment<AuthenticationState> NotAuthorized { get; set; }

        /// <summary>
        /// The content that will be displayed if the user is not authenticated.
        /// </summary>
        [Parameter] public RenderFragment<AuthenticationState> NotAuthenticated { get; set; }

        /// <summary>
        /// The content that will be displayed if the user is authorized.
        /// If you specify a value for this parameter, do not also specify a value for <see cref="ChildContent"/>.
        /// </summary>
        [Parameter] public RenderFragment<AuthenticationState> Authorized { get; set; }

        /// <summary>
        /// The content that will be displayed while asynchronous authorization is in progress.
        /// </summary>
        [Parameter] public RenderFragment Authorizing { get; set; }

        /// <summary>
        /// The resource to which access is being controlled.
        /// </summary>
        [Parameter] public object Resource { get; set; }

        [CascadingParameter] private Task<AuthenticationState> AuthenticationState { get; set; }

        /// <inheritdoc />
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            // We're using the same sequence number for each of the content items here
            // so that we can update existing instances if they are the same shape
            if (_currentAuthenticationState == null)
            {
                builder.AddContent(0, Authorizing);
            }
            else if (_isAuthorized)
            {
                var authorized = Authorized ?? ChildContent;
                builder.AddContent(0, authorized?.Invoke(_currentAuthenticationState));
            }
            else if (!_isAuthenticated)
            {
                builder.AddContent(0, NotAuthenticated?.Invoke(_currentAuthenticationState));
            }
            else
            {
                builder.AddContent(0, NotAuthorized?.Invoke(_currentAuthenticationState));
            }
        }

        /// <inheritdoc />
        protected override async Task OnParametersSetAsync()
        {
            // We allow 'ChildContent' for convenience in basic cases, and 'Authorized' for symmetry
            // with 'NotAuthorized' in other cases. Besides naming, they are equivalent. To avoid
            // confusion, explicitly prevent the case where both are supplied.
            if (ChildContent != null && Authorized != null)
            {
                throw new InvalidOperationException($"Do not specify both '{nameof(Authorized)}' and '{nameof(ChildContent)}'.");
            }

            if (AuthenticationState == null)
            {
                throw new InvalidOperationException($"Authorization requires a cascading parameter of type Task<{nameof(AuthenticationState)}>. Consider using {typeof(CascadingAuthenticationState).Name} to supply this.");
            }

            // First render in pending state
            // If the task has already completed, this render will be skipped
            _currentAuthenticationState = null;

            // Then render in completed state
            // Importantly, we *don't* call StateHasChanged between the following async steps,
            // otherwise we'd display an incorrect UI state while waiting for IsAuthorizedAsync
            _currentAuthenticationState = await AuthenticationState;
            SetAuthorizedAndAuthenticated(_currentAuthenticationState.User);
        }

        private void SetAuthorizedAndAuthenticated(ClaimsPrincipal user)
        {
            var userWithData = SessionHelper.GetCurrentUser(user);

            _isAuthenticated = userWithData != null;
            _isAuthorized = userWithData?.Permissions.Any(p => p == RequiredPermission || p == Permissions.SuperAdmin) ?? false;
        }
    }
</code>```

The authentication and authorization checks are working perfectly fine, but the issue is that the page OnInitializedAsync or OnParametersSetAsync fire before the LoginRedirect OnInitialized.

I'm kicking off my calls for data (to an API, that uses a token stored on the logged in user's data) in OnInitializedAsync which results in it attempting to load the data (with no auth token) instead of just redirecting.  If I comment out the data call the redirect works as expected without issue, so it's just a timing/sequence of events issue.

Is there a solution to this? Should I just be changing my api client code to silently fail instead of throwing an unauthorized exception if the auth token is missing?

This is also my app.razor component:

```<code>CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <LoginRedirect />
                </NotAuthorized>
                <Authorizing>
                    <p>Checking authorization...</p>
                </Authorizing>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>These aren't the droids you're looking for.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>
</code>```

答:
Not being familiar with the internals AuthorizeViewWithPermissions, I can only venture to say that the LoginRedirect component should be exposed from the NotAuthorized property element, as NotAuthorized convey the dual meaning of having no permissions to access a resource, as well as not authenticated. You can be authenticated, but not authorized, and you can be authorized if you are authenticated only (this is the default), unless you define policies to be more specific about your requirements.

In terms of coding, please see how it is done in the default VS template:

```<code> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
                @if (!context.User.Identity.IsAuthenticated)
                {
                    <RedirectToLogin />
                }
                else
                {
                    <p>You are not authorized to access this resource.</p>
                }
            </NotAuthorized>
        </AuthorizeRouteView>
</code>```

Again, your posted code is partial, and I can only guess... But I think that you have an issue with the design of your AuthorizeViewWithPermissions, related to what I was referring to above. Try to design it otherwise. Don't look for workaround, for this can prove fatal in the long run. Just try to change the design, based on understanding how the system works...

Hope this helps...

Body:
Might be trying to solve this the wrong way, but here's the situation.

I have a component designed to redirect to login if the user trying to access it isn't authenticated, and display not found if they aren't authorized for the page requested.

<AuthorizeViewWithPermissions RequiredPermission="RequiredPermission">
    <Authorized>
        @ChildContent
    </Authorized>
    <NotAuthenticated>
        <LoginRedirect />
    </NotAuthenticated>
    <NotAuthorized>
        <NotFoundRedirect />
    </NotAuthorized>
</AuthorizeViewWithPermissions>

@code {
    [Parameter] public RenderFragment ChildContent { get; set; }

    [Parameter] public Permissions RequiredPermission { get; set; }

    protected override void OnInitialized()
    {

    }
}

LoginRedirect is this:

    public class LoginRedirect : ComponentBase
    {
        [Inject] protected NavigationManager NavigationManager { get; set; }

        protected override void OnInitialized()
        {
            NavigationManager.NavigateTo("/Login", true);
        }
    }

internals of AuthorizeViewWithPermissions:

    ///
    /// Largely borrowed from the original AuthorizeView, but cut up a bit to use custom permissions and cut out a lot of stuff that isn't needed.
    ///
    public class AuthorizeViewWithPermissions : ComponentBase
    {
        private AuthenticationState _currentAuthenticationState;

        private bool _isAuthorized;

        private bool _isAuthenticated;

        ///
        /// The permission type required to display the content
        ///
        [Parameter] public Permissions RequiredPermission { get; set; }

        ///
        /// The content that will be displayed if the user is authorized.
        ///
        [Parameter] public RenderFragment<AuthenticationState> ChildContent { get; set; }

        ///
        /// The content that will be displayed if the user is not authorized.
        ///
        [Parameter] public RenderFragment<AuthenticationState> NotAuthorized { get; set; }

        ///
        /// The content that will be displayed if the user is not authenticated.
        ///
        [Parameter] public RenderFragment<AuthenticationState> NotAuthenticated { get; set; }

        ///
        /// The content that will be displayed if the user is authorized.
        /// If you specify a value for this parameter, do not also specify a value for <see cref="ChildContent"/>.
        ///
        [Parameter] public RenderFragment<AuthenticationState> Authorized { get; set; }

        ///
        /// The content that will be displayed while asynchronous authorization is in progress.
        ///
        [Parameter] public RenderFragment Authorizing { get; set; }

        ///
        /// The resource to which access is being controlled.
        ///
        [Parameter] public object Resource { get; set; }

        [CascadingParameter] private Task<AuthenticationState> AuthenticationState { get; set; }

        /// <inheritdoc />
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            // We're using the same sequence number for each of the content items here
            // so that we can update existing instances if they are the same shape
            if (_currentAuthenticationState == null)
            {
                builder.AddContent(0, Authorizing);
            }
            else if (_isAuthorized)
            {
                var authorized = Authorized ?? ChildContent;
                builder.AddContent(0, authorized?.Invoke(_currentAuthenticationState));
            }
            else if (!_isAuthenticated)
            {
                builder.AddContent(0, NotAuthenticated?.Invoke(_currentAuthenticationState));
            }
            else
            {
                builder.AddContent(0, NotAuthorized?.Invoke(_currentAuthenticationState));
            }
        }

        /// <inheritdoc />
        protected override async Task OnParametersSetAsync()
        {
            // We allow 'ChildContent' for convenience in basic cases, and 'Authorized' for symmetry
            // with 'NotAuthorized' in other cases. Besides naming, they are equivalent. To avoid
            // confusion, explicitly prevent the case where both are supplied.
            if (ChildContent != null && Authorized != null)
            {
                throw new InvalidOperationException($"Do not specify both '{nameof(Authorized)}' and '{nameof(ChildContent)}'.");
            }

            if (AuthenticationState == null)
            {
                throw new InvalidOperationException($"Authorization requires a cascading parameter of type Task<{nameof(AuthenticationState)}>. Consider using {typeof(CascadingAuthenticationState).Name} to supply this.");
            }

            // First render in pending state
            // If the task has already completed, this render will be skipped
            _currentAuthenticationState = null;

            // Then render in completed state
            // Importantly, we *don't* call StateHasChanged between the following async steps,
            // otherwise we'd display an incorrect UI state while waiting for IsAuthorizedAsync
            _currentAuthenticationState = await AuthenticationState;
            SetAuthorizedAndAuthenticated(_currentAuthenticationState.User);
        }

        private void SetAuthorizedAndAuthenticated(ClaimsPrincipal user)
        {
            var userWithData = SessionHelper.GetCurrentUser(user);

            _isAuthenticated = userWithData != null;
            _isAuthorized = userWithData?.Permissions.Any(p => p == RequiredPermission || p == Permissions.SuperAdmin) ?? false;
        }
    }

The authentication and authorization checks are working perfectly fine, but the issue is that the page OnInitializedAsync or OnParametersSetAsync fire before the LoginRedirect OnInitialized.

I'm kicking off my calls for data (to an API, that uses a token stored on the logged in user's data) in OnInitializedAsync which results in it attempting to load the data (with no auth token) instead of just redirecting.  If I comment out the data call the redirect works as expected without issue, so it's just a timing/sequence of events issue.

Is there a solution to this? Should I just be changing my api client code to silently fail instead of throwing an unauthorized exception if the auth token is missing?

This is also my app.razor component:

CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <LoginRedirect />
                </NotAuthorized>
                <Authorizing>

Checking authorization...

                </Authorizing>
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">

These aren't the droids you're looking for.

            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

Body:
Not being familiar with the internals AuthorizeViewWithPermissions, I can only venture to say that the LoginRedirect component should be exposed from the NotAuthorized property element, as NotAuthorized convey the dual meaning of having no permissions to access a resource, as well as not authenticated. You can be authenticated, but not authorized, and you can be authorized if you are authenticated only (this is the default), unless you define policies to be more specific about your requirements.

In terms of coding, please see how it is done in the default VS template:

 <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
                @if (!context.User.Identity.IsAuthenticated)
                {
                    <RedirectToLogin />
                }
                else
                {
                    <p>You are not authorized to access this resource.</p>
                }
            </NotAuthorized>
        </AuthorizeRouteView>

Again, your posted code is partial, and I can only guess... But I think that you have an issue with the design of your AuthorizeViewWithPermissions, related to what I was referring to above. Try to design it otherwise. Don't look for workaround, for this can prove fatal in the long run. Just try to change the design, based on understanding how the system works...

Hope this helps...


问:
Why doesn't Html.fromHtml not working for String in Android?

One String value is coming from my firebase:

if (task.isSuccessful()) {
    //   binding.contentMain.noData.setVisibility(View.GONE);
    for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult()))
        postMap.putAll(document.getData());

    try {
        if (postMap != null)
            //binding.desc1.setText(Objects.requireNonNull(postMap.get(CONTENT)).toString());
            binding.desc1.setText(Html.fromHtml(Objects.requireNonNull(postMap.get(CONTENT)).toString()));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
```

<p>Now, I'll tell you what is coming inside String from Firestore, Actually I only manually written as a String field inside Firestore collection.:</p>

```This is the first text. \n\n This is a second text. \n This is the third text. \n\n Done. \n
```

Make sure that above line is just one String/firestore field.

In firestore, I stored the above value as a String, and fetching that value and showing it in Android. But it is not taking a new line. Instead, it is showing written \n along with other characters.

I tried with and without HTML. with \n and \r\n.

UPDATE: You can see below image how I stored in Firestore.
https://drive.google.com/open?id=19yry9top_W8LREw5SEaZKWYWSlnCP1io

答:
Your string is

```<code>This is the first text. \n\n This is a second text. \n This is the third text. \n\n Done. \n
</code>```

This is quite weird.

1) Do you want next line after a full stop?

2) Can you edit or format the string at the time of saving?

If your case is 1 then what you can do is

Remove all the /n character and replace with "".

String stringWithoutNewLine = yourString.replaceAll("\n","")

Then it gonna look like this

```<code>This is the first text.  This is a second text.  This is the third text.  Done.
</code>```

Now remove all the ".   " in the string and replace it with new line.

String formattedString = yourString.replaceAll(".

",System.lineSeparator())

You can chain these in one line and it will work because replaceAll returns a new String

Can you try this

```<code>if (task.isSuccessful()) {
    //   binding.contentMain.noData.setVisibility(View.GONE);
    for (QueryDocumentSnapshot document: Objects.requireNonNull(task.getResult()))
        postMap.putAll(document.getData());

    try {
        if (postMap != null)
            //binding.desc1.setText(Objects.requireNonNull(postMap.get(CONTENT)).toString());
            String string = postMap.get(CONTENT).toString();
            String finalString = string.replaceAll("\n","").replaceAll(".  ",System.lineSeparator())
            binding.desc1.setText(finalString)
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

Body:
One String value is coming from my firebase:

if (task.isSuccessful()) {
    //   binding.contentMain.noData.setVisibility(View.GONE);
    for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult()))
        postMap.putAll(document.getData());

    try {
        if (postMap != null)
            //binding.desc1.setText(Objects.requireNonNull(postMap.get(CONTENT)).toString());
            binding.desc1.setText(Html.fromHtml(Objects.requireNonNull(postMap.get(CONTENT)).toString()));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Now, I'll tell you what is coming inside String from Firestore, Actually I only manually written as a String field inside Firestore collection.:

This is the first text. \n\n This is a second text. \n This is the third text. \n\n Done. \n

Make sure that above line is just one String/firestore field.

In firestore, I stored the above value as a String, and fetching that value and showing it in Android. But it is not taking a new line. Instead, it is showing written \n along with other characters.

I tried with and without HTML. with \n and \r\n.

UPDATE: You can see below image how I stored in Firestore.
https://drive.google.com/open?id=19yry9top_W8LREw5SEaZKWYWSlnCP1io

Body:
Your string is

This is the first text. \n\n This is a second text. \n This is the third text. \n\n Done. \n

This is quite weird.

1) Do you want next line after a full stop?

2) Can you edit or format the string at the time of saving?

If your case is 1 then what you can do is

Remove all the /n character and replace with "".

String stringWithoutNewLine = yourString.replaceAll("\n","")

Then it gonna look like this

This is the first text.  This is a second text.  This is the third text.  Done.

Now remove all the ".   " in the string and replace it with new line.

String formattedString = yourString.replaceAll(".

",System.lineSeparator())

You can chain these in one line and it will work because replaceAll returns a new String

Can you try this

if (task.isSuccessful()) {
    //   binding.contentMain.noData.setVisibility(View.GONE);
    for (QueryDocumentSnapshot document: Objects.requireNonNull(task.getResult()))
        postMap.putAll(document.getData());

    try {
        if (postMap != null)
            //binding.desc1.setText(Objects.requireNonNull(postMap.get(CONTENT)).toString());
            String string = postMap.get(CONTENT).toString();
            String finalString = string.replaceAll("\n","").replaceAll(".  ",System.lineSeparator())
            binding.desc1.setText(finalString)
    } catch (Exception e) {
        e.printStackTrace();
    }
}


问:
Publish snapshot artifacts to azure devops artifacts
I have a Gradle build set up in Azure DevOps, which compiles the code in an Azure DevOps git repository, then publishes the generated JARs (as Maven artifacts) to Azure Artifacts, as explained here. Code in other Azure DevOps git repositories can then reference these components as dependencies. This is fine for formal releases of these components (with unique version numbers), but I also need a way to get this working for in-progress snapshot releases. The problem is that I cannot publish an artifact with the same version number (e.g. 1.2.3-SNAPSHOT) more than once. This seems to be because packages in Azure are immutable.

From my understanding, that would mean that Azure Artifacts cannot be used to store in-progress snapshot artifacts. Is that correct?

If it is, is there any alternative that still uses Azure DevOps? I can see that I can publish artifacts to Azure Blob Storage, but presumably this is something you have to pay for on top of existing use of Azure Artifacts. I can also see that there's a number of GitHub Maven plugins for treating a GitHub repo as a Maven repo, but I can't find anything similar for using an Azure DevOps repo as a place to publish Maven artifacts.

In case it makes a difference, I'm talking about the cloud-based Azure stuff, nothing on-premise.

答:
Specifically for maven, there's a difference in how a jar is packaged in a SNAPSHOT as compared to other versions.

Eg. let's say I version my jar as 1.0.0-PRERELEASE, now this version is immutable. Once I publish this to any artifact repository it cannot be overridden. Usually package management systems store the artifact in this kind of logical path - <group_id>/<artifact_id>/<version>/<artifact_id>_<version>.jar.

But for SNAPSHOTs this is slightly different. In maven, SNAPSHOTs are mutable. This means you can override a SNAPSHOT. And this makes sense as by definition SNAPSHOTs are like an image of your code in active development. How SNAPSHOTs are stored in a package management feed is something like <group_id>/<artifact_id>/<version(SNAPSHOT)>/<artifact_id>_<version>_<jar_timestamp>.jar.

This naming convention of the jar in this case makes it mutable. In a single SNAPSHOT version, there can be multiple jars present with different timestamps. And when maven looks for a SNAPSHOT dependency to download, it always picks the most recent one (again logical as that's the most recent snapshot).

At present azure artifacts implements these concepts exactly how they are supposed to. Perhaps this wasn't there before and has been pushed in an update.

http://maven.apache.org/guides/getting-started/index.html#What_is_a_SNAPSHOT_version
https://xebia.com/blog/continuous-releasing-of-maven-artifacts/


问:
Getting error while GetEnv in JNI_OnLoad() and app crashing when removed these lines, error goes away
App is crashing in JNI_OnLoad(). I have checked the status it is zero. Still, the app is crashing. I want to create env variable to cache method IDs to use them for callback for java functions. I have tried caching jvm in context struct and doing same in callback() method but App is crashing. I am new bie to this concept. Can anybody explain what I am missing here.

Please find Attached code:

```<code>#include <jni.h>
#include <string>
#include "Numbers.h"

#include <android/log.h>

#define  LOG_TAG    "logs"

#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)

typedef struct number_ctx{
    JavaVM  *javaVM;
    jclass   mathsClass;
    jobject  mathsObj;
    jclass   mainActivityClass;
    jobject  mainActivityObj;
    pthread_mutex_t  lock;
} NumbersCtx;
NumbersCtx g_ctx;

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
    JNIEnv* env;
    memset(&g_ctx, 0, sizeof(g_ctx));

    g_ctx.javaVM = vm;

    int status = vm ->GetEnv((void **)env, JNI_VERSION_1_6);

    LOGD("Status is %d ", status);
    if (vm ->GetEnv((void **)env, JNI_VERSION_1_6) != JNI_OK) {
        LOGD("Some error");
        return JNI_ERR; // JNI version not supported.
    }

    if(env->ExceptionCheck()) {
        env->ExceptionDescribe();
        env->ExceptionClear();
    }
    /*

    jclass  clz = env->FindClass(
                                    "com/example/maths/Maths1");
    g_ctx.mathsClass = static_cast<jclass>(env->NewGlobalRef(clz));

    jmethodID  jniHelperCtor = env->GetMethodID(g_ctx.mathsClass,
                                                   "printMessage", "()V");
    jobject    handler = env->NewObject(g_ctx.mathsClass,
                                           jniHelperCtor);
    g_ctx.mathsObj = env->NewGlobalRef(handler);

    g_ctx.mainActivityObj = NULL;*/
    return  JNI_VERSION_1_6;
}

void callback() {

}
</code>```

答:
You forgot to use the Address-Of operator (&) when calling GetEnv. GetEnv expects a pointer-to-a-pointer, but you're just passing it a pointer that you've cast to a pointer-to-a-pointer, which is not the same thing.

So instead of

```<code>vm ->GetEnv((void **)env, JNI_VERSION_1_6)
</code>```

you should be using

```<code>vm ->GetEnv((void **)&env, JNI_VERSION_1_6)
</code>```

The end result of leaving out the Address-Of operator in this case is that GetEnv will store the JNIEnv* who-knows-where, and your env variable most likely won't contain a valid JNIEnv*.

Body:
App is crashing in JNI_OnLoad(). I have checked the status it is zero. Still, the app is crashing. I want to create env variable to cache method IDs to use them for callback for java functions. I have tried caching jvm in context struct and doing same in callback() method but App is crashing. I am new bie to this concept. Can anybody explain what I am missing here.

Please find Attached code:

#include <jni.h>
#include <string>
#include "Numbers.h"

#include <android/log.h>

#define  LOG_TAG    "logs"

#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)

typedef struct number_ctx{
    JavaVM  *javaVM;
    jclass   mathsClass;
    jobject  mathsObj;
    jclass   mainActivityClass;
    jobject  mainActivityObj;
    pthread_mutex_t  lock;
} NumbersCtx;
NumbersCtx g_ctx;

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
    JNIEnv* env;
    memset(&g_ctx, 0, sizeof(g_ctx));

    g_ctx.javaVM = vm;

    int status = vm ->GetEnv((void **)env, JNI_VERSION_1_6);

    LOGD("Status is %d ", status);
    if (vm ->GetEnv((void **)env, JNI_VERSION_1_6) != JNI_OK) {
        LOGD("Some error");
        return JNI_ERR; // JNI version not supported.
    }

    if(env->ExceptionCheck()) {
        env->ExceptionDescribe();
        env->ExceptionClear();
    }
    /*

    jclass  clz = env->FindClass(
                                    "com/example/maths/Maths1");
    g_ctx.mathsClass = static_cast<jclass>(env->NewGlobalRef(clz));

    jmethodID  jniHelperCtor = env->GetMethodID(g_ctx.mathsClass,
                                                   "printMessage", "()V");
    jobject    handler = env->NewObject(g_ctx.mathsClass,
                                           jniHelperCtor);
    g_ctx.mathsObj = env->NewGlobalRef(handler);

    g_ctx.mainActivityObj = NULL;*/
    return  JNI_VERSION_1_6;
}

void callback() {

}

Body:
You forgot to use the Address-Of operator (&) when calling GetEnv. GetEnv expects a pointer-to-a-pointer, but you're just passing it a pointer that you've cast to a pointer-to-a-pointer, which is not the same thing.

So instead of

vm ->GetEnv((void **)env, JNI_VERSION_1_6)

you should be using

vm ->GetEnv((void **)&env, JNI_VERSION_1_6)

The end result of leaving out the Address-Of operator in this case is that GetEnv will store the JNIEnv* who-knows-where, and your env variable most likely won't contain a valid JNIEnv*.


问:
How to next activity after progress indicator in Flutter WebView?
I am trying to build a webview project, I want to go to next page after loading indicator, but it's not working, is there anything i missed or mess up?  I want after loading indicator my loaded webviewsite will show automatically.
I am trying to build a webview project, I want to go to next page after loading indicator, but it's not working, is there anything i missed or mess up?  I want after loading indicator my loaded webviewsite will show automatically

Here is my code-

```<code>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:web2app/widgets/drawer.dart';
import 'package:webview_flutter/webview_flutter.dart';

const String flutterUrl = 'https://flutter.dev/';
const String wikiUrl = 'https://google.com/';

class X extends StatefulWidget {
  XState createState() => XState();
}

class XState extends State<X> {
  WebViewController _controller;

  bool isLoading = false;

  @override
  void initState() {
    setState(() {
      isLoading = true;
    });
    super.initState();
  }

  _back() async {
    if (await _controller.canGoBack()) {
      await _controller.goBack();
    }
  }

  _forward() async {
    if (await _controller.canGoForward()) {
      await _controller.goForward();
    }
  }

  _loadPage() async {
    var url = await _controller.currentUrl();
    _controller.loadUrl(
      url == flutterUrl ? wikiUrl : flutterUrl,
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.deepOrange,
          title: Text('Web2App'),
          actions: <Widget>[
            IconButton(icon: Icon(Icons.arrow_back_ios), onPressed: _back),
            IconButton(
                icon: Icon(Icons.arrow_forward_ios), onPressed: _forward),
            SizedBox(
              width: 10,
            ),
          ],
        ),
        drawer: Drawer(
          child: DrawerPage(),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _loadPage,
          child: Icon(Icons.refresh),
        ),
        body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                isLoading
                    ? Container(
                        child: CircularPercentIndicator(
                          radius: 120.0,
                          lineWidth: 13.0,
                          animation: true,
                          animationDuration: 4500,
                          percent: 1,
                          footer: new Text(
                            "Loading...",
                            style: new TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 17.0),
                          ),
                          circularStrokeCap: CircularStrokeCap.round,
                          progressColor: Colors.purple,
                        ),
                      )
                    : WebView(
                        key: Key('webview'),
                        initialUrl: flutterUrl,
                        javascriptMode: JavascriptMode.unrestricted,
                        onWebViewCreated:
                            (WebViewController webViewController) {
                          _controller = webViewController;
                        },
                      )
              ]),
        ));
  }
}
</code>```

答:
try this it will work fine with you</p>

```<code>
class WebViewScreen extends StatefulWidget {
  final String title;
  final String selectedUrl;

  WebViewScreen({@required this.title, @required this.selectedUrl});

  @override
  _WebViewScreenState createState() => _WebViewScreenState();
}

class _WebViewScreenState extends State<WebViewScreen> {
  Completer<WebViewController> _controller = Completer<WebViewController>();
  bool isLoading = true;

  num position = 1;

  final key = UniqueKey();

  doneLoading(String A) {
    setState(() {
      position = 0;
    });
  }

  startLoading(String A) {
    setState(() {
      position = 1;
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: IndexedStack(index: position, children: <Widget>[
          WebView(
            initialUrl: widget.selectedUrl,
            javascriptMode: JavascriptMode.unrestricted,
            key: key,
            onPageFinished: doneLoading,
            onPageStarted: startLoading,
            onWebViewCreated: (WebViewController webViewController) {
              _controller.complete(webViewController);
            },
          ),
          Container(
            color: Colors.white,
            child: Center(child: CustomAppProgressBar),
          ),
        ]));
  }
}

</code>```

Body:
I am trying to build a webview project, I want to go to next page after loading indicator, but it's not working, is there anything i missed or mess up?  I want after loading indicator my loaded webviewsite will show automatically.
I am trying to build a webview project, I want to go to next page after loading indicator, but it's not working, is there anything i missed or mess up?  I want after loading indicator my loaded webviewsite will show automatically

Here is my code-

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:web2app/widgets/drawer.dart';
import 'package:webview_flutter/webview_flutter.dart';

const String flutterUrl = 'https://flutter.dev/';
const String wikiUrl = 'https://google.com/';

class X extends StatefulWidget {
  XState createState() => XState();
}

class XState extends State<X> {
  WebViewController _controller;

  bool isLoading = false;

  @override
  void initState() {
    setState(() {
      isLoading = true;
    });
    super.initState();
  }

  _back() async {
    if (await _controller.canGoBack()) {
      await _controller.goBack();
    }
  }

  _forward() async {
    if (await _controller.canGoForward()) {
      await _controller.goForward();
    }
  }

  _loadPage() async {
    var url = await _controller.currentUrl();
    _controller.loadUrl(
      url == flutterUrl ? wikiUrl : flutterUrl,
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.deepOrange,
          title: Text('Web2App'),
          actions: <Widget>[
            IconButton(icon: Icon(Icons.arrow_back_ios), onPressed: _back),
            IconButton(
                icon: Icon(Icons.arrow_forward_ios), onPressed: _forward),
            SizedBox(
              width: 10,
            ),
          ],
        ),
        drawer: Drawer(
          child: DrawerPage(),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _loadPage,
          child: Icon(Icons.refresh),
        ),
        body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                isLoading
                    ? Container(
                        child: CircularPercentIndicator(
                          radius: 120.0,
                          lineWidth: 13.0,
                          animation: true,
                          animationDuration: 4500,
                          percent: 1,
                          footer: new Text(
                            "Loading...",
                            style: new TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 17.0),
                          ),
                          circularStrokeCap: CircularStrokeCap.round,
                          progressColor: Colors.purple,
                        ),
                      )
                    : WebView(
                        key: Key('webview'),
                        initialUrl: flutterUrl,
                        javascriptMode: JavascriptMode.unrestricted,
                        onWebViewCreated:
                            (WebViewController webViewController) {
                          _controller = webViewController;
                        },
                      )
              ]),
        ));
  }
}

Body:
try this it will work fine with you

class WebViewScreen extends StatefulWidget {
  final String title;
  final String selectedUrl;

  WebViewScreen({@required this.title, @required this.selectedUrl});

  @override
  _WebViewScreenState createState() => _WebViewScreenState();
}

class _WebViewScreenState extends State<WebViewScreen> {
  Completer<WebViewController> _controller = Completer<WebViewController>();
  bool isLoading = true;

  num position = 1;

  final key = UniqueKey();

  doneLoading(String A) {
    setState(() {
      position = 0;
    });
  }

  startLoading(String A) {
    setState(() {
      position = 1;
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: IndexedStack(index: position, children: <Widget>[
          WebView(
            initialUrl: widget.selectedUrl,
            javascriptMode: JavascriptMode.unrestricted,
            key: key,
            onPageFinished: doneLoading,
            onPageStarted: startLoading,
            onWebViewCreated: (WebViewController webViewController) {
              _controller.complete(webViewController);
            },
          ),
          Container(
            color: Colors.white,
            child: Center(child: CustomAppProgressBar),
          ),
        ]));
  }
}


问:
How can I handle the cancel and the ok button in the dialog
I want when I click the ok button is the dialog it does something,same as the cancel button

override
    fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

```<code>    val builder = AlertDialog.Builder(this.requireActivity())

    // Dialog will have "Make a selection" as the title
    builder.setMessage("Details successfully captured.Do you wish to proceed and book your seat?")
        // An OK button that does nothing
        .setPositiveButton("OK") { dialog, id ->
            // Nothing happening here

        }
        // A "Cancel" button that does nothing
        .setNegativeButton("Cancel") { dialog, id ->
            // Nothing happening here either
        }
</code>```

答:
I replaced my code to this and it worked out</p>

```<code>    val intent = Intent(this.requireActivity(), PickSeatActivity::class.java)
         startActivity(intent)
</code>```

Body:
I want when I click the ok button is the dialog it does something,same as the cancel button

override
    fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

    val builder = AlertDialog.Builder(this.requireActivity())

    // Dialog will have "Make a selection" as the title
    builder.setMessage("Details successfully captured.Do you wish to proceed and book your seat?")
        // An OK button that does nothing
        .setPositiveButton("OK") { dialog, id ->
            // Nothing happening here

        }
        // A "Cancel" button that does nothing
        .setNegativeButton("Cancel") { dialog, id ->
            // Nothing happening here either
        }

Body:
I replaced my code to this and it worked out

    val intent = Intent(this.requireActivity(), PickSeatActivity::class.java)
         startActivity(intent)


问:
Firestore security rules: get parameter to use in security rules
I am currently writing some security rules to secure my firestore database, but I am having some issues. I want to be able to get data from my query parameters to put into my rules (I want to be able to use clientId):

db.collection('Users').doc(userId).where('connections', 'array-contains', clientId).get();

I want to be able to use the clientId in my firestore security rules so that I can query another collection using that client id, as I dont think that firestore security rules provides "where" capability in the get queries. Is this at all possible?

Like so:
request.auth.uid in get(/databases/$(database)/documents/Users/$(clientId)).data.connections

Thanks for your help.

答:
I've also been struggling with the same problem for a while and finally managed to solve it:

Database

```<code>/familyMembers/{familyMemberId}
{
    parents
        userId1
            userId: "userId1"
        userId2
            userId: "userId2"
}
</code>```

Security rules

```<code>match /familyMembers/{familyMemberId}/{document=**} {
    allow read, write: if resource.data.parents[request.auth.uid] != null;
}

match /anotherCollection/{familyMemberId}/{document=**} {
    allow read, write: if request.auth.uid in get(/databases/$(database)/documents/familyMembers/$(familyMemberId)).data.parents;
}
</code>```

Query from Swift code

```<code>db.collection("familyMembers").whereField("parents.\(userId).userId", isEqualTo: userId).getDocuments()
</code>```

Reference: https://groups.google.com/forum/#!searchin/firebase-talk/jannica%7Csort:date/firebase-talk/1rTmJmNyJNQ/x2P8vPdqAQAJ

Body:
I've also been struggling with the same problem for a while and finally managed to solve it:

Database

/familyMembers/{familyMemberId}
{
    parents
        userId1
            userId: "userId1"
        userId2
            userId: "userId2"
}

Security rules

match /familyMembers/{familyMemberId}/{document=**} {
    allow read, write: if resource.data.parents[request.auth.uid] != null;
}

match /anotherCollection/{familyMemberId}/{document=**} {
    allow read, write: if request.auth.uid in get(/databases/$(database)/documents/familyMembers/$(familyMemberId)).data.parents;
}

Query from Swift code

db.collection("familyMembers").whereField("parents.\(userId).userId", isEqualTo: userId).getDocuments()

Reference: https://groups.google.com/forum/#!searchin/firebase-talk/jannica%7Csort:date/firebase-talk/1rTmJmNyJNQ/x2P8vPdqAQAJ


问:
C/C++ Variadic Macro Function Overloading
I am trying to build a simple c++ logger for learning purposes, but I seem to be stuck at the following issue. Let's say that I have a namespace that contains two functions as follows:

namespace l {
    void _p(const char* file, const int line, int vl, const char* fmt, ...) {
        printf("%d:%s:%d: ", vl, file, line);
        va_list __args;
        va_start(__args, fmt);
        vfprintf(stdout, fmt, __args);
        printf("\n");
        va_end(__args);
    }
    void _p(const char* file, const int line, const char* fmt, ...) {
        printf("%s:%d: ", file, line);
        va_list __args;
        va_start(__args, fmt);
        vfprintf(stdout, fmt, __args);
        printf("\n");
        va_end(__args);
    }
}
```

<p>and the main function is as follows:</p>

<pre class="lang-cpp prettyprint-override"><code>int main(int argc, char** argv)
{
    l::_p(__FILE__, __LINE__, 12, "%s", "Hello World!");
    l::_p(__FILE__, __LINE__, "%s", "Hello World!");
    return 0;
}
</code>```

what I would like to have is a macro such that when the user types: l::p(12, "%s", "Hello World!"); it would be replaced by l::_p(__FILE__, __LINE__, 12, "%s", "Hello World!"); at compile time. Similarly when the user types l::p("%s", "Hello World!"); it would be replaced by l::_p(__FILE__, __LINE__, "%s", "Hello World!"); at compile time

答:
what I would like to have is a macro such that when the user types: l::p(12, "%s", "Hello World!"); it would be replaced by l::_p(__FILE__, __LINE__, 12, "%s", "Hello World!"); at compile time.

Sure, you can do:

```<code>#define p(...)  _p(__FILE__, __LINE__, __VA_ARGS__)
</code>```

Macros are processed at preprocessing stage at which point compiler is not aware about anything complicated like namespace. So such a macro can be confusing to unaware programmers that will later try to define a function named p or call a function pointer named p.

Preferably in C++ use stream-like interface with a macro instead like BOOST_LOG does for example, (and since C++20 you could use source_location).

Body:
I am trying to build a simple c++ logger for learning purposes, but I seem to be stuck at the following issue. Let's say that I have a namespace that contains two functions as follows:

namespace l {
    void _p(const char* file, const int line, int vl, const char* fmt, ...) {
        printf("%d:%s:%d: ", vl, file, line);
        va_list __args;
        va_start(__args, fmt);
        vfprintf(stdout, fmt, __args);
        printf("\n");
        va_end(__args);
    }
    void _p(const char* file, const int line, const char* fmt, ...) {
        printf("%s:%d: ", file, line);
        va_list __args;
        va_start(__args, fmt);
        vfprintf(stdout, fmt, __args);
        printf("\n");
        va_end(__args);
    }
}

and the main function is as follows:

int main(int argc, char** argv)
{
    l::_p(__FILE__, __LINE__, 12, "%s", "Hello World!");
    l::_p(__FILE__, __LINE__, "%s", "Hello World!");
    return 0;
}

what I would like to have is a macro such that when the user types: l::p(12, "%s", "Hello World!"); it would be replaced by l::_p(__FILE__, __LINE__, 12, "%s", "Hello World!"); at compile time. Similarly when the user types l::p("%s", "Hello World!"); it would be replaced by l::_p(__FILE__, __LINE__, "%s", "Hello World!"); at compile time

Body:
what I would like to have is a macro such that when the user types: l::p(12, "%s", "Hello World!"); it would be replaced by l::_p(__FILE__, __LINE__, 12, "%s", "Hello World!"); at compile time.

Sure, you can do:

#define p(...)  _p(__FILE__, __LINE__, __VA_ARGS__)

Macros are processed at preprocessing stage at which point compiler is not aware about anything complicated like namespace. So such a macro can be confusing to unaware programmers that will later try to define a function named p or call a function pointer named p.

Preferably in C++ use stream-like interface with a macro instead like BOOST_LOG does for example, (and since C++20 you could use source_location).


问:
How to get the index of element in an array and return the next element in Hive?
I have two tables.

table1:

```<code>id    |   array1
1     |     ['a', 'b', 'c']
2     |     ['b', 'a', 'c']
3     |     ['c', 'b', 'a']
</code>```

table2:

```<code>id    |    value2
1     |     'b'
3     |     'a'
</code>```

I wish to get the following table:

```<code>id    |    value3
1     |     'c'
2     |     'b'
3     |     'c'
</code>```

Explanation: what I want is that if the id in table1 does't exist in table2, then return the first element of array1. if the id in table1 exists in table2, then return the next element of value2 in array1 (in this case if value2 is the last element in array1, return the first element of array1)

How can I achieve this goal?

答:
Explode array using posexplode, join with table2, calculate position for joined rows, aggregate, extract array elements.

Demo:

```<code>with table1 as(
select stack(3,
1, array('a', 'b', 'c'),
2, array('b', 'a', 'c'),
3, array('c', 'b', 'a')
) as (id,array1)
),

table2 as(
select stack(2,
1,'b',
3,'a'
) as (id,value2)
)

select s.id, nvl(s.array1[pos], s.array1[0]) value3
from
(
select s.id, s.array1, min(case when t2.id is not null then s.pos+1 end) pos
from
(
select t.id, t.array1, a.pos, a.value1
  from table1 t
       lateral view posexplode(t.array1) a as pos, value1
)s left join table2 t2 on s.id=t2.id and s.value1=t2.value2
group by s.id, s.array1
)s
order by id
</code>```

Result:

```<code>id  value3
1   c
2   b
3   c
</code>```

Body:
I have two tables.

table1:

id    |   array1
1     |     ['a', 'b', 'c']
2     |     ['b', 'a', 'c']
3     |     ['c', 'b', 'a']

table2:

id    |    value2
1     |     'b'
3     |     'a'

I wish to get the following table:

id    |    value3
1     |     'c'
2     |     'b'
3     |     'c'

Explanation: what I want is that if the id in table1 does't exist in table2, then return the first element of array1. if the id in table1 exists in table2, then return the next element of value2 in array1 (in this case if value2 is the last element in array1, return the first element of array1)

How can I achieve this goal?

Body:
Explode array using posexplode, join with table2, calculate position for joined rows, aggregate, extract array elements.

Demo:

with table1 as(
select stack(3,
1, array('a', 'b', 'c'),
2, array('b', 'a', 'c'),
3, array('c', 'b', 'a')
) as (id,array1)
),

table2 as(
select stack(2,
1,'b',
3,'a'
) as (id,value2)
)

select s.id, nvl(s.array1[pos], s.array1[0]) value3
from
(
select s.id, s.array1, min(case when t2.id is not null then s.pos+1 end) pos
from
(
select t.id, t.array1, a.pos, a.value1
  from table1 t
       lateral view posexplode(t.array1) a as pos, value1
)s left join table2 t2 on s.id=t2.id and s.value1=t2.value2
group by s.id, s.array1
)s
order by id

Result:

id  value3
1   c
2   b
3   c


问:
Javascript json
does anyone know what this is not working? i have been trying for days now.

```<code>function loadContent(obj, getcmt)
{
var params = $(obj).attr('href').split('?');

$.get(BASE_DIR+'content/load.php?'+params[1],
     function(json) {
       var result = eval('('+json+')');
       if (result.returnval == 1) {
         $('#content').fadeOut('fast', function() { $(this).html(result.content).fadeIn('slow'); });

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

Firebug just give an error "missing } after property list"
and link to jquery. and another debugger show json as the reason why.

any help is greatly appreciated!

EDIT:

The top work fine but the following dont work:

```<code><div id="content">
    <a href="{$content.item_url}" onclick="return loadContent2(this, 'page', '2')">
</a>
</div>
</code>```

how ever if the single quote in onClick is not there, it work. like so:

```<code><div id="content">
    <a href="{$content.item_url}" onclick="return loadContent2(this, "page", "2")">
</a>
</div>
</code>```

However the function in question loadContent2 does not work.

答:
Try it using jQuery's built-in tools:

```<code>function loadContent(obj, getcmt) {
    var params = $(obj).attr('href').split('?');
    $.getJSON(BASE_DIR+'content/load.php?'+params[1], function(json) {
        if (json.returnval == 1) {
            $('#content').fadeOut('fast', function() {
                $(this).html(json.content).fadeIn('slow');
            });
        }
    });
    return false;
}
</code>```

This uses $.getJSON() which is awesome.

if that has problems, check your response:

```<code>$.getJSON(BASE_DIR+'content/load.php?'+params[1], function(json) {
    console.debug(json);
});
</code>```

Title: Javascript json

Body:
does anyone know what this is not working? i have been trying for days now.

function loadContent(obj, getcmt)
{
var params = $(obj).attr('href').split('?');

$.get(BASE_DIR+'content/load.php?'+params[1],
     function(json) {
       var result = eval('('+json+')');
       if (result.returnval == 1) {
         $('#content').fadeOut('fast', function() { $(this).html(result.content).fadeIn('slow'); });

       }
    });
return false;
}

Firebug just give an error "missing } after property list"
and link to jquery. and another debugger show json as the reason why.

any help is greatly appreciated!

EDIT:

The top work fine but the following dont work:

how ever if the single quote in onClick is not there, it work. like so:

However the function in question loadContent2 does not work.

Body:
Try it using jQuery's built-in tools:

function loadContent(obj, getcmt) {
    var params = $(obj).attr('href').split('?');
    $.getJSON(BASE_DIR+'content/load.php?'+params[1], function(json) {
        if (json.returnval == 1) {
            $('#content').fadeOut('fast', function() {
                $(this).html(json.content).fadeIn('slow');
            });
        }
    });
    return false;
}

This uses $.getJSON() which is awesome.

if that has problems, check your response:

$.getJSON(BASE_DIR+'content/load.php?'+params[1], function(json) {
    console.debug(json);
});


问:
Why [tag:weasyprint] xhtml-to-pdf does not fit A4 page?
I try to convert an "xhtml web page" to an "A4 portrait pdf" with weasyprint Python 3 API.
Here  is the page.

But the pdf file, at the end, does not fit A4 page.

Here is the python code :

```<code>#!/usr/bin/python3

from weasyprint import HTML, CSS
import subprocess

Page = HTML(url="https://educadhoc.hachette-livre.fr/extract/complet/9782401058705/show-page/page325.xhtml")
Style = CSS(string='''
    @page {
        size: A4 portrait;
        max-height:100%;
        max-width:100%;
        }
''')
Page.write_pdf(target="Try.pdf", zoom=1, stylesheets=[Style])
subprocess.Popen(["evince", "Try.pdf"])
</code>```

It does not fit A4 even with "size A4 portrait" in CSS style and "zoom=1" in write_pdf method!

(There is also lines shifts in the pdf file ! ...)

What do you suggest ?

答:
Yes !
I changed ...
Stop using Weasyprint and go to selenium, more customizable

```<code>#!/usr/bin/python3
# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

######  SELENIUM PARAMETERS
path_to_binary = "/usr/bin/firefox-esr"
path_to_webdriver = "/usr/local/bin/geckodriver"
capabilities = webdriver.DesiredCapabilities().FIREFOX
my_options = Options()
my_options.headless = True
my_options.add_argument("--width=1426")
my_options.add_argument("--height=2048")
my_options.binary_location = path_to_binary
my_service = Service(path_to_webdriver)

######  GO GO GO !
driver = webdriver.Firefox(service=my_service, options=my_options)
driver.get("https://educadhoc.hachette-livre.fr/extract/complet/9782401058705/show-page/page325.xhtml")
driver.execute_script("document.body.style.transform = 'scale(3)'")
driver.find_element_by_tag_name("body").screenshot("TRY.png")
driver.implicitly_wait(2)
driver.close()
</code>```

It works like a charm but in a png image file (not too bad) ; the original web page is 1426x2048 according to the Firefox inspector.

I put a scale(3) that you can adjust according to you in the driver.execute_script line in order to have a 3x more high image size and quality ... (but 3x more heavy !)

You need to install a webdriver (the firefox's one in my case) in the correct path (/usr/local/bin/geckodriver in my case) and you have to locate the binary path too (/usr/local/bin/firefox-esr in my case).

The last webdriver of Firefox (for Linux, Mac or Win) is downloadable at  : https://github.com/mozilla/geckodriver/releases

Then, you can do what you want with this PNG file ! (e.g. use imagemagick to convert into differnet format like pdf if you want ...) Link to Convert

Hope it helps you and the others Python beginners ...

Body:
I try to convert an "xhtml web page" to an "A4 portrait pdf" with weasyprint Python 3 API.
Here  is the page.

But the pdf file, at the end, does not fit A4 page.

Here is the python code :

#!/usr/bin/python3

from weasyprint import HTML, CSS
import subprocess

Page = HTML(url="https://educadhoc.hachette-livre.fr/extract/complet/9782401058705/show-page/page325.xhtml")
Style = CSS(string='''
    @page {
        size: A4 portrait;
        max-height:100%;
        max-width:100%;
        }
''')
Page.write_pdf(target="Try.pdf", zoom=1, stylesheets=[Style])
subprocess.Popen(["evince", "Try.pdf"])

It does not fit A4 even with "size A4 portrait" in CSS style and "zoom=1" in write_pdf method!

(There is also lines shifts in the pdf file ! ...)

What do you suggest ?

Body:
Yes !
I changed ...
Stop using Weasyprint and go to selenium, more customizable

#!/usr/bin/python3
# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

######  SELENIUM PARAMETERS
path_to_binary = "/usr/bin/firefox-esr"
path_to_webdriver = "/usr/local/bin/geckodriver"
capabilities = webdriver.DesiredCapabilities().FIREFOX
my_options = Options()
my_options.headless = True
my_options.add_argument("--width=1426")
my_options.add_argument("--height=2048")
my_options.binary_location = path_to_binary
my_service = Service(path_to_webdriver)

######  GO GO GO !
driver = webdriver.Firefox(service=my_service, options=my_options)
driver.get("https://educadhoc.hachette-livre.fr/extract/complet/9782401058705/show-page/page325.xhtml")
driver.execute_script("document.body.style.transform = 'scale(3)'")
driver.find_element_by_tag_name("body").screenshot("TRY.png")
driver.implicitly_wait(2)
driver.close()

It works like a charm but in a png image file (not too bad) ; the original web page is 1426x2048 according to the Firefox inspector.

I put a scale(3) that you can adjust according to you in the driver.execute_script line in order to have a 3x more high image size and quality ... (but 3x more heavy !)

You need to install a webdriver (the firefox's one in my case) in the correct path (/usr/local/bin/geckodriver in my case) and you have to locate the binary path too (/usr/local/bin/firefox-esr in my case).

The last webdriver of Firefox (for Linux, Mac or Win) is downloadable at  : https://github.com/mozilla/geckodriver/releases

Then, you can do what you want with this PNG file ! (e.g. use imagemagick to convert into differnet format like pdf if you want ...) Link to Convert

Hope it helps you and the others Python beginners ...


问:
How do I remove and re-sort (reindex) columns after applying style in python pandas?
Is there a way to remove columns or rows after applying style in python pandas? And re-sort them?

```<code>styled = df.style.apply(colorize, axis=None)
#remove _x columns
yonly = list(sorted(set(styled.columns) - set(df.filter(regex='_x$').columns)))
###Remove columns that end with "_x" here
styled.to_excel('styled.xlsx', engine='openpyxl', freeze_panes=(1,1))
</code>```

Most things I tried were unavailable, i.e.
styled.reindex(columns=yonly) returned AttributeError: 'Styler' object has no attribute 'reindex'

styled.columns = yonly returned AttributeError: 'list' object has no attribute 'get_indexer'

styled = styled[yonly] returns
TypeError: 'Styler' object is not subscriptable

Follow-up from Colour specific cells from two columns that don't match, using python pandas style.where (or otherwise) and export to excel

答:
I'm not sure about re-sorting, but if you only want to remove (hide) some columns use Styler's

hide_columns method.

For example to hide columns 'A' and 'B':

```<code>hide_columns(['A', 'B'])
</code>```

Body:
Is there a way to remove columns or rows after applying style in python pandas? And re-sort them?

styled = df.style.apply(colorize, axis=None)
#remove _x columns
yonly = list(sorted(set(styled.columns) - set(df.filter(regex='_x$').columns)))
###Remove columns that end with "_x" here
styled.to_excel('styled.xlsx', engine='openpyxl', freeze_panes=(1,1))

Most things I tried were unavailable, i.e.
styled.reindex(columns=yonly) returned AttributeError: 'Styler' object has no attribute 'reindex'

styled.columns = yonly returned AttributeError: 'list' object has no attribute 'get_indexer'

styled = styled[yonly] returns
TypeError: 'Styler' object is not subscriptable

Follow-up from Colour specific cells from two columns that don't match, using python pandas style.where (or otherwise) and export to excel

Body:
I'm not sure about re-sorting, but if you only want to remove (hide) some columns use Styler's

hide_columns method.

For example to hide columns 'A' and 'B':

hide_columns(['A', 'B'])


问:
Is there a function like millis() of Arduino in python?
Is there a function like millis() of Arduino (not delay() function) in python?
I want to stop a specific part of program for a while ,but not the whole program.</p>

答:
Try using utime functions

https://docs.micropython.org/en/latest/library/utime.html

Hope that helps.


问:
Why does using Shell to run a .MSI file sometimes fail in VB6?
I am attempting to launch the .NET CF installer from a VB6 app using the following code (for the sake of brevity I have replaced the full path to the installer with "(full path)"):

```<code>Shell "C:\WINDOWS\system32\msiexec.exe /fa ""(full path)\NETCFSetupv35.msi"""
</code>```

I've run this on four machines so far.  On two it works fine, on the other two it fails.  When it works, the CF installer just runs.  When it fails, the first thing it does is pop up a dialog saying, "The feature you are trying to use is on a CD ROM or other removable disk that is not available."  The dialog provides a text box to enter a path and a browse button to find it, so I provide the path, click the open button and get this error, "Error 1706.No valid source could be found for product Microsoft .NET Compact Framework 3.5.  The Windows Installer cannot continue."

Can anyone tell me what's going wrong here?  What is missing from the machines upon which it fails?

答:
Possibly a problem with the Compact Framework MSI itself? You could try Microsoft support (do you have a MSDN subscription?), or posting on a newsgroup.

Alternatively try adding the logging argument to your command line "/l* LogFile.txt" (don't include the quotes) and then try to understand the log.

OwnerDisplayName: raven

ContentLicense: CC BY-SA 2.5

Body:
I am attempting to launch the .NET CF installer from a VB6 app using the following code (for the sake of brevity I have replaced the full path to the installer with "(full path)"):

Shell "C:\WINDOWS\system32\msiexec.exe /fa ""(full path)\NETCFSetupv35.msi"""

I've run this on four machines so far.  On two it works fine, on the other two it fails.  When it works, the CF installer just runs.  When it fails, the first thing it does is pop up a dialog saying, "The feature you are trying to use is on a CD ROM or other removable disk that is not available."  The dialog provides a text box to enter a path and a browse button to find it, so I provide the path, click the open button and get this error, "Error 1706.No valid source could be found for product Microsoft .NET Compact Framework 3.5.  The Windows Installer cannot continue."

Can anyone tell me what's going wrong here?  What is missing from the machines upon which it fails?

OwnerDisplayName: MarkJ


问:
Does anyone know the algorithm used for navigating a Pac-Man maze?
I need an algorithm for this pacman maze. Can anyone help?</p>

答: You don't say what kind of algorithm you want, but if you are implementing the movement of the ghosts, then you should read "Understanding Pac-Man Ghost Behavior" by Chad Birch.</p>


问:
Testing code that uses an IntersectionObserver
I have a JavaScript component in my application that handles infinite scroll pagination, and i'm trying to rewrite it to use the IntersectionObserver, as described here, however I'm having issues in testing it.

Is there a way to drive the behavior of the observer in a QUnit test, i.e. to trigger the observer callback with some entries described in my tests?

A possible solution I have come up with is to expose the callback function in the component's prototype and to invoke it directly in my test, something like this:

```<code>InfiniteScroll.prototype.observerCallback = function(entries) {
    //handle the infinite scroll
}

InfiniteScroll.prototype.initObserver = function() {
    var io = new IntersectionObserver(this.observerCallback);
    io.observe(someElements);
}

//In my test
var component = new InfiniteScroll();
component.observerCallback(someEntries);
//Do some assertions about the state after the callback has been executed
</code>```

I don't really like this approach since it's exposing the fact that the component uses an IntersectionObserver internally, which is an implementation detail that in my opinion should not be visible to client code, so is there any better way to test this (ideally not using jQuery)?

答:
None of the posted answered worked for me because of our configuration of TypeScript and React (tsx) we're using. Here's what finally worked:</p>

```<code>beforeEach(() => {
  // IntersectionObserver isn't available in test environment
  const mockIntersectionObserver = jest.fn();
  mockIntersectionObserver.mockReturnValue({
    observe: () => null,
    unobserve: () => null,
    disconnect: () => null
  });
  window.IntersectionObserver = mockIntersectionObserver;
});
</code>```

Body:
I have a JavaScript component in my application that handles infinite scroll pagination, and i'm trying to rewrite it to use the IntersectionObserver, as described here, however I'm having issues in testing it.

Is there a way to drive the behavior of the observer in a QUnit test, i.e. to trigger the observer callback with some entries described in my tests?

A possible solution I have come up with is to expose the callback function in the component's prototype and to invoke it directly in my test, something like this:

InfiniteScroll.prototype.observerCallback = function(entries) {
    //handle the infinite scroll
}

InfiniteScroll.prototype.initObserver = function() {
    var io = new IntersectionObserver(this.observerCallback);
    io.observe(someElements);
}

//In my test
var component = new InfiniteScroll();
component.observerCallback(someEntries);
//Do some assertions about the state after the callback has been executed

I don't really like this approach since it's exposing the fact that the component uses an IntersectionObserver internally, which is an implementation detail that in my opinion should not be visible to client code, so is there any better way to test this (ideally not using jQuery)?

Body:
None of the posted answered worked for me because of our configuration of TypeScript and React (tsx) we're using. Here's what finally worked:

beforeEach(() => {
  // IntersectionObserver isn't available in test environment
  const mockIntersectionObserver = jest.fn();
  mockIntersectionObserver.mockReturnValue({
    observe: () => null,
    unobserve: () => null,
    disconnect: () => null
  });
  window.IntersectionObserver = mockIntersectionObserver;
});


问:
How to log out users from web client application that uses JWT tokens
I have an ASP.Net Core 3.1 web-api application that uses MS Identity framework to generate JWT tokens for the logged in user.

Then I have a client application (html , javascript) that connects to that web-api.

I also have an android application that connects to the same web-api application.

I want to log out a user from web client when it logins from the android application.
How to do that?

答:
This is the challenge with JWT token. TO validate JWT token client doesn't need to talk to token issuer. If the client does then no use of using a JWT token.

You can follow the below approach to handle logoff scenario:

Approach 1) Keep JWT token a very short life span.

Approach 2) Maintain a distributed cache - where all the logged off JWT token can be stored and before validating the token check with the distributed cache.