问:
Computing most recent smaller value
I have an excel sheet with dates (sorted) in one column and values in another. Ex:

```<code>1/1/2019     10
1/2/2019     12
1/3/2019     8
1/4/2019     20
1/10/2019    8
1/12/2019    22
</code>```

I want to compute in a third column, the most recent date such that value was less than or equal to the current value (if the current is the lowest, then use the current date).  So, for the sample data above,

```<code>1/1/2019     10    1/1/2019
1/2/2019     12    1/1/2019
1/3/2019     8     1/3/2019
1/4/2019     20    1/3/2019
1/10/2019    8     1/3/2019
1/12/2019    22    1/10/2019
</code>```

Is there a way of accomplishing this without VBA macros?

答:
Here's a way.  Paste these in and copy down the column.

```<code>Column C:  =IF(COUNTIF(B2:B6,D1)=0,A1,MINIFS(A2:A6,B2:B6,D1))

Column D:  =CONCATENATE("<",TEXT(VALUE(B1),"#"))
</code>```

You can hide column D to make it prettier.  It's the criteria being used by the COUNTIF and MINIFS.  Column C is the output.

```<code>1/1/2019    10  1/3/2019    <10
1/2/2019    12  1/3/2019    <12
1/3/2019    8   1/3/2019    <8
1/4/2019    20  1/10/2019   <20
1/10/2019   8   1/10/2019   <8
1/12/2019   22  1/12/2019   <22
</code>```

Formula view:

```<code>43466   10  =IF(COUNTIF(B2:B6,D1)=0,A1,MINIFS(A2:A6,B2:B6,D1))  =CONCATENATE("<",TEXT(VALUE(B1),"#"))
43467   12  =IF(COUNTIF(B3:B7,D2)=0,A2,MINIFS(A3:A7,B3:B7,D2))  =CONCATENATE("<",TEXT(VALUE(B2),"#"))
43468   8   =IF(COUNTIF(B4:B8,D3)=0,A3,MINIFS(A4:A8,B4:B8,D3))  =CONCATENATE("<",TEXT(VALUE(B3),"#"))
43469   20  =IF(COUNTIF(B5:B9,D4)=0,A4,MINIFS(A5:A9,B5:B9,D4))  =CONCATENATE("<",TEXT(VALUE(B4),"#"))
43475   8   =IF(COUNTIF(B6:B10,D5)=0,A5,MINIFS(A6:A10,B6:B10,D5))   =CONCATENATE("<",TEXT(VALUE(B5),"#"))
43477   22  =IF(COUNTIF(B7:B11,D6)=0,A6,MINIFS(A7:A11,B7:B11,D6))   =CONCATENATE("<",TEXT(VALUE(B6),"#"))
</code>```

This is a little sloppy in that you could use a named value or absolute value for the end of the range, e.g. B$6.  Otherwise you're going to be looking at cells below your table, which is fine as long as they're empty, but kind of sloppy.

```<code>Column C:  =IF(COUNTIF(B2:B$6,D1)=0,A1,MINIFS(A2:A$6,B2:B$6,D1))
</code>```

Title: Computing most recent smaller value

Body:
I have an excel sheet with dates (sorted) in one column and values in another. Ex:

1/1/2019     10
1/2/2019     12
1/3/2019     8
1/4/2019     20
1/10/2019    8
1/12/2019    22

I want to compute in a third column, the most recent date such that value was less than or equal to the current value (if the current is the lowest, then use the current date).  So, for the sample data above,

1/1/2019     10    1/1/2019
1/2/2019     12    1/1/2019
1/3/2019     8     1/3/2019
1/4/2019     20    1/3/2019
1/10/2019    8     1/3/2019
1/12/2019    22    1/10/2019

Is there a way of accomplishing this without VBA macros?

Body:
Here's a way.  Paste these in and copy down the column.

Column C:  =IF(COUNTIF(B2:B6,D1)=0,A1,MINIFS(A2:A6,B2:B6,D1))

Column D:  =CONCATENATE("<",TEXT(VALUE(B1),"#"))

You can hide column D to make it prettier.  It's the criteria being used by the COUNTIF and MINIFS.  Column C is the output.

1/1/2019    10  1/3/2019    <10
1/2/2019    12  1/3/2019    <12
1/3/2019    8   1/3/2019    <8
1/4/2019    20  1/10/2019   <20
1/10/2019   8   1/10/2019   <8
1/12/2019   22  1/12/2019   <22

Formula view:

43466   10  =IF(COUNTIF(B2:B6,D1)=0,A1,MINIFS(A2:A6,B2:B6,D1))  =CONCATENATE("<",TEXT(VALUE(B1),"#"))
43467   12  =IF(COUNTIF(B3:B7,D2)=0,A2,MINIFS(A3:A7,B3:B7,D2))  =CONCATENATE("<",TEXT(VALUE(B2),"#"))
43468   8   =IF(COUNTIF(B4:B8,D3)=0,A3,MINIFS(A4:A8,B4:B8,D3))  =CONCATENATE("<",TEXT(VALUE(B3),"#"))
43469   20  =IF(COUNTIF(B5:B9,D4)=0,A4,MINIFS(A5:A9,B5:B9,D4))  =CONCATENATE("<",TEXT(VALUE(B4),"#"))
43475   8   =IF(COUNTIF(B6:B10,D5)=0,A5,MINIFS(A6:A10,B6:B10,D5))   =CONCATENATE("<",TEXT(VALUE(B5),"#"))
43477   22  =IF(COUNTIF(B7:B11,D6)=0,A6,MINIFS(A7:A11,B7:B11,D6))   =CONCATENATE("<",TEXT(VALUE(B6),"#"))

This is a little sloppy in that you could use a named value or absolute value for the end of the range, e.g. B$6.  Otherwise you're going to be looking at cells below your table, which is fine as long as they're empty, but kind of sloppy.

Column C:  =IF(COUNTIF(B2:B$6,D1)=0,A1,MINIFS(A2:A$6,B2:B$6,D1))


来源: stackexchange

问:
How do I pause or delay blinking text animation, so my text displays for a short period of time?
I have a button with some text that blinks, however I want to delay it for a short time when the text is visible, giving the user enough time to read the text before it fades to transparent.</p>

```<code>.btn-blink{
 border: 2px solid #4aa570;
 margin-bottom:20px;
 color:#fff;background:#4aa570;
 animation:blinkingText 3.2s infinite;
}

@keyframes blinkingText{
    0%{ color: #fff;    }
    25%{color: transparent; }
    50%{color: #fff;    }
    75%{color: transparent;}
    100%{color: #fff;   }
    }
</code>```

答:
Disperse the transitions in your @keyframes by percentage to make it irregular.</p>

```<code>@keyframes blinkingText {
    0% {color: #fff;}
    50% {color: #fff;}
    75% {color: transparent;}
    100% {color: #fff;}
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a button with some text that blinks, however I want to delay it for a short time when the text is visible, giving the user enough time to read the text before it fades to transparent.

.btn-blink{
 border: 2px solid #4aa570;
 margin-bottom:20px;
 color:#fff;background:#4aa570;
 animation:blinkingText 3.2s infinite;
}

@keyframes blinkingText{
    0%{ color: #fff;    }
    25%{color: transparent; }
    50%{color: #fff;    }
    75%{color: transparent;}
    100%{color: #fff;   }
    }

Body:
Disperse the transitions in your @keyframes by percentage to make it irregular.

@keyframes blinkingText {
    0% {color: #fff;}
    50% {color: #fff;}
    75% {color: transparent;}
    100% {color: #fff;}
}


问:
How can I toggle the value of an svg text element with D3.js when user clicks the text?
I have just started to learn D3.js and have written a small program to test some ideas that I plan to implement in a larger program. Referring to the code here, the initial value of the text is 0. I am trying to have the value toggle between 1 and 0 when a user clicks on the text. There is something wrong with what I’ve coded in .on(“click”…) because the text does not change to 1.  What am I doing wrong?

I've found examples of updating .attr, but I can't find anything about toggling .text in the manner I want.

```<code>            var txt1 = g.append("text")
                        .attr("id", "txt1")
                        .text("0")
                        .attr("x", 10)
                        .attr("y", 17)
                        .attr("font-family", "Arial")
                        .attr("font-size", "12")
                        .attr("fill", "black")
                        .on("click", function(){
                            if (d3.select(this).text === "0"){
                                d3.select(this).text("1")
                            }
                            else{
                                d3.select(this).text("0");
                            }
                        } )
</code>```

When I click on the text element the first time I expect to see it change to "1".

答:
To get the text content of the SVG element directly you can use textContent or innerHTML in modern browsers. For instance:

var svg = d3.select("svg")
var txt1 = svg.append("text")
  .text("0")
  .attr("x", 10)
  .attr("y", 20)
  .on("click", function() {
    console.log(this.textContent)
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg></code>```

However, because you're using a D3 selection, not an SVG node, you should use text as a getter, which is text(). By the way, text() internally uses textContent:

```<code>export default function(value) {
  return arguments.length
      ? this.each(value == null
          ? textRemove : (typeof value === "function"
          ? textFunction
          : textConstant)(value))
      : this.node().textContent;
}
</code>```

Finally, you don't need that if block. To toggle between 0 and 1, just do:

```<code>this.textContent = 1 - (+this.textContent);
</code>```

You can even drop the unary plus, since the string will be converted to a number anyway:

```<code>this.textContent = 1 - this.textContent;
</code>```

Here is the snippet:

var svg = d3.select("svg")
var txt1 = svg.append("text")
  .text("0")
  .attr("x", 10)
  .attr("y", 20)
  .on("click", function() {
    this.textContent = 1 - (+this.textContent);
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg></code>```

Body:
I have just started to learn D3.js and have written a small program to test some ideas that I plan to implement in a larger program. Referring to the code here, the initial value of the text is 0. I am trying to have the value toggle between 1 and 0 when a user clicks on the text. There is something wrong with what I’ve coded in .on(“click”…) because the text does not change to 1.  What am I doing wrong?

I've found examples of updating .attr, but I can't find anything about toggling .text in the manner I want.

            var txt1 = g.append("text")
                        .attr("id", "txt1")
                        .text("0")
                        .attr("x", 10)
                        .attr("y", 17)
                        .attr("font-family", "Arial")
                        .attr("font-size", "12")
                        .attr("fill", "black")
                        .on("click", function(){
                            if (d3.select(this).text === "0"){
                                d3.select(this).text("1")
                            }
                            else{
                                d3.select(this).text("0");
                            }
                        } )

When I click on the text element the first time I expect to see it change to "1".

Body:
To get the text content of the SVG element directly you can use textContent or innerHTML in modern browsers. For instance:

var svg = d3.select("svg")
var txt1 = svg.append("text")
  .text("0")
  .attr("x", 10)
  .attr("y", 20)
  .on("click", function() {
    console.log(this.textContent)
  })

<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>

However, because you're using a D3 selection, not an SVG node, you should use text as a getter, which is text(). By the way, text() internally uses textContent:

export default function(value) {
  return arguments.length
      ? this.each(value == null
          ? textRemove : (typeof value === "function"
          ? textFunction
          : textConstant)(value))
      : this.node().textContent;
}

Finally, you don't need that if block. To toggle between 0 and 1, just do:

this.textContent = 1 - (+this.textContent);

You can even drop the unary plus, since the string will be converted to a number anyway:

this.textContent = 1 - this.textContent;

Here is the snippet:

var svg = d3.select("svg")
var txt1 = svg.append("text")
  .text("0")
  .attr("x", 10)
  .attr("y", 20)
  .on("click", function() {
    this.textContent = 1 - (+this.textContent);
  })

<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>


问:
Trying to hide elements of my game until a condition is met
I have done how to disable tabs and enable. But now I want to hide elements so it's more rewarding when a player unlocks something.

I've tried this:

```<code><div id="turtle" style="visibility: hidden;">
                <label class="radio">
                    <input type="radio" name="turtle">
                </label><img src="turtle.jpg" alt="Smiley face"
height="42" width="42"></div>
            <br />
</code>```

Makes the pet disappear:

Then making a script in JavaScript for each pet when they unlock so they become visible but it is not working correctly.

I thought since rebirth is 4 (did this to test if it works normally starts at 0) my turtle would be the only one revealed.

This is my JavaScript code:

```<code> rebirths = 4

function checkUnlock() {
    if (rebirths >= 4) {
        document.getElementById("turtle").visibility = "visible";
    } else {
        document.getElementById("turtle").visibility = "hidden";
    }

    if (Magiclv >= 10) {
        document.getElementById("lizard").visibility = "visible";
    } else {
        document.getElementById("lizard").visibility = "hidden";
    }

    if (wolf >= 1) {
    document.getElementById("wolf").visibility = "visible";
    } else {
        document.getElementById("wolf").visibility = "hidden";
    }

  function Turtlepassive(){
      if (rebirths >= 3){

      }
  }
</code>```

The rest of my HTML code:

```<code>   <div class="main_container">
        <p>This is the Pets
            <br />
            <br />
            <div id="turtle" class="control">
                <label class="radio">
                    <input type="radio" name="turtle">
                </label><img src="turtle.jpg" alt="Smiley face" height="42"
width="42"></div>
            <br />
            <br />
            <div id="lizard" class="control">
                <label class="radio">
                    <input type="radio" name="lizard">
                </label><img src="lizard.png" alt="Smiley face" height="42"
width="42"></div>
            <br />
            <div id="wolf" class="control">
                <label class="radio">
                    <input type="radio" name="wolf">
                </label><img src="wolf.png" alt="Smiley face" height="60"
width="60"></div>
            <br />

            <script type="text/javascript" src="Pets.js"></script>

        </p>
    </div>
</code>```

I expect the pets to be hidden until their condition is met. New to HTML so confused on how visibility works. But the actual output is they are all revealed and not tied to the conditions.

答:
You've almost got it, but you need to call document.getElementById('turtle').style.visibility = 'hidden';

One thing: you don't need to call document.getElementById every time, you can define the pets as variables:

```<code>const turtle = document.getElementById('turtle');
const lizard = document.getElementById('lizard');
...

if (rebirths >= 4) {
  turtle.style.visibility = 'visible'
} else {
  turtle.style.visibility = 'hidden'
}
</code>```

...and you could shorten that even further with a ternary:

```<code>turtle.style.visibility = rebirths >= 4 ? 'visible' : 'hidden';
</code>```

Body:
I have done how to disable tabs and enable. But now I want to hide elements so it's more rewarding when a player unlocks something.

I've tried this:

                    <input type="radio" name="turtle">

Makes the pet disappear:

Then making a script in JavaScript for each pet when they unlock so they become visible but it is not working correctly.

I thought since rebirth is 4 (did this to test if it works normally starts at 0) my turtle would be the only one revealed.

This is my JavaScript code:

 rebirths = 4

function checkUnlock() {
    if (rebirths >= 4) {
        document.getElementById("turtle").visibility = "visible";
    } else {
        document.getElementById("turtle").visibility = "hidden";
    }

    if (Magiclv >= 10) {
        document.getElementById("lizard").visibility = "visible";
    } else {
        document.getElementById("lizard").visibility = "hidden";
    }

    if (wolf >= 1) {
    document.getElementById("wolf").visibility = "visible";
    } else {
        document.getElementById("wolf").visibility = "hidden";
    }

  function Turtlepassive(){
      if (rebirths >= 3){

      }
  }

The rest of my HTML code:

This is the Pets

                    <input type="radio" name="turtle">

                    <input type="radio" name="lizard">

                    <input type="radio" name="wolf">

I expect the pets to be hidden until their condition is met. New to HTML so confused on how visibility works. But the actual output is they are all revealed and not tied to the conditions.

Body:
You've almost got it, but you need to call document.getElementById('turtle').style.visibility = 'hidden';

One thing: you don't need to call document.getElementById every time, you can define the pets as variables:

const turtle = document.getElementById('turtle');
const lizard = document.getElementById('lizard');
...

if (rebirths >= 4) {
  turtle.style.visibility = 'visible'
} else {
  turtle.style.visibility = 'hidden'
}

...and you could shorten that even further with a ternary:

turtle.style.visibility = rebirths >= 4 ? 'visible' : 'hidden';


问:
How to access a service in ASP.NET Core before building the WebHost?
Let's assume that we have the following Program.cs:

public static class Program
{
    public static async Task Main(string[] args)
    {
        await CreateWebHostBuilder(args).Build().RunAsync();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost
            .CreateDefaultBuilder(args)
            .ConfigureKestrel(options => { options.AllowSynchronousIO = false; })
            .ConfigureFanciness()
            .ConfigureLogging(ConfigureApplicationLogging)
            .UseStartup<Startup>();
    }

    private static void ConfigureApplicationLogging(WebHostBuilderContext context, ILoggingBuilder loggingBuilder)
    {
        var loggingConfiguration = context.Configuration.GetSection("Logging");

        loggingBuilder.AddConfiguration(loggingConfiguration);

        // var fancyService = SomehowGet<IFancyService>();
        // if (fancyService.IsEnabled)
        //     loggingBuilder.AddEventLog(loggingConfiguration);
    }

    public static IWebHostBuilder ConfigureFanciness(this IWebHostBuilder hostBuilder)
    {
        return hostBuilder.ConfigureServices(delegate (WebHostBuilderContext context, IServiceCollection services)
        {
            var fancinessConfiguration = context.Configuration.GetSection("Fanciness");
            services.Configure<FancinessSettings>(fancinessConfiguration);
            services.AddSingleton<IFancyService, FancyService>();

            // var fancyService = SomehowGet<IFancyService>();
            // fancyService.Initialize();
        });
    }
}
```

<p>And the following <code>FancyService.cs</code>:</p>

<pre class="lang-cs prettyprint-override"><code>public sealed class FancyService : IFancyService
{
    private readonly ILogger<FancyService> logger;
    private readonly IOptions<FancinessSettings> settings;

    public FancyService(ILogger<FancyService> logger, IOptions<FancinessSettings> settings)
    {
        this.logger = logger;
        this.settings = settings;
    }

    public bool IsEnabled { get; private set; }

    public void Initialize()
    {
        // do the initialization work and set IsEnabled to some value
    }
}

</code>```

As demonstrated in the example files, loggingBuilder.AddEventLog(loggingConfiguration) depends on IFancyService.IsEnabled that is set when IFancyService.Initialize() is called.

To do that, I need access to an instance of IFancyService; is there a way to achieve this?

答:
As discussed in comments, if your FancyService has no constructor dependency on ILogger<> :

```<code>public sealed class FancyService : IFancyService
{
    public FancyService(IOptions<FancinessSettings> settings)
    { ... }

</code>```

to initialize the IFancyService, simply use an implementation factory to create a IFancyService instance:

public static IWebHostBuilder ConfigureFanciness(this IWebHostBuilder hostBuilder)
{
    return hostBuilder.ConfigureServices(delegate (WebHostBuilderContext context, IServiceCollection services)
    {
        var fancinessConfiguration = context.Configuration.GetSection("Fanciness");
        services.Configure<FancinessSettings>(fancinessConfiguration);
        services.AddSingleton<IFancyService, FancyService>(sp =>{
            var fancy=ActivatorUtilities.CreateInstance(sp,typeof(FancyService)) as FancyService;
            fancy.Initialize();
            return fancy;
        });
    });
}
```
<p>The same trick could also be used to register a logger provider. Since an <code>ILogger<></code> service depends on <code>IEnumerable<ILoggerProvider></code>, we could register an <code>ILoggerProvider</code> instance that provides an additional <code>INullLogger</code> in order to configure the logging behavior according to the current <code>IFancyService</code> :</p>
<pre class="lang-cs prettyprint-override"><code>private static void ConfigureApplicationLogging(WebHostBuilderContext context, ILoggingBuilder loggingBuilder)
{
    var loggingConfiguration = context.Configuration.GetSection("Logging");

    var descriptor=ServiceDescriptor.Singleton<ILoggerProvider,NullLoggerProvider>(sp =>{
        var provider = NullLoggerProvider.Instance;
        var fancy = sp.GetRequiredService<IFancyService>();
        if(fancy.IsEnabled)
        {
            loggingBuilder.AddDebug();
            loggingBuilder.AddEventLog(loggingConfiguration);
            loggingBuilder.AddEventSourceLogger();
            // ... add more configuration as you like
        }else{
            loggingBuilder.AddConsole();
        }
        return provider;
    });
    loggingBuilder.Services.TryAddEnumerable(descriptor);
    loggingBuilder.AddConfiguration(loggingConfiguration);
}
</code>```

As a side note, be aware once the logger has been built, don't change the IFancyService.IsEnabled. That's because the ILogger<> service is a registered as a singleton and never changed once created.

Body:
Let's assume that we have the following Program.cs:

public static class Program
{
    public static async Task Main(string[] args)
    {
        await CreateWebHostBuilder(args).Build().RunAsync();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost
            .CreateDefaultBuilder(args)
            .ConfigureKestrel(options => { options.AllowSynchronousIO = false; })
            .ConfigureFanciness()
            .ConfigureLogging(ConfigureApplicationLogging)
            .UseStartup<Startup>();
    }

    private static void ConfigureApplicationLogging(WebHostBuilderContext context, ILoggingBuilder loggingBuilder)
    {
        var loggingConfiguration = context.Configuration.GetSection("Logging");

        loggingBuilder.AddConfiguration(loggingConfiguration);

        // var fancyService = SomehowGet<IFancyService>();
        // if (fancyService.IsEnabled)
        //     loggingBuilder.AddEventLog(loggingConfiguration);
    }

    public static IWebHostBuilder ConfigureFanciness(this IWebHostBuilder hostBuilder)
    {
        return hostBuilder.ConfigureServices(delegate (WebHostBuilderContext context, IServiceCollection services)
        {
            var fancinessConfiguration = context.Configuration.GetSection("Fanciness");
            services.Configure<FancinessSettings>(fancinessConfiguration);
            services.AddSingleton<IFancyService, FancyService>();

            // var fancyService = SomehowGet<IFancyService>();
            // fancyService.Initialize();
        });
    }
}

And the following FancyService.cs:

public sealed class FancyService : IFancyService
{
    private readonly ILogger<FancyService> logger;
    private readonly IOptions<FancinessSettings> settings;

    public FancyService(ILogger<FancyService> logger, IOptions<FancinessSettings> settings)
    {
        this.logger = logger;
        this.settings = settings;
    }

    public bool IsEnabled { get; private set; }

    public void Initialize()
    {
        // do the initialization work and set IsEnabled to some value
    }
}

As demonstrated in the example files, loggingBuilder.AddEventLog(loggingConfiguration) depends on IFancyService.IsEnabled that is set when IFancyService.Initialize() is called.

To do that, I need access to an instance of IFancyService; is there a way to achieve this?

Body:
As discussed in comments, if your FancyService has no constructor dependency on ILogger<> :

public sealed class FancyService : IFancyService
{
    public FancyService(IOptions<FancinessSettings> settings)
    { ... }

to initialize the IFancyService, simply use an implementation factory to create a IFancyService instance:

public static IWebHostBuilder ConfigureFanciness(this IWebHostBuilder hostBuilder)
{
    return hostBuilder.ConfigureServices(delegate (WebHostBuilderContext context, IServiceCollection services)
    {
        var fancinessConfiguration = context.Configuration.GetSection("Fanciness");
        services.Configure<FancinessSettings>(fancinessConfiguration);
        services.AddSingleton<IFancyService, FancyService>(sp =>{
            var fancy=ActivatorUtilities.CreateInstance(sp,typeof(FancyService)) as FancyService;
            fancy.Initialize();
            return fancy;
        });
    });
}

The same trick could also be used to register a logger provider. Since an ILogger<> service depends on IEnumerable<ILoggerProvider>, we could register an ILoggerProvider instance that provides an additional INullLogger in order to configure the logging behavior according to the current IFancyService :

private static void ConfigureApplicationLogging(WebHostBuilderContext context, ILoggingBuilder loggingBuilder)
{
    var loggingConfiguration = context.Configuration.GetSection("Logging");

    var descriptor=ServiceDescriptor.Singleton<ILoggerProvider,NullLoggerProvider>(sp =>{
        var provider = NullLoggerProvider.Instance;
        var fancy = sp.GetRequiredService<IFancyService>();
        if(fancy.IsEnabled)
        {
            loggingBuilder.AddDebug();
            loggingBuilder.AddEventLog(loggingConfiguration);
            loggingBuilder.AddEventSourceLogger();
            // ... add more configuration as you like
        }else{
            loggingBuilder.AddConsole();
        }
        return provider;
    });
    loggingBuilder.Services.TryAddEnumerable(descriptor);
    loggingBuilder.AddConfiguration(loggingConfiguration);
}

As a side note, be aware once the logger has been built, don't change the IFancyService.IsEnabled. That's because the ILogger<> service is a registered as a singleton and never changed once created.


问:
how do I let a iterator operate on a list using the assignment operator
Dear stackoverflow community, I have question about how to let the qlistiterator operate on a qlist. According to qt's documentation, qlistiterator has a assignment operator "=", like this:

QListIterator & QListIterator::operator=(const QList<T> & list)
```

<p>For my code, I have two members in my mainwindow class:</p>

<pre class="lang-cpp prettyprint-override"><code>QList<int> timepoints;
QListIterator<int> timeIter(QList<int> &list);
</code>```

and in the constructor:

```<code>timeIter=timepoints;
</code>```

but this line gives an error:

```<code>invalid use of member function (did you forget the '()' ?)
</code>```

Anyone can help explain why?

答:
QListIterator is being wrongly declared as a member function instead of a member variable.

In your class declaration use:

```<code>class YourClass {
    QListIterator<int> timeIter;
};
</code>```

The assignment operator allows you to reassign the iterator. It can't be used as you're intending because QListIterator doesn't have a default constructor. Therefore to do what you're trying to do, use an initializer:

```<code>YourClass::YourClass()
    :timeIter{timepoints}
{
}
</code>```

Body:
Dear stackoverflow community, I have question about how to let the qlistiterator operate on a qlist. According to qt's documentation, qlistiterator has a assignment operator "=", like this:

QListIterator & QListIterator::operator=(const QList<T> & list)

For my code, I have two members in my mainwindow class:

QList<int> timepoints;
QListIterator<int> timeIter(QList<int> &list);

and in the constructor:

timeIter=timepoints;

but this line gives an error:

invalid use of member function (did you forget the '()' ?)

Anyone can help explain why?

Body:
QListIterator is being wrongly declared as a member function instead of a member variable.

In your class declaration use:

class YourClass {
    QListIterator<int> timeIter;
};

The assignment operator allows you to reassign the iterator. It can't be used as you're intending because QListIterator doesn't have a default constructor. Therefore to do what you're trying to do, use an initializer:

YourClass::YourClass()
    :timeIter{timepoints}
{
}


问:
Uncaught TypeError for Array
I'm a beginner working on a simple Tic Tac Toe game in Java Script. Each of the game fields is defined in the "fields" array. I want to have a "for" loop to change the value in the field to "X" on click.

Here is the code that I'm using, which gives me the following error message: Uncaught TypeError: Cannot set property 'textContent' of undefined
    at HTMLTableCellElement.fields..onclick . The console log works just fine.

```<code>for(var b=0; b < fields.length; b++){
    fields[b].onclick = function(){
    console.log("content changed")
    fields[b].textContent= 'X'}
};
</code>```

I don't understand why this is not working, while this works exactly as expected and changes the value of every cell to "g":

```<code>for(var b=0; b < fields.length; b++){
    fields[b].textContent ="g"
};
</code>```

And when I use one field from the array, it also works just fine.

```<code>fields[3].onclick = function(){
console.log("content changed")
fields[3].textContent= 'X'}
</code>```

Why is my code giving me the error message?

答:
Your index b is resolved to the value at the end of the loop when it tries set the eventlistener and textContent.

Try "let" instead of "var" (works for me with let).

for(let b=0; b < fields.length; b++)

Title: Uncaught TypeError for Array

Body:
I'm a beginner working on a simple Tic Tac Toe game in Java Script. Each of the game fields is defined in the "fields" array. I want to have a "for" loop to change the value in the field to "X" on click.

Here is the code that I'm using, which gives me the following error message: Uncaught TypeError: Cannot set property 'textContent' of undefined
    at HTMLTableCellElement.fields..onclick . The console log works just fine.

for(var b=0; b < fields.length; b++){
    fields[b].onclick = function(){
    console.log("content changed")
    fields[b].textContent= 'X'}
};

I don't understand why this is not working, while this works exactly as expected and changes the value of every cell to "g":

for(var b=0; b < fields.length; b++){
    fields[b].textContent ="g"
};

And when I use one field from the array, it also works just fine.

fields[3].onclick = function(){
console.log("content changed")
fields[3].textContent= 'X'}

Why is my code giving me the error message?


问:
How to format an Array of Arrays of Object in JS
I want to formatting this Array in a computed property in VueJS, but I have one problem in the moment to access to newArray, all of elements in one only array

```<code>getNewArray(){
const newArray = []
const = this.data.map(item =>{
    for(let i in item){
       newArray.push(item.value)
  }
return newArray
})
}
</code>```

```<code>data:[
    [
    {idStatus: 2, value: '120'},
    {idStatus: 3, value: '130'},
    {idStatus: 4, value: '140'},
    {idStatus: 5, value: '150'}
    ],
    [
    {idStatus: 1, value: '160'},
    {idStatus: 2, value: '180'},
    {idStatus: 4, value: '10'},
    {idStatus: 5, value: '20'}
    ],
    [
    {idStatus: 3, value: '567'},
    {idStatus: 6, value: '234'},
    {idStatus: 9, value: '747'},
    {idStatus: 7, value: '789'}
    ],
    [
    {idStatus: 8, value: '340'},
    {idStatus: 5, value: '560'},
    {idStatus: 6, value: '120'},
    {idStatus: 2, value: '100'}
    ],
    [
    {idStatus: 1, value: '106'},
    {idStatus: 5, value: '345'},
    {idStatus: 7, value: '756'},
    {idStatus: 9, value: '946'}
    ]
    ]
</code>```

The result that I want to obtain is this

```<code>    data:[
    [120,130,140,150],
    [160,180,10,20],
    [567,234,747,789],
    [340,560,120,100],
    [106,345,756,946]
    ]
</code>```

答:
```<code>var data = [
    [
    {idStatus: 2, value: '120'},
    {idStatus: 3, value: '130'},
    {idStatus: 4, value: '140'},
    {idStatus: 5, value: '150'}
    ],
    [
    {idStatus: 1, value: '160'},
    {idStatus: 2, value: '180'},
    {idStatus: 4, value: '10'},
    {idStatus: 5, value: '20'}
    ],
    [
    {idStatus: 3, value: '567'},
    {idStatus: 6, value: '234'},
    {idStatus: 9, value: '747'},
    {idStatus: 7, value: '789'}
    ],
    [
    {idStatus: 8, value: '340'},
    {idStatus: 5, value: '560'},
    {idStatus: 6, value: '120'},
    {idStatus: 2, value: '100'}
    ],
    [
    {idStatus: 1, value: '106'},
    {idStatus: 5, value: '345'},
    {idStatus: 7, value: '756'},
    {idStatus: 9, value: '946'}
    ]
]

function getNewArray() {
    //convert string to int
    return data.map(item => item.map(v => parseInt(v.value)))
}
let newArray = getNewArray();

console.log(newArray);
console.log(JSON.stringify(newArray));
</code>```

print:[[120,130,140,150], [160,180,10,20],[567,234,747,789],[340,560,120,100],[106,345,756,946]]

Body:
I want to formatting this Array in a computed property in VueJS, but I have one problem in the moment to access to newArray, all of elements in one only array

getNewArray(){
const newArray = []
const = this.data.map(item =>{
    for(let i in item){
       newArray.push(item.value)
  }
return newArray
})
}

data:[
    [
    {idStatus: 2, value: '120'},
    {idStatus: 3, value: '130'},
    {idStatus: 4, value: '140'},
    {idStatus: 5, value: '150'}
    ],
    [
    {idStatus: 1, value: '160'},
    {idStatus: 2, value: '180'},
    {idStatus: 4, value: '10'},
    {idStatus: 5, value: '20'}
    ],
    [
    {idStatus: 3, value: '567'},
    {idStatus: 6, value: '234'},
    {idStatus: 9, value: '747'},
    {idStatus: 7, value: '789'}
    ],
    [
    {idStatus: 8, value: '340'},
    {idStatus: 5, value: '560'},
    {idStatus: 6, value: '120'},
    {idStatus: 2, value: '100'}
    ],
    [
    {idStatus: 1, value: '106'},
    {idStatus: 5, value: '345'},
    {idStatus: 7, value: '756'},
    {idStatus: 9, value: '946'}
    ]
    ]

The result that I want to obtain is this

    data:[
    [120,130,140,150],
    [160,180,10,20],
    [567,234,747,789],
    [340,560,120,100],
    [106,345,756,946]
    ]

Body:
var data = [
    [
    {idStatus: 2, value: '120'},
    {idStatus: 3, value: '130'},
    {idStatus: 4, value: '140'},
    {idStatus: 5, value: '150'}
    ],
    [
    {idStatus: 1, value: '160'},
    {idStatus: 2, value: '180'},
    {idStatus: 4, value: '10'},
    {idStatus: 5, value: '20'}
    ],
    [
    {idStatus: 3, value: '567'},
    {idStatus: 6, value: '234'},
    {idStatus: 9, value: '747'},
    {idStatus: 7, value: '789'}
    ],
    [
    {idStatus: 8, value: '340'},
    {idStatus: 5, value: '560'},
    {idStatus: 6, value: '120'},
    {idStatus: 2, value: '100'}
    ],
    [
    {idStatus: 1, value: '106'},
    {idStatus: 5, value: '345'},
    {idStatus: 7, value: '756'},
    {idStatus: 9, value: '946'}
    ]
]

function getNewArray() {
    //convert string to int
    return data.map(item => item.map(v => parseInt(v.value)))
}
let newArray = getNewArray();

console.log(newArray);
console.log(JSON.stringify(newArray));

print:[[120,130,140,150], [160,180,10,20],[567,234,747,789],[340,560,120,100],[106,345,756,946]]


问:
UPDATE to remove duplicates from comma-separated list
In my Postgres db, I have a table with some columns where one column B has values as follows:

```<code>A      B
a1     b0, b1, b1
a2     b2, b3
a3     b4, b4, b5, b5
</code>```

My expected output should be like this:

```<code>A      B
a1     b0, b1
a2     b2, b3
a3     b4, b5
</code>```

Is there a simple UPDATE in Postgres to do this?

答:
Assuming: current version of Postgres, data type of B is text, separator in your list is ', ', remove all duplicates, preserve original order of elements, most or all rows have duplicates:

Then this should be simplest and fastest:

```<code>UPDATE tbl
SET    B = array_to_string( ARRAY(
         SELECT elem
         FROM   unnest(string_to_array(B, ', ')) WITH ORDINALITY x(elem, ord)
         GROUP  BY 1
         ORDER  BY min(ord)
         ), ', ');
</code>```

The drawback: all rows are updated, even if nothing changes. If that affects more than a few rows, it can be avoided ...

If any assumptions do not hold, there may be a different / better / faster solution.

Related:

Distinct values from an array?

PostgreSQL unnest() with element number

Body:
In my Postgres db, I have a table with some columns where one column B has values as follows:

A      B
a1     b0, b1, b1
a2     b2, b3
a3     b4, b4, b5, b5

My expected output should be like this:

A      B
a1     b0, b1
a2     b2, b3
a3     b4, b5

Is there a simple UPDATE in Postgres to do this?

Body:
Assuming: current version of Postgres, data type of B is text, separator in your list is ', ', remove all duplicates, preserve original order of elements, most or all rows have duplicates:

Then this should be simplest and fastest:

UPDATE tbl
SET    B = array_to_string( ARRAY(
         SELECT elem
         FROM   unnest(string_to_array(B, ', ')) WITH ORDINALITY x(elem, ord)
         GROUP  BY 1
         ORDER  BY min(ord)
         ), ', ');

The drawback: all rows are updated, even if nothing changes. If that affects more than a few rows, it can be avoided ...

If any assumptions do not hold, there may be a different / better / faster solution.

Related:

Distinct values from an array?

PostgreSQL unnest() with element number


问:
spamassassin rdns reversedns
Spamassasin gives the following flag on my emails:

*

0.8 RDNS_NONE              Delivered to internal network by a host with no rDNS

"This test checks to see if there is a reverse DNS entry
  for the last untrusted relay. Note that this may be done by
  interpreting information in the relevant Received header - if reverse
  DNS checks are not performed by the first trusted relay, or if they
  are not recorded in the Received header, this test will be triggered
  (regardless of the actual rDNS status)."

*

The only ip I can see on my emails are 94.143.11.2 -> which you can reverse dns to trophymanager.com. Google and hotmail have no problems with this - but Spamassassin gives it a flag - what am I missing here?

答:
If your hosting account comes with an IP address, you might be able to change this within the dashboard of your hosting account, or open a ticket with your host if you're not sure.

That solved my "SMTP Reverse DNS Mismatch" error on https://mxtoolbox.com

However, mxtoolbox.com still complains "Reverse DNS is not a valid Hostname" the explanation from them is:

Your Reverse DNS Record (PTR) is not a valid host name. According to
  email sending best practices, a PTR Record should be a valid host
  name. If the PTR Record is not a valid hostname, there is a likelihood
  that you will experience email delivery issues with anti-spam
  services.

I looked up my registrar -- Namecheap says:

A PTR (pointer) record maps an IP address to the domain name. It’s
  often called a "reverse DNS entry" because it converts an IP address
  to a name.

PTR records are mostly used as a security and anti-spam measure, to
  verify that a mail server address is allowed to send an email to a
  particular hostname. The reverse DNS entry checks if a server name is
  indeed associated with an IP address from where the connection was
  initiated.

In order to set up a reverse DNS entry that will connect an IP address
  to your domain (e.g., 127.0.0.1 should be mapped to yourdomain.com),
  you will need to contact your IP address provider to create a PTR
  record for the IP address.

It's possible I just need to wait a day, because when I updated the reverse DNS with my host there was a message saying "please wait 6-12 hours." If I remember, I'll come back and write an update.

ContentLicense: CC BY-SA 3.0

Title: spamassassin rdns reversedns


问:
Python to delete a row in excel spreadsheet
I have a really large excel file and i need to delete about 20,000 rows, contingent on meeting a simple condition and excel won't let me delete such a complex range when using a filter. The condition is:

If the first column contains the value, X, then I need to be able to delete the entire row.

I'm trying to automate this using python and xlwt, but am not quite sure where to start. Seeking some code snippits to get me started...
Grateful for any help that's out there!

答:
Don't delete. Just copy what you need.

read the original file

open a new file

iterate over rows of the original file (if the first column of the row does not contain the value X, add this row to the new file)

close both files

rename the new file into the original file


问:
Using the ODR register directly On STM32
Modify the code for WriteLED() to use the ODR register directly. The code should read the current
value of the register and then write back a modified value depending on what LEDs are to be turns
on or off.

Example Code Given to me

```<code>void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
/* Check the parameters */
assert_param(IS_GPIO_PIN(GPIO_Pin));
GPIOx->ODR ˆ= GPIO_Pin;
}
</code>```

Code That Needs to be Altered

```<code>WriteLED (uint8_t LED, uint8_t State)
{
  // Check for correct state
 if ((State != LED_OFF) && (State != LED_ON))
  {
    return;
  }

  // Turn on/off the LED
  switch (LED)
    {
    case 'L':
      HAL_GPIO_WritePin (LD4_GPIO_Port, LD4_Pin, State);
      break;
    case 'T':
      HAL_GPIO_WritePin (LD3_GPIO_Port, LD3_Pin, State);
      break;
    case 'B':
      HAL_GPIO_WritePin (LD6_GPIO_Port, LD6_Pin, State);
      break;
    case 'R':
      HAL_GPIO_WritePin (LD5_GPIO_Port, LD5_Pin, State);
      break;
    }

  return;
}
</code>```

What should the above code look like when outputting to ODR register

答:
You need to understand C bitwise operations. The three are ^ (exclusive OR), & (bitwise and), | (bitwise or)

To clear a bit
GPIO->ODR &= ~pin_mask;

To set a bit
GPIO->ODR |= pin_mask;

This should give you enough information.

Body:
Modify the code for WriteLED() to use the ODR register directly. The code should read the current
value of the register and then write back a modified value depending on what LEDs are to be turns
on or off.

Example Code Given to me

void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
/* Check the parameters */
assert_param(IS_GPIO_PIN(GPIO_Pin));
GPIOx->ODR ˆ= GPIO_Pin;
}

Code That Needs to be Altered

WriteLED (uint8_t LED, uint8_t State)
{
  // Check for correct state
 if ((State != LED_OFF) && (State != LED_ON))
  {
    return;
  }

  // Turn on/off the LED
  switch (LED)
    {
    case 'L':
      HAL_GPIO_WritePin (LD4_GPIO_Port, LD4_Pin, State);
      break;
    case 'T':
      HAL_GPIO_WritePin (LD3_GPIO_Port, LD3_Pin, State);
      break;
    case 'B':
      HAL_GPIO_WritePin (LD6_GPIO_Port, LD6_Pin, State);
      break;
    case 'R':
      HAL_GPIO_WritePin (LD5_GPIO_Port, LD5_Pin, State);
      break;
    }

  return;
}

What should the above code look like when outputting to ODR register


问:
How would I return all null values from a left join?
I am trying to left join two tables (A and B) together and would like to return all values that have a column in table B marked as null in mySQL.

The two tables I am joining are both very large and I am running into an issue where my connection will timeout after 6000 seconds due to the DBMS settings; is there a way to make this query run more efficiently?

Another bit of information: Even if I limit the query to 10 rows, it will still timeout and give me the error code listed below.

```<code>select *
from Table_A a
left join Table_B b
on a.field_X = b.field_X
where b.Field_X is null;
</code>```

I am experiencing the following error code: "Error Code 2013. Lost Connection to MySQL server during query."

Side note: I am a new SQL user and may need to ask for clarification on some answers. Thank you in advance!

答:
First, you only need columns from a because the b columns are all null.  You can write this as:

```<code>select a.*
from Table_A a left join
     Table_B b
     on a.field_X = b.field_X
where b.Field_X is null;
</code>```

Then for this query, I recommend an index on table_b(field_x).

Body:
I am trying to left join two tables (A and B) together and would like to return all values that have a column in table B marked as null in mySQL.

The two tables I am joining are both very large and I am running into an issue where my connection will timeout after 6000 seconds due to the DBMS settings; is there a way to make this query run more efficiently?

Another bit of information: Even if I limit the query to 10 rows, it will still timeout and give me the error code listed below.

select *
from Table_A a
left join Table_B b
on a.field_X = b.field_X
where b.Field_X is null;

I am experiencing the following error code: "Error Code 2013. Lost Connection to MySQL server during query."

Side note: I am a new SQL user and may need to ask for clarification on some answers. Thank you in advance!

Body:
First, you only need columns from a because the b columns are all null.  You can write this as:

select a.*
from Table_A a left join
     Table_B b
     on a.field_X = b.field_X
where b.Field_X is null;

Then for this query, I recommend an index on table_b(field_x).


问:
Input inside div not clickable
I can't make these inputs clickable

Every item must be clickable and pass input value "id" to form action route

```<code><form action="/rodada/">
 {{#musicas.1}}
 {{#.}}
 <div class="opcao">
  {{titulo}} - {{artista}}
  <input id="opcao" class="shh" type="submit" name="musicaAtual" value="
  {{idTrackDeezer}}">
 </div>
 {{/.}}
 {{/musicas.1}}
</form>
</code>```

css:

```<code>#wp-respostas{
    margin-top: 8%;
}
.opcao{
    background-color: #fba69d;
    text-align: left;
    border: 1px solid salmon;
    border-radius: 5px;
    padding: 4px 0px 4px 4px;
    margin-bottom: 5px;
}

.shh{
    display: none !important;
}
</code>```

FINAL RESULT (not clickable)

Working code (thanks, Dan Oswalt):

```<code>{{#musicas.1}}
{{#.}}
<div class="opcao" onclick="window.open('/rodada/?id={{idTrackDeezer}}', '_self');">
{{titulo}} - {{artista}}
</div>
{{/.}}
{{/musicas.1}}
</code>```

答:
If GET request is ok, try attaching

onclick="window.location = '/rodada/?id={{idTrackDeezer}}'";

or

onclick="window.open('/rodada/?id={{idTrackDeezer}}')";

to the div instead of trying to use a form.

Otherwise, for POST, you'll have to use AJAX or do some workaround to create a form and submit the value.

Title: Input inside div not clickable

Body:
I can't make these inputs clickable

Every item must be clickable and pass input value "id" to form action route

<form action="/rodada/">
 {{#musicas.1}}
 {{#.}}

  {{titulo}} - {{artista}}
  <input id="opcao" class="shh" type="submit" name="musicaAtual" value="
  {{idTrackDeezer}}">

 {{/.}}
 {{/musicas.1}}
</form>

css:

#wp-respostas{
    margin-top: 8%;
}
.opcao{
    background-color: #fba69d;
    text-align: left;
    border: 1px solid salmon;
    border-radius: 5px;
    padding: 4px 0px 4px 4px;
    margin-bottom: 5px;
}

.shh{
    display: none !important;
}

FINAL RESULT (not clickable)

Working code (thanks, Dan Oswalt):

{{#musicas.1}}
{{#.}}

{{titulo}} - {{artista}}

{{/.}}
{{/musicas.1}}


问:
How do I implement a switch-case of different functions in python?
How do I implement a switch-case of different functions in python? The function arguments are different in each case. </p>

答:
Python does not have a switch-case statement. You could of course use if/elif-blocks instead to test a variable and call the relevant function depending on the variables value. But I think you could implement a more elegant solution using Pythons built-in dictionaries. The arguments are held in a list and/or dictionary and passed directly to the called function.

Something along the line of:

```<code>def function1(arg1, arg2):
    print "I'm function1"

def function2(arg1, arg2, arg3):
    print "I'm function2"

functions = {"key1": function1,
             "key2": function2}

switch_var = "key2"
args = [1, 2, 3]
kwargs = {}

functions[switch_var](*args, **kwargs)
</code>```

Body:
Python does not have a switch-case statement. You could of course use if/elif-blocks instead to test a variable and call the relevant function depending on the variables value. But I think you could implement a more elegant solution using Pythons built-in dictionaries. The arguments are held in a list and/or dictionary and passed directly to the called function.

Something along the line of:

def function1(arg1, arg2):
    print "I'm function1"

def function2(arg1, arg2, arg3):
    print "I'm function2"

functions = {"key1": function1,
             "key2": function2}

switch_var = "key2"
args = [1, 2, 3]
kwargs = {}

functions[switch_var](*args, **kwargs)


问:
How to find distance between two anagrams in a string
Requirement: Given string, find distance between all occurrences of anagrams of strings
Example: "programmerxxddporragmmerbbffprogrammer"
String pat = "programmer";

Expected output: 4
distance between two palidromes of "programmer" is 4

```<code>//Java program to search all anagrams
//of a pattern in a text
public class Pattern
{
    static final int MAX = 256;

    // This function returns true if contents
    // of arr1[] and arr2[] are same, otherwise
    // false.
    static boolean compare(char arr1[], char arr2[])
    {
        for (int i = 0; i < MAX; i++)
            if (arr1[i] != arr2[i])
                return false;
        return true;
    }

    // This function search for all permutations
    // of pat[] in txt[]
    static void search(String pat, String txt)
    {
        int M = pat.length();
        int N = txt.length();

        // countP[]: Store count of all
        // characters of pattern
        // countTW[]: Store count of current
        // window of text
        char[] countP = new char[MAX];
        char[] countTW = new char[MAX];
        for (int i = 0; i < M; i++)
        {
            (countP[pat.charAt(i)])++;
            (countTW[txt.charAt(i)])++;
        }

        // Traverse through remaining characters
        // of pattern
        for (int i = M; i < N; i++)
        {
            // Compare counts of current window
            // of text with counts of pattern[]
            if (compare(countP, countTW))
                System.out.println("Found at Index " +
                                        (i - M));

            // Add current character to current
            // window
            (countTW[txt.charAt(i)])++;

            // Remove the first character of previous
            // window
            countTW[txt.charAt(i-M)]--;
        }

        // Check for the last window in text
        if (compare(countP, countTW)) {
            System.out.println("Found at Index " +
                                    (N - M));
            System.out.println(N-M-M);
        }
    }

    /* Driver program to test above function */
    public static void main(String args[])
    {
        String txt = "programmerxxddporragmmerbbffprogrammer";
        String pat = "programmer";
        search(pat, txt);
    }
}
</code>```

I am required to print first instance of the difference between two anagrams. In my case, 4. My code is printing for the final string like this:

答:
So your code was doing well at finding the palindromes. So I adapted it to track where it found the last palindrome so that when it finds a new one, it can take the distance between, which would be the indices of each minus the length of the pattern (I chose to track all differences, but you could suppress that). Here is the code adapted to report the distance each time (the rest is unchanged).

```<code>//Java program to search all anagrams
//of a pattern in a text
public class Pattern{
static final int MAX = 256;

// This function returns true if contents
// of arr1[] and arr2[] are same, otherwise
// false.
static boolean compare(char arr1[], char arr2[])
{
    for (int i = 0; i < MAX; i++)
        if (arr1[i] != arr2[i])
            return false;
    return true;
}

// This function search for all permutations
// of pat[] in txt[]
static void search(String pat, String txt)
{
    int M = pat.length();
    int N = txt.length();
    int lastFoundIndex = -1;

    // countP[]: Store count of all
    // characters of pattern
    // countTW[]: Store count of current
    // window of text
    char[] countP = new char[MAX];
    char[] countTW = new char[MAX];
    for (int i = 0; i < M; i++)
    {
        (countP[pat.charAt(i)])++;
        (countTW[txt.charAt(i)])++;
    }

    // Traverse through remaining characters
    // of pattern
    for (int i = M; i < N; i++)
    {
        // Compare counts of current window
        // of text with counts of pattern[]
        if (compare(countP, countTW)) {
            System.out.println("Found at Index " +
                                    (i - M));
                                    if (lastFoundIndex==-1){
            lastFoundIndex = i-M;}
            else {
            System.out.println("Distance between is: "+(i-M-lastFoundIndex-pat.length()));
            lastFoundIndex = i-M;

        }
        }

        // Add current character to current
        // window
        (countTW[txt.charAt(i)])++;

        // Remove the first character of previous
        // window
        countTW[txt.charAt(i-M)]--;
    }

    // Check for the last window in text
    if (compare(countP, countTW)) {
        System.out.println("Found at Index " +
                                (N - M));
        if (lastFoundIndex==-1){
            lastFoundIndex = N-M;
        }
        else{

            System.out.println("Distance between is: "+(N-M-lastFoundIndex-pat.length()));
            lastFoundIndex = N-M;
        }
    }
}

/* Driver program to test above function */
public static void main(String args[])
{
    String txt = "programmerxxddporragmmerbbffprogrammer";
    String pat = "programmer";
    search(pat, txt);
}
}
</code>```

output is

```<code>Found at Index 0
Found at Index 14
Distance between is: 4
Found at Index 28
Distance between is: 4
</code>```

REVISION:
I then went back and implemented the whole thing differently, possibly less efficiently, but easier for me to follow (output was the same).

```<code>//Java program to search all anagrams
//of a pattern in a text
import java.util.Arrays;
public class Pattern {
    // Method to sort a string alphabetically (from https://www.geeksforgeeks.org/sort-a-string-in-java-2-different-ways/)
    public static String sortString(String inputString) {
        // convert input string to char array
        char tempArray[] = inputString.toCharArray();

        // sort tempArray
        Arrays.sort(tempArray);

        // return new sorted string
        return new String(tempArray);
    }

    // This function searches for all permutations
    // of pat in txt
    static void search(String pat, String txt) {
        String patSorted = sortString(pat); //sort the pattern once
        int M = pat.length();
        int N = txt.length();
        int lastFoundIndex = -1; //last place found
        for (int i = 0; N - i >= M; i++) { //while there are still enough remaining characters from this index on in txt
            if (sortString(txt.substring(i, i + M)).equals(patSorted)) {
                System.out.println("Found at Index " + i);
                if (lastFoundIndex == -1) {
                    lastFoundIndex = i;
                } else {
                    System.out.println("Distance between is: " + (i - lastFoundIndex - M));
                    lastFoundIndex = i;
                }
            }

        }

    }

    /* Driver program to test above function */
    public static void main(String args[]) {
        String txt = "programmerxxddporragmmerbbffprogrammer";
        String pat = "programmer";
        search(pat, txt);
    }
}
</code>```

Body:
Requirement: Given string, find distance between all occurrences of anagrams of strings
Example: "programmerxxddporragmmerbbffprogrammer"
String pat = "programmer";

Expected output: 4
distance between two palidromes of "programmer" is 4

//Java program to search all anagrams
//of a pattern in a text
public class Pattern
{
    static final int MAX = 256;

    // This function returns true if contents
    // of arr1[] and arr2[] are same, otherwise
    // false.
    static boolean compare(char arr1[], char arr2[])
    {
        for (int i = 0; i < MAX; i++)
            if (arr1[i] != arr2[i])
                return false;
        return true;
    }

    // This function search for all permutations
    // of pat[] in txt[]
    static void search(String pat, String txt)
    {
        int M = pat.length();
        int N = txt.length();

        // countP[]: Store count of all
        // characters of pattern
        // countTW[]: Store count of current
        // window of text
        char[] countP = new char[MAX];
        char[] countTW = new char[MAX];
        for (int i = 0; i < M; i++)
        {
            (countP[pat.charAt(i)])++;
            (countTW[txt.charAt(i)])++;
        }

        // Traverse through remaining characters
        // of pattern
        for (int i = M; i < N; i++)
        {
            // Compare counts of current window
            // of text with counts of pattern[]
            if (compare(countP, countTW))
                System.out.println("Found at Index " +
                                        (i - M));

            // Add current character to current
            // window
            (countTW[txt.charAt(i)])++;

            // Remove the first character of previous
            // window
            countTW[txt.charAt(i-M)]--;
        }

        // Check for the last window in text
        if (compare(countP, countTW)) {
            System.out.println("Found at Index " +
                                    (N - M));
            System.out.println(N-M-M);
        }
    }

    /* Driver program to test above function */
    public static void main(String args[])
    {
        String txt = "programmerxxddporragmmerbbffprogrammer";
        String pat = "programmer";
        search(pat, txt);
    }
}

I am required to print first instance of the difference between two anagrams. In my case, 4. My code is printing for the final string like this:

Body:
So your code was doing well at finding the palindromes. So I adapted it to track where it found the last palindrome so that when it finds a new one, it can take the distance between, which would be the indices of each minus the length of the pattern (I chose to track all differences, but you could suppress that). Here is the code adapted to report the distance each time (the rest is unchanged).

//Java program to search all anagrams
//of a pattern in a text
public class Pattern{
static final int MAX = 256;

// This function returns true if contents
// of arr1[] and arr2[] are same, otherwise
// false.
static boolean compare(char arr1[], char arr2[])
{
    for (int i = 0; i < MAX; i++)
        if (arr1[i] != arr2[i])
            return false;
    return true;
}

// This function search for all permutations
// of pat[] in txt[]
static void search(String pat, String txt)
{
    int M = pat.length();
    int N = txt.length();
    int lastFoundIndex = -1;

    // countP[]: Store count of all
    // characters of pattern
    // countTW[]: Store count of current
    // window of text
    char[] countP = new char[MAX];
    char[] countTW = new char[MAX];
    for (int i = 0; i < M; i++)
    {
        (countP[pat.charAt(i)])++;
        (countTW[txt.charAt(i)])++;
    }

    // Traverse through remaining characters
    // of pattern
    for (int i = M; i < N; i++)
    {
        // Compare counts of current window
        // of text with counts of pattern[]
        if (compare(countP, countTW)) {
            System.out.println("Found at Index " +
                                    (i - M));
                                    if (lastFoundIndex==-1){
            lastFoundIndex = i-M;}
            else {
            System.out.println("Distance between is: "+(i-M-lastFoundIndex-pat.length()));
            lastFoundIndex = i-M;

        }
        }

        // Add current character to current
        // window
        (countTW[txt.charAt(i)])++;

        // Remove the first character of previous
        // window
        countTW[txt.charAt(i-M)]--;
    }

    // Check for the last window in text
    if (compare(countP, countTW)) {
        System.out.println("Found at Index " +
                                (N - M));
        if (lastFoundIndex==-1){
            lastFoundIndex = N-M;
        }
        else{

            System.out.println("Distance between is: "+(N-M-lastFoundIndex-pat.length()));
            lastFoundIndex = N-M;
        }
    }
}

/* Driver program to test above function */
public static void main(String args[])
{
    String txt = "programmerxxddporragmmerbbffprogrammer";
    String pat = "programmer";
    search(pat, txt);
}
}

output is

Found at Index 0
Found at Index 14
Distance between is: 4
Found at Index 28
Distance between is: 4

REVISION:
I then went back and implemented the whole thing differently, possibly less efficiently, but easier for me to follow (output was the same).

//Java program to search all anagrams
//of a pattern in a text
import java.util.Arrays;
public class Pattern {
    // Method to sort a string alphabetically (from https://www.geeksforgeeks.org/sort-a-string-in-java-2-different-ways/)
    public static String sortString(String inputString) {
        // convert input string to char array
        char tempArray[] = inputString.toCharArray();

        // sort tempArray
        Arrays.sort(tempArray);

        // return new sorted string
        return new String(tempArray);
    }

    // This function searches for all permutations
    // of pat in txt
    static void search(String pat, String txt) {
        String patSorted = sortString(pat); //sort the pattern once
        int M = pat.length();
        int N = txt.length();
        int lastFoundIndex = -1; //last place found
        for (int i = 0; N - i >= M; i++) { //while there are still enough remaining characters from this index on in txt
            if (sortString(txt.substring(i, i + M)).equals(patSorted)) {
                System.out.println("Found at Index " + i);
                if (lastFoundIndex == -1) {
                    lastFoundIndex = i;
                } else {
                    System.out.println("Distance between is: " + (i - lastFoundIndex - M));
                    lastFoundIndex = i;
                }
            }

        }

    }

    /* Driver program to test above function */
    public static void main(String args[]) {
        String txt = "programmerxxddporragmmerbbffprogrammer";
        String pat = "programmer";
        search(pat, txt);
    }
}


问:
I am not able to remove elements from the list
The task that I have to do is showing all other elements rather than (Americano). I tried to use 'Record.remove("Americano") but it shows the error

```<code>Record.remove("Americano")
ValueError: list.remove(x): x not in list
</code>```

What should I Do......

=========================this is the result of=======================     Record.append(record[1]) print(Record) ->

```<code>['Menu_name', 'Cafe_latte', 'Americano', 'Americano', 'Smoothie_queen', 'Americano', 'Americano', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Amorparty', 'Plain_yogurt', 'Americano', 'Americano', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Cafe_latte', 'Berry_smoothie', 'Berry_smoothie', 'Plain_yogurt', 'Berry_smoothie', 'Plane_yougurt', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Americano', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Plain_yogurt', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Cofe_latte', 'Plain_yogurt', 'Cafe_mocha', 'Americano', 'Berry_smoothie', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Americano', 'Plain_yogurt', 'Americano', 'Americano', 'Cofe_latte', 'Berry_smoothie', 'Berry_smudie', 'American_air', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Plain_yogurt', 'Cafe_latte', 'Cafe_mocha', 'Cafe_mocha', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Plain_yogurt']
</code>```

```<code>def load_menu():
    Menu = []
    #========= STEP 1 ==========
    menufile = open("menu.txt", "r")

    for line in menufile:
        menu = line.split()
        Menu.append(menu)

    menufile.close()

    for menu in Menu:
        print(menu[0]," : ",menu[1])
    #========= STEP 1 ==========
    return Menu

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

    for line in recordfile:
        record = line.split()
        Record.append(record[1])
        Record.remove("Americano")
    print(Record)

    recordfile.close()
    #========= STEP 3 ==========
</code>```

答:
You should use:</p>

```<code>def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

    for line in recordfile:
        record = line.rstrip().split()
        Record.append(record[1])
        Record.remove("Americano")
    print(Record)

    recordfile.close()
</code>```

Body:
The task that I have to do is showing all other elements rather than (Americano). I tried to use 'Record.remove("Americano") but it shows the error

Record.remove("Americano")
ValueError: list.remove(x): x not in list

What should I Do......

=========================this is the result of=======================     Record.append(record[1]) print(Record) ->

['Menu_name', 'Cafe_latte', 'Americano', 'Americano', 'Smoothie_queen', 'Americano', 'Americano', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Amorparty', 'Plain_yogurt', 'Americano', 'Americano', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_latte', 'Americano', 'Cafe_latte', 'Berry_smoothie', 'Berry_smoothie', 'Plain_yogurt', 'Berry_smoothie', 'Plane_yougurt', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Americano', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Plain_yogurt', 'Cafe_mocha', 'Plain_yogurt', 'Americano', 'Cofe_latte', 'Plain_yogurt', 'Cafe_mocha', 'Americano', 'Berry_smoothie', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Cafe_latte', 'Cafe_latte', 'Cafe_mocha', 'Americano', 'Plain_yogurt', 'Americano', 'Americano', 'Cofe_latte', 'Berry_smoothie', 'Berry_smudie', 'American_air', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_latte', 'Americano', 'Plain_yogurt', 'Cafe_latte', 'Cafe_mocha', 'Cafe_mocha', 'Plain_yogurt', 'Berry_smoothie', 'Berry_smoothie', 'Cafe_mocha', 'Cafe_mocha', 'Berry_smoothie', 'Cafe_mocha', 'Plain_yogurt']

def load_menu():
    Menu = []
    #========= STEP 1 ==========
    menufile = open("menu.txt", "r")

    for line in menufile:
        menu = line.split()
        Menu.append(menu)

    menufile.close()

    for menu in Menu:
        print(menu[0]," : ",menu[1])
    #========= STEP 1 ==========
    return Menu

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

    for line in recordfile:
        record = line.split()
        Record.append(record[1])
        Record.remove("Americano")
    print(Record)

    recordfile.close()
    #========= STEP 3 ==========

Body:
You should use:

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    recordfile = open("ledger_"+date+".txt","r")

    for line in recordfile:
        record = line.rstrip().split()
        Record.append(record[1])
        Record.remove("Americano")
    print(Record)

    recordfile.close()


问:
Keycloak unable to get access token
I'm trying to use AuthzClient to obtain an access token from a public client in my Spring app.

Here is the code:

```<code>AuthzClient authzClient = AuthzClient.create();
AuthorizationRequest request = new AuthorizationRequest();
AuthorizationResponse response = authzClient.authorization(username, password)
                                .authorize(request);
String token = response.getToken();
</code>```

But I keep getting this error message:

org.keycloak.authorization.client.util.HttpResponseException: Unexpected response from server: 400 / Bad Request / Response from server: {"error":"invalid_request","error_description":"Client does not support permissions"}

Can someone please help me figure out what I'm doing wrong?

答:
First you need to enable authorization service for your client. So you should go to your client settings page on the admin console and click the Authorization Enabled switch to ON, and then click Save button.

See also:
Keycloak Authorization Services Guide - 2.3. Enabling Authorization Services

Title: Keycloak unable to get access token

Body:
I'm trying to use AuthzClient to obtain an access token from a public client in my Spring app.

Here is the code:

AuthzClient authzClient = AuthzClient.create();
AuthorizationRequest request = new AuthorizationRequest();
AuthorizationResponse response = authzClient.authorization(username, password)
                                .authorize(request);
String token = response.getToken();

But I keep getting this error message:

org.keycloak.authorization.client.util.HttpResponseException: Unexpected response from server: 400 / Bad Request / Response from server: {"error":"invalid_request","error_description":"Client does not support permissions"}

Can someone please help me figure out what I'm doing wrong?


问:
ASP.NET VB.NET - Winforms to Web - implementing LostFocus listview control equivalent for web
Background: I have a winForm app that registers a user in the database based on the information provided, auto-generates a random password and username, and e-mails the user a link to take an application based on the marketing company selected.

Problem:

When the user selects the lbCarrier(s), the Bundles don't show up in the listbox b/c the lostfocus feature doesn't work for asp.net. What code can I use to auto-populate the Bundles listbox based on what is selected in lbCarrier listbox for ASP.NET.

Code from default.aspx.vb:

```<code>Private Sub lbCarriers_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbCarriers.LostFocus
    Dim splt() As String
    Dim ac1 As Array
    bundles.Items.Clear()
    For Each item In lbCarriers.Items

        splt = Split(item.text, "|")
        ac1 = proxy.GetContractingBundles("test", "test", Trim(splt(0)))
        For Each Pitem In ac1
            bundles.Items.Add(Trim(splt(2)) & " | " & Pitem.FormBundleName)
        Next
    Next
End Sub

Protected Sub lbCarriers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lbCarriers.SelectedIndexChanged

End Sub
</code>```

答:
I got the bundles listbox to populate w/ autopostback set to true but the bundles listbox populates as soon as you click on an lbcarrier and it doesn't allow you select more than one carrier.

Do you have any ideas on how to allow multiselect with the postback feature on?

code on default.aspx:

```<code>            <asp:ListBox AutoPostback="true" ID="lbCarriers" runat="server" Height="86px" Width="250px">
            </asp:ListBox>
</code>```

code on default.aspx.vb:

```<code>Protected Sub lbCarriers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lbCarriers.SelectedIndexChanged

    Dim splt() As String
    Dim ac1 As Array
    bundles.Items.Clear()
    Dim item As ListItem = lbCarriers.SelectedItem
    splt = item.ToString().Split("|")
    ac1 = proxy.GetContractingBundles("test", "test", Trim(splt(0)))
    For Each Pitem In ac1
        bundles.Items.Add(Trim(splt(2)) & " | " & Pitem.FormBundleName)
    Next
End Sub
</code>```

Body:
Background: I have a winForm app that registers a user in the database based on the information provided, auto-generates a random password and username, and e-mails the user a link to take an application based on the marketing company selected.

Problem:

When the user selects the lbCarrier(s), the Bundles don't show up in the listbox b/c the lostfocus feature doesn't work for asp.net. What code can I use to auto-populate the Bundles listbox based on what is selected in lbCarrier listbox for ASP.NET.

Code from default.aspx.vb:

Private Sub lbCarriers_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbCarriers.LostFocus
    Dim splt() As String
    Dim ac1 As Array
    bundles.Items.Clear()
    For Each item In lbCarriers.Items

        splt = Split(item.text, "|")
        ac1 = proxy.GetContractingBundles("test", "test", Trim(splt(0)))
        For Each Pitem In ac1
            bundles.Items.Add(Trim(splt(2)) & " | " & Pitem.FormBundleName)
        Next
    Next
End Sub

Protected Sub lbCarriers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lbCarriers.SelectedIndexChanged

End Sub

Body:
I got the bundles listbox to populate w/ autopostback set to true but the bundles listbox populates as soon as you click on an lbcarrier and it doesn't allow you select more than one carrier.

Do you have any ideas on how to allow multiselect with the postback feature on?

code on default.aspx:

            <asp:ListBox AutoPostback="true" ID="lbCarriers" runat="server" Height="86px" Width="250px">
            </asp:ListBox>

code on default.aspx.vb:

Protected Sub lbCarriers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lbCarriers.SelectedIndexChanged

    Dim splt() As String
    Dim ac1 As Array
    bundles.Items.Clear()
    Dim item As ListItem = lbCarriers.SelectedItem
    splt = item.ToString().Split("|")
    ac1 = proxy.GetContractingBundles("test", "test", Trim(splt(0)))
    For Each Pitem In ac1
        bundles.Items.Add(Trim(splt(2)) & " | " & Pitem.FormBundleName)
    Next
End Sub


问:
Asking for user input when using Invoke-Command
Recently ive been using a Powershell command in a Domain setting to Log off Remote users Who Do not log off at night After turning over with our night crew. I am using the command

```<code>    Invoke-Command -ComputerName $name { quser }
</code>```

After verifying the person is logged in.

```<code>    Invoke-Command -ComputerName $name { logoff 2 }
</code>```

(2 being the Session ID)
This works fine but it gets tiresome having to edit the .ps1 file everytime to change the name of the workstation. I'm trying to edit this command so it will ask for user input and then use the user input as the workstation that the Command is being run on, but whenever i use the following code it does not work.

```<code>    $name = Read-Host -Prompt 'Enter the name of the computer'
    Invoke-Command -ComputerName computer1 { quser }
</code>```

This is only for quser right now after i get this sorted ill work on including Logoff 2. Sorry if im missing any information pretty new to Powershell.

答:
Since the remote desktop command-line tools can work remotely, there's no need to invoke a remote session with PowerShell. Try the following script that will log off all users on a remote machine.

```<code>param([string]$ComputerName)

# Cleanup the quser.exe output a little and turn it into an object
# Modified from: https://ss64.com/nt/query-user.html

$sessions = (quser /server:$ComputerName) -replace '\s{2,}', ',' -replace '>','' | ConvertFrom-Csv

foreach ($session in $sessions)
{
    Write-Output "Logging off user $($session.USERNAME) with session ID $($session.ID) on $ComputerName..."
    (logoff $session.ID /server:$ComputerName /V)
}
</code>```

Example usage if script is saved as LogOffUsers.ps1 and run from a PowerShell prompt.

```<code>.\LogOffUsers.ps1 -ComputerName SFWEB01
</code>```

Body:
Recently ive been using a Powershell command in a Domain setting to Log off Remote users Who Do not log off at night After turning over with our night crew. I am using the command

    Invoke-Command -ComputerName $name { quser }

After verifying the person is logged in.

    Invoke-Command -ComputerName $name { logoff 2 }

(2 being the Session ID)
This works fine but it gets tiresome having to edit the .ps1 file everytime to change the name of the workstation. I'm trying to edit this command so it will ask for user input and then use the user input as the workstation that the Command is being run on, but whenever i use the following code it does not work.

    $name = Read-Host -Prompt 'Enter the name of the computer'
    Invoke-Command -ComputerName computer1 { quser }

This is only for quser right now after i get this sorted ill work on including Logoff 2. Sorry if im missing any information pretty new to Powershell.

Body:
Since the remote desktop command-line tools can work remotely, there's no need to invoke a remote session with PowerShell. Try the following script that will log off all users on a remote machine.

param([string]$ComputerName)

# Cleanup the quser.exe output a little and turn it into an object
# Modified from: https://ss64.com/nt/query-user.html

$sessions = (quser /server:$ComputerName) -replace '\s{2,}', ',' -replace '>','' | ConvertFrom-Csv

foreach ($session in $sessions)
{
    Write-Output "Logging off user $($session.USERNAME) with session ID $($session.ID) on $ComputerName..."
    (logoff $session.ID /server:$ComputerName /V)
}

Example usage if script is saved as LogOffUsers.ps1 and run from a PowerShell prompt.

.\LogOffUsers.ps1 -ComputerName SFWEB01


问:
How do I remove horizontal lines from Mime Message?
Noob, creating his first dynamic webpage, where a user can enter a message, along with their first and last name, email and phone number. I care most about the message, which I intend to forward via email, along with the other information, if provided. I have written a simple python script (site will be Flask, python and HTML), but it is inserting an unwanted horizontal line between each output, i.e.

Dear Bob

Message contents go here

first name

My goal is to have the outgoing message resemble an actual email, i.e. like above, but without the horizontal lines. I found most of the below code online, which is largely working. Simple answers that I can understand are preferred to clever ones I cannot (I'm a Noob).

```<code>def to_mail(first, last, phone, email, User_Complaint, addressed_to):
    # E mail account details
    my_sending_email = 'testing@gmail.com'
    sending_email_password = 'pass'

    # set up the SMTP server
    s = smtplib.SMTP(host='smtp.gmail.com', port=587)
    s.starttls()
    s.login(my_sending_email, sending_email_password)

    msg = MIMEMultipart()

    msg['Subject'] = 'Reporting an Issue With the Courts'
    msg['From'] = my_sending_email
    msg['To'] = addressed_to

    # Body of Email
    intro = MIMEText("Dear Leader")
    message_contents = MIMEText(User_Complaint)

    # use of .attach appears to insert the horizontal line
    msg.attach(intro)
    msg.attach(message_contents)

    # Party's Contact Info to append at bottom of email
    msg.attach(MIMEText(first + last))
    msg.attach(MIMEText(phone))
    msg.attach(MIMEText(email))

    s.send_message(msg)
    del msg

    s.quit()
</code>```

I just want to generate normal looking email content in the message body, i.e.

"Dear Leader,

I really like your hair. I'm your biggest fan.

(each biographic entry following should be on its own newline, but this automatically puts it on one line)
Stan Lee\n
stan@lee.com\n
647-647-1234"

答:
You need to use a single msg.attach to avoid multiple horizontal lines:

```<code># Body of Email
text = "Dear Leader\n" + User_Complaint + "\n" + phone + "\n" + email
html = """\
<html>
  <head></head>
  <body>
    <p>Dear Leader<br>
       I really like your hair. I'm your biggest fan.<br>
       (each biographic entry following should be on
its own newline, but this automatically puts it on one line)
Stan Lee\n stan@lee.com\n 647-647-1234.
    </p>
  </body>
</html>
"""

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

s.send_message(msg)
del msg
s.quit()
</code>```

It's more better to define the mail body inside html an txt files and render this files using jinja2 template engine. So you need to create two files:

mail.text

```<code>Dear Bob!\n
{{ User_Complaint }}\n
{{ phone }} \n
{{ email }}
</code>```

mail.html

```<code><html>
  <head></head>
  <body>
    <p>
    Dear Bob!<br/>
    {{ User_Complaint }}<br/>
    {{ phone }}<br/>
    {{ email }}
   </p>
  </body>
</html>
</code>```

And to_mail function will be similar to this:

```<code>from flask import render_template
def to_mail(first, last, phone, email, User_Complaint, addressed_to):

    # The old code
    #...
    # Body of Email
    part1 = render_template("mail.txt",
    User_Complaint = User_Complaint,
    email=email, phone=phone)

    part2 = render_template("mail.html",
    User_Complaint = User_Complaint,
    email=email, phone=phone)

    msg.attach(part1)
    msg.attach(part2)

    s.send_message(msg)
    del msg
    s.quit()
</code>```

It's not bad idea to use flask-mail to send mail.

Body:
Noob, creating his first dynamic webpage, where a user can enter a message, along with their first and last name, email and phone number. I care most about the message, which I intend to forward via email, along with the other information, if provided. I have written a simple python script (site will be Flask, python and HTML), but it is inserting an unwanted horizontal line between each output, i.e.

Dear Bob

Message contents go here

first name

My goal is to have the outgoing message resemble an actual email, i.e. like above, but without the horizontal lines. I found most of the below code online, which is largely working. Simple answers that I can understand are preferred to clever ones I cannot (I'm a Noob).

def to_mail(first, last, phone, email, User_Complaint, addressed_to):
    # E mail account details
    my_sending_email = 'testing@gmail.com'
    sending_email_password = 'pass'

    # set up the SMTP server
    s = smtplib.SMTP(host='smtp.gmail.com', port=587)
    s.starttls()
    s.login(my_sending_email, sending_email_password)

    msg = MIMEMultipart()

    msg['Subject'] = 'Reporting an Issue With the Courts'
    msg['From'] = my_sending_email
    msg['To'] = addressed_to

    # Body of Email
    intro = MIMEText("Dear Leader")
    message_contents = MIMEText(User_Complaint)

    # use of .attach appears to insert the horizontal line
    msg.attach(intro)
    msg.attach(message_contents)

    # Party's Contact Info to append at bottom of email
    msg.attach(MIMEText(first + last))
    msg.attach(MIMEText(phone))
    msg.attach(MIMEText(email))

    s.send_message(msg)
    del msg

    s.quit()

I just want to generate normal looking email content in the message body, i.e.

"Dear Leader,

I really like your hair. I'm your biggest fan.

(each biographic entry following should be on its own newline, but this automatically puts it on one line)
Stan Lee\n
stan@lee.com\n
647-647-1234"

Body:
You need to use a single msg.attach to avoid multiple horizontal lines:

# Body of Email
text = "Dear Leader\n" + User_Complaint + "\n" + phone + "\n" + email
html = """\
<html>
  <head></head>
  <body>
    <p>Dear Leader<br>
       I really like your hair. I'm your biggest fan.<br>
       (each biographic entry following should be on
its own newline, but this automatically puts it on one line)
Stan Lee\n stan@lee.com\n 647-647-1234.
    </p>
  </body>
</html>
"""

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

msg.attach(part1)
msg.attach(part2)

s.send_message(msg)
del msg
s.quit()

It's more better to define the mail body inside html an txt files and render this files using jinja2 template engine. So you need to create two files:

mail.text

Dear Bob!\n
{{ User_Complaint }}\n
{{ phone }} \n
{{ email }}

mail.html

<html>
  <head></head>
  <body>
    <p>
    Dear Bob!<br/>
    {{ User_Complaint }}<br/>
    {{ phone }}<br/>
    {{ email }}
   </p>
  </body>
</html>

And to_mail function will be similar to this:

from flask import render_template
def to_mail(first, last, phone, email, User_Complaint, addressed_to):

    # The old code
    #...
    # Body of Email
    part1 = render_template("mail.txt",
    User_Complaint = User_Complaint,
    email=email, phone=phone)

    part2 = render_template("mail.html",
    User_Complaint = User_Complaint,
    email=email, phone=phone)

    msg.attach(part1)
    msg.attach(part2)

    s.send_message(msg)
    del msg
    s.quit()

It's not bad idea to use flask-mail to send mail.


问:
Sql query to map user log table to user first, last and previous activity
I have a user log table, partitioned on action_date (table name - user_action_log) consisting billions of rows, with columns

user_id, action_name, action_date

Sample data -

```<code>+---------+-------------+-------------+
| user_id | action_name | action_date |
+---------+-------------+-------------+
| 123     | login       | 2018-01-30  |
| 123     | logout      | 2018-01-31  |
| 123     | click       | 2018-02-28  |
| 123     | comment     | 2018-02-15  |
| 123     | post        | 2018-03-15  |
+---------+-------------+-------------+
</code>```

I want to write an ETL/sql to transform this data into something like this (table name - user_action_record).

user_id (Primary key), first_action_date, last_action_date, previous_action_date

Sample output data -

```<code>+---------+-------------------+------------------+---------------------------+
| user_id | first_action_date | last_action_date | previous_last_action_date |
+---------+-------------------+------------------+---------------------------+
| 123     | 2018-01-30        | 2018-03-15       | 2018-02-28                |
+---------+-------------------+------------------+---------------------------+
</code>```

I tried dividing problem into 2 steps -

Insert new users which are not present in user_action_record.

Update existing user by updating "previous_last_action_date" from value in "last_action_date" and update last_action_date based on user_action_log table.

The problem is that, since user_action_log is partitioned on action_date, i can query that table on a daily basis (action_date = CURRENT_DATE)

Can anybody help me with sqls to populate my target table in this case?

-- Edited with additional info below

Source and expected target table on day '2018-01-30'

```<code>+---------+-------------+-------------+
| user_id | action_name | action_date |
+---------+-------------+-------------+
| 123     | login       | 2018-01-30  |
| 123     | logout      | 2018-01-30  |
| 123     | click       | 2018-01-30  |
+---------+-------------+-------------+

</code>```

```<code>+---------+-------------------+------------------+---------------------------+
| user_id | first_action_date | last_action_date | previous_last_action_date |
+---------+-------------------+------------------+---------------------------+
| 123     | 2018-01-30        | 2018-01-30       | 2018-01-30                |
+---------+-------------------+------------------+---------------------------+
</code>```

Source and expected target table on day '2018-01-31'

```<code>+---------+-------------+-------------+
| user_id | action_name | action_date |
+---------+-------------+-------------+
| 123     | login       | 2018-01-30  |
| 123     | logout      | 2018-01-30  |
| 123     | click       | 2018-01-30  |
| 123     | login       | 2018-01-31  |
| 123     | logout      | 2018-01-31  |
+---------+-------------+-------------+

</code>```

```<code>+---------+-------------------+------------------+---------------------------+
| user_id | first_action_date | last_action_date | previous_last_action_date |
+---------+-------------------+------------------+---------------------------+
| 123     | 2018-01-30        | 2018-01-31       | 2018-01-30                |
+---------+-------------------+------------------+---------------------------+
</code>```

Source and expected target table on day '2018-02-15'

```<code>+---------+-------------+-------------+
| user_id | action_name | action_date |
+---------+-------------+-------------+
| 123     | login       | 2018-01-30  |
| 123     | logout      | 2018-01-30  |
| 123     | click       | 2018-01-30  |
| 123     | login       | 2018-01-31  |
| 123     | logout      | 2018-01-31  |
| 123     | logout      | 2018-02-15  |
| 123     | logout      | 2018-02-15  |
+---------+-------------+-------------+

</code>```

```<code>+---------+-------------------+------------------+---------------------------+
| user_id | first_action_date | last_action_date | previous_last_action_date |
+---------+-------------------+------------------+---------------------------+
| 123     | 2018-01-30        | 2018-02-15       | 2018-01-31                |
+---------+-------------------+------------------+---------------------------+
</code>```

答:
In earlier versions of MySQL, you can use the group_concat()/substring_index() trick:

```<code>select user_id,
       min(action_date) as first_action_date,
       max(action_date) as last_action_date,
       substring_index(substring_index(group_concat(action_date order by action_date desc), ',', 2), ',', -1) as second_to_last_date
from user_action_log ual
group by user_id;
</code>```

Another alternative is a correlated subqueries:

```<code>select user_id,
       min(action_date) as first_action_date,
       max(action_date) as last_action_date,
       (select max(ual2.action_date)
        from user_action_log ual2
        where ual2.user_id = ual.user_id and
              ual2.action_date < max(ual.action_date)
      ) as second_to_last_date
from user_action_log ual
group by user_id;
</code>```

Body:
I have a user log table, partitioned on action_date (table name - user_action_log) consisting billions of rows, with columns

user_id, action_name, action_date

Sample data -

+---------+-------------+-------------+
| user_id | action_name | action_date |
+---------+-------------+-------------+
| 123     | login       | 2018-01-30  |
| 123     | logout      | 2018-01-31  |
| 123     | click       | 2018-02-28  |
| 123     | comment     | 2018-02-15  |
| 123     | post        | 2018-03-15  |
+---------+-------------+-------------+

I want to write an ETL/sql to transform this data into something like this (table name - user_action_record).

user_id (Primary key), first_action_date, last_action_date, previous_action_date

Sample output data -

+---------+-------------------+------------------+---------------------------+
| user_id | first_action_date | last_action_date | previous_last_action_date |
+---------+-------------------+------------------+---------------------------+
| 123     | 2018-01-30        | 2018-03-15       | 2018-02-28                |
+---------+-------------------+------------------+---------------------------+

I tried dividing problem into 2 steps -

Insert new users which are not present in user_action_record.

Update existing user by updating "previous_last_action_date" from value in "last_action_date" and update last_action_date based on user_action_log table.

The problem is that, since user_action_log is partitioned on action_date, i can query that table on a daily basis (action_date = CURRENT_DATE)

Can anybody help me with sqls to populate my target table in this case?

-- Edited with additional info below

Source and expected target table on day '2018-01-30'

+---------+-------------+-------------+
| user_id | action_name | action_date |
+---------+-------------+-------------+
| 123     | login       | 2018-01-30  |
| 123     | logout      | 2018-01-30  |
| 123     | click       | 2018-01-30  |
+---------+-------------+-------------+

+---------+-------------------+------------------+---------------------------+
| user_id | first_action_date | last_action_date | previous_last_action_date |
+---------+-------------------+------------------+---------------------------+
| 123     | 2018-01-30        | 2018-01-30       | 2018-01-30                |
+---------+-------------------+------------------+---------------------------+

Source and expected target table on day '2018-01-31'

+---------+-------------+-------------+
| user_id | action_name | action_date |
+---------+-------------+-------------+
| 123     | login       | 2018-01-30  |
| 123     | logout      | 2018-01-30  |
| 123     | click       | 2018-01-30  |
| 123     | login       | 2018-01-31  |
| 123     | logout      | 2018-01-31  |
+---------+-------------+-------------+

+---------+-------------------+------------------+---------------------------+
| user_id | first_action_date | last_action_date | previous_last_action_date |
+---------+-------------------+------------------+---------------------------+
| 123     | 2018-01-30        | 2018-01-31       | 2018-01-30                |
+---------+-------------------+------------------+---------------------------+

Source and expected target table on day '2018-02-15'

+---------+-------------+-------------+
| user_id | action_name | action_date |
+---------+-------------+-------------+
| 123     | login       | 2018-01-30  |
| 123     | logout      | 2018-01-30  |
| 123     | click       | 2018-01-30  |
| 123     | login       | 2018-01-31  |
| 123     | logout      | 2018-01-31  |
| 123     | logout      | 2018-02-15  |
| 123     | logout      | 2018-02-15  |
+---------+-------------+-------------+

+---------+-------------------+------------------+---------------------------+
| user_id | first_action_date | last_action_date | previous_last_action_date |
+---------+-------------------+------------------+---------------------------+
| 123     | 2018-01-30        | 2018-02-15       | 2018-01-31                |
+---------+-------------------+------------------+---------------------------+

Body:
In earlier versions of MySQL, you can use the group_concat()/substring_index() trick:

select user_id,
       min(action_date) as first_action_date,
       max(action_date) as last_action_date,
       substring_index(substring_index(group_concat(action_date order by action_date desc), ',', 2), ',', -1) as second_to_last_date
from user_action_log ual
group by user_id;

Another alternative is a correlated subqueries:

select user_id,
       min(action_date) as first_action_date,
       max(action_date) as last_action_date,
       (select max(ual2.action_date)
        from user_action_log ual2
        where ual2.user_id = ual.user_id and
              ual2.action_date < max(ual.action_date)
      ) as second_to_last_date
from user_action_log ual
group by user_id;