问:
Issue With Nested If Statement
I was trying to ask the user if he/she wants another cupcake only if the cost of the first cupcake is less than their budget (maxPrice), but that does not work. It prints nothing after receiving user input. The error occurs where the program states: "if(anotherCupcake == "yes")" and it also occurs when it states, "anotherCupcake == "no".
Here's my code:</p>
```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(int argc, char**argv)
{
    float maxPrice;
    char flavor[20];
    char flavor2[20];
    float price;
    double price2;
    char anotherCupcake[20];
    double newPrice;

   // int idxToDel = 2;
    //memove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);

    printf("Please enter starting budget: ");
    scanf("%f", &maxPrice);
    printf("Enter the flavor of cupcake 1: ");
    scanf("%s", &flavor);
    printf("Enter the price of %s cupcake: $", flavor);
    scanf("%f", &price);

    //determining if you have enough money for a second cupcake
    if(price == maxPrice)
    {
        printf("\nOops! No more money left to spend on anymore cupcakes...enjoy the %s one! Bye!", flavor);
    }
    else if(price > maxPrice)
    {

        newPrice=maxPrice-price;
        printf("\nWow, you overspent on that first cupcake...you owe $%.2lf. Bye!", fabs(newPrice)*1.0);
    }
    else
    {
        printf("Ok, looks like you you have $%.2f left to spend on cupcakes...  Would you like to get another one?", maxPrice - price);
        scanf("%s", &anotherCupcake);

        //figuring out what second cupcake you want
        if(anotherCupcake == "yes")
        {
           printf("Enter the flavor of cupcake 2: ");
           scanf("%s", &flavor2);
           printf("Enter the price of cupcake 2 $: ");
           scanf("%f", &price2);
           printf("Done! Enjoy your %s and %s cupcakes! Bye!", flavor, flavor2);

        }
        if(anotherCupcake == "no")
        {
            printf("Ok then...Enjoy that one %s cupcake! Bye!", flavor);
        }
    }
    return 0;
}

</code>```

答:
try use string compare to compare values of two string. It may work.</p>
```<code>if(strcmp("yes", anotherCupcake) == 0)
 {
   printf("Enter the flavor of cupcake 2: ");
   scanf("%s", &flavor2);
   printf("Enter the price of cupcake 2 $: ");
   scanf("%f", &price2);
   printf("Done! Enjoy your %s and %s cupcakes! Bye!", flavor, flavor2);
}
</code>```

Title: Issue With Nested If Statement

Body:
I was trying to ask the user if he/she wants another cupcake only if the cost of the first cupcake is less than their budget (maxPrice), but that does not work. It prints nothing after receiving user input. The error occurs where the program states: "if(anotherCupcake == "yes")" and it also occurs when it states, "anotherCupcake == "no".
Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(int argc, char**argv)
{
    float maxPrice;
    char flavor[20];
    char flavor2[20];
    float price;
    double price2;
    char anotherCupcake[20];
    double newPrice;

   // int idxToDel = 2;
    //memove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);

    printf("Please enter starting budget: ");
    scanf("%f", &maxPrice);
    printf("Enter the flavor of cupcake 1: ");
    scanf("%s", &flavor);
    printf("Enter the price of %s cupcake: $", flavor);
    scanf("%f", &price);

    //determining if you have enough money for a second cupcake
    if(price == maxPrice)
    {
        printf("\nOops! No more money left to spend on anymore cupcakes...enjoy the %s one! Bye!", flavor);
    }
    else if(price > maxPrice)
    {

        newPrice=maxPrice-price;
        printf("\nWow, you overspent on that first cupcake...you owe $%.2lf. Bye!", fabs(newPrice)*1.0);
    }
    else
    {
        printf("Ok, looks like you you have $%.2f left to spend on cupcakes...  Would you like to get another one?", maxPrice - price);
        scanf("%s", &anotherCupcake);

        //figuring out what second cupcake you want
        if(anotherCupcake == "yes")
        {
           printf("Enter the flavor of cupcake 2: ");
           scanf("%s", &flavor2);
           printf("Enter the price of cupcake 2 $: ");
           scanf("%f", &price2);
           printf("Done! Enjoy your %s and %s cupcakes! Bye!", flavor, flavor2);

        }
        if(anotherCupcake == "no")
        {
            printf("Ok then...Enjoy that one %s cupcake! Bye!", flavor);
        }
    }
    return 0;
}

Body:
try use string compare to compare values of two string. It may work.

if(strcmp("yes", anotherCupcake) == 0)
 {
   printf("Enter the flavor of cupcake 2: ");
   scanf("%s", &flavor2);
   printf("Enter the price of cupcake 2 $: ");
   scanf("%f", &price2);
   printf("Done! Enjoy your %s and %s cupcakes! Bye!", flavor, flavor2);
}


来源: stackexchange

问:
Any tools to check for duplicate VB.NET code?
I wish to get a quick feeling for how much “copy and paste” coding we have, there are many tools for C# / Java to check for this type of thing.  Are there any such tools that work well with VB.NET?

(I have seen what looks like lots of repeated code, but wish to get some number to help me make a case for sorting it out)

Update on progress.

I have just tried Simian.

It does not seem to be able to produce a nicely formatted report I can sent by email

It does not cope when the names of local variables, or parameters etc may have been changed, e.g it just matches on lines of text being the same.

Clone Doctor does not support VB.NET (only C# and VB 6 and lot of other)

October 2010: VB.net added to langauges supported by CloneDR

Clone Detective for Visual Studio only supports C#

SolidSDD - Source Code Duplication Detector only supports C, C++, C# and Java

DuplicateFinder is open source, but otherwise looks very match like Simian, e.g it just works on lines of text

ConQAT - Continuous Quality Assessment Toolkit seems to have a clone detector that works for VB.NET (not tried it yet)

Gendarme is a bit like FXCop and has a AvoidCodeDuplicatedInSameClassRule rule, this looks very promising, as it avoids the problem of working at the text level.  Just tried it, it is the best solution so far, pity it does not search with a greater scope.

Before claiming that this question is a duplicate, please check that the other question addresses VB.NET, as a lot of tools that work well for C# don't work so well for VB.NET. (However it would not surprise me if this question is a real duplicate)

答: Atomiq supports vb.net amongst other languages, and the results are nicely presented.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to apply a function to specific columns of a pandas dataframe?
I would like to apply a function to specific columns of a pandas data frame. Here is an illustration:

```<code># import modules
from pandas_datareader import data as pdr

# import parameters
start = "2020-01-01"
end = "2021-01-01"
symbols = ["AAPL"]

# get the data
data = pdr.get_data_yahoo(symbols, start, end)

def mult(row):
    return row['Close']*2, row['Open']/3

data[['Close', 'Open']].apply(mult, axis = 1)

print(data.head())
</code>```

The result:

```<code>Attributes  Adj Close      Close       High        Low       Open       Volume
Symbols          AAPL       AAPL       AAPL       AAPL       AAPL         AAPL
Date
2020-01-02  73.894333  75.087502  75.150002  73.797501  74.059998  135480400.0
2020-01-03  73.175926  74.357498  75.144997  74.125000  74.287498  146322800.0
2020-01-06  73.759003  74.949997  74.989998  73.187500  73.447502  118387200.0
2020-01-07  73.412109  74.597504  75.224998  74.370003  74.959999  108872000.0
2020-01-08  74.593048  75.797501  76.110001  74.290001  74.290001  132079200.0
</code>```

Any thoughts as to why that doesn't work?

答:
Two things:

(i) You never assign it back to the original DataFrame, so it never gets updated.

(ii) If your function is not anymore complex, for simple multiplication, vectorized operation is better, so instead of the function, do the multiplication directly on the column:

```<code>data['Close'] *= 2
data['Open'] /= 3
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to apply a function to specific columns of a pandas data frame. Here is an illustration:

# import modules
from pandas_datareader import data as pdr

# import parameters
start = "2020-01-01"
end = "2021-01-01"
symbols = ["AAPL"]

# get the data
data = pdr.get_data_yahoo(symbols, start, end)

def mult(row):
    return row['Close']*2, row['Open']/3

data[['Close', 'Open']].apply(mult, axis = 1)

print(data.head())

The result:

Attributes  Adj Close      Close       High        Low       Open       Volume
Symbols          AAPL       AAPL       AAPL       AAPL       AAPL         AAPL
Date
2020-01-02  73.894333  75.087502  75.150002  73.797501  74.059998  135480400.0
2020-01-03  73.175926  74.357498  75.144997  74.125000  74.287498  146322800.0
2020-01-06  73.759003  74.949997  74.989998  73.187500  73.447502  118387200.0
2020-01-07  73.412109  74.597504  75.224998  74.370003  74.959999  108872000.0
2020-01-08  74.593048  75.797501  76.110001  74.290001  74.290001  132079200.0

Any thoughts as to why that doesn't work?

Body:
Two things:

(i) You never assign it back to the original DataFrame, so it never gets updated.

(ii) If your function is not anymore complex, for simple multiplication, vectorized operation is better, so instead of the function, do the multiplication directly on the column:

data['Close'] *= 2
data['Open'] /= 3


问:
Swagger not loading - Failed to load API definition: Fetch error undefined
Trying to setup swagger in conjunction with a web application hosted on IIS express. API is built using ASP Net Core. I have followed the instructions prescribed on the relevant microsoft help page regarding Swashbuckle and ASP.NET Core.

Thus far I have got the swagger page to load up and can see that the SwaggerDoc that I have defined is loading, however no API's are present. Currently am getting the following error:

"Fetch error undefined ./swagger/v1/swagger.json"

```<code>public class Startup
{

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // services.AddDbContext<TodoContext>(opt =>
        // opt.UseInMemoryDatabase("TodoList"));
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "API WSVAP (WebSmartView)", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("./swagger/v1/swagger.json", "My API V1");
            c.RoutePrefix = string.Empty;
        });

        app.UseMvc();
    }
}
</code>```

答:
I had a similar Fetch error 404 swagger/v1/swagger.json, when trying to integrate Swagger documentation in ASP.NET Core 3.1 Web API project. I tried almost all of the above suggestions but failed.
After an hour of hit-and-trial, I decided to give NSwag a try using this reference, instead of Swashbuckle and it just worked like a charm :)

Body:
Trying to setup swagger in conjunction with a web application hosted on IIS express. API is built using ASP Net Core. I have followed the instructions prescribed on the relevant microsoft help page regarding Swashbuckle and ASP.NET Core.

Thus far I have got the swagger page to load up and can see that the SwaggerDoc that I have defined is loading, however no API's are present. Currently am getting the following error:

"Fetch error undefined ./swagger/v1/swagger.json"

public class Startup
{

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // services.AddDbContext<TodoContext>(opt =>
        // opt.UseInMemoryDatabase("TodoList"));
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "API WSVAP (WebSmartView)", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("./swagger/v1/swagger.json", "My API V1");
            c.RoutePrefix = string.Empty;
        });

        app.UseMvc();
    }
}


问:
My data groups are not staying in order on my bar chart in R
I am making a bar chart with sd error bars on R but my Months (9, 10, 11, 12) won't stay in the correct order when placed on the graph. Does anybody know how to make it so they don't swap order?

```<code>library(tidyverse)
library(RColorBrewer)
d <- structure(list(Month = c("9", "9", "9", "10", "10", "10", "11", "11", "11", "12", "12", "12"), genus = c("Crustacean", "Mollusc", "Seaweed", "Crustacean", "Mollusc", "Seaweed","Crustacean", "Mollusc", "Seaweed","Crustacean", "Mollusc", "Seaweed"),
                    shannon = c(0,
                                1.1594324,
                                1.37245692,
                                0,
                                0.84868133,
                                1.54327422,
                                0.06432965,
                                1.1748941,
                                1.54612048,
                                0,
                                1.1045688,
                                1.7212854),
                    sd = c(0,
                           0.3288658,
                           0.7824814,
                           0,
                           0.8148536,
                           0.5015486,
                           0.1286593,
                           0.446148,
                           0.800392,
                           0,
                           0.1804363,
                           0.4421767)),
               row.names = c(NA, -12L), class = "data.frame")

d %>%
  ggplot(aes(x = genus, y = shannon, fill = Month)) +
  geom_col(width = 0.5,
           position = position_dodge(0.5)) +
  geom_errorbar(aes(ymin = shannon - sd, ymax = shannon + sd),
                width = 0.2,
                position = position_dodge(0.5)) +
  scale_fill_brewer(palette = "Blues") +
  theme_minimal()
</code>```

答:
Here comes a base R solution. Beforehand you should look where your months get coded as character, for this example we may convert it to numeric.

```<code>d$Month <- as.numeric(d$Month)

b <- barplot(shannon ~ Month + genus, d, beside=T, ylim=c(0, max(rowSums(d[3:4]))),
             col=hcl.colors(4, 'Blues', rev=T), legend.text=unique(d$Month),
             args.legend=list(x='topleft', title='Month', bty='n'))
with(d[order(d$genus), ], arrows(b, shannon - sd, b, shannon + sd, code=3,
                                 angle=90, length=.05, xpd=TRUE)))
</code>```

R will warn you that in this example some arrows have length zero and therefore aren't plotted.

Data:

```<code>d <- structure(list(Month = c("9", "9", "9", "10", "10", "10", "11",
"11", "11", "12", "12", "12"), genus = c("Crustacean", "Mollusc",
"Seaweed", "Crustacean", "Mollusc", "Seaweed", "Crustacean",
"Mollusc", "Seaweed", "Crustacean", "Mollusc", "Seaweed"), shannon = c(0,
1.1594324, 1.37245692, 0, 0.84868133, 1.54327422, 0.06432965,
1.1748941, 1.54612048, 0, 1.1045688, 1.7212854), sd = c(0, 0.3288658,
0.7824814, 0, 0.8148536, 0.5015486, 0.1286593, 0.446148, 0.800392,
0, 0.1804363, 0.4421767)), row.names = c(NA, -12L), class = "data.frame")
</code>```

Body:
I am making a bar chart with sd error bars on R but my Months (9, 10, 11, 12) won't stay in the correct order when placed on the graph. Does anybody know how to make it so they don't swap order?

library(tidyverse)
library(RColorBrewer)
d <- structure(list(Month = c("9", "9", "9", "10", "10", "10", "11", "11", "11", "12", "12", "12"), genus = c("Crustacean", "Mollusc", "Seaweed", "Crustacean", "Mollusc", "Seaweed","Crustacean", "Mollusc", "Seaweed","Crustacean", "Mollusc", "Seaweed"),
                    shannon = c(0,
                                1.1594324,
                                1.37245692,
                                0,
                                0.84868133,
                                1.54327422,
                                0.06432965,
                                1.1748941,
                                1.54612048,
                                0,
                                1.1045688,
                                1.7212854),
                    sd = c(0,
                           0.3288658,
                           0.7824814,
                           0,
                           0.8148536,
                           0.5015486,
                           0.1286593,
                           0.446148,
                           0.800392,
                           0,
                           0.1804363,
                           0.4421767)),
               row.names = c(NA, -12L), class = "data.frame")

d %>%
  ggplot(aes(x = genus, y = shannon, fill = Month)) +
  geom_col(width = 0.5,
           position = position_dodge(0.5)) +
  geom_errorbar(aes(ymin = shannon - sd, ymax = shannon + sd),
                width = 0.2,
                position = position_dodge(0.5)) +
  scale_fill_brewer(palette = "Blues") +
  theme_minimal()

Body:
Here comes a base R solution. Beforehand you should look where your months get coded as character, for this example we may convert it to numeric.

d$Month <- as.numeric(d$Month)

b <- barplot(shannon ~ Month + genus, d, beside=T, ylim=c(0, max(rowSums(d[3:4]))),
             col=hcl.colors(4, 'Blues', rev=T), legend.text=unique(d$Month),
             args.legend=list(x='topleft', title='Month', bty='n'))
with(d[order(d$genus), ], arrows(b, shannon - sd, b, shannon + sd, code=3,
                                 angle=90, length=.05, xpd=TRUE)))

R will warn you that in this example some arrows have length zero and therefore aren't plotted.

Data:

d <- structure(list(Month = c("9", "9", "9", "10", "10", "10", "11",
"11", "11", "12", "12", "12"), genus = c("Crustacean", "Mollusc",
"Seaweed", "Crustacean", "Mollusc", "Seaweed", "Crustacean",
"Mollusc", "Seaweed", "Crustacean", "Mollusc", "Seaweed"), shannon = c(0,
1.1594324, 1.37245692, 0, 0.84868133, 1.54327422, 0.06432965,
1.1748941, 1.54612048, 0, 1.1045688, 1.7212854), sd = c(0, 0.3288658,
0.7824814, 0, 0.8148536, 0.5015486, 0.1286593, 0.446148, 0.800392,
0, 0.1804363, 0.4421767)), row.names = c(NA, -12L), class = "data.frame")


问:
Javascript unit testing framework that doesn't work in strict mode
Is there a way to unit test code from not strict mode. Most of the testing frameworks, mocha, jest, etc are strict mode only. My code involves use of eval that needs non-strict mode scope that I cannot rewrite into strict mode compatible form. Any idea or do I need to write my own unit testing framework.</p>

答: I ended up using Karma with jasmine. Setting it to browser mode means no modules and no strict mode, yay.</p>


问:
Why would people use `$a = $b = 2;` in PHP?
Why would people use this format? Whats different between this and $a=2; $b=2;?

答:
It is a shorter coding style and is particularly useful when the various elements (the $a, $b and 2 in your example) are significantly longer.  Especially when the RHS is long.

For example:

```<code>$currentElement = $firstElement = $this->someCalculation($someparameter, $someotherparamter)->root;
</code>```

Body:
It is a shorter coding style and is particularly useful when the various elements (the $a, $b and 2 in your example) are significantly longer.  Especially when the RHS is long.

For example:

$currentElement = $firstElement = $this->someCalculation($someparameter, $someotherparamter)->root;


问:
YouTube Iframe API onError event does not fire in recent months
I'm pretty sure YouTube Iframe API "onError" event will fire in the past since I run a project based on this API. But recently "onError" event will not fire, even the simplest error.

This is a simple sample code based on official page( https://developers.google.com/youtube/iframe_api_reference ) and is workable:

```<code><iframe id="existing-iframe-example"
        width="640" height="360"
        src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1"
        frameborder="0"
        style="border: solid 4px #37474F"
></iframe>

<script type="text/javascript">
  var tag = document.createElement('script');
  tag.id = 'iframe-demo';
  tag.src = 'https://www.youtube.com/iframe_api';
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('existing-iframe-example', {
        events: {
          'onReady': onPlayerReady,
          'onStateChange': onPlayerStateChange,
          'onError': onError
        }
    });
  }
  function onError(event) {
    console.log(event.data)
  }

  function onPlayerReady(event) {

  }

  function onPlayerStateChange(event) {
    console.log(event.data);
  }
</script>
</code>```

Once change the video id string "M7lc1UVf-VE" as a wrong one, such as "M7lc1UVf", it should fire "onError" event, but doesn't now.

According to official page guide: https://developers.google.com/youtube/players/support → "Google engineers monitor and answer questions with the youtube-iframe-api tag", hope Google engineers can see this post and fix the "onError" problems.

答:
I found a workaround for this. I found that, at least in my case, the onError callback doesn't fire on initial load (when it's most needed!) but will fire after the rest of the player loads completely.

If you absolutely need the onError event to work, you can reload the video within a loaded player. Remove the autoplay param from the playerParams object-- this causes the hack to fail. Add loadByVideoId (for autoplay) or cueByVideoId with the same video id to the onReady callback.

This will reload the current video and the onError callback will fire if needed. Otherwise, there will be little to no noticeable effect--other than the video being briefly cued before it plays if autoplay is expected.

Let me know if you'd like more info-- hope that helps!

EDIT:

Here is a codesandbox demonstrating the issue. Note that the
error isn't added to the list until the "reset" button is clicked.
(As of Feb 12, 2022, while the bug still exists.)

Here is a codesandbox demonstrating the workaround I found. Notice the onReady callback, and the error populating on the list.

UPDATE:
I don't know when it happened-- the devs at Google never updated my issue-- but it looks like this bug may have been resolved. The first demo now lists the error code on load as expected. For anyone that implemented this workaround, you may be able to remove the hack now.

Body:
I'm pretty sure YouTube Iframe API "onError" event will fire in the past since I run a project based on this API. But recently "onError" event will not fire, even the simplest error.

This is a simple sample code based on official page( https://developers.google.com/youtube/iframe_api_reference ) and is workable:

Once change the video id string "M7lc1UVf-VE" as a wrong one, such as "M7lc1UVf", it should fire "onError" event, but doesn't now.

According to official page guide: https://developers.google.com/youtube/players/support → "Google engineers monitor and answer questions with the youtube-iframe-api tag", hope Google engineers can see this post and fix the "onError" problems.


问:
How to use python to check if a computer is in a domain or is in workgroup
I want to check if a computer is in a domain or in a workgroup using python

for example:

def run_check():
    # code here

result = run_check()
if result == "Domain":
    print("Domain")
elif result == "Workgroup":
    print("Workgroup")
else:
    print("None")
```

I tried using os.environ['USERDNSDOMAIN'] but it gives either WorkGroupName or DomainName and I cant tell if the name is for a Workgroup or a Domain

Can you help me out?

Thanks in advance

答:
Apply Windows Management Instrumentation (wmi module):

```<code>import wmi

wmi_os = wmi.WMI().Win32_ComputerSystem()[0]
print( wmi_os.Name, 'PartOfDomain?', wmi_os.PartOfDomain)
</code>```

```<code>MY-PC PartOfDomain? False
</code>```

Note: print(wmi_os) shows all properties (and their values) of the Win32_ComputerSystem class instance.

All properties are print(wmi_os.__dict__['properties'].keys())

```<code>dict_keys(['AdminPasswordStatus', 'AutomaticManagedPagefile', 'AutomaticResetBootOption', 'AutomaticResetCapability', 'BootOptionOnLimit', 'BootOptionOnWatchDog', 'BootROMSupported', 'BootStatus', 'BootupState', 'Caption', 'ChassisBootupState', 'ChassisSKUNumber', 'CreationClassName', 'CurrentTimeZone', 'DaylightInEffect', 'Description', 'DNSHostName', 'Domain', 'DomainRole', 'EnableDaylightSavingsTime', 'FrontPanelResetStatus', 'HypervisorPresent', 'InfraredSupported', 'InitialLoadInfo', 'InstallDate', 'KeyboardPasswordStatus', 'LastLoadInfo', 'Manufacturer', 'Model', 'Name', 'NameFormat', 'NetworkServerModeEnabled', 'NumberOfLogicalProcessors', 'NumberOfProcessors', 'OEMLogoBitmap', 'OEMStringArray', 'PartOfDomain', 'PauseAfterReset', 'PCSystemType', 'PCSystemTypeEx', 'PowerManagementCapabilities', 'PowerManagementSupported', 'PowerOnPasswordStatus', 'PowerState', 'PowerSupplyState', 'PrimaryOwnerContact', 'PrimaryOwnerName', 'ResetCapability', 'ResetCount', 'ResetLimit', 'Roles', 'Status', 'SupportContactDescription', 'SystemFamily', 'SystemSKUNumber', 'SystemStartupDelay', 'SystemStartupOptions', 'SystemStartupSetting', 'SystemType', 'ThermalState', 'TotalPhysicalMemory', 'UserName', 'WakeUpType', 'Workgroup'])
</code>```

You could be interested mainly in following ones:

```<code>Caption
DNSHostName
Domain
DomainRole
Name
NameFormat
PartOfDomain
Roles
UserName
Workgroup
</code>```

Body:
I want to check if a computer is in a domain or in a workgroup using python

for example:

def run_check():
    # code here

result = run_check()
if result == "Domain":
    print("Domain")
elif result == "Workgroup":
    print("Workgroup")
else:
    print("None")

I tried using os.environ['USERDNSDOMAIN'] but it gives either WorkGroupName or DomainName and I cant tell if the name is for a Workgroup or a Domain

Can you help me out?

Thanks in advance

Body:
Apply Windows Management Instrumentation (wmi module):

import wmi

wmi_os = wmi.WMI().Win32_ComputerSystem()[0]
print( wmi_os.Name, 'PartOfDomain?', wmi_os.PartOfDomain)

MY-PC PartOfDomain? False

Note: print(wmi_os) shows all properties (and their values) of the Win32_ComputerSystem class instance.

All properties are print(wmi_os.__dict__['properties'].keys())

dict_keys(['AdminPasswordStatus', 'AutomaticManagedPagefile', 'AutomaticResetBootOption', 'AutomaticResetCapability', 'BootOptionOnLimit', 'BootOptionOnWatchDog', 'BootROMSupported', 'BootStatus', 'BootupState', 'Caption', 'ChassisBootupState', 'ChassisSKUNumber', 'CreationClassName', 'CurrentTimeZone', 'DaylightInEffect', 'Description', 'DNSHostName', 'Domain', 'DomainRole', 'EnableDaylightSavingsTime', 'FrontPanelResetStatus', 'HypervisorPresent', 'InfraredSupported', 'InitialLoadInfo', 'InstallDate', 'KeyboardPasswordStatus', 'LastLoadInfo', 'Manufacturer', 'Model', 'Name', 'NameFormat', 'NetworkServerModeEnabled', 'NumberOfLogicalProcessors', 'NumberOfProcessors', 'OEMLogoBitmap', 'OEMStringArray', 'PartOfDomain', 'PauseAfterReset', 'PCSystemType', 'PCSystemTypeEx', 'PowerManagementCapabilities', 'PowerManagementSupported', 'PowerOnPasswordStatus', 'PowerState', 'PowerSupplyState', 'PrimaryOwnerContact', 'PrimaryOwnerName', 'ResetCapability', 'ResetCount', 'ResetLimit', 'Roles', 'Status', 'SupportContactDescription', 'SystemFamily', 'SystemSKUNumber', 'SystemStartupDelay', 'SystemStartupOptions', 'SystemStartupSetting', 'SystemType', 'ThermalState', 'TotalPhysicalMemory', 'UserName', 'WakeUpType', 'Workgroup'])

You could be interested mainly in following ones:

Caption
DNSHostName
Domain
DomainRole
Name
NameFormat
PartOfDomain
Roles
UserName
Workgroup


问:
collapse R package: rearraning or reposition columns in custom order
I'm using collapse R package want to reposition columns. In tidyverse or dplyr, this can be achieved by using everything() function. However everything() function is not working with fselect function from collapse. Any thoughts.

```<code>library(collapse)
library(tidyverse)

wlddev %>%
  qDT() %>%
  fselect(date, year, decade)

             date year decade
    1: 1961-01-01 1960   1960
    2: 1962-01-01 1961   1960
    3: 1963-01-01 1962   1960
    4: 1964-01-01 1963   1960
    5: 1965-01-01 1964   1960
   ---
13172: 2017-01-01 2016   2010
13173: 2018-01-01 2017   2010
13174: 2019-01-01 2018   2010
13175: 2020-01-01 2019   2010
13176: 2021-01-01 2020   2020

wlddev %>%
  qDT() %>%
  fselect(date, year, decade, everything())

Error in `peek_vars()`:
! `everything()` must be used within a *selecting* function.
i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.
Run `rlang::last_error()` to see where the error occurred.
</code>```

答:
With collapse, there is colorder where we can specify the pos

colorder(X, ..., pos = c("front", "end", "exchange"))

```<code>library(collapse)
library(dplyr)
wlddev %>%
   qDT %>%
   colorder(date, year, decade, pos = "front")
</code>```

-output

```<code>            date  year decade     country  iso3c             region              income   OECD    PCGDP LIFEEX  GINI       ODA      POP
           <Date> <int>  <int>      <char> <fctr>             <fctr>              <fctr> <lgcl>    <num>  <num> <num>     <num>    <num>
    1: 1961-01-01  1960   1960 Afghanistan    AFG         South Asia          Low income  FALSE       NA 32.446    NA 116769997  8996973
    2: 1962-01-01  1961   1960 Afghanistan    AFG         South Asia          Low income  FALSE       NA 32.962    NA 232080002  9169410
    3: 1963-01-01  1962   1960 Afghanistan    AFG         South Asia          Low income  FALSE       NA 33.471    NA 112839996  9351441
    4: 1964-01-01  1963   1960 Afghanistan    AFG         South Asia          Low income  FALSE       NA 33.971    NA 237720001  9543205
    5: 1965-01-01  1964   1960 Afghanistan    AFG         South Asia          Low income  FALSE       NA 34.463    NA 295920013  9744781
   ---
13172: 2017-01-01  2016   2010    Zimbabwe    ZWE Sub-Saharan Africa Lower middle income  FALSE 1224.310 60.294    NA 687659973 14030390
13173: 2018-01-01  2017   2010    Zimbabwe    ZWE Sub-Saharan Africa Lower middle income  FALSE 1263.321 60.812  44.3 753909973 14236745
13174: 2019-01-01  2018   2010    Zimbabwe    ZWE Sub-Saharan Africa Lower middle income  FALSE 1305.783 61.195    NA 794510010 14439018
13175: 2020-01-01  2019   2010    Zimbabwe    ZWE Sub-Saharan Africa Lower middle income  FALSE 1183.099 61.490  50.3 988039978 14645468
13176: 2021-01-01  2020   2020    Zimbabwe    ZWE Sub-Saharan Africa Lower middle income  FALSE       NA     NA    NA
</code>```

Body:
I'm using collapse R package want to reposition columns. In tidyverse or dplyr, this can be achieved by using everything() function. However everything() function is not working with fselect function from collapse. Any thoughts.

library(collapse)
library(tidyverse)

wlddev %>%
  qDT() %>%
  fselect(date, year, decade)

             date year decade
    1: 1961-01-01 1960   1960
    2: 1962-01-01 1961   1960
    3: 1963-01-01 1962   1960
    4: 1964-01-01 1963   1960
    5: 1965-01-01 1964   1960
   ---
13172: 2017-01-01 2016   2010
13173: 2018-01-01 2017   2010
13174: 2019-01-01 2018   2010
13175: 2020-01-01 2019   2010
13176: 2021-01-01 2020   2020

wlddev %>%
  qDT() %>%
  fselect(date, year, decade, everything())

Error in `peek_vars()`:
! `everything()` must be used within a *selecting* function.
i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.
Run `rlang::last_error()` to see where the error occurred.

Body:
With collapse, there is colorder where we can specify the pos

colorder(X, ..., pos = c("front", "end", "exchange"))

library(collapse)
library(dplyr)
wlddev %>%
   qDT %>%
   colorder(date, year, decade, pos = "front")

-output

            date  year decade     country  iso3c             region              income   OECD    PCGDP LIFEEX  GINI       ODA      POP
           <Date> <int>  <int>      <char> <fctr>             <fctr>              <fctr> <lgcl>    <num>  <num> <num>     <num>    <num>
    1: 1961-01-01  1960   1960 Afghanistan    AFG         South Asia          Low income  FALSE       NA 32.446    NA 116769997  8996973
    2: 1962-01-01  1961   1960 Afghanistan    AFG         South Asia          Low income  FALSE       NA 32.962    NA 232080002  9169410
    3: 1963-01-01  1962   1960 Afghanistan    AFG         South Asia          Low income  FALSE       NA 33.471    NA 112839996  9351441
    4: 1964-01-01  1963   1960 Afghanistan    AFG         South Asia          Low income  FALSE       NA 33.971    NA 237720001  9543205
    5: 1965-01-01  1964   1960 Afghanistan    AFG         South Asia          Low income  FALSE       NA 34.463    NA 295920013  9744781
   ---
13172: 2017-01-01  2016   2010    Zimbabwe    ZWE Sub-Saharan Africa Lower middle income  FALSE 1224.310 60.294    NA 687659973 14030390
13173: 2018-01-01  2017   2010    Zimbabwe    ZWE Sub-Saharan Africa Lower middle income  FALSE 1263.321 60.812  44.3 753909973 14236745
13174: 2019-01-01  2018   2010    Zimbabwe    ZWE Sub-Saharan Africa Lower middle income  FALSE 1305.783 61.195    NA 794510010 14439018
13175: 2020-01-01  2019   2010    Zimbabwe    ZWE Sub-Saharan Africa Lower middle income  FALSE 1183.099 61.490  50.3 988039978 14645468
13176: 2021-01-01  2020   2020    Zimbabwe    ZWE Sub-Saharan Africa Lower middle income  FALSE       NA     NA    NA


问:
Calling a Function During Array Creation to export contents of folder containing Zip files
I am having trouble trying to call a function for a script that I'm using to build a list of zip files in a folder on my PC.  The final CSV I need is to create is a list of the zip files with their uncompressed sizes.  Here is what I have so far (compiled from several posts):

Function to get the uncompressed size:

```<code>function Get-UncompressedZipFileSize {

param (
    $Path
)

$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace($Path)
$size = 0
foreach ($item in $zip.items()) {
    if ($item.IsFolder) {
        $size += Get-UncompressedZipFileSize -Path $item.Path
    } else {
        $size += $item.size
    }
}

[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$shell) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

return $size
}
</code>```

Here is my Array Creation:

```<code>$arr = @()
gci C:\zips -recurse | ? {$_.PSIsContainer -eq $False} | % {
$obj = New-Object PSObject
$obj | Add-Member NoteProperty Name $_.Name
$obj | Add-Member NoteProperty FullPath $_.FullName
$arr += $obj
}
$arr | Export-CSV -notypeinformation c:\zips
</code>```

I'm stuck at creating a new member object into my array that will call the get-uncompressedzipfilesize function to pass that size back into the array as a new column in my zip. Is something like this even possible.?

答:
To make this simpler, since you're only calling your function to get the size of the current folder (zip), you can use a Calculated Property for this:

```<code>$Path = "C:\Zips"
Get-ChildItem -Path $Path -Directory -Recurse |
    Select-Object -Property Name, FullName,
    @{
        Name = "Size"
        Expression = {
            Get-UncompressedZipFileSize -Path $_.FullName
        }
    } | Export-Csv -Path "$Path\zip.csv" -Force -NoTypeInformation -Append
</code>```

On another note, if you ever find yourself explicitly adding to an array, take advantage of PowerShell's pipeline streaming.

```<code>$Path = "C:\Zips"
Get-ChildItem -Path $Path -Directory -Recurse |
    ForEach-Object -Process {
        [PSCustomObject]@{
            Name = $_.Name
            FullPath = $_.FullName
            Size = Get-UncompressedZipFileSize -Path $_.FullName
        } | Export-Csv -Path "$Path\zip.csv" -Force -NoTypeInformation -Append
    }
</code>```

Not only is adding to a fixed array (+=) computationally expensive (if you have a large directory), it is slow. Fixed arrays mean just that, they are a fixed size and in order for you to add to it, it needs to be broken down and recreated. An alternate solution would by an arraylist but, in this case - and in most cases - it's not needed.

Get-ChildItem also includes a -Directory switch to search for just folders. Presented in V3.

I would recommend searching for the file extension of the compressed folders as well so you don't run into any issues using -Filter.

Body:
I am having trouble trying to call a function for a script that I'm using to build a list of zip files in a folder on my PC.  The final CSV I need is to create is a list of the zip files with their uncompressed sizes.  Here is what I have so far (compiled from several posts):

Function to get the uncompressed size:

function Get-UncompressedZipFileSize {

param (
    $Path
)

$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace($Path)
$size = 0
foreach ($item in $zip.items()) {
    if ($item.IsFolder) {
        $size += Get-UncompressedZipFileSize -Path $item.Path
    } else {
        $size += $item.size
    }
}

[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$shell) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

return $size
}

Here is my Array Creation:

$arr = @()
gci C:\zips -recurse | ? {$_.PSIsContainer -eq $False} | % {
$obj = New-Object PSObject
$obj | Add-Member NoteProperty Name $_.Name
$obj | Add-Member NoteProperty FullPath $_.FullName
$arr += $obj
}
$arr | Export-CSV -notypeinformation c:\zips

I'm stuck at creating a new member object into my array that will call the get-uncompressedzipfilesize function to pass that size back into the array as a new column in my zip. Is something like this even possible.?

Body:
To make this simpler, since you're only calling your function to get the size of the current folder (zip), you can use a Calculated Property for this:

$Path = "C:\Zips"
Get-ChildItem -Path $Path -Directory -Recurse |
    Select-Object -Property Name, FullName,
    @{
        Name = "Size"
        Expression = {
            Get-UncompressedZipFileSize -Path $_.FullName
        }
    } | Export-Csv -Path "$Path\zip.csv" -Force -NoTypeInformation -Append

On another note, if you ever find yourself explicitly adding to an array, take advantage of PowerShell's pipeline streaming.

$Path = "C:\Zips"
Get-ChildItem -Path $Path -Directory -Recurse |
    ForEach-Object -Process {
        [PSCustomObject]@{
            Name = $_.Name
            FullPath = $_.FullName
            Size = Get-UncompressedZipFileSize -Path $_.FullName
        } | Export-Csv -Path "$Path\zip.csv" -Force -NoTypeInformation -Append
    }

Not only is adding to a fixed array (+=) computationally expensive (if you have a large directory), it is slow. Fixed arrays mean just that, they are a fixed size and in order for you to add to it, it needs to be broken down and recreated. An alternate solution would by an arraylist but, in this case - and in most cases - it's not needed.

Get-ChildItem also includes a -Directory switch to search for just folders. Presented in V3.

I would recommend searching for the file extension of the compressed folders as well so you don't run into any issues using -Filter.


问:
Google Sheets: Conditional Formatting - color all non-empty cells in a row within a range based on the value of another cell?
 Hello!

 So I have different (non-numeric) values in Column B (B3:B). And I have transactions (formatted as currency) in Columns C through E (range C3:E). So I want every cell in any given row within that range to be colored, whenever that cell  has some value (non-empty) AND the corresponding cell (of the same row) in Column B has "$" value in it.

 In other words I need a formula that would check the whole (C3:E) range, find all non-empty cells (assuming that there will be blank cells in that range), check the corresponding (of the same row number) cells in Column B and, if those corresponding cells contain "$" value, color all the non-empty cells in that row (even if there are several non-empty cells in there) within the (C3:E) range.

Let's say we see that in row 7 there are two cells (and they are within our C3:E range) that have values 23.54 and 67.90 (non-empty). That's the first condition. And we also see that the value of the corresponding cell in row 7 of Column B (B7) is "$". That's the second condition. So only cells C7 and E7 (not the whole C7-E7 row) must be colored by conditional formatting. So in the table I provided only cells D4, C7 and E7 must be colored.

 That's the custom formula for Conditional Formatting that I came up with =AND(NOT(ISBLANK(C3:E)),AND($B3="$")) but the problem is that it colors the whole row instead of the non-empty cells in that row only.

 Where am I making a mistake?

Please advise.

     Column B      Column C     Column D     Column E

3      None               14.50                                    12.00
4         $                                         45.90
5      Some               23.90
6       Few
7        $                    23.54                                   67.90

P.S: What would the formula be to color the cells that contain anything else but "$" with another color?

Body:
try like this:

=($B3="$")*(C3<>"")


问:
Find the right pattern for code duplication
I have a car service that is using car api to work with the car. The problem is that I use get_driver_car in every single method of my service to get the car object and in the end I use update_car method to save the data. From my perspective, it seems like these two methods can be used from another method but I have no idea how to refactor this code. I would be glad to hear all suggestions</p>
```<code>class CarService(object):
    def __init__(self):
        self.api = CarApiService()

    def add_branding(self, car_id: str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']
        if 'sticker' not in car['amenities']:
            car['amenities'].append('sticker')

        if 'lightbox' not in car['amenities']:
            car['amenities'].append('lightbox')

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})

    def remove_branding(self, car_id: str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']

        if 'sticker' in car['amenities']:
            del car['amenities'][car['amenities'].index('sticker')]

        if 'lightbox' in car['amenities']:
            del car['amenities'][car['amenities'].index('lightbox')]

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})

    def add_booster(self, car_id:str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']

        if car['booster_count'] == 0:
            car['booster_count'] = 1
        else:
            return None

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})

    def remove_booster(self, car_id: str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']

        if car['booster_count'] == 1:
            car['booster_count'] = 0
        else:
            return None

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})
    def create_car_request(self, car: dict) -> dict:
        del car['is_readonly']
        del car['created_date']

        return car
</code>```

答:
The most basic step towards optimizing something like this is to create helper methods for the repeated logic.

We can replace a complicated line of code:

```<code>return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})
</code>```

With a simple one:

```<code>return self._update_helper(car_id, car)
</code>```

By implementing an internal helper method:

```<code>def _update_helper(self, car_id: str, car: dict):
    return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})
</code>```

All of your repetitive methods share the same structure:

Access the car from the API.

Perform some modification on the car.

Send the modified car back to the API.

The differences exist only in step #2.  You should be able to create some sort of wrapper or decorator to take a step #2 modification and turn it into a complete function.

Unfortunately I don't code in Python so I'm unsure of the syntax here.

```<code>def _create_car_modifier(self, func):
    def inner(self, car_id: str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']
        if func(car) is None:
            return
        else
            return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})
    return inner
</code>```

Body:
I have a car service that is using car api to work with the car. The problem is that I use get_driver_car in every single method of my service to get the car object and in the end I use update_car method to save the data. From my perspective, it seems like these two methods can be used from another method but I have no idea how to refactor this code. I would be glad to hear all suggestions

class CarService(object):
    def __init__(self):
        self.api = CarApiService()

    def add_branding(self, car_id: str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']
        if 'sticker' not in car['amenities']:
            car['amenities'].append('sticker')

        if 'lightbox' not in car['amenities']:
            car['amenities'].append('lightbox')

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})

    def remove_branding(self, car_id: str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']

        if 'sticker' in car['amenities']:
            del car['amenities'][car['amenities'].index('sticker')]

        if 'lightbox' in car['amenities']:
            del car['amenities'][car['amenities'].index('lightbox')]

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})

    def add_booster(self, car_id:str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']

        if car['booster_count'] == 0:
            car['booster_count'] = 1
        else:
            return None

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})

    def remove_booster(self, car_id: str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']

        if car['booster_count'] == 1:
            car['booster_count'] = 0
        else:
            return None

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})
    def create_car_request(self, car: dict) -> dict:
        del car['is_readonly']
        del car['created_date']

        return car

Body:
The most basic step towards optimizing something like this is to create helper methods for the repeated logic.

We can replace a complicated line of code:

return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})

With a simple one:

return self._update_helper(car_id, car)

By implementing an internal helper method:

def _update_helper(self, car_id: str, car: dict):
    return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})

All of your repetitive methods share the same structure:

Access the car from the API.

Perform some modification on the car.

Send the modified car back to the API.

The differences exist only in step #2.  You should be able to create some sort of wrapper or decorator to take a step #2 modification and turn it into a complete function.

Unfortunately I don't code in Python so I'm unsure of the syntax here.

def _create_car_modifier(self, func):
    def inner(self, car_id: str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']
        if func(car) is None:
            return
        else
            return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})
    return inner


问:
How to use scss variable in css
I need to change the font size using a variable as prescribed by the author. I am not sure on how to do it. The author claims tha t it ,can be done using css.

This is my css line

```<code>font-size:var(--sb-font-size:38px);
</code>```

https://github.com/MurhafSousli/ngx-sharebuttons/blob/master/CHANGELOG.MD

答:
Sass/SCSS variables are all compiled away. This means you would see just the value in your compiled CSS. By contrast CSS custom properties "variables" are actually included in the CSS output.

More information about...

SASS/SCSS Variables

CSS Custom Properties "Variables"

Usage of CSS custom properties "variables":

:root {
  --sb-font-size: 38px;
}

.your-element {
  font-size: var(--sb-font-size);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="your-element">Hey</p></code>```

Usage of SASS variables:

```<code>$sb-font-size: 38px;

.your-element {
  font-size: $sb-font-size:
}
</code>```

Title: How to use scss variable in css

Body:
I need to change the font size using a variable as prescribed by the author. I am not sure on how to do it. The author claims tha t it ,can be done using css.

This is my css line

font-size:var(--sb-font-size:38px);

https://github.com/MurhafSousli/ngx-sharebuttons/blob/master/CHANGELOG.MD

Body:
Sass/SCSS variables are all compiled away. This means you would see just the value in your compiled CSS. By contrast CSS custom properties "variables" are actually included in the CSS output.

More information about...

SASS/SCSS Variables

CSS Custom Properties "Variables"

Usage of CSS custom properties "variables":

:root {
  --sb-font-size: 38px;
}

.your-element {
  font-size: var(--sb-font-size);
}

<p class="your-element">Hey</p>

Usage of SASS variables:

$sb-font-size: 38px;

.your-element {
  font-size: $sb-font-size:
}


问:
Create a pizza like circle
Is there any way to create a circle with a missing segment like the picture using JavaScript or CSS3?

答:
You can use conic-gradient

.a {
  width: 300px;
  height: 300px;
  border-radius: 50%;
  background: conic-gradient(green 20deg, transparent 20deg 60deg, green 60deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a"></div></code>```

Or use it as mask:

.a {
  width: 300px;
  height: 300px;
  border-radius: 50%;
  --mask: conic-gradient(green 20deg, transparent 20deg 60deg, green 60deg);
  -webkit-mask: var(--mask);
          mask: var(--mask);
  background: linear-gradient(purple,red);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a"></div></code>```

Title: Create a pizza like circle

Body:
You can use conic-gradient

.a {
  width: 300px;
  height: 300px;
  border-radius: 50%;
  background: conic-gradient(green 20deg, transparent 20deg 60deg, green 60deg);
}

<div class="a"></div>

Or use it as mask:

.a {
  width: 300px;
  height: 300px;
  border-radius: 50%;
  --mask: conic-gradient(green 20deg, transparent 20deg 60deg, green 60deg);
  -webkit-mask: var(--mask);
          mask: var(--mask);
  background: linear-gradient(purple,red);
}

<div class="a"></div>


问:
bring down a spring boot service when no load and come up when request come
is there any way that spring-boot application goes down when there is no request and come up a request come? I know there has to be orchestration service. but is there is a way in spring boot? is there any code reference where a light spring boot application there? maybe by gateway etc.</p>

答:
That is an excellent use case for services like AWS lambda and its analogues on other cloud platforms. You can also make an application using Spring Cloud Function and deploy it for example to above mentioned service. As far as I know it would start up the application only when the request arrives and shut it down after it. You can see a tutorial https://www.baeldung.com/spring-cloud-function
Not sure if that is what you want, let me know if that helps!</p>


问:
bash or zsh: how to pass multiple inputs to interactive piped parameters?
I have 3 different files that I want to compare

words_freq
words_freq_deduped
words_freq_alpha

For each file, I run a command like so, which I iterate on constantly to compare the results.

For example, I would do this:

```<code>$ cat words_freq | grep -v '[soe]'
$ cat words_freq_deduped | grep -v '[soe]'
$ cat words_freq_alpha | grep -v '[soe]'
</code>```

and then review the results, and then do it again, with an additional filter

```<code>$ cat words_freq | grep -v '[soe]' | grep a | grep r | head -n20
a

$ cat words_freq_deduped | grep -v '[soe]' | grep a | grep r | head -n20
b

$ cat words_freq_alpha | grep -v '[soe]' | grep a | grep r | head -n20
c
</code>```

This continues on until I've analyzed my data.

I would like to write a script that could take the piped portions, and pass it to each of these files, as I iterate on the grep/head portions of the command.

e.g. The following would dump the results of running the 3 commands above AND also compare the 3 results, and dump additional calculations on them

```<code>$ myScript | grep -v '[soe]' | grep a | grep r | head -n20
the letters were in all 3 runs, and it took 5 seconds
a
b
c
</code>```

How can I do this using bash/python or zsh for the myScript part?

EDIT: After asking the question, it occurred to me that I could use eval to do it, like so, which I've added as an answer as well

The following approach allows me to process multiple files by using eval, which I know is frowned upon - any other suggestions are greatly appreciated!

```<code>$ myScript "grep -v '[soe]' | grep a | grep r | head -n20"
</code>```

myScript

```<code>#!/usr/bin/env bash
function doIt(){
  FILE=$1
  CMD="cat $1 | $2"
  echo processing file "$FILE"
  eval "$CMD"
  echo
}

doIt words_freq "$@"
doIt words_freq_deduped "$@"
doIt words_freq_alpha "$@"
</code>```

答:
You can't avoid your shell from running pipes itself, so using it like that isn't very practical - you'd need to either quote everything and then eval it, which would make it hard to pass arguments with spaces, or quote every pipe, which you can then eval, making it so you have to quote every pipe. But yeah, these solutions are kinda hacky.

I'd suggest doing one of these two:

Keep your editor open, and put whatever you want to run inside the doIt function itself before you run it. Then run it in your shell without any arguments:

#!/usr/bin/env bash

doIt() {
  # grep -v '[soe]' < "$1"
  grep -v '[soe]' < "$1" | grep a | grep r | head -n20
}

doIt words_freq
doIt words_freq_deduped
doIt words_freq_alpha
```
<p>Or, you could always use a "for" in your shell, which you can use Ctrl+r to find in your history when you want to use:</p>
<pre class="lang-sh prettyprint-override"><code>$ for f in words_freq*; do grep -v '[soe]' < "$f" | grep a | grep r | head -n20; done
</code>```

But if you really want your approach, I tried to make it accept spaces, but it ended up being even hackier:

#!/usr/bin/env bash

doIt() {
  local FILE=$1
  shift
  echo processing file "$FILE"
  local args=()

  for n in $(seq 1 $#); do
    arg=$1
    shift
    if [[ $arg == '|' ]]; then
      args+=('|')
    else
      args+=("\"$arg\"")
    fi
  done
  eval "cat '$FILE' | ${args[@]}"
}

doIt words_freq "$@"
doIt words_freq_deduped "$@"
doIt words_freq_alpha "$@"
```
<p>With this version you can use it like this:</p>
```$ ./myScript grep "a a" "|" head -n1
```

Notice that it need you to quote the |, and that it now handles arguments with spaces.

Body:
I have 3 different files that I want to compare

words_freq
words_freq_deduped
words_freq_alpha

For each file, I run a command like so, which I iterate on constantly to compare the results.

For example, I would do this:

$ cat words_freq | grep -v '[soe]'
$ cat words_freq_deduped | grep -v '[soe]'
$ cat words_freq_alpha | grep -v '[soe]'

and then review the results, and then do it again, with an additional filter

$ cat words_freq | grep -v '[soe]' | grep a | grep r | head -n20
a

$ cat words_freq_deduped | grep -v '[soe]' | grep a | grep r | head -n20
b

$ cat words_freq_alpha | grep -v '[soe]' | grep a | grep r | head -n20
c

This continues on until I've analyzed my data.

I would like to write a script that could take the piped portions, and pass it to each of these files, as I iterate on the grep/head portions of the command.

e.g. The following would dump the results of running the 3 commands above AND also compare the 3 results, and dump additional calculations on them

$ myScript | grep -v '[soe]' | grep a | grep r | head -n20
the letters were in all 3 runs, and it took 5 seconds
a
b
c

How can I do this using bash/python or zsh for the myScript part?

EDIT: After asking the question, it occurred to me that I could use eval to do it, like so, which I've added as an answer as well

The following approach allows me to process multiple files by using eval, which I know is frowned upon - any other suggestions are greatly appreciated!

$ myScript "grep -v '[soe]' | grep a | grep r | head -n20"

myScript

#!/usr/bin/env bash
function doIt(){
  FILE=$1
  CMD="cat $1 | $2"
  echo processing file "$FILE"
  eval "$CMD"
  echo
}

doIt words_freq "$@"
doIt words_freq_deduped "$@"
doIt words_freq_alpha "$@"

Body:
You can't avoid your shell from running pipes itself, so using it like that isn't very practical - you'd need to either quote everything and then eval it, which would make it hard to pass arguments with spaces, or quote every pipe, which you can then eval, making it so you have to quote every pipe. But yeah, these solutions are kinda hacky.

I'd suggest doing one of these two:

Keep your editor open, and put whatever you want to run inside the doIt function itself before you run it. Then run it in your shell without any arguments:

#!/usr/bin/env bash

doIt() {
  # grep -v '[soe]' < "$1"
  grep -v '[soe]' < "$1" | grep a | grep r | head -n20
}

doIt words_freq
doIt words_freq_deduped
doIt words_freq_alpha

Or, you could always use a "for" in your shell, which you can use Ctrl+r to find in your history when you want to use:

$ for f in words_freq*; do grep -v '[soe]' < "$f" | grep a | grep r | head -n20; done

But if you really want your approach, I tried to make it accept spaces, but it ended up being even hackier:

#!/usr/bin/env bash

doIt() {
  local FILE=$1
  shift
  echo processing file "$FILE"
  local args=()

  for n in $(seq 1 $#); do
    arg=$1
    shift
    if [[ $arg == '|' ]]; then
      args+=('|')
    else
      args+=("\"$arg\"")
    fi
  done
  eval "cat '$FILE' | ${args[@]}"
}

doIt words_freq "$@"
doIt words_freq_deduped "$@"
doIt words_freq_alpha "$@"

With this version you can use it like this:

$ ./myScript grep "a a" "|" head -n1

Notice that it need you to quote the |, and that it now handles arguments with spaces.


问:
How to extract and compare the libc versions at runtime?
How to extract and compare the libc versions at runtime with the following restrictions?

stable solution (commands output parsing is discarded as this may vary)

should not rely on executing external tools like ldd, gcc or others

must work on a statically linked binary (AppRun)

will be implemented in C

Context:

In the AppImage project have been working on a feature to allow creating backward compatible bundles. To achieve this we created a program named AppRun. Things program compares the system glibc version with the one shipped in the bundle and configures the bundle to use the newer at runtime. This program is statically linked and should not depend on external tools.

Right now we scan the libc.so file for occurrences of GLIBC_X.XX and store the greater. But this is no longer working in the latest binary include in Ubuntu 20.04. The binary is 2.31 but there are no GLIBC_2.31 strings in the file therefore the method fails.

Related issues:

https://github.com/AppImageCrafters/AppRun/issues/35

https://github.com/AppImageCrafters/appimage-builder/issues/145

答:
This program compares the system glibc version with the one shipped in the bundle and configures the bundle to use the newer at runtime.

Note that "configuring at runtime" involves more than just pointing the programs to the "correct" libc.so.6, as this answer explains.

Right now we scan the libc.so file for occurrences of GLIBC_X.XX and store the greater. But this is no longer working in the latest binary include in Ubuntu 20.04.

You appear to have a fundamental misunderstanding of how symbol versioning works. This answer may help understanding this better.

Your method is working.

The binary is 2.31 but there are no GLIBC_2.31 strings in the file therefore the method fails.

As above referenced answer explains, this means that GLIBC-2.31 didn't introduce any new ABI-incompatible symbols, and programs linked against that version of GLIBC will work when older GLIBC version is present at runtime (but may run into GLIBC bugs fixed between versions 2.30 and 2.31, etc.).


问:
How to add legend to plot from CausalImpact package?
I see the other post here about this, but I'm relatively new to R so the answers weren't helpful to me. I'd really appreciate some more in-depth help with how to do this.

I've already made a plot using the commands from the Causal Impact package. In the package documentation, it clearly says that the plots are ggplot2 objects and can be customized the same way as any other object like that. I've successfully done that, adding titles and customizing colors. I need to add a legend (it's required at the journal I'm submitting to). Here is an example of what my graph currently looks like and the code I used to get there.

```<code>library(ggplot2)
devtools::install_github("google/CausalImpact")
library(CausalImpact)

## note that I took this example code from the package documentation up until I customize the plot

#create data
set.seed(1)
x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100)
y <- 1.2 * x1 + rnorm(100)
y[71:100] <- y[71:100] + 10
data <- cbind(y, x1)

#causal impact analysis
> pre.period <- c(1, 70)
> post.period <- c(71, 100)
> impact <- CausalImpact(data, pre.period, post.period)

#graph
example<-plot(impact, c("original", "cumulative")) +
    labs(
        x = "Time",
        y = "Clicks (Millions)",
        title = "Figure. Analysis of click behavior after intervention.") +
    theme(plot.title = element_text(hjust = 0.5),
          plot.caption = element_text(hjust = 0),
          panel.background = element_rect(fill = "transparent"), # panel bg
          plot.background = element_rect(fill = "transparent", color = NA), # plot bg
          panel.grid.major = element_blank(), # get rid of major grid
          panel.grid.minor = element_blank())  # get rid of minor grid

</code>```

In my head, the solution I'd like is to have a legend for each panel of the plot. The first legend (next to the 'original' panel) would show a solid line represents the observed data, the dotted line represents the estimated counterfactual, and the colored band represents the 95% CrI around the estimated counterfactual. The second legend (next to the 'cumulative' panel) would show the dotted line represents the estimated change in trend associated with the intervention and the colored band again represents the 95% CrI around the estimation. Maybe there's a better solution than that, but that's what I've thought of.

Here is a section of the underlying code that runs when you plot:

```<code># Initialize plot
  q <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
  q <- q + xlab("") + ylab("")
  if (length(metrics) > 1) {
    q <- q + facet_grid(metric ~ ., scales = "free_y")
  }

  # Add prediction intervals
  q <- q + geom_ribbon(aes(ymin = lower, ymax = upper),
                       data, fill = "slategray2")

  # Add pre-period markers
  xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                    impact$model$post.period,
                                    time(impact$series))
  q <- q + geom_vline(xintercept = xintercept,
                      colour = "darkgrey", size = 0.8, linetype = "dashed")

  # Add zero line to pointwise and cumulative plot
  q <- q + geom_line(aes(y = baseline),
                     colour = "darkgrey", size = 0.8, linetype = "solid",
                     na.rm = TRUE)

  # Add point predictions
  q <- q + geom_line(aes(y = mean), data,
                     size = 0.6, colour = "darkblue", linetype = "dashed",
                     na.rm = TRUE)

  # Add observed data
  q <- q + geom_line(aes(y = response), size = 0.6,  na.rm = TRUE)
  return(q)
}
</code>```

One of the answers in that older post here said that I'd have to adapt the pre-existing function to get a legend, and I don't really have the skills yet to see what I'd have to change or add. I thought that legends were supposed to be automatically added according to what's in the aes() bit of the ggplot code, so I'm a little confused why there isn't one in the first place. Can someone help me with this?

答:
Here is an updated/edited version of an earlier solution in order to merge aesthetics into one legend. The requirement was to merge linetype and fill (ribbon color) into one legend.

In order to merge legends, the same aesthetics have to be used in the geoms and the scales have to account for the different variables, have the same name and the same labels. So geom_ribbon() needs to have a linetype in the aes() as well as fill, and the geom_line() needs to have a fill in the aes() as well as the linetype. One side effect of adding a linetype to geom_ribbon() is that you then get a line around both edges of the band. On the other hand, fill is not applicable to geom_line so you just get a warning message that the fill aesthetic will be ignored.

The way to address this is to apply a linetype of "blank" to the relevant value in scale_linetype_manual().  Similarly, we use "transparent" in scale_fill_manual() to avoid applying a color to the other elements of the scale.

What I didn't realize before working through this is that it is possible to create a legend for an aesthetic for values across multiple variables. The values just have to be mapped appropriately in the scale. So I truly learned something new putting this together.

```<code>CreateImpactPlot <- function(impact, metrics = c("original",  "cumulative")) {
    # Creates a plot of observed data and counterfactual predictions.
    #
    # Args:
    #   impact:  \code{CausalImpact} results object returned by
    #            \code{CausalImpact()}.
    #   metrics: Which metrics to include in the plot. Can be any combination of
    #            "original", "pointwise", and "cumulative".
    #
    # Returns:
    #   A ggplot2 object that can be plotted using plot().

    # Create data frame of: time, response, mean, lower, upper, metric
    data <- CreateDataFrameForPlot(impact)

    # Select metrics to display (and their order)
    assert_that(is.vector(metrics))
    metrics <- match.arg(metrics, several.ok = TRUE)
    data <- data[data$metric %in% metrics, , drop = FALSE]
    data$metric <- factor(data$metric, metrics)

    # Make data longer
    data_long <- data %>%
        tidyr::pivot_longer(cols = c("baseline", "mean", "response"), names_to = "variable",
                            values_to = "value", values_drop_na = TRUE)

    # Initialize plot
    q1 <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    q1 <- q1 + xlab("") + ylab("")

    q3 <- ggplot(data %>%
                     filter(metric == "cumulative") %>%
                     mutate(metric = factor(metric, levels = c("cumulative"))), aes(x = time)) + theme_bw(base_size = 15)
    q3 <- q3 + xlab("") + ylab("")

    # Add prediction intervals

    q1 <- q1 + geom_ribbon(data = data %>%
                               filter(metric == "original") %>%
                               mutate(metric = factor(metric, levels = c("original"))), aes(x = time, ymin = lower, ymax = upper, fill = metric,
                                                                                linetype = metric))
    q3 <- q3 + geom_ribbon(data = data %>%
                               filter(metric == "cumulative") %>%
                               mutate(metric = factor(metric, levels = c("cumulative"))), aes(x = time, ymin = lower, ymax = upper, fill = metric))

    # Add pre-period markers
    xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                      impact$model$post.period,
                                      time(impact$series))

    q1 <- q1 + geom_vline(xintercept = xintercept,
                          colour = "darkgrey", size = 0.8, linetype = "dashed")

    q3 <- q3 + geom_vline(xintercept = xintercept,
                          colour = "darkgrey", size = 0.8, linetype = "dashed")

    # Add zero line to cumulative plot
    # Add point predictions
    # Add observed data

    q1 <- q1 + geom_line(data = data_long %>% dplyr::filter(metric == "original"),
                         aes(x = time, y = value, linetype = variable, group = variable,
                             size = variable, fill = variable, color = variable),
                         na.rm = TRUE)+
        scale_linetype_manual(name = "Legend", labels = c("mean"= "estimated counterfactual", "response" = "oberserved", "original" = "95% Crl counterfactual"),
                              values = c("dashed", "solid", "blank"), limits = c("mean", "response","original")) +

        scale_fill_manual(name = "Legend", labels = c("mean"= "estimated counterfactual", "response" = "oberserved", "original" = "95% Crl counterfactual"),
                              values = c("transparent", "transparent","slategray2"), limits = c("mean", "response","original")) +  #limits controls the order in the legend

        scale_size_manual(values = c(0.6, 0.8, 0.5)) +
        scale_color_manual(values = c("darkgray", "darkblue")) +
        theme(legend.position = "right", axis.text.x = element_blank(), axis.title.y = element_blank()) +
        guides(size = "none", color = "none")+
        facet_wrap(~metric[1], strip.position = "right", drop = TRUE) #use facet_wrap to generate the stip

    q3 <- q3 + geom_line(data = data_long %>% dplyr::filter(metric == "cumulative"),
                         aes(x = time, y = value, linetype = variable, group = variable,
                              fill = variable),
                         na.rm = TRUE) +
        scale_linetype_manual(name = "Legend", labels = c("mean"= "estimated trend change", "baseline" = "oberserved", "cumulative" = "95% Crl estimation"),
                              values = c("dashed", "solid", "blank"), limits = c("mean", "baseline","cumulative")) +

        scale_fill_manual(name = "Legend", labels = c("mean"= "estimated trend change", "baseline" = "oberserved", "cumulative" = "95% Crl estimation"),
                          values = c("transparent", "transparent","slategray2"), limits = c("mean", "baseline","cumulative")) +  #limits controls the order in the legend

        theme(legend.position = "right", axis.title.y = element_blank())+
        labs(x = "Time") +
        facet_wrap(~metric, strip.position = "right", drop = TRUE) #use facet_wrap to generate the stip

    g1 <- grid::textGrob("Clicks (Millions)", rot = 90, gp=gpar(fontsize = 15), x= 0.85)

    wrap_elements(g1) | (q1/q3)

    patchwork <- wrap_elements(g1) | (q1/q3)

    q <- patchwork

    return(q)
}

# To run the function

plot(impact, c("original", "cumulative")) +
    plot_annotation(title = "Figure. Analysis of click behavior after intervention"
                    , theme = theme(plot.title = element_text(hjust = 0.5))) &
    theme(
        panel.background = element_rect(fill = "transparent"), # panel bg
        plot.background = element_rect(fill = "transparent", color = NA), # plot bg
        panel.grid.major = element_blank(), # get rid of major grid
        panel.grid.minor = element_blank())
</code>```

Body:
I see the other post here about this, but I'm relatively new to R so the answers weren't helpful to me. I'd really appreciate some more in-depth help with how to do this.

I've already made a plot using the commands from the Causal Impact package. In the package documentation, it clearly says that the plots are ggplot2 objects and can be customized the same way as any other object like that. I've successfully done that, adding titles and customizing colors. I need to add a legend (it's required at the journal I'm submitting to). Here is an example of what my graph currently looks like and the code I used to get there.

library(ggplot2)
devtools::install_github("google/CausalImpact")
library(CausalImpact)

## note that I took this example code from the package documentation up until I customize the plot

#create data
set.seed(1)
x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100)
y <- 1.2 * x1 + rnorm(100)
y[71:100] <- y[71:100] + 10
data <- cbind(y, x1)

#causal impact analysis
> pre.period <- c(1, 70)
> post.period <- c(71, 100)
> impact <- CausalImpact(data, pre.period, post.period)

#graph
example<-plot(impact, c("original", "cumulative")) +
    labs(
        x = "Time",
        y = "Clicks (Millions)",
        title = "Figure. Analysis of click behavior after intervention.") +
    theme(plot.title = element_text(hjust = 0.5),
          plot.caption = element_text(hjust = 0),
          panel.background = element_rect(fill = "transparent"), # panel bg
          plot.background = element_rect(fill = "transparent", color = NA), # plot bg
          panel.grid.major = element_blank(), # get rid of major grid
          panel.grid.minor = element_blank())  # get rid of minor grid

In my head, the solution I'd like is to have a legend for each panel of the plot. The first legend (next to the 'original' panel) would show a solid line represents the observed data, the dotted line represents the estimated counterfactual, and the colored band represents the 95% CrI around the estimated counterfactual. The second legend (next to the 'cumulative' panel) would show the dotted line represents the estimated change in trend associated with the intervention and the colored band again represents the 95% CrI around the estimation. Maybe there's a better solution than that, but that's what I've thought of.

Here is a section of the underlying code that runs when you plot:

# Initialize plot
  q <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
  q <- q + xlab("") + ylab("")
  if (length(metrics) > 1) {
    q <- q + facet_grid(metric ~ ., scales = "free_y")
  }

  # Add prediction intervals
  q <- q + geom_ribbon(aes(ymin = lower, ymax = upper),
                       data, fill = "slategray2")

  # Add pre-period markers
  xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                    impact$model$post.period,
                                    time(impact$series))
  q <- q + geom_vline(xintercept = xintercept,
                      colour = "darkgrey", size = 0.8, linetype = "dashed")

  # Add zero line to pointwise and cumulative plot
  q <- q + geom_line(aes(y = baseline),
                     colour = "darkgrey", size = 0.8, linetype = "solid",
                     na.rm = TRUE)

  # Add point predictions
  q <- q + geom_line(aes(y = mean), data,
                     size = 0.6, colour = "darkblue", linetype = "dashed",
                     na.rm = TRUE)

  # Add observed data
  q <- q + geom_line(aes(y = response), size = 0.6,  na.rm = TRUE)
  return(q)
}

One of the answers in that older post here said that I'd have to adapt the pre-existing function to get a legend, and I don't really have the skills yet to see what I'd have to change or add. I thought that legends were supposed to be automatically added according to what's in the aes() bit of the ggplot code, so I'm a little confused why there isn't one in the first place. Can someone help me with this?

Body:
Here is an updated/edited version of an earlier solution in order to merge aesthetics into one legend. The requirement was to merge linetype and fill (ribbon color) into one legend.

In order to merge legends, the same aesthetics have to be used in the geoms and the scales have to account for the different variables, have the same name and the same labels. So geom_ribbon() needs to have a linetype in the aes() as well as fill, and the geom_line() needs to have a fill in the aes() as well as the linetype. One side effect of adding a linetype to geom_ribbon() is that you then get a line around both edges of the band. On the other hand, fill is not applicable to geom_line so you just get a warning message that the fill aesthetic will be ignored.

The way to address this is to apply a linetype of "blank" to the relevant value in scale_linetype_manual().  Similarly, we use "transparent" in scale_fill_manual() to avoid applying a color to the other elements of the scale.

What I didn't realize before working through this is that it is possible to create a legend for an aesthetic for values across multiple variables. The values just have to be mapped appropriately in the scale. So I truly learned something new putting this together.

CreateImpactPlot <- function(impact, metrics = c("original",  "cumulative")) {
    # Creates a plot of observed data and counterfactual predictions.
    #
    # Args:
    #   impact:  \code{CausalImpact} results object returned by
    #            \code{CausalImpact()}.
    #   metrics: Which metrics to include in the plot. Can be any combination of
    #            "original", "pointwise", and "cumulative".
    #
    # Returns:
    #   A ggplot2 object that can be plotted using plot().

    # Create data frame of: time, response, mean, lower, upper, metric
    data <- CreateDataFrameForPlot(impact)

    # Select metrics to display (and their order)
    assert_that(is.vector(metrics))
    metrics <- match.arg(metrics, several.ok = TRUE)
    data <- data[data$metric %in% metrics, , drop = FALSE]
    data$metric <- factor(data$metric, metrics)

    # Make data longer
    data_long <- data %>%
        tidyr::pivot_longer(cols = c("baseline", "mean", "response"), names_to = "variable",
                            values_to = "value", values_drop_na = TRUE)

    # Initialize plot
    q1 <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    q1 <- q1 + xlab("") + ylab("")

    q3 <- ggplot(data %>%
                     filter(metric == "cumulative") %>%
                     mutate(metric = factor(metric, levels = c("cumulative"))), aes(x = time)) + theme_bw(base_size = 15)
    q3 <- q3 + xlab("") + ylab("")

    # Add prediction intervals

    q1 <- q1 + geom_ribbon(data = data %>%
                               filter(metric == "original") %>%
                               mutate(metric = factor(metric, levels = c("original"))), aes(x = time, ymin = lower, ymax = upper, fill = metric,
                                                                                linetype = metric))
    q3 <- q3 + geom_ribbon(data = data %>%
                               filter(metric == "cumulative") %>%
                               mutate(metric = factor(metric, levels = c("cumulative"))), aes(x = time, ymin = lower, ymax = upper, fill = metric))

    # Add pre-period markers
    xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                      impact$model$post.period,
                                      time(impact$series))

    q1 <- q1 + geom_vline(xintercept = xintercept,
                          colour = "darkgrey", size = 0.8, linetype = "dashed")

    q3 <- q3 + geom_vline(xintercept = xintercept,
                          colour = "darkgrey", size = 0.8, linetype = "dashed")

    # Add zero line to cumulative plot
    # Add point predictions
    # Add observed data

    q1 <- q1 + geom_line(data = data_long %>% dplyr::filter(metric == "original"),
                         aes(x = time, y = value, linetype = variable, group = variable,
                             size = variable, fill = variable, color = variable),
                         na.rm = TRUE)+
        scale_linetype_manual(name = "Legend", labels = c("mean"= "estimated counterfactual", "response" = "oberserved", "original" = "95% Crl counterfactual"),
                              values = c("dashed", "solid", "blank"), limits = c("mean", "response","original")) +

        scale_fill_manual(name = "Legend", labels = c("mean"= "estimated counterfactual", "response" = "oberserved", "original" = "95% Crl counterfactual"),
                              values = c("transparent", "transparent","slategray2"), limits = c("mean", "response","original")) +  #limits controls the order in the legend

        scale_size_manual(values = c(0.6, 0.8, 0.5)) +
        scale_color_manual(values = c("darkgray", "darkblue")) +
        theme(legend.position = "right", axis.text.x = element_blank(), axis.title.y = element_blank()) +
        guides(size = "none", color = "none")+
        facet_wrap(~metric[1], strip.position = "right", drop = TRUE) #use facet_wrap to generate the stip

    q3 <- q3 + geom_line(data = data_long %>% dplyr::filter(metric == "cumulative"),
                         aes(x = time, y = value, linetype = variable, group = variable,
                              fill = variable),
                         na.rm = TRUE) +
        scale_linetype_manual(name = "Legend", labels = c("mean"= "estimated trend change", "baseline" = "oberserved", "cumulative" = "95% Crl estimation"),
                              values = c("dashed", "solid", "blank"), limits = c("mean", "baseline","cumulative")) +

        scale_fill_manual(name = "Legend", labels = c("mean"= "estimated trend change", "baseline" = "oberserved", "cumulative" = "95% Crl estimation"),
                          values = c("transparent", "transparent","slategray2"), limits = c("mean", "baseline","cumulative")) +  #limits controls the order in the legend

        theme(legend.position = "right", axis.title.y = element_blank())+
        labs(x = "Time") +
        facet_wrap(~metric, strip.position = "right", drop = TRUE) #use facet_wrap to generate the stip

    g1 <- grid::textGrob("Clicks (Millions)", rot = 90, gp=gpar(fontsize = 15), x= 0.85)

    wrap_elements(g1) | (q1/q3)

    patchwork <- wrap_elements(g1) | (q1/q3)

    q <- patchwork

    return(q)
}

# To run the function

plot(impact, c("original", "cumulative")) +
    plot_annotation(title = "Figure. Analysis of click behavior after intervention"
                    , theme = theme(plot.title = element_text(hjust = 0.5))) &
    theme(
        panel.background = element_rect(fill = "transparent"), # panel bg
        plot.background = element_rect(fill = "transparent", color = NA), # plot bg
        panel.grid.major = element_blank(), # get rid of major grid
        panel.grid.minor = element_blank())


问:
Git remove file from all commits
I made a "little" mistake and added a "little" (>100MB) file to my local repo.

Two commits later I'm trying to push to remote repo in github that have a limit of 100MB.

I can remove the file from my current commit with git rm --cached, but it still in previous commits.

How can I remove the file from all commits?
I've tried this answer about git filter-branch but don't work for my.

答:
Concerning the observation:

I've tried this answer about git filter-branch but don't work for my.

Further details on why the linked answer doesn't work would be useful. Leaving that aside, I've successful used the code below on multiple occasions to achieve the same objective:

```<code>git filter-branch --force --index-filter \
    "git rm --cached --ignore-unmatch <your-file>" \
    --prune-empty --tag-name-filter cat -- --all
</code>```

This command is broadly similar to what is being discussed in the answer that OP linked. For clarity, it is worth adding that this command was discussed in the Removing sensitive data from repository GitHub help article1.

1 It appears that article have moved so I've linked the archive.is page.

Title: Git remove file from all commits

Body:
Concerning the observation:

I've tried this answer about git filter-branch but don't work for my.

Further details on why the linked answer doesn't work would be useful. Leaving that aside, I've successful used the code below on multiple occasions to achieve the same objective:

git filter-branch --force --index-filter \
    "git rm --cached --ignore-unmatch <your-file>" \
    --prune-empty --tag-name-filter cat -- --all

This command is broadly similar to what is being discussed in the answer that OP linked. For clarity, it is worth adding that this command was discussed in the Removing sensitive data from repository GitHub help article1.

1 It appears that article have moved so I've linked the archive.is page.


问:
How to change 1d array to 2d array under certain conditions
Is there a way through python numpy operations to produce the following result?

Input 1d array :

```<code>[3, 0, 0, 2, 2, 1]
</code>```

Output 2d array :

```<code>3 0 0 2 2 1
0 0 0 2 2 1
0 0 0 2 2 1
2 2 2 2 2 1
2 2 2 2 2 1
1 1 1 1 1 1
</code>```

Body:
Is there a way through python numpy operations to produce the following result?

Input 1d array :

[3, 0, 0, 2, 2, 1]

Output 2d array :

3 0 0 2 2 1
0 0 0 2 2 1
0 0 0 2 2 1
2 2 2 2 2 1
2 2 2 2 2 1
1 1 1 1 1 1

Body:
Adir's solution is brilliant and should be accepted.

EDIT: original answer --

It seems that you want to essentially make a matrix by "rotating" a vector like a wiper blade from the top left corner. This produces that pattern:

def wiper_blade_matrix(x):
    n = len(x)
    z = np.zeros((n, n), x.dtype)
    for k in range(-(n - 1), n):
        z[np.where(np.eye(n, k=k))] += x[abs(k):]
    return z

Usage:

In [4]: wiper_blade_matrix(np.array([0, 0, 0, 1, 1, 2]))
Out[4]:
array([[0, 0, 0, 1, 1, 2],
       [0, 0, 0, 1, 1, 2],
       [0, 0, 0, 1, 1, 2],
       [1, 1, 1, 1, 1, 2],
       [1, 1, 1, 1, 1, 2],
       [2, 2, 2, 2, 2, 2]])

In [5]: wiper_blade_matrix(np.array([0, 0, 0, 5, 1, 2]))
Out[5]:
array([[0, 0, 0, 5, 1, 2],
       [0, 0, 0, 5, 1, 2],
       [0, 0, 0, 5, 1, 2],
       [5, 5, 5, 5, 1, 2],
       [1, 1, 1, 1, 1, 2],
       [2, 2, 2, 2, 2, 2]])

In [6]: wiper_blade_matrix(np.array([3, 0, 0, 2, 2, 1]))
Out[6]:
array([[3, 0, 0, 2, 2, 1],
       [0, 0, 0, 2, 2, 1],
       [0, 0, 0, 2, 2, 1],
       [2, 2, 2, 2, 2, 1],
       [2, 2, 2, 2, 2, 1],
       [1, 1, 1, 1, 1, 1]])


问:
mulitpart upload not working with android + rails
i want to upload a file + String to my Rails app via an Android App.  But I'll always get a weird error, when using the multipart upload in rails.

I'm using Apache HttpClient 4.1.1 + httpMime Lib 4.1.1 on Client Side and Rails 3.0.10 on Serverside.

```<code>CountingMultipartEntity mpEntity = new CountingMultipartEntity(this);
File file = new File(getRealPathFromURI(Uri.parse(local_uri)));
ContentBody cbFile = new FileBody(file, "image/jpeg");

mpEntity.addPart("artifact[binary_payload]", cbFile);
mpEntity.addPart("artifact[description]", new StringBody("test", Charset.forName("UTF-8")));

HttpPost post = new HttpPost(url);
post.setEntity(mpEntity);

HttpResponse response = mHttpClient.execute(post);
</code>```

this would be the error line in rails:

```<code>Error during failsafe response: ActionView::Template::Error
  /Users/magu/.rvm/gems/ruby-1.9.2-p136@ssp/gems/activesupport-3.0.10/lib/active_support/whiny_nil.rb:48:in `method_missing'
  /Users/magu/.rvm/gems/ruby-1.9.2-p136@ssp/gems/actionpack-3.0.10/lib/action_dispatch/http/parameters.rb:10:in `parameters'
...
  /Users/magu/.rvm/gems/ruby-1.9.2-p136@ssp/
09:51:55 NoMethodError (undefined method `rewind' for "test":String):
</code>```

I cannout find any solution for this - anyone have a hint?

thanks,
Martin

答:
Create your Multipart entity like this:

```<code>MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
</code>```

And it's going to work.

Body:
i want to upload a file + String to my Rails app via an Android App.  But I'll always get a weird error, when using the multipart upload in rails.

I'm using Apache HttpClient 4.1.1 + httpMime Lib 4.1.1 on Client Side and Rails 3.0.10 on Serverside.

CountingMultipartEntity mpEntity = new CountingMultipartEntity(this);
File file = new File(getRealPathFromURI(Uri.parse(local_uri)));
ContentBody cbFile = new FileBody(file, "image/jpeg");

mpEntity.addPart("artifact[binary_payload]", cbFile);
mpEntity.addPart("artifact[description]", new StringBody("test", Charset.forName("UTF-8")));

HttpPost post = new HttpPost(url);
post.setEntity(mpEntity);

HttpResponse response = mHttpClient.execute(post);

this would be the error line in rails:

Error during failsafe response: ActionView::Template::Error
  /Users/magu/.rvm/gems/ruby-1.9.2-p136@ssp/gems/activesupport-3.0.10/lib/active_support/whiny_nil.rb:48:in `method_missing'
  /Users/magu/.rvm/gems/ruby-1.9.2-p136@ssp/gems/actionpack-3.0.10/lib/action_dispatch/http/parameters.rb:10:in `parameters'
...
  /Users/magu/.rvm/gems/ruby-1.9.2-p136@ssp/
09:51:55 NoMethodError (undefined method `rewind' for "test":String):

I cannout find any solution for this - anyone have a hint?

thanks,
Martin

Body:
Create your Multipart entity like this:

MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );

And it's going to work.


问:
How to apply a function to specific columns of a pandas dataframe?
I would like to apply a function to specific columns of a pandas data frame. Here is an illustration:

```<code># import modules
from pandas_datareader import data as pdr

# import parameters
start = "2020-01-01"
end = "2021-01-01"
symbols = ["AAPL"]

# get the data
data = pdr.get_data_yahoo(symbols, start, end)

def mult(row):
    return row['Close']*2, row['Open']/3

data[['Close', 'Open']].apply(mult, axis = 1)

print(data.head())
</code>```

The result:

```<code>Attributes  Adj Close      Close       High        Low       Open       Volume
Symbols          AAPL       AAPL       AAPL       AAPL       AAPL         AAPL
Date
2020-01-02  73.894333  75.087502  75.150002  73.797501  74.059998  135480400.0
2020-01-03  73.175926  74.357498  75.144997  74.125000  74.287498  146322800.0
2020-01-06  73.759003  74.949997  74.989998  73.187500  73.447502  118387200.0
2020-01-07  73.412109  74.597504  75.224998  74.370003  74.959999  108872000.0
2020-01-08  74.593048  75.797501  76.110001  74.290001  74.290001  132079200.0
</code>```

Any thoughts as to why that doesn't work?

答:
I think the problem is that you are not assigning the return of the mult functions to any variable.

One way to achieve what you want is:

```<code># import modules
from pandas_datareader import data as pdr

# import parameters
start = "2020-01-01"
end = "2021-01-01"
symbols = ["AAPL"]

# get the data
data = pdr.get_data_yahoo(symbols, start, end)

def mult(df):
    df['Close'] = 2 * df['Close']
    df['Open'] = df['Open'] / 3
    return df

mult(data)

print(data.head())

Attributes  Adj Close       Close       High        Low       Open  \
Symbols          AAPL        AAPL       AAPL       AAPL       AAPL
Date
2020-01-02  73.894325  150.175003  75.150002  73.797501  24.686666
2020-01-03  73.175926  148.714996  75.144997  74.125000  24.762499
2020-01-06  73.759010  149.899994  74.989998  73.187500  24.482501
2020-01-07  73.412117  149.195007  75.224998  74.370003  24.986666
2020-01-08  74.593048  151.595001  76.110001  74.290001  24.763334
</code>```

Body:
I would like to apply a function to specific columns of a pandas data frame. Here is an illustration:

# import modules
from pandas_datareader import data as pdr

# import parameters
start = "2020-01-01"
end = "2021-01-01"
symbols = ["AAPL"]

# get the data
data = pdr.get_data_yahoo(symbols, start, end)

def mult(row):
    return row['Close']*2, row['Open']/3

data[['Close', 'Open']].apply(mult, axis = 1)

print(data.head())

The result:

Attributes  Adj Close      Close       High        Low       Open       Volume
Symbols          AAPL       AAPL       AAPL       AAPL       AAPL         AAPL
Date
2020-01-02  73.894333  75.087502  75.150002  73.797501  74.059998  135480400.0
2020-01-03  73.175926  74.357498  75.144997  74.125000  74.287498  146322800.0
2020-01-06  73.759003  74.949997  74.989998  73.187500  73.447502  118387200.0
2020-01-07  73.412109  74.597504  75.224998  74.370003  74.959999  108872000.0
2020-01-08  74.593048  75.797501  76.110001  74.290001  74.290001  132079200.0

Any thoughts as to why that doesn't work?

Body:
I think the problem is that you are not assigning the return of the mult functions to any variable.

One way to achieve what you want is:

# import modules
from pandas_datareader import data as pdr

# import parameters
start = "2020-01-01"
end = "2021-01-01"
symbols = ["AAPL"]

# get the data
data = pdr.get_data_yahoo(symbols, start, end)

def mult(df):
    df['Close'] = 2 * df['Close']
    df['Open'] = df['Open'] / 3
    return df

mult(data)

print(data.head())

Attributes  Adj Close       Close       High        Low       Open  \
Symbols          AAPL        AAPL       AAPL       AAPL       AAPL
Date
2020-01-02  73.894325  150.175003  75.150002  73.797501  24.686666
2020-01-03  73.175926  148.714996  75.144997  74.125000  24.762499
2020-01-06  73.759010  149.899994  74.989998  73.187500  24.482501
2020-01-07  73.412117  149.195007  75.224998  74.370003  24.986666
2020-01-08  74.593048  151.595001  76.110001  74.290001  24.763334


问:
How to get the Window handle (hwnd) by Executable path or name?
Is there a way to get the hwnd-object from a specific window by only providing the executable path or name?

Like GetForegroundWindow() from win32gui but not just the foreground window.

Id imagine something like this: GetWindowByPath("C:/mypath/Spotify.exe") or GetWindowByName("Spotify"). Maybe with ahk? (I have no clue about AHK)

I've now read other questions and docs for hours and havn't found a way.
Thanks in advance :)

答:
There is no direct way, you need to approach it from each end and meet in the middle which is the process id.

If this was native code you could use the Toolhelp functions to enumerate all the processes and look at the filename of each. When you find a match, remember the process id.

Then you can call EnumWindows to find all top-level windows. In the callback you would call GetWindowThreadProcessId on each window until you find one that matches the process id you found earlier.


问:
check if scrollbar is visible with virtual dom
So I was reading the solution here: https://stackoverflow.com/Questions/4814398/how-can-i-check-if-a-scrollbar-is-visible

This is what I am going with...

```<code>function hasScrollbar() {
    console.log(
        "hasScrollbar:",
        document.body.scrollHeight > document.body.clientHeight
    );
    return document.body.scrollHeight > document.body.clientHeight;
}
</code>```
```<code><div
    className="landing-top"
    style={{ paddingRight: hasScrollbar() ? "0px" : `${scrollBarWidth}px` }}
></div>
</code>```

However, because of reacts virtual dom, it doesn't seem to be reading it correctly...

Does anyone have any ideas?

答:
You can try using

const overflows = document.body.scrollHeight > document.body.clientHeight;

Body:
So I was reading the solution here: https://stackoverflow.com/Questions/4814398/how-can-i-check-if-a-scrollbar-is-visible

This is what I am going with...

function hasScrollbar() {
    console.log(
        "hasScrollbar:",
        document.body.scrollHeight > document.body.clientHeight
    );
    return document.body.scrollHeight > document.body.clientHeight;
}

<div
    className="landing-top"
    style={{ paddingRight: hasScrollbar() ? "0px" : `${scrollBarWidth}px` }}
>

However, because of reacts virtual dom, it doesn't seem to be reading it correctly...

Does anyone have any ideas?


问:
Is class.getName() expensive?
In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:

```<code>public class MyClass {
  private static final String CLASS_NAME = MyClass.class.getName();
  //...
}
</code>```

What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName() call directly where the name is needed?

答:
Here is the implementation of Class.getName()

```<code>public String getName() {
if (name == null)
    name = getName0();
return name;
}
</code>```

As you can see the value of name is cached, so the call is not too expensive. It is just as call of regular getter. Anyway if you call it very often it is probably a good style to define constant.

Title: Is class.getName() expensive?

Body:
In many classes of a project I am working on, I see private static final members named CLASS_NAME, which are defined like this:

public class MyClass {
  private static final String CLASS_NAME = MyClass.class.getName();
  //...
}

What are the benefits, if any, of doing this to get the class name, rather than doing the MyClass.class.getName() call directly where the name is needed?

Body:
Here is the implementation of Class.getName()

public String getName() {
if (name == null)
    name = getName0();
return name;
}

As you can see the value of name is cached, so the call is not too expensive. It is just as call of regular getter. Anyway if you call it very often it is probably a good style to define constant.