问:
Authorization Bearer token not being sent in request using Swagger in Asp.Net Core
I am using Swagger to test my APIs in the Asp.Net Core application. I am sending the request using by entering the token like this Authorization: Bearer {token}. but the Authorization header is not being sent in requests.

Asp.Net Core version 3.1 and Swashbuckle.AspNetCore 5.4.1

Startup.cs Code:

```<code>public class Startup
{
    private const string _apiVersion = "v1";
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ClockSkew = TimeSpan.FromMinutes(0),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "MyProject API",
                Description = "MyProject"
            });
            options.DocInclusionPredicate((docName, description) => true);

            // Define the BearerAuth scheme that's in use
            options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey
            });
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseAuthentication();
        loggerFactory.AddLog4Net();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        // Enable middleware to serve generated Swagger as a JSON endpoint
        app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; });

        // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
        app.UseSwaggerUI(options =>
        {
            // specifying the Swagger JSON endpoint.
            options.SwaggerEndpoint($"/swagger/{_apiVersion}/swagger.json", $"MyProject API {_apiVersion}");
            //options.IndexStream = () => Assembly.GetExecutingAssembly()
            //    .GetManifestResourceStream("MyProject.Web.Host.wwwroot.swagger.ui.index.html");
            options.DisplayRequestDuration(); // Controls the display of the request duration (in milliseconds) for "Try it out" requests.
        }); // URL: /swagger
    }
}
</code>```

答:
The culprit

Configuration looks fine. It seems that the auth name you defined is the possible culprit.

```<code>services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "MyProject API",
            Description = "MyProject"
        });
        options.DocInclusionPredicate((docName, description) => true);

        // options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
                             // "bearerAuth" -> "oauth2"
        options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme()
        {
            Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.ApiKey
        });

        // Add this filter as well.
        options.OperationFilter<SecurityRequirementsOperationFilter>();
    });
</code>```

You must use the definition name as "oauth2" unless you manually pass the securitySchemaName into the constructor. As a matter of fact the SecurityRequirementsOperationFilter uses the standard name by default. Just look at the securitySchemaName's default value.

```<code>public SecurityRequirementsOperationFilter(bool includeUnauthorizedAndForbiddenResponses = true, string securitySchemaName = "oauth2")
{
    Func<IEnumerable<AuthorizeAttribute>, IEnumerable<string>> policySelector = (IEnumerable<AuthorizeAttribute> authAttributes) => authAttributes.Where((Func<AuthorizeAttribute, bool>)((AuthorizeAttribute a) => !string.IsNullOrEmpty(a.Policy))).Select((Func<AuthorizeAttribute, string>)((AuthorizeAttribute a) => a.Policy));
    filter = new SecurityRequirementsOperationFilter<AuthorizeAttribute>(policySelector, includeUnauthorizedAndForbiddenResponses, securitySchemaName);
}
</code>```

It works fine in my environment. Please try with this configuration and please don't forget to add the filter option.

Body:
I am using Swagger to test my APIs in the Asp.Net Core application. I am sending the request using by entering the token like this Authorization: Bearer {token}. but the Authorization header is not being sent in requests.

Asp.Net Core version 3.1 and Swashbuckle.AspNetCore 5.4.1

Startup.cs Code:

public class Startup
{
    private const string _apiVersion = "v1";
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ClockSkew = TimeSpan.FromMinutes(0),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "MyProject API",
                Description = "MyProject"
            });
            options.DocInclusionPredicate((docName, description) => true);

            // Define the BearerAuth scheme that's in use
            options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey
            });
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseAuthentication();
        loggerFactory.AddLog4Net();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        // Enable middleware to serve generated Swagger as a JSON endpoint
        app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; });

        // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
        app.UseSwaggerUI(options =>
        {
            // specifying the Swagger JSON endpoint.
            options.SwaggerEndpoint($"/swagger/{_apiVersion}/swagger.json", $"MyProject API {_apiVersion}");
            //options.IndexStream = () => Assembly.GetExecutingAssembly()
            //    .GetManifestResourceStream("MyProject.Web.Host.wwwroot.swagger.ui.index.html");
            options.DisplayRequestDuration(); // Controls the display of the request duration (in milliseconds) for "Try it out" requests.
        }); // URL: /swagger
    }
}

Body:
The culprit

Configuration looks fine. It seems that the auth name you defined is the possible culprit.

services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "MyProject API",
            Description = "MyProject"
        });
        options.DocInclusionPredicate((docName, description) => true);

        // options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
                             // "bearerAuth" -> "oauth2"
        options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme()
        {
            Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.ApiKey
        });

        // Add this filter as well.
        options.OperationFilter<SecurityRequirementsOperationFilter>();
    });

You must use the definition name as "oauth2" unless you manually pass the securitySchemaName into the constructor. As a matter of fact the SecurityRequirementsOperationFilter uses the standard name by default. Just look at the securitySchemaName's default value.

public SecurityRequirementsOperationFilter(bool includeUnauthorizedAndForbiddenResponses = true, string securitySchemaName = "oauth2")
{
    Func<IEnumerable<AuthorizeAttribute>, IEnumerable<string>> policySelector = (IEnumerable<AuthorizeAttribute> authAttributes) => authAttributes.Where((Func<AuthorizeAttribute, bool>)((AuthorizeAttribute a) => !string.IsNullOrEmpty(a.Policy))).Select((Func<AuthorizeAttribute, string>)((AuthorizeAttribute a) => a.Policy));
    filter = new SecurityRequirementsOperationFilter<AuthorizeAttribute>(policySelector, includeUnauthorizedAndForbiddenResponses, securitySchemaName);
}

It works fine in my environment. Please try with this configuration and please don't forget to add the filter option.


来源: stackexchange

问:
Unable to Group and Sum Properly
I have data similar to this Sample Data:

```<code>   Cities Country    Date Cases
1      BE       A 2/12/20    12
2      BD       A 2/12/20   244
3      BF       A 2/12/20     1
4               V 2/12/20    13
5               Q 2/13/20     2
6               D 2/14/20     4
7      GH       N 2/15/20     6
8      DA       N 2/15/20   624
9      AG       J 2/15/20   204
10     FS       U 2/16/20   433
11     FR       U 2/16/20    38
</code>```

I want to organize the data by on the date and country and then sum a country's daily case. However, I try something like, it reveal the total sum:

```<code>my_data %>%
  group_by(Country, Date)%>%
  summarize(Cases=sum(Cases))
</code>```

答:
Your summarize function is likely being called from another package (plyr?). Try calling dplyr::sumarize like this:

```<code>my_data %>%
  group_by(Country, Date)%>%
  dplyr::summarize(Cases=sum(Cases))
# A tibble: 7 x 3
# Groups:   Country [7]
  Country Date    Cases
  <fct>   <fct>   <int>
1 A       2/12/20   257
2 D       2/14/20     4
3 J       2/15/20   204
4 N       2/15/20   630
5 Q       2/13/20     2
6 U       2/16/20   471
7 V       2/12/20    13
</code>```

I sympathize with you that this is can be very frustrating. I have gotten into a habit of always using dplyr::select, dplyr::filter and dplyr::summarize. Otherwise you spend needless time frustrated about why your code isn't working.

ContentLicense: CC BY-SA 4.0

Title: Unable to Group and Sum Properly

Body:
I have data similar to this Sample Data:

   Cities Country    Date Cases
1      BE       A 2/12/20    12
2      BD       A 2/12/20   244
3      BF       A 2/12/20     1
4               V 2/12/20    13
5               Q 2/13/20     2
6               D 2/14/20     4
7      GH       N 2/15/20     6
8      DA       N 2/15/20   624
9      AG       J 2/15/20   204
10     FS       U 2/16/20   433
11     FR       U 2/16/20    38

I want to organize the data by on the date and country and then sum a country's daily case. However, I try something like, it reveal the total sum:

my_data %>%
  group_by(Country, Date)%>%
  summarize(Cases=sum(Cases))

Body:
Your summarize function is likely being called from another package (plyr?). Try calling dplyr::sumarize like this:

my_data %>%
  group_by(Country, Date)%>%
  dplyr::summarize(Cases=sum(Cases))
# A tibble: 7 x 3
# Groups:   Country [7]
  Country Date    Cases
  <fct>   <fct>   <int>
1 A       2/12/20   257
2 D       2/14/20     4
3 J       2/15/20   204
4 N       2/15/20   630
5 Q       2/13/20     2
6 U       2/16/20   471
7 V       2/12/20    13

I sympathize with you that this is can be very frustrating. I have gotten into a habit of always using dplyr::select, dplyr::filter and dplyr::summarize. Otherwise you spend needless time frustrated about why your code isn't working.


问:
DRF SimpleJWT remove password and add date field
I created a custom user model extending from AbstractBaseUser where the only data I'm getting from the user is a userID, user (the username field) and date (required and in the format dd-mm-yyyy) and the creation of the user works fine as you can see from the DB in the next image

Used password = None and last_login = None to refer i didn't want password and last_login tables.

Then, created a view where only authenticated users can access.

To handle the authentication, used simpleJWT. In urls.py

```<code># JWT Token
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain'),
# Get a new token before the old expires.
path('api/token/refresh/', TokenRefreshView.as_view, name='token_refresh'),
</code>```

And by going to http://127.0.0.1:8000/api/token/ , this is what I see (which works as expected)

I've tested previously with User and Password in a different project with user model that included that data (User and Password) and worked fine. Now, here, if I try Posting with an existing user but with no password, I get a warning and not being able to Post

This field may not be blank.

If i add anything other than a blank space, the following error appears

TypeError at /api/token/
  object of type 'NoneType' has no len()

How can I remove the Password field? Also, how could I add a Date field too?

答:
I also faced the same problem and somehow I have manage to solve this problem.

Here is the solution,

Override the TokenObtainPairSerializer class __init__ method like below,

Use del password so It wont ask you the password and add whatever fields you want.

class CustomSerializer(TokenObtainPairSerializer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields[self.username_field] = serializers.CharField()
        del self.fields['password']
        self.fields['last_login'] = serializers.DateField(initial=datetime.date.today)

This works really well.

Here is the reference - How to skip or remove password field in simplejwt token authentication in django rest framework??

Let me know if anyone have better solution of this.

Body:
I created a custom user model extending from AbstractBaseUser where the only data I'm getting from the user is a userID, user (the username field) and date (required and in the format dd-mm-yyyy) and the creation of the user works fine as you can see from the DB in the next image

Used password = None and last_login = None to refer i didn't want password and last_login tables.

Then, created a view where only authenticated users can access.

To handle the authentication, used simpleJWT. In urls.py

# JWT Token
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain'),
# Get a new token before the old expires.
path('api/token/refresh/', TokenRefreshView.as_view, name='token_refresh'),

And by going to http://127.0.0.1:8000/api/token/ , this is what I see (which works as expected)

I've tested previously with User and Password in a different project with user model that included that data (User and Password) and worked fine. Now, here, if I try Posting with an existing user but with no password, I get a warning and not being able to Post

This field may not be blank.

If i add anything other than a blank space, the following error appears

TypeError at /api/token/
  object of type 'NoneType' has no len()

How can I remove the Password field? Also, how could I add a Date field too?


问:
Fastest way to select multiple elements from a list to build a dataframe
I have a list that contains multiple data.frames. I want to select every nth data.frame from the list and combine them into a single data.frame which can be written to a csv.

Here is an example of the list structure:

```<code>one.title <- data.frame(id = '1a', title = 'first title')

one.author <- data.frame(first_name = c('Susan', 'Alice'),
                     last_name  = c('Smith', 'Johnson') )

second.title <- data.frame(id = '2b', title = 'second_title')

second.author <- data.frame(first_name = c('Sarah', 'Mary'),
                        last_name  = c('Davis', 'Proctor') )

one.list <- list()

one.list[[1]]$title <- one.title
one.list[[1]]$author <- one.author
one.list[[2]]$title <- second.title
one.list[[2]]$author <- second.author
</code>```

Here's my current solution that produces a single data frame for the 'authors' fields:

```<code>build_author_table <- function(result.l){

  list_to_df <- function(i){

  x <- result.l[[i]]$author

  return(x)
}

authors_df_l <-(lapply(1:length(result.l), FUN = list_to_df))

authors_df <- do.call("rbind", lapply(authors_df_l, as.data.frame))

return(authors_df)
}
</code>```

This produces the output I want:

```<code>    first_name last_name
1      Susan     Smith
2      Alice   Johnson
3      Sarah     Davis
4       Mary   Proctor
</code>```

But as you can probably imagine, when scaled to thousands of records with much larger text fields in the data.frame, it is painfully slow.

Can anyone suggest a faster, more efficient way to produce the final data.frame?

答:
Try this:

one.title <- data.frame(id = '1a', title = 'first title')

one.author <- data.frame(first_name = c('Susan', 'Alice'),
                         last_name  = c('Smith', 'Johnson') )

second.title <- data.frame(id = '2b', title = 'second_title')

second.author <- data.frame(first_name = c('Sarah', 'Mary'),
                            last_name  = c('Davis', 'Proctor') )

one.list <- list(
  list(title = one.title, author =  one.author),
  list(title = second.title, author =  second.author)
)

authors_df_l = lapply(one.list, function(item) item$author)

do.call("rbind",authors_df_l)
```

Body:
I have a list that contains multiple data.frames. I want to select every nth data.frame from the list and combine them into a single data.frame which can be written to a csv.

Here is an example of the list structure:

one.title <- data.frame(id = '1a', title = 'first title')

one.author <- data.frame(first_name = c('Susan', 'Alice'),
                     last_name  = c('Smith', 'Johnson') )

second.title <- data.frame(id = '2b', title = 'second_title')

second.author <- data.frame(first_name = c('Sarah', 'Mary'),
                        last_name  = c('Davis', 'Proctor') )

one.list <- list()

one.list[[1]]$title <- one.title
one.list[[1]]$author <- one.author
one.list[[2]]$title <- second.title
one.list[[2]]$author <- second.author

Here's my current solution that produces a single data frame for the 'authors' fields:

build_author_table <- function(result.l){

  list_to_df <- function(i){

  x <- result.l[[i]]$author

  return(x)
}

authors_df_l <-(lapply(1:length(result.l), FUN = list_to_df))

authors_df <- do.call("rbind", lapply(authors_df_l, as.data.frame))

return(authors_df)
}

This produces the output I want:

    first_name last_name
1      Susan     Smith
2      Alice   Johnson
3      Sarah     Davis
4       Mary   Proctor

But as you can probably imagine, when scaled to thousands of records with much larger text fields in the data.frame, it is painfully slow.

Can anyone suggest a faster, more efficient way to produce the final data.frame?


问:
Is there a way to get in SQL the column name and its values for the whole table?
I have a table like this:

```<code>col1   col2
-----------
val1   val2
</code>```

and would like to get a string like

```<code>col1 = val1, col2 = val2
</code>```

to insert everything in another environment.

I couldn't find an easy way so far to do this - I manage to get the column names and of course the values but how can I combine both?

```<code>SELECT s.name
FROM sys.columns s
WHERE object_id = OBJECT_ID('myTable')
</code>```

答:
Are you looking for concat()?

```<code>concat('col1 = ', val1, ', col2 = ', val2)
</code>```

Body:
I have a table like this:

col1   col2
-----------
val1   val2

and would like to get a string like

col1 = val1, col2 = val2

to insert everything in another environment.

I couldn't find an easy way so far to do this - I manage to get the column names and of course the values but how can I combine both?

SELECT s.name
FROM sys.columns s
WHERE object_id = OBJECT_ID('myTable')

Body:
Are you looking for concat()?

concat('col1 = ', val1, ', col2 = ', val2)


问:
Elixir - ** (Jason.DecodeError) unexpected end of input at position 0
After successfully polling an API nine times, this error sprang up. What is it attempting to communicate? Why does it come up after so many good polls? What concrete steps should I take to resolve this?

Thanks for addressing these questions! :)

答:
The argument you are passing to Jason.decode is not valid JSON. In this case it's most likely the response body you got back from the API endpoint. It's likely a string of plain text or HTML, such as:

```<code>Internal Server Error
</code>```

You will need to share your code in order for someone to provide a version of the code that can handle all of the responses you are getting from the API.

Body:
The argument you are passing to Jason.decode is not valid JSON. In this case it's most likely the response body you got back from the API endpoint. It's likely a string of plain text or HTML, such as:

Internal Server Error

You will need to share your code in order for someone to provide a version of the code that can handle all of the responses you are getting from the API.


问:
Padding missing on one side of scrollable div
Take a look at my snippet.
The parent div has a scrollbar and a child div.
Why is the padding (5px) missing on the right side?

#moh
{
  background:red;
  overflow-x:auto;
  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="moh">
    <div></div>
</div></code>```

To get the bounty I want to know the reason for the missing padding. Maybe there is a name for this phenomenon. Or may it be a browser bug?

It would be excellent to know the part in the CSS or HTML specification which is responsible for the missing padding. But this is not required to get the bounty (Because I know it's hard to find).

答:
#wrap
    {
      overflow-x:auto;
      width:100px;
    }

#inner
    {
      background:red;
      padding: 15px;
      width: 500px;
    }

#inner div
    {
      width:500px;
      height:100px;
      background:green;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrap">
  <div id="inner">
      <div></div>
  </div>
</div></code>```

one solution would be this:
I had to add some more HTML but hope it solves your problem

Body:
Take a look at my snippet.
The parent div has a scrollbar and a child div.
Why is the padding (5px) missing on the right side?

#moh
{
  background:red;
  overflow-x:auto;
  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}

To get the bounty I want to know the reason for the missing padding. Maybe there is a name for this phenomenon. Or may it be a browser bug?

It would be excellent to know the part in the CSS or HTML specification which is responsible for the missing padding. But this is not required to get the bounty (Because I know it's hard to find).

Body:
#wrap
    {
      overflow-x:auto;
      width:100px;
    }

#inner
    {
      background:red;
      padding: 15px;
      width: 500px;
    }

#inner div
    {
      width:500px;
      height:100px;
      background:green;
    }

<div id="wrap">
  <div id="inner">
      <div></div>
  </div>
</div>

one solution would be this:
I had to add some more HTML but hope it solves your problem


问:
Overload of a nested template function
I was thinking a lot what title to put on my question and failed anyway, so if you find a good one, please edit it.

I am trying to write a print function for a vector or other container<T> and have another print function for container<container<T>>, so here what I came up with:

```<code>template<typename T>
void print(T const& cont){
    for (const auto& i : cont) {
        cout << i << " ";
    }
    cout << endl;
}

template<typename T, template<typename> typename Cont>
void print(Cont<T> const& cont) {
    for (const auto& i : cont) {
        print(i);
    }
}
</code>```

and I have my 2 target containers here:

```<code>vector<vector<int>> subsets;
vector<int> subset;
</code>```

When I invoke print(subset); the program works as expected,  but when i invoke print(subsets), compiler starts complaining:

```<code>error C2679: binary '<<': no operator found which takes a right-hand operand of type 'const std::vector<int,std::allocator<int>>' (or there is no acceptable conversion)
</code>```

My conclusion is that its still trying to call the non-nested template print function and failing on cout as I am trying to cout a vector.

Can anyone explain why the overload resolution is not working as I expect and what I did wrong here? Even when I rename the nested-template function to printn, its started to complain for a different reason:

```<code>error C2784: 'void prints(const Cont<T> &)': could not deduce template argument for 'const Cont<T> &' from 'std::vector<std::vector<int,std::allocator<int>>,std::allocator<std::vector<int,std::allocator<int>>>>'
</code>```

答:
The short, simple and insufficient answer is that std::vector has 2 template parameters.  You should also include some spacing:

```<code>template<class T, class A, template<class, class>class C>
void print(C<T,A> const& cont) {
  std::cout << "[ ";
  bool bFirst = true;
  for (const auto& i : cont) {
    if (!bFirst)
      std::cout << ", ";
    bFirst = false;
    print(i);
  }
  std::cout << " ]";
}
</code>```

So that overload was never called.

Once you do this, your code doesn't work, because you don't have an element-printer.  So replace your other loop-printer with an element-printer:

```<code>template<typename T>
void print(T const& i){
  std::cout << i;
}
</code>```

Live example.

Test code:

```<code>std::vector<int> a={1,2,3};
print(a);
std::cout << "\n";
std::vector<std::vector<int>> b = {a, a, a};
print(b);
std::cout << "\n";
</code>```

Output:

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

this is insufficient, because you really should do something fancier to detect "is this object iterable" and "is this object tuple-like" if you want a more serious general purpose printer.  Detecting Cont templates is a poor substitute.

Here is code to detect if something is iterable (ignore the bad checked answer, read the one I linked to).

Then do a SFINAE test for "is the argument iterable" in print for the one that does a for(:) loop.

The next thing you'll want to do is detect if the object is tuple-like.  If it is, you want to print out each element of the tuple.  This give you std::map and std::unordered_map support.  Note that a std::array is both tuple-like and iterable.

This is a bit harder than detecting "iterable", and varies more with which C++ standard you are working with, because tuple-like-ness is expanding with new versions of C++.  You can be lazy and just detect std::pair and std::tuple, which will cover 99% of use cases.

Title: Overload of a nested template function

Body:
I was thinking a lot what title to put on my question and failed anyway, so if you find a good one, please edit it.

I am trying to write a print function for a vector or other container<T> and have another print function for container<container<T>>, so here what I came up with:

template<typename T>
void print(T const& cont){
    for (const auto& i : cont) {
        cout << i << " ";
    }
    cout << endl;
}

template<typename T, template<typename> typename Cont>
void print(Cont<T> const& cont) {
    for (const auto& i : cont) {
        print(i);
    }
}

and I have my 2 target containers here:

vector<vector<int>> subsets;
vector<int> subset;

When I invoke print(subset); the program works as expected,  but when i invoke print(subsets), compiler starts complaining:

error C2679: binary '<<': no operator found which takes a right-hand operand of type 'const std::vector<int,std::allocator<int>>' (or there is no acceptable conversion)

My conclusion is that its still trying to call the non-nested template print function and failing on cout as I am trying to cout a vector.

Can anyone explain why the overload resolution is not working as I expect and what I did wrong here? Even when I rename the nested-template function to printn, its started to complain for a different reason:

error C2784: 'void prints(const Cont<T> &)': could not deduce template argument for 'const Cont<T> &' from 'std::vector<std::vector<int,std::allocator<int>>,std::allocator<std::vector<int,std::allocator<int>>>>'

Body:
The short, simple and insufficient answer is that std::vector has 2 template parameters.  You should also include some spacing:

template<class T, class A, template<class, class>class C>
void print(C<T,A> const& cont) {
  std::cout << "[ ";
  bool bFirst = true;
  for (const auto& i : cont) {
    if (!bFirst)
      std::cout << ", ";
    bFirst = false;
    print(i);
  }
  std::cout << " ]";
}

So that overload was never called.

Once you do this, your code doesn't work, because you don't have an element-printer.  So replace your other loop-printer with an element-printer:

template<typename T>
void print(T const& i){
  std::cout << i;
}

Live example.

Test code:

std::vector<int> a={1,2,3};
print(a);
std::cout << "\n";
std::vector<std::vector<int>> b = {a, a, a};
print(b);
std::cout << "\n";

Output:

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

this is insufficient, because you really should do something fancier to detect "is this object iterable" and "is this object tuple-like" if you want a more serious general purpose printer.  Detecting Cont<A,B> templates is a poor substitute.

Here is code to detect if something is iterable (ignore the bad checked answer, read the one I linked to).

Then do a SFINAE test for "is the argument iterable" in print for the one that does a for(:) loop.

The next thing you'll want to do is detect if the object is tuple-like.  If it is, you want to print out each element of the tuple.  This give you std::map and std::unordered_map support.  Note that a std::array is both tuple-like and iterable.

This is a bit harder than detecting "iterable", and varies more with which C++ standard you are working with, because tuple-like-ness is expanding with new versions of C++.  You can be lazy and just detect std::pair and std::tuple, which will cover 99% of use cases.


问:
MongoDB MapReduce : use positional operator $ in map function
I have a collection with entries that look like that :

{"userid": 1, "contents": [ { "tag": "whatever", "value": 100 },  {"tag": "whatever2", "value": 110 } ] }

I'm performing a MapReduce on this collection with queries such as {"contents.tag": "whatever"}.

What I'd like to do in my map function is emiting the field "value" corresponding to the entry in the array "contents" that matched the query without having to iterate through the whole array. Under normal circumstances, I could do that using the $ positional operator with something like contents.$.value. But in the MapReduce case, it's not working.

To summarize, here is the code I have right now :`

```<code>map=function(){
        emit(this.userid, WHAT DO I WRITE HERE TO EMIT THE VALUE I WANT ?);
    }
    reduce=function(key,values){
        return values[0]; //this reduce function does not make sense, just for the example
    }
    res=db.runCommand(
    {
        "mapreduce": "collection",
        "query": {'contents.tag':'whatever'},
        "map": map,
        "reduce": reduce,
        "out": "test_mr"
    }
    );`
</code>```

Any idea ?

Thanks !

答:
This will not work without iterating over the whole array. In MongoDB a query is intended to match an entire document.

When dealing with Map / Reduce, the query is simply trimming the number of documents that are passed into the map function. However, the map function has no knowledge of the query that was run. The two are disconnected.

The source code around the M/R is here.

There is an upcoming aggregation feature that will more closely match this desire. But there's no timeline on this feature.

ContentLicense: CC BY-SA 3.0

Body:
I have a collection with entries that look like that :

{"userid": 1, "contents": [ { "tag": "whatever", "value": 100 },  {"tag": "whatever2", "value": 110 } ] }

I'm performing a MapReduce on this collection with queries such as {"contents.tag": "whatever"}.

What I'd like to do in my map function is emiting the field "value" corresponding to the entry in the array "contents" that matched the query without having to iterate through the whole array. Under normal circumstances, I could do that using the $ positional operator with something like contents.$.value. But in the MapReduce case, it's not working.

To summarize, here is the code I have right now :`

map=function(){
        emit(this.userid, WHAT DO I WRITE HERE TO EMIT THE VALUE I WANT ?);
    }
    reduce=function(key,values){
        return values[0]; //this reduce function does not make sense, just for the example
    }
    res=db.runCommand(
    {
        "mapreduce": "collection",
        "query": {'contents.tag':'whatever'},
        "map": map,
        "reduce": reduce,
        "out": "test_mr"
    }
    );`

Any idea ?

Thanks !


问:
Hold 2 selected item
I would like to add on my website a kind of selector with button like the picture.
I already succeed with one button with the following code.
But I want to keep the first selection hold and select a second button. Sorry for my english I don't know if you understand me, I found this website which is actually doing exactly what I want.

Thank you in advance if you can help me.enter image description here

```<code>$(function($){

  var $go = 'test1';
  var $notgo = 'test2';

  $('.romain-test-btn').each( function(){

  $(this).click( function(){

    $('.romain-test-retour').fadeIn();

    if (($(this).attr('id') == 1 ) || ($(this).attr('id') == 3 )){

     $('.romain-test-retour').html( $go );

        }else{

           $('.romain-test-retour').html( $notgo );

        }

    $('.romain-test-btn').fadeOut();

  });

  });

 });
</code>```

答:
I couldn't understand exactly what you meant. But I think the problem is your query select $('.romain-test-retour').
When you select by class name, all the elemets that has this class selected and function html apply on all that elements. You need to change your query select by id for example.

.selected {
  color: red;
}
```

<pre class="lang-html prettyprint-override"><code><button class="mybtn" id="btn1">btn1</button>
<button class="mybtn" id="btn2">btn2</button>
<button class="mybtn" id="btn3">btn3</button>
<button class="mybtn" id="btn4">btn4</button>
</code>```

```<code>$(function($){

  $('.mybtn').click( function(){
    if($(this).hasClass('selected') || $('.selected').length <= 1)
      $(this).toggleClass('selected');
  });

 });
</code>```

Title: Hold 2 selected item

Body:
I would like to add on my website a kind of selector with button like the picture.
I already succeed with one button with the following code.
But I want to keep the first selection hold and select a second button. Sorry for my english I don't know if you understand me, I found this website which is actually doing exactly what I want.

Thank you in advance if you can help me.enter image description here

$(function($){

  var $go = 'test1';
  var $notgo = 'test2';

  $('.romain-test-btn').each( function(){

  $(this).click( function(){

    $('.romain-test-retour').fadeIn();

    if (($(this).attr('id') == 1 ) || ($(this).attr('id') == 3 )){

     $('.romain-test-retour').html( $go );

        }else{

           $('.romain-test-retour').html( $notgo );

        }

    $('.romain-test-btn').fadeOut();

  });

  });

 });

Body:
I couldn't understand exactly what you meant. But I think the problem is your query select $('.romain-test-retour').
When you select by class name, all the elemets that has this class selected and function html apply on all that elements. You need to change your query select by id for example.

.selected {
  color: red;
}

<button class="mybtn" id="btn1">btn1</button>
<button class="mybtn" id="btn2">btn2</button>
<button class="mybtn" id="btn3">btn3</button>
<button class="mybtn" id="btn4">btn4</button>

$(function($){

  $('.mybtn').click( function(){
    if($(this).hasClass('selected') || $('.selected').length <= 1)
      $(this).toggleClass('selected');
  });

 });


问:
Filtering pivot table in Sisense with negation
I'm trying to implement a simple filter in Sisense, but I can't figure it out.

My data is stored in a PostgresQL DB. A minimal example looks something like this:

```<code>CREATE TABLE fact_table (
    first_name text,
    salary integer
);

INSERT INTO fact_table VALUES ('John', 100), ('Jack', 200), ('Mary', 300), ('Klaus', 400);

CREATE TABLE dim_table (
    first_name text,
    last_name text
);

INSERT INTO dim_table VALUES ('John', 'Smith'), ('Jack', 'Smith'), ('John', 'Jackson'), ('Mary', 'Smith'), ('Klaus', 'Jackson');
</code>```

I want to create a pivot table with the first_name in the rows and salary as values in Sisense.

Now there are two scenarios I want to filter for:

1) Select all first_names, for which someone with the last name 'Smith' exists

=> easy in Sisense, just create a relationship on first_name <-> first_name and filter on 'Smith'

Our result set is {Jack, John, Mary} and their respective salary.

2) Select all first_names, which are not shared by someone with the last name 'Smith'. This is the negation of 1).
Our expected result set {Klaus}.

I don't know how to do this. It's trivial in SQL:
SELECT * FROM fact_table WHERE first_name NOT IN (SELECT first_name FROM dim_table WHERE last_name = 'Smith');

I haven't found any suitable option in Sisense. If I create a list filter and deselect Smith, I get all non-Smiths from my dim_table, which is not the same logically (and returns John instead of Klaus).

I must be missing something obvious. Any ideas?

Thanks a lot!

答: I think both your 1st and 2nd scenario of filter can be achieved by the custom SQL in the elasticube. You need to do a left join on both tables and get every row from fact. In your filter of first_name then you can deselect first_name as "Smith" but select NULL values to show "Klaus"

Body:
I'm trying to implement a simple filter in Sisense, but I can't figure it out.

My data is stored in a PostgresQL DB. A minimal example looks something like this:

CREATE TABLE fact_table (
    first_name text,
    salary integer
);

INSERT INTO fact_table VALUES ('John', 100), ('Jack', 200), ('Mary', 300), ('Klaus', 400);

CREATE TABLE dim_table (
    first_name text,
    last_name text
);

INSERT INTO dim_table VALUES ('John', 'Smith'), ('Jack', 'Smith'), ('John', 'Jackson'), ('Mary', 'Smith'), ('Klaus', 'Jackson');

I want to create a pivot table with the first_name in the rows and salary as values in Sisense.

Now there are two scenarios I want to filter for:

1) Select all first_names, for which someone with the last name 'Smith' exists

=> easy in Sisense, just create a relationship on first_name <-> first_name and filter on 'Smith'

Our result set is {Jack, John, Mary} and their respective salary.

2) Select all first_names, which are not shared by someone with the last name 'Smith'. This is the negation of 1).
Our expected result set {Klaus}.

I don't know how to do this. It's trivial in SQL:
SELECT * FROM fact_table WHERE first_name NOT IN (SELECT first_name FROM dim_table WHERE last_name = 'Smith');

I haven't found any suitable option in Sisense. If I create a list filter and deselect Smith, I get all non-Smiths from my dim_table, which is not the same logically (and returns John instead of Klaus).

I must be missing something obvious. Any ideas?

Thanks a lot!


问:
How to deal with a merge conflict caused by files moved in the target branch
I am very new to git, but I have some changes that I would like to make and there are some merge conflicts. These conflicts come from some files that have been moved in the target branch. How do I deal with these conflicts? The files have only been moved, so the changes that I made still hold, it just tells me that the file was deleted in the target branch. Should I make a new branch off of the updated target branch, and make the changes again?</p>

答:
Before creating the pull request,

Merge back the latest develop branch to your feature branch.

Then you will see the merge conflicts while merging this. So solve the merge conflicts locally (Better keep the develop's changes and then add your change in the files. Or if you think there is no other change in the develop other than the move, then keep yours and move the files after that. Use your judgement on fixing conflicts).

Then create the pull request against the develop.

You cannot always avoid the conflicts. But by merging the develop to your feature branch frequently, you can make your life easiler.


问:
How to get the text inside a h2 tag in selenium python
how to get the text inside the html tag and assert if it is present on the page.

html-

```<code><h2>  You are suggested the Low Fat Vegan Diet </h2>
</code>```

i tried-

```<code>message = driver.find_elements_by_tag_name('h2').Text()
</code>```

AttributeError: 'list' object has no attribute 'Text'

```<code> message = driver.find_elements_by_tag_name('h2').getText()
</code>```

AttributeError: 'list' object has no attribute 'getText'

how do i get the text and assert it is present in the page?

答:
It's hard to tell without the full HTML, but if you have multiple h2 elements you will need to iterate through them to get the text.

```<code>message = driver.find_elements_by_tag_name('h2')
for i in message:
    print(i.text)
</code>```

Otherwise, you should be able to select the text with .text

```<code>message = driver.find_elements_by_tag_name('h2').text
</code>```

Body:
how to get the text inside the html tag and assert if it is present on the page.

html-

  You are suggested the Low Fat Vegan Diet

i tried-

message = driver.find_elements_by_tag_name('h2').Text()

AttributeError: 'list' object has no attribute 'Text'

 message = driver.find_elements_by_tag_name('h2').getText()

AttributeError: 'list' object has no attribute 'getText'

how do i get the text and assert it is present in the page?

Body:
It's hard to tell without the full HTML, but if you have multiple h2 elements you will need to iterate through them to get the text.

message = driver.find_elements_by_tag_name('h2')
for i in message:
    print(i.text)

Otherwise, you should be able to select the text with .text

message = driver.find_elements_by_tag_name('h2').text


问:
Why doesn't "case" with "when > 2" work?
Why is this not working?</p>

```<code>case ARGV.length
  when 0
    abort "Error 1"
  when > 2
    abort "Error 2"
end
</code>```

答:
It's not valid ruby syntax.

What you need is

```<code>case
  when ARGV.length == 0
    abort "Error 1"
  when ARGV.length > 2
    abort "Error 2"
end
</code>```

When you write case x, the important part you need to understand is that ruby takes the x and then applies a comparison to the argument or expressions you insert in the when clause.

The line where you say when x >2 reads to ruby like:

```<code>if ARGV.length == > 2
</code>```

When you remove a specific object from the case statements, you can apply conditionals within the when statements .

Body:
Why is this not working?

case ARGV.length
  when 0
    abort "Error 1"
  when > 2
    abort "Error 2"
end

Body:
It's not valid ruby syntax.

What you need is

case
  when ARGV.length == 0
    abort "Error 1"
  when ARGV.length > 2
    abort "Error 2"
end

When you write case x, the important part you need to understand is that ruby takes the x and then applies a comparison to the argument or expressions you insert in the when clause.

The line where you say when x >2 reads to ruby like:

if ARGV.length == > 2

When you remove a specific object from the case statements, you can apply conditionals within the when statements .


问:
Identifying rowspan and colspan: html table using beautiful soup
I am having an issue with the beautiful soup module and re module. I am trying to write a python script that automatically converts HTML code into latex code. To draw tables, I have to first read various table attributes in HTML code such as rowspan and colspan.
Here is my table in HTML code:

```<code><html>
<body>
   <table border = "1">
       <tr>
           <td>Name</td>
           <td colspan="2">Alice</td>
       </tr>
       <tr>
           <td>Type</td>
           <td colspan="2">Client</td>
       </tr>
       <tr>
           <td rowspan="3">Parameters</td>
           <td>Param1</td>
           <td>Value</td>
       </tr>
       <tr>
           <td>Param2</td>
           <td>Value</td>
       </tr>
       <tr>
           <td>Param3</td>
           <td>Value</td>
       </tr>
</html>
</code>```

First I have to locate where colspan and rowspan appear. I wrote the following script to do that:

```<code>import re

from bs4 import BeautifulSoup

with open('table.html')as file:
    soup = BeautifulSoup(file, 'lxml')

for table in soup.find_all("tr"):
    for item in table.find_all('td'):
        row = re.findall(r'rowspan="[0-255]"', str(item))
        col = re.findall(r'colspan="[0-255]"', str(item))
        print(row)
        print(col)

</code>```

Output is:

```<code>[]
[]
[]
['colspan="2"']
[]
[]
[]
['colspan="2"']
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[Finished in 1.622s]
</code>```

I am fine with colspan. But not ok with rowspan. In 13th line of my HTML code, I have rowspan.  Why it is not in my output? Please help.

答:
The issue here is with the regex.

```<code>rowspan="[0-255]"
</code>```

Here 0-2 a single character in the range between 0 and 2 and 55 matches a single character in the list 5 (case sensitive). So this regex can only match

rowspan="0"

rowspan="1"

rowspan="2"

rowspan="5"

You can also use the HTMLParser module to parse the tag attributes.(It's part of standard library)

```<code>>>> from html.parser import HTMLParser
>>>
>>> class MyParser(HTMLParser):
...     def __init__(self, *args, **kwargs):
...         self.results = []
...         super(MyParser, self).__init__(*args, **kwargs)
...     def handle_starttag(self, tag, attrs):
...         if tag == "td":
...             for attr, value in attrs:
...                 if ("colspan" == attr) or ("rowspan" == attr):
...                     self.results.append("{}=\"{}\"".format(attr, value))
...
>>> parser = MyParser()
>>>
>>> parser.feed(
...     """
... <html>
... <body>
...    <table border = "1">
...        <tr>
...            <td>Name</td>
...            <td colspan="2">Alice</td>
...        </tr>
...        <tr>
...            <td>Type</td>
...            <td colspan="2">Client</td>
...        </tr>
...        <tr>
...            <td rowspan="3">Parameters</td>
...            <td>Param1</td>
...            <td>Value</td>
...        </tr>
...        <tr>
...            <td>Param2</td>
...            <td>Value</td>
...        </tr>
...        <tr>
...            <td>Param3</td>
...            <td>Value</td>
...        </tr>
... </html>
... """
... )
>>>
>>> print(parser.results)
['colspan="2"', 'colspan="2"', 'rowspan="3"']
</code>```

Body:
I am having an issue with the beautiful soup module and re module. I am trying to write a python script that automatically converts HTML code into latex code. To draw tables, I have to first read various table attributes in HTML code such as rowspan and colspan.
Here is my table in HTML code:

           Name
           Alice

           Type
           Client

           Parameters
           Param1
           Value

           Param2
           Value

           Param3
           Value

First I have to locate where colspan and rowspan appear. I wrote the following script to do that:

import re

from bs4 import BeautifulSoup

with open('table.html')as file:
    soup = BeautifulSoup(file, 'lxml')

for table in soup.find_all("tr"):
    for item in table.find_all('td'):
        row = re.findall(r'rowspan="[0-255]"', str(item))
        col = re.findall(r'colspan="[0-255]"', str(item))
        print(row)
        print(col)

Output is:

[]
[]
[]
['colspan="2"']
[]
[]
[]
['colspan="2"']
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[Finished in 1.622s]

I am fine with colspan. But not ok with rowspan. In 13th line of my HTML code, I have rowspan.  Why it is not in my output? Please help.

Body:
The issue here is with the regex.

rowspan="[0-255]"

Here 0-2 a single character in the range between 0 and 2 and 55 matches a single character in the list 5 (case sensitive). So this regex can only match

rowspan="0"

rowspan="1"

rowspan="2"

rowspan="5"

You can also use the HTMLParser module to parse the tag attributes.(It's part of standard library)

>>> from html.parser import HTMLParser
>>>
>>> class MyParser(HTMLParser):
...     def __init__(self, *args, **kwargs):
...         self.results = []
...         super(MyParser, self).__init__(*args, **kwargs)
...     def handle_starttag(self, tag, attrs):
...         if tag == "td":
...             for attr, value in attrs:
...                 if ("colspan" == attr) or ("rowspan" == attr):
...                     self.results.append("{}=\"{}\"".format(attr, value))
...
>>> parser = MyParser()
>>>
>>> parser.feed(
...     """
... <html>
... <body>
...    <table border = "1">
...        <tr>
...            <td>Name</td>
...            <td colspan="2">Alice</td>
...        </tr>
...        <tr>
...            <td>Type</td>
...            <td colspan="2">Client</td>
...        </tr>
...        <tr>
...            <td rowspan="3">Parameters</td>
...            <td>Param1</td>
...            <td>Value</td>
...        </tr>
...        <tr>
...            <td>Param2</td>
...            <td>Value</td>
...        </tr>
...        <tr>
...            <td>Param3</td>
...            <td>Value</td>
...        </tr>
... </html>
... """
... )
>>>
>>> print(parser.results)
['colspan="2"', 'colspan="2"', 'rowspan="3"']


问:
Replace \r from json in shell
I have below JSON in a variable name TASK_DEFINTIION
It has a \r character at the end of "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r" under containerDefinitions

I am using TASK_DEFINITION_AFTER= 'echo $TASK_DEFINTIION | sed "s/\\r//g"' to remove the \r but seems it is removing all the hidden carriage return but not removing the one which is visible as regular character.

Any help would be highly appriciated.

```<code>{
      "memory": "1024",
      "networkMode": "awsvpc",
      "family": "ecs-php-demo",
      "placementConstraints": [],
      "cpu": "512",
      "executionRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "volumes": [],
      "requiresCompatibilities": [
        "FARGATE"
      ],
      "taskRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "containerDefinitions": [
        {
          "memoryReservation": 256,
          "environment": [],
          "name": "ecs-php-demo",
          "mountPoints": [],
          "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r",
          "cpu": 0,
          "portMappings": [
            {
              "protocol": "tcp",
              "containerPort": 8080,
              "hostPort": 8080
            }
          ],
          "logConfiguration": {
            "logDriver": "awslogs",
            "options": {
              "awslogs-region": "us-east-1",
              "awslogs-stream-prefix": "ecs",
              "awslogs-group": "/ecs/ecs-php-demo"
            }
          },
          "essential": true,
          "volumesFrom": []
        }
      ]
    }
</code>```

答:
you can use jq to replace key value:

```<code>jq '.containerDefinitions[].image="700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01"' file.json
</code>```

but unfortunately, jq does not support in-place editing, so you must redirect to a temporary file first and then replace your original file with it, or use sponge utility from the more utils package, like that:

```<code>jq '.containerDefinitions[].image="700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01"' file.json|sponge file.json
</code>```

A pure jq solution to remove \r with gsub :

```<code>jq '.containerDefinitions[].image|=gsub("[\r]"; "")' file.json|sponge file.json
</code>```

output sample :

```<code>{
  "memory": "1024",
  "networkMode": "awsvpc",
  "family": "ecs-php-demo",
  "placementConstraints": [],
  "cpu": "512",
  "executionRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
  "volumes": [],
  "requiresCompatibilities": [
    "FARGATE"
  ],
  "taskRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
  "containerDefinitions": [
    {
      "memoryReservation": 256,
      "environment": [],
      "name": "ecs-php-demo",
      "mountPoints": [],
      "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01",
      "cpu": 0,
      "portMappings": [
        {
          "protocol": "tcp",
          "containerPort": 8080,
          "hostPort": 8080
        }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-region": "us-east-1",
          "awslogs-stream-prefix": "ecs",
          "awslogs-group": "/ecs/ecs-php-demo"
        }
      },
      "essential": true,
      "volumesFrom": []
    }
  ]
}
</code>```

Title: Replace \r from json in shell

Body:
I have below JSON in a variable name TASK_DEFINTIION
It has a \r character at the end of "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r" under containerDefinitions

I am using TASK_DEFINITION_AFTER= 'echo $TASK_DEFINTIION | sed "s/\\r//g"' to remove the \r but seems it is removing all the hidden carriage return but not removing the one which is visible as regular character.

Any help would be highly appriciated.

{
      "memory": "1024",
      "networkMode": "awsvpc",
      "family": "ecs-php-demo",
      "placementConstraints": [],
      "cpu": "512",
      "executionRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "volumes": [],
      "requiresCompatibilities": [
        "FARGATE"
      ],
      "taskRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
      "containerDefinitions": [
        {
          "memoryReservation": 256,
          "environment": [],
          "name": "ecs-php-demo",
          "mountPoints": [],
          "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01\r",
          "cpu": 0,
          "portMappings": [
            {
              "protocol": "tcp",
              "containerPort": 8080,
              "hostPort": 8080
            }
          ],
          "logConfiguration": {
            "logDriver": "awslogs",
            "options": {
              "awslogs-region": "us-east-1",
              "awslogs-stream-prefix": "ecs",
              "awslogs-group": "/ecs/ecs-php-demo"
            }
          },
          "essential": true,
          "volumesFrom": []
        }
      ]
    }

Body:
you can use jq to replace key value:

jq '.containerDefinitions[].image="700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01"' file.json

but unfortunately, jq does not support in-place editing, so you must redirect to a temporary file first and then replace your original file with it, or use sponge utility from the more utils package, like that:

jq '.containerDefinitions[].image="700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01"' file.json|sponge file.json

A pure jq solution to remove \r with gsub :

jq '.containerDefinitions[].image|=gsub("[\r]"; "")' file.json|sponge file.json

output sample :

{
  "memory": "1024",
  "networkMode": "awsvpc",
  "family": "ecs-php-demo",
  "placementConstraints": [],
  "cpu": "512",
  "executionRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
  "volumes": [],
  "requiresCompatibilities": [
    "FARGATE"
  ],
  "taskRoleArn": "arn:aws:iam::700707367057:role/ecsTaskExecutionRole",
  "containerDefinitions": [
    {
      "memoryReservation": 256,
      "environment": [],
      "name": "ecs-php-demo",
      "mountPoints": [],
      "image": "700707367057.dkr.ecr.us-east-1.amazonaws.com/php-demo:feature-feature01",
      "cpu": 0,
      "portMappings": [
        {
          "protocol": "tcp",
          "containerPort": 8080,
          "hostPort": 8080
        }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-region": "us-east-1",
          "awslogs-stream-prefix": "ecs",
          "awslogs-group": "/ecs/ecs-php-demo"
        }
      },
      "essential": true,
      "volumesFrom": []
    }
  ]
}


问:
finding json diff fails using JSONAssert
I was hoping to use Jackson to find JSON diff but it does not give detailed error messages.

So I tried using JSOnAssert to find the diff between two JSON strings.

```<code>JSONAssert.assertEquals(expectedJsonResponse, actualJsonResponse, false);
</code>```

Sadly, it does not appear to match correctly and give the detailed error messages as in the examples. If you have used it, Can you please clarify?

```<code>java.lang.AssertionError: data[0] Could not find match for element {"errors":[{"httpStatus":"BAD_REQUEST","personId":null,"details":"User ID [UNKNOWN]. Invalid ID: NONSENSE"}],"successfulIds":["A0","B1","C3"]}
at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:222)
</code>```

Actual JSON:

```<code>{"_links":{"self":{"href":"https://myserver.com:1000/api/person/upload? myCsvFile={myCsvFile}","templated":true}},"data":[{"successfulIds":["A0","XYZ","C3"],"errors":[{"personId":null,"httpStatus":"BAD_REQUEST","details":"User ID [UNKNOWN]. Invalid ID: NONSENSE"}]}]}
</code>```

Expected JSON:

```<code>{
    "_links": {
        "self": {
            "href": "https://myserver.com:1000/api/person/upload?myCsvFile={myCsvFile}",
            "templated": true
        }
    },
    "data": [
        {
            "successfulIds": [
                "A0",
                "B1",
                "C3"
            ],
            "errors": [
                {
                    "personId": null,
                    "httpStatus": "BAD_REQUEST",
                    "details": "User ID [UNKNOWN]. Invalid ID: NONSENSE"
                }
            ]
        }
    ]
}
</code>```

答:
I tried to email the address at http://jsonassert.skyscreamer.org/ but got a

The following message to jsonassert-dev@skyscreamer.org was
  undeliverable. The reason for the problem:
  5.1.0 - Unknown address error 550-"5.1.1 The email account that you tried to reach does not exist

So I tried ZJsonPatch. I like the fact that using Jackson with it, the ordering of the members does not matter. In other words, I first try to check for equality using Jackson. Jackson is ordering independent. Then if it fails, I use ZJsonPatch to tell me what the diff is.

```<code>{"op":"replace","path":"/data/0/successfulIds/1","value":"B9"}
</code>```

which handles nested JSON well.

```<code>ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(expectedJsonResponse);
JsonNode actual = mapper.readTree(actualJsonResponse);

try {
    assertEquals(expected, actual);
} catch (AssertionError ae) {
    JsonNode patch = JsonDiff.asJson(actual, expected);
    throw new Exception(patch.toString(), ae);
}
</code>```

Body:
I was hoping to use Jackson to find JSON diff but it does not give detailed error messages.

So I tried using JSOnAssert to find the diff between two JSON strings.

JSONAssert.assertEquals(expectedJsonResponse, actualJsonResponse, false);

Sadly, it does not appear to match correctly and give the detailed error messages as in the examples. If you have used it, Can you please clarify?

java.lang.AssertionError: data[0] Could not find match for element {"errors":[{"httpStatus":"BAD_REQUEST","personId":null,"details":"User ID [UNKNOWN]. Invalid ID: NONSENSE"}],"successfulIds":["A0","B1","C3"]}
at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:222)

Actual JSON:

{"_links":{"self":{"href":"https://myserver.com:1000/api/person/upload? myCsvFile={myCsvFile}","templated":true}},"data":[{"successfulIds":["A0","XYZ","C3"],"errors":[{"personId":null,"httpStatus":"BAD_REQUEST","details":"User ID [UNKNOWN]. Invalid ID: NONSENSE"}]}]}

Expected JSON:

{
    "_links": {
        "self": {
            "href": "https://myserver.com:1000/api/person/upload?myCsvFile={myCsvFile}",
            "templated": true
        }
    },
    "data": [
        {
            "successfulIds": [
                "A0",
                "B1",
                "C3"
            ],
            "errors": [
                {
                    "personId": null,
                    "httpStatus": "BAD_REQUEST",
                    "details": "User ID [UNKNOWN]. Invalid ID: NONSENSE"
                }
            ]
        }
    ]
}

Body:
I tried to email the address at http://jsonassert.skyscreamer.org/ but got a

The following message to jsonassert-dev@skyscreamer.org was
  undeliverable. The reason for the problem:
  5.1.0 - Unknown address error 550-"5.1.1 The email account that you tried to reach does not exist

So I tried ZJsonPatch. I like the fact that using Jackson with it, the ordering of the members does not matter. In other words, I first try to check for equality using Jackson. Jackson is ordering independent. Then if it fails, I use ZJsonPatch to tell me what the diff is.

{"op":"replace","path":"/data/0/successfulIds/1","value":"B9"}

which handles nested JSON well.

ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(expectedJsonResponse);
JsonNode actual = mapper.readTree(actualJsonResponse);

try {
    assertEquals(expected, actual);
} catch (AssertionError ae) {
    JsonNode patch = JsonDiff.asJson(actual, expected);
    throw new Exception(patch.toString(), ae);
}


问:
ElementNotInteractableException: element not interactable: element has zero size appears since upgrade to chromedriver 83
I use the following docker image to run my cucumber tests:

https://hub.docker.com/r/selenium/standalone-chrome/

Unfortunately, starting from today it seems that whenever I run my tests I get the errors below. They appear at the start of each test. It does not matter what I do on the page.

**13:38:26      [exec] org.openqa.selenium.ElementNotInteractableException: element not interactable: element has zero size

13:38:26      [exec]   (Session info: chrome=83.0.4103.61)**

I did some digging and I noticed the chromedriver version was updated from 81 to 83. I managed to fix this issue by using an older docker image from that docker hub link which has chromedriver 81. But if I attempt to use chromedriver 83 again it will not work.

Has anyone else encountered this? Is there a new chrome option I need to add because of the update?

答:
I had the same problem as you with chrome driver updating to 83, i was able to get around this problem.

 WebDriverWait wait = new WebDriverWait(this.Driver, TimeSpan.FromSeconds(10));
            var result = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.CssSelector(".btnSaveChanges")));
            ExcuteJquery("$j(\".btnSaveChanges div:contains('" + Text + "')\").click()");```

Using Jquery will help you access this

Body:
I had the same problem as you with chrome driver updating to 83, i was able to get around this problem.

 WebDriverWait wait = new WebDriverWait(this.Driver, TimeSpan.FromSeconds(10));
            var result = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.CssSelector(".btnSaveChanges")));
            ExcuteJquery("$j(\".btnSaveChanges div:contains('" + Text + "')\").click()");

Using Jquery will help you access this


问:
Tika- Pandas bridge to export PDF content to Excel?
I would like Python to read a PDF file ("Spain.pdf" containing 11 columns and 59 rows, one of which is a header) and export its contents to Excel.

There are many PDF-Excel threads on here, but none that I consulted address the concept of a bridge from parsed Tika content to Pandas data frames that write to Excel.

I've searched this site (and elsewhere), talked to a couple of programmers, and consulted some manuals and books. I can't R_every_FM because, as a novice, I don't know where to focus: i.e., do I want to flush content into a Pandas data frame?

From SO and Sweigart (2015) I found Tika, Tabula, and PyPDF2 to parse PDF content. Tika worked best for me. (The Tabula app is great for manual dumps, but the Python module doesn't run for me.) I used the following code:

```<code>from tika import parser
raw = parser.from_file('spain.pdf')
print(raw['content'])
</code>```

which prints clean content to my console.

I'm trying to transfer this content into a data frame, which I could then export to Excel via XlsxWriter (or a similar module):

```<code>import pandas as pd
dataSpain = pd.DataFrame({'Survey': ["Key","ISO","Country","Region","Province","Comarca","City","Name","Age","Gender","Hospital"]})
datatoexcel = pd.ExcelWriter("FromPython.xlsx",engine='xlsxwriter')
dataSpain.to_excel(datatoexcel, sheet_name='Sheet1')
datatoexcel.save()
</code>```

Could someone please point me in the right direction? Any thoughts would be appreciated. Many thanks for your attention.

Code is written in Atom 1.45 and run via Windows PowerShell 5.1. Environment is Python v3.8.0 on a Microsoft Surface 2 laptop running Windows 10 Home v1903.

答:
Seems like the main issue you're experiencing is that the Pandas ExcelWriter code you're using is asking for another Python library called xlsxwriter to serve as an engine (as opposed to the default openpyxl library) which you might not have installed as it is independent of Pandas.

So first step would be to make sure you install it ( pip install xlsxwriter)
I ran the following code in a terminal/command line based on your post and it worked fine:

```<code>import pandas as pd
dataSpain = pd.DataFrame({'Survey': ["Key","ISO","Country","Region","Province","Comarca","City","Name","Age","Gender","Hospital"]})
with pd.ExcelWriter('FromPython.xlsx',engine='xlsxwriter') as writer:
    dataSpain.to_excel(writer)
</code>```

If it doesn't work, the next step would be to share the error you're getting. Hope this helps!

Body:
I would like Python to read a PDF file ("Spain.pdf" containing 11 columns and 59 rows, one of which is a header) and export its contents to Excel.

There are many PDF-Excel threads on here, but none that I consulted address the concept of a bridge from parsed Tika content to Pandas data frames that write to Excel.

I've searched this site (and elsewhere), talked to a couple of programmers, and consulted some manuals and books. I can't R_every_FM because, as a novice, I don't know where to focus: i.e., do I want to flush content into a Pandas data frame?

From SO and Sweigart (2015) I found Tika, Tabula, and PyPDF2 to parse PDF content. Tika worked best for me. (The Tabula app is great for manual dumps, but the Python module doesn't run for me.) I used the following code:

from tika import parser
raw = parser.from_file('spain.pdf')
print(raw['content'])

which prints clean content to my console.

I'm trying to transfer this content into a data frame, which I could then export to Excel via XlsxWriter (or a similar module):

import pandas as pd
dataSpain = pd.DataFrame({'Survey': ["Key","ISO","Country","Region","Province","Comarca","City","Name","Age","Gender","Hospital"]})
datatoexcel = pd.ExcelWriter("FromPython.xlsx",engine='xlsxwriter')
dataSpain.to_excel(datatoexcel, sheet_name='Sheet1')
datatoexcel.save()

Could someone please point me in the right direction? Any thoughts would be appreciated. Many thanks for your attention.

Code is written in Atom 1.45 and run via Windows PowerShell 5.1. Environment is Python v3.8.0 on a Microsoft Surface 2 laptop running Windows 10 Home v1903.

Body:
Seems like the main issue you're experiencing is that the Pandas ExcelWriter code you're using is asking for another Python library called xlsxwriter to serve as an engine (as opposed to the default openpyxl library) which you might not have installed as it is independent of Pandas.

So first step would be to make sure you install it ( pip install xlsxwriter)
I ran the following code in a terminal/command line based on your post and it worked fine:

import pandas as pd
dataSpain = pd.DataFrame({'Survey': ["Key","ISO","Country","Region","Province","Comarca","City","Name","Age","Gender","Hospital"]})
with pd.ExcelWriter('FromPython.xlsx',engine='xlsxwriter') as writer:
    dataSpain.to_excel(writer)

If it doesn't work, the next step would be to share the error you're getting. Hope this helps!


问:
comboBox.SelectedItem problem
ComboBox is binding database

```<code>string str= comboBox1.SelectedItem.ToString();
</code>```

the line gives System.Data.DataRowView value for str but not giving selected item name.

答:
Use the DisplayMember and ValueMember Properties for the combobox before you assign the DataSource, and use SelectedValue instead of SelectedItem.

For example, if you have a List<MyClass> - where MyClass has a property int ID , and another one string Title - and you want to assign it as the DataSource of comboBox1, you should write:

```<code>List<MyClass> myList;
...

comboBox1.DisplayMember = "Title";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = myList;
</code>```

Now comboBox1.SelectedValue is an object{int}, which can be casted to int and used.

Title: comboBox.SelectedItem problem

Body:
ComboBox is binding database

string str= comboBox1.SelectedItem.ToString();

the line gives System.Data.DataRowView value for str but not giving selected item name.

Body:
Use the DisplayMember and ValueMember Properties for the combobox before you assign the DataSource, and use SelectedValue instead of SelectedItem.

For example, if you have a List<MyClass> - where MyClass has a property int ID , and another one string Title - and you want to assign it as the DataSource of comboBox1, you should write:

List<MyClass> myList;
...

comboBox1.DisplayMember = "Title";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = myList;

Now comboBox1.SelectedValue is an object{int}, which can be casted to int and used.


问:
Puppeteer iterate div and then from result, iterate child element
I want to return an object from the HTML as below:

HTML

```<code><div id="collection">
  <div class="div">
    <h1 class="title">Title 1</h1>
    <ul class="list">
      <li>list item 1</li>
      <li>list item 2</li>
      <li>list item 3</li>
    </ul>
  </div>
  <div class="div">
    <h1 class="title">Title 2</h1>
    <ul class="list">
      <li>list item 1a</li>
      <li>list item 2a</li>
      <li>list item 3a</li>
      <li>list item 4a</li>
    </ul>
  </div>
  <div class="div">
    <h1 class="title">Title 3</h1>
  </div>
</div>
</code>```

Required result:

```<code>{
  title: "Title 1",
  list:{
    item: "list item 1",
    item: "list item 2",
    item: "list item 3"
  }
},
{
  title: "Title 2",
  list:{
    item: "list item 1a",
    item: "list item 2a",
    item: "list item 3a",
    item: "list item 4a"
  }
},
{
  title: "Title 3",
  list:{}
}

</code>```

So far I have:

```<code>const result = await page.$$eval('div.div, (divs) => divs.map((div) => {
   return {
      title: div.querySelector('.title').innerText,
   }
}));
console.log(result)
</code>```

I am unsure on how I can use page.$$eval to then iterate another element; in this case the ul.
Any help would be appreciated.

Thanks

答:
You can do it like this with Puppeteer. Just uncomment the page.evaluate() function. I just commented it so that you can run the snippet and see the results.

You can't have multiple object entries with keys that are all the same, so a better solution might be to return an array with the li values, as the keys do not matter anyway, right?

const result = []

//await page.evaluate(() => {
  const divs = document.querySelectorAll('.div')
  divs.forEach(div => {
    const obj = {
      title: div.querySelector('.title').innerText,
      list: [...div.querySelectorAll('ul li')].map(i => i.innerText)
    }
    result.push(obj)
  })
//})

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="collection">
  <div class="div">
    <h1 class="title">Title 1</h1>
    <ul class="list">
      <li>list item 1</li>
      <li>list item 2</li>
      <li>list item 3</li>
    </ul>
  </div>
  <div class="div">
    <h1 class="title">Title 2</h1>
    <ul class="list">
      <li>list item 1a</li>
      <li>list item 2a</li>
      <li>list item 3a</li>
      <li>list item 4a</li>
    </ul>
  </div>
  <div class="div">
    <h1 class="title">Title 3</h1>
  </div>
</div></code>```

Body:
I want to return an object from the HTML as below:

HTML

Title 1

list item 1

list item 2

list item 3

Title 2

list item 1a

list item 2a

list item 3a

list item 4a

Title 3

Required result:

{
  title: "Title 1",
  list:{
    item: "list item 1",
    item: "list item 2",
    item: "list item 3"
  }
},
{
  title: "Title 2",
  list:{
    item: "list item 1a",
    item: "list item 2a",
    item: "list item 3a",
    item: "list item 4a"
  }
},
{
  title: "Title 3",
  list:{}
}

So far I have:

const result = await page.$$eval('div.div, (divs) => divs.map((div) => {
   return {
      title: div.querySelector('.title').innerText,
   }
}));
console.log(result)

I am unsure on how I can use page.$$eval to then iterate another element; in this case the ul.
Any help would be appreciated.

Thanks

Body:
You can do it like this with Puppeteer. Just uncomment the page.evaluate() function. I just commented it so that you can run the snippet and see the results.

You can't have multiple object entries with keys that are all the same, so a better solution might be to return an array with the li values, as the keys do not matter anyway, right?

const result = []

//await page.evaluate(() => {
  const divs = document.querySelectorAll('.div')
  divs.forEach(div => {
    const obj = {
      title: div.querySelector('.title').innerText,
      list: [...div.querySelectorAll('ul li')].map(i => i.innerText)
    }
    result.push(obj)
  })
//})

console.log(result)

<div id="collection">
  <div class="div">
    <h1 class="title">Title 1</h1>
    <ul class="list">
      <li>list item 1</li>
      <li>list item 2</li>
      <li>list item 3</li>
    </ul>
  </div>
  <div class="div">
    <h1 class="title">Title 2</h1>
    <ul class="list">
      <li>list item 1a</li>
      <li>list item 2a</li>
      <li>list item 3a</li>
      <li>list item 4a</li>
    </ul>
  </div>
  <div class="div">
    <h1 class="title">Title 3</h1>
  </div>
</div>


问:
ElasticSearch: Create should queries from a dynamic list of criterias with NEST
Using ElasticSearch 7.6 I want to find all points which are inside a list of areas.
There are several other filter criterias that are added to a list of QueryContainerDescriptors and applied on  the final search.

```<code> var queries = new List<Func<QueryContainerDescriptor<MySearchableObject>, QueryContainer>>();
</code>```

This example works for one area, where Coordinates is a dictionary

```<code>foreach (var area in areas)
{
    var pointsList = area.Coordinates.Values.Select(p => new GeoLocation(p.Latitude, p.Longitude)).ToList();

    queries.Add(sqs => sqs
        .GeoPolygon(r => r
            .Field(f => f.Position)
            .ValidationMethod(GeoValidationMethod.Strict)
            .Points(pointsList)));
}
</code>```

and also this:

```<code>queries.Add(sqs => sqs.Bool(b=>b.Should(bs => GeoPolygonShouldQuery(bs, area))));

private static QueryContainer GeoPolygonShouldQuery(QueryContainerDescriptor<MySearchableObject> bs, FilterArea area)
{
     return bs
    .GeoPolygon(r => r
        .Field(f => f.Position)
        .ValidationMethod(GeoValidationMethod.Strict)
        .Points(area.Coordinates.Values.Select(p => new GeoLocation(p.Latitude, p.Longitude))));
}
</code>```

How would I get around to append a should clause for each area in the list?

Similar to this:

```<code>queries.Add(sqs => sqs.Bool(b => b.Should(
                bs => bs.GeoPolygon(r => r.Field(f => f.Position)
                    .Points(areas.ElementAt(0).Coordinates.Values.Select(p => new GeoLocation(p.Latitude, p.Longitude)).ToList())),
                bs => bs.GeoPolygon(r => r.Field(f => f.Position)
                    .Points(areas.ElementAt(1).Coordinates.Values.Select(p => new GeoLocation(p.Latitude, p.Longitude)).ToList()))
                )));
</code>```

答:
After a bit more trial and error, this seems to solve the issue:

var areas = FindFilterAreas(query.Areas);
queries.Add(sqs => sqs.Bool(b => b.Should(MyQueries(b, areas))));

private static List<Func<QueryContainerDescriptor<SearchableSituation>, QueryContainer>> MyQueries(BoolQueryDescriptor<SearchableSituation> qd, IEnumerable<FilterArea> areas)
{
    List<Func<QueryContainerDescriptor<SearchableSituation>, QueryContainer>> queries = new List<Func<QueryContainerDescriptor<SearchableSituation>, QueryContainer>>();

    foreach (var area in areas)
    {
        var pointsList = area.Coordinates.Values.Select(p => new GeoLocation(p.Latitude, p.Longitude)).ToList();

        queries.Add(sqs => sqs
            .GeoPolygon(r => r
                .Field(f => f.Position)
                .ValidationMethod(GeoValidationMethod.Strict)
                .Points(pointsList))
        );
    }

    return queries;
}
```

Body:
Using ElasticSearch 7.6 I want to find all points which are inside a list of areas.
There are several other filter criterias that are added to a list of QueryContainerDescriptors and applied on  the final search.

 var queries = new List<Func<QueryContainerDescriptor<MySearchableObject>, QueryContainer>>();

This example works for one area, where Coordinates is a dictionary

foreach (var area in areas)
{
    var pointsList = area.Coordinates.Values.Select(p => new GeoLocation(p.Latitude, p.Longitude)).ToList();

    queries.Add(sqs => sqs
        .GeoPolygon(r => r
            .Field(f => f.Position)
            .ValidationMethod(GeoValidationMethod.Strict)
            .Points(pointsList)));
}

and also this:

queries.Add(sqs => sqs.Bool(b=>b.Should(bs => GeoPolygonShouldQuery(bs, area))));

private static QueryContainer GeoPolygonShouldQuery(QueryContainerDescriptor<MySearchableObject> bs, FilterArea area)
{
     return bs
    .GeoPolygon(r => r
        .Field(f => f.Position)
        .ValidationMethod(GeoValidationMethod.Strict)
        .Points(area.Coordinates.Values.Select(p => new GeoLocation(p.Latitude, p.Longitude))));
}

How would I get around to append a should clause for each area in the list?

Similar to this:

queries.Add(sqs => sqs.Bool(b => b.Should(
                bs => bs.GeoPolygon(r => r.Field(f => f.Position)
                    .Points(areas.ElementAt(0).Coordinates.Values.Select(p => new GeoLocation(p.Latitude, p.Longitude)).ToList())),
                bs => bs.GeoPolygon(r => r.Field(f => f.Position)
                    .Points(areas.ElementAt(1).Coordinates.Values.Select(p => new GeoLocation(p.Latitude, p.Longitude)).ToList()))
                )));


问:
How to test a ctor taking std::initializer_list with a compile-time known length?
For testing purposes, I want to call a constructor with a simple std::initializer_list. Say the value doesn't matter and the length, value and type is known at compile time, like { 42, 42, 42,... N-times }.

Since its constructor is private, I tried my luck with some pack expansion:

```<code>template< int Count, typename ValueType, int Value, int... Values >
struct Generator
    : Generator< Count-1, ValueType, Value, Value, Values... >
{};

template< typename ValueType, int Value, int... Values >
struct Generator< 0, ValueType, Value, Values... >
{
    static constexpr inline std::initializer_list<ValueType>
    get()
    { return { static_cast<ValueType>(Values)... }; }
};
</code>```

So Generator<3,int,10>::get() gives me {10,10,10}, yeah! But I seem to have a life-time issue, as the initializer_list is just a proxy object, returned from an {..}-expression inside a function. The test doesn't see the values I'm expecting. Am I overlooking something?

```<code>struct A {
    A(std::initializer_list<int> l)
    { for(auto i:l) std::cout << i << std::endl; }
};

int main() {
    A a { Generator<3, int, 10>::get() };
    return 0;
}
// prints:
// 32765
// 1762362376
// 32765
</code>```

Live: https://godbolt.org/z/jYWKB3

答:
Yes, it's a life-time issue. Although every value in the curly braces is known at compile time, the initializer_list is just a proxy having two pointers (or pointer+size), and they point to dead stack memory after the function finishes.

I solved it by moving the construction of the software under test into the variadic template:

```<code>template< typename TestType, int Count, typename ValueType, int Value, int... Values >
struct InitListCtorTest
    : InitListCtorTest< TestType, Count-1, ValueType, Value, Value, Values... >
{};

template< typename TestType, typename ValueType, int Value, int... Values >
struct InitListCtorTest< TestType, 0, ValueType, Value, Values... >
{
    TestType m_testobj { static_cast<ValueType>(Values)... };
};

struct SUT {
    SUT(std::initializer_list<int> l){/*...*/}
};

int main() {
    InitListCtorTest<SUT,3,int,10> gen;
    // Test, if gen.m_testobj has 3 elements with value 10.
    return 0;
}
</code>```

Body:
For testing purposes, I want to call a constructor with a simple std::initializer_list. Say the value doesn't matter and the length, value and type is known at compile time, like { 42, 42, 42,... N-times }.

Since its constructor is private, I tried my luck with some pack expansion:

template< int Count, typename ValueType, int Value, int... Values >
struct Generator
    : Generator< Count-1, ValueType, Value, Value, Values... >
{};

template< typename ValueType, int Value, int... Values >
struct Generator< 0, ValueType, Value, Values... >
{
    static constexpr inline std::initializer_list<ValueType>
    get()
    { return { static_cast<ValueType>(Values)... }; }
};

So Generator<3,int,10>::get() gives me {10,10,10}, yeah! But I seem to have a life-time issue, as the initializer_list is just a proxy object, returned from an {..}-expression inside a function. The test doesn't see the values I'm expecting. Am I overlooking something?

struct A {
    A(std::initializer_list<int> l)
    { for(auto i:l) std::cout << i << std::endl; }
};

int main() {
    A a { Generator<3, int, 10>::get() };
    return 0;
}
// prints:
// 32765
// 1762362376
// 32765

Live: https://godbolt.org/z/jYWKB3

Body:
Yes, it's a life-time issue. Although every value in the curly braces is known at compile time, the initializer_list is just a proxy having two pointers (or pointer+size), and they point to dead stack memory after the function finishes.

I solved it by moving the construction of the software under test into the variadic template:

template< typename TestType, int Count, typename ValueType, int Value, int... Values >
struct InitListCtorTest
    : InitListCtorTest< TestType, Count-1, ValueType, Value, Value, Values... >
{};

template< typename TestType, typename ValueType, int Value, int... Values >
struct InitListCtorTest< TestType, 0, ValueType, Value, Values... >
{
    TestType m_testobj { static_cast<ValueType>(Values)... };
};

struct SUT {
    SUT(std::initializer_list<int> l){/*...*/}
};

int main() {
    InitListCtorTest<SUT,3,int,10> gen;
    // Test, if gen.m_testobj has 3 elements with value 10.
    return 0;
}


问:
Android Studio - How to perform doubleClick in Kotlin?
A boring thing when some more advanced technologies impose their standards is to have to do with the "double click" to perform an action. But what I'm looking for is an easy way to implement it without having to rewrite the code a thousand times.

I would like to implement double click in my project using Kotlin.
Could someone help me?
Thanks in Advance

just to know: I would like a way to understand how to do double click or to prevent  that user do a doubleclick

答:
GestureDetector contains OnDoubleTapListener which allows us to handle double-clicks. It is the easiest way to implement a double-click listener.
Also, you can try to find existing solutions like these:

https://github.com/pedromassango/doubleClick

https://github.com/fkirc/DoubleClickListener-for-Android

There are several posts on StackOverflow related to this theme. Please, check them.

how to implement double click in android

How to detect double click event for buttons in android

Double click event in android

According to clicks generating, I suppose you can call performClick() method several times with delay.


问:
how to stop overwriting an index number in python list which is already written once?
I have a list with index number 0 to 5. I am telling user to input position where they want to mark ('X') into the list and then printing the list each time the user input's a index number. I want the user to input only once in a index number of the list and if user try to overwrite the written value in a list I want to give a message to user as a input 'you can't go there please try again in different position'. I want to keep running the input until the user enters a value in non-written position in the list.

I tried to do it in OOP as I am practicing OOP. I make a board then display the board with print_Board() method. In method input_Value() I tried to make it run under a while loop and break the loop when all positions are filled... also used a try catch error... which will check if the input value must have the index number from 1 to 6 only.

```<code>class Overwrite:

    list = ['.', '.', '.', '.', '.', '.']

    def print_Board(self):
        print(self.list[0:3])
        print(self.list[3:6])

    def input_Value(self):
        while True:
            try:
                self.position = input('enter a number between 1 to 6:')     # input a value
                if self.position not in ['1', '2', '3', '4', '5', '6']: # checking if the number is in range(1 to 6) or not
                    print('please try again a number between 1 to 6')
                    continue
                self.position = int(self.position) - 1  # putting -1 so that user input is different than
                self.list[self.position] = 'X'
                self.print_Board()
            except IndexError:
                print('please try again a number between 1 to 6:')
            except ValueError:
                print('please try again a number between 1 to 6:')
            else:
                if '.' not in self.list:  # it will stop the program when all the positions are filled
                    break

    def gameplay(self):
        self.print_Board()
        self.input_Value()
</code>```

答:
Check if that list element is already equal to X, and if so, print a message and continue the input loop.

```<code>self.position = int(self.position) - 1
if self.list[self.position] == 'X':
    print('you already entered that position, please try again')
    continue
else:
    self.list[self.position] = 'X'
</code>```

Body:
I have a list with index number 0 to 5. I am telling user to input position where they want to mark ('X') into the list and then printing the list each time the user input's a index number. I want the user to input only once in a index number of the list and if user try to overwrite the written value in a list I want to give a message to user as a input 'you can't go there please try again in different position'. I want to keep running the input until the user enters a value in non-written position in the list.

I tried to do it in OOP as I am practicing OOP. I make a board then display the board with print_Board() method. In method input_Value() I tried to make it run under a while loop and break the loop when all positions are filled... also used a try catch error... which will check if the input value must have the index number from 1 to 6 only.

class Overwrite:

    list = ['.', '.', '.', '.', '.', '.']

    def print_Board(self):
        print(self.list[0:3])
        print(self.list[3:6])

    def input_Value(self):
        while True:
            try:
                self.position = input('enter a number between 1 to 6:')     # input a value
                if self.position not in ['1', '2', '3', '4', '5', '6']: # checking if the number is in range(1 to 6) or not
                    print('please try again a number between 1 to 6')
                    continue
                self.position = int(self.position) - 1  # putting -1 so that user input is different than
                self.list[self.position] = 'X'
                self.print_Board()
            except IndexError:
                print('please try again a number between 1 to 6:')
            except ValueError:
                print('please try again a number between 1 to 6:')
            else:
                if '.' not in self.list:  # it will stop the program when all the positions are filled
                    break

    def gameplay(self):
        self.print_Board()
        self.input_Value()

Body:
Check if that list element is already equal to X, and if so, print a message and continue the input loop.

self.position = int(self.position) - 1
if self.list[self.position] == 'X':
    print('you already entered that position, please try again')
    continue
else:
    self.list[self.position] = 'X'


问:
Rails Layout name inside view
How can I print out the name of current layout in a view?

Example

```<code>puts controller.current_layout
</code>```

Thx

答:
This works with Rails 3.0.7:

```<code>controller.send :_layout
</code>```

Obviously, it's a private method, so use at your own risk.

ContentLicense: CC BY-SA 2.5

Title: Rails Layout name inside view

Body:
How can I print out the name of current layout in a view?

Example

puts controller.current_layout

Thx

Body:
This works with Rails 3.0.7:

controller.send :_layout

Obviously, it's a private method, so use at your own risk.


问:
Google Cloud load balancer redirect if from a certain region
I have two static pages (English, Danish) which are currently in Google Cloud Storage Bucket. This bucket contains en and dk folders for those static pages. Also, I have a Load Balancer with Google CDN feature.

I want to achieve that when a person connects to the website from Denmark, that person would get the Danish static page. Meanwhile, people outside Denmark would receive the English site.

How can I achieve this goal in the load balancer level?

P.s. I think it can be done with forwardingRules but I couldn’t figure out how the rules should look like.

答:
I did some research and I think that your needs could be solved with a LB using the header-based routing, using the Accept-Language vary as the routeRules for the URL query.
This guide can help you to achieve this configuration, but you need to adapt it to be ruled by the Accept-Language header parameters that could be more useful for your case.</p>


问:
WPF Binding brush generates marshalling error
I'm quite confused as at runtime I get this error:
The application called an interface that was marshalled for a different thread. (0x8001010E (RPC_E_WRONG_THREAD))'

I have a on object that has:

```<code>            <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <TextBlock
                Grid.Column="0"
                FontFamily="Segoe MDL2 Assets"
                Foreground="{Binding ImageColor, Mode=OneWay}"
                Text="{Binding ImageSrc, Mode=OneWay}" />
            <TextBlock
                Grid.Column="1"
                VerticalAlignment="Center"
                Text="{Binding VisitDescr, Mode=OneWay}" />
        </Grid>
</code>```

in the class I have

```<code>    public string ImageSrc
    {
        get
        {
            switch (Type)
            {
                case "c1":
                    return "\xE8B9";
                    break;
                default:
                    return "\xE8A5";
                    break;
            }
        }
    }

    public Brush ImageColor
    {
        get
        {
            switch (Type)
            {
                case "c1":
                    return new SolidColorBrush(Colors.MediumOrchid);
                    break;
                case "c2":
                    return new SolidColorBrush(Colors.DarkOrchid);
                default:
                    return new SolidColorBrush(Colors.Red);
                    break;
            }
        }
    }
</code>```

The image is returned without any error but the Color generate the error and is NOT changed.

How is it possible I get a marshalled error?

答:
I've found the issue... it was using the work library.
I've updated it to:

```<code>using System.Windows.Media;
</code>```

and now is working.
But why it got Marshalling and not type conversion error?

Body:
I'm quite confused as at runtime I get this error:
The application called an interface that was marshalled for a different thread. (0x8001010E (RPC_E_WRONG_THREAD))'

I have a on object that has:

            <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <TextBlock
                Grid.Column="0"
                FontFamily="Segoe MDL2 Assets"
                Foreground="{Binding ImageColor, Mode=OneWay}"
                Text="{Binding ImageSrc, Mode=OneWay}" />
            <TextBlock
                Grid.Column="1"
                VerticalAlignment="Center"
                Text="{Binding VisitDescr, Mode=OneWay}" />
        </Grid>

in the class I have

    public string ImageSrc
    {
        get
        {
            switch (Type)
            {
                case "c1":
                    return "\xE8B9";
                    break;
                default:
                    return "\xE8A5";
                    break;
            }
        }
    }

    public Brush ImageColor
    {
        get
        {
            switch (Type)
            {
                case "c1":
                    return new SolidColorBrush(Colors.MediumOrchid);
                    break;
                case "c2":
                    return new SolidColorBrush(Colors.DarkOrchid);
                default:
                    return new SolidColorBrush(Colors.Red);
                    break;
            }
        }
    }

The image is returned without any error but the Color generate the error and is NOT changed.

How is it possible I get a marshalled error?

Body:
I've found the issue... it was using the work library.
I've updated it to:

using System.Windows.Media;

and now is working.
But why it got Marshalling and not type conversion error?