问:
How to create HTML element for JavaScript and not for HTML
I have this simplified code:

const chancesData = ["facebook","twitter","google"];
        let inputsArr = [];
        const inputsArrFill = chancesData.map((cur, index) => {
          const input = (document.createElement("input").value =
            chancesData[index]);
          inputsArr.push(input); //I want the pushed value to be something like this "<input value"facebook">"
          return inputsArr;
          //so the returned array (should) be something like this:
          //["<input value"facebook">","<input value"twitter">","<input value"google">"]
        });
        console.dir(inputsArrFill);
  ```
</div>
</div>
</p>

<p>as you can see if you opened this coed in your console, the returned array looks like this:</p>

```['facebook', 'twiiter', 'google']
```

<p>I want it to look like this:</p>

```['<input value="facebook">','<input value="twitter">','<input value="google">']
```

答:
The result of an assignment expression, is the assigned value. With

```<code>const input = (document.createElement("input").value =
        chancesData[index]);
</code>```

you did not store a reference to the created HTML element into your variable, you stored the assigned value, chancesData[index].

You need to do these two things in separate steps.

const chancesData = ["facebook","twitter","google"];
        let inputsArr = [];
        const inputsArrFill = chancesData.map((cur, index) => {
          const input = document.createElement("input");
          input.value = chancesData[index];

          inputsArr.push(input); //I want the pushed value to be something like this "<input value"facebook">"
          return inputsArr;
          //so the returned array (should) be something like this:
          //["<input value"facebook">","<input value"twitter">","<input value"google">"]
        });
        console.dir(inputsArrFill);```

But if you really want <input value="facebook"> as a result, then you will probably have to push that in string form to begin with. You have little control over how an HTML element object gets displayed by the console.

Body:
I have this simplified code:

const chancesData = ["facebook","twitter","google"];
        let inputsArr = [];
        const inputsArrFill = chancesData.map((cur, index) => {
          const input = (document.createElement("input").value =
            chancesData[index]);
          inputsArr.push(input); //I want the pushed value to be something like this "<input value"facebook">"
          return inputsArr;
          //so the returned array (should) be something like this:
          //["<input value"facebook">","<input value"twitter">","<input value"google">"]
        });
        console.dir(inputsArrFill);

as you can see if you opened this coed in your console, the returned array looks like this:

['facebook', 'twiiter', 'google']

I want it to look like this:

['<input value="facebook">','<input value="twitter">','<input value="google">']

Body:
The result of an assignment expression, is the assigned value. With

const input = (document.createElement("input").value =
        chancesData[index]);

you did not store a reference to the created HTML element into your variable, you stored the assigned value, chancesData[index].

You need to do these two things in separate steps.

const chancesData = ["facebook","twitter","google"];
        let inputsArr = [];
        const inputsArrFill = chancesData.map((cur, index) => {
          const input = document.createElement("input");
          input.value = chancesData[index];

          inputsArr.push(input); //I want the pushed value to be something like this "<input value"facebook">"
          return inputsArr;
          //so the returned array (should) be something like this:
          //["<input value"facebook">","<input value"twitter">","<input value"google">"]
        });
        console.dir(inputsArrFill);

But if you really want <input value="facebook"> as a result, then you will probably have to push that in string form to begin with. You have little control over how an HTML element object gets displayed by the console.


来源: stackexchange

问:
IExceptionHandlerPathFeature returns null when calling a controller-action when user's role authorization isnt fullfilled
When a logged in user request the access to an action method where doesnt meet the minimum required  role it the error action method returns a null object from  IExceptionHandlerPathFeature, it doesnt really change anything if it runs  on development,staging or production also I noticed when I tried to use default exception pages the exception page returned was blank, now I had to use custom exception pages to avoid this, I am not sure if this is related somehow

Startup.cs

```<code>public class Startup
    {
        private IConfiguration _config;

        public Startup(IConfiguration config)
        {
            _config = config;
        }

        public void ConfigureServices(IServiceCollection services)
        {

            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {   options.Password.RequiredLength = 8;
                options.Password.RequireDigit = true;
                options.Password.RequiredUniqueChars = 2;
                options.Password.RequireNonAlphanumeric = true;
            }).AddEntityFrameworkStores<AppDbContext>()/*.AddDefaultTokenProviders()*/;

            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));
            services.AddMvc(options=>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddXmlDataContractSerializerFormatters();
            //services.AddSingleton<IEmployeeRepository, EmployeeRepository>();
            services.AddScoped<IEmployeeRepository, SQLEmployeeRepository>();
            services.AddSingleton<IDepartmentRepository, DepartmentRepository>();
        }

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

            if (env.IsDevelopment())
            {

                app.UseDeveloperExceptionPage(new DeveloperExceptionPageOptions()
                {
                    SourceCodeLineCount = 0,
                });
            }
            else
            {

                //app.UseStatusCodePagesWithReExecute("/Error/{0}").UseMiddleware<ErrorController>("/Error/{0}");
                //app.UseStatusCodePagesWithReExecute("/Error/");
                app.UseExceptionHandler("/Error");
            }

            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseMvc(route =>
            {
                route.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");

            });
            app.UseStaticFiles();

        }
    }

</code>```

ErrorController.cs

```<code>public class ErrorController : Controller
    {
        private readonly IHostingEnvironment hostingEnvironment;
        private readonly ILogger<ErrorController> logger;
        public ErrorController(IHostingEnvironment _hostingEnvironment, ILogger<ErrorController> _logger)
        {
            logger = _logger;
            hostingEnvironment = _hostingEnvironment;
        }
        // GET: /<controller>/
        [Route("Error/{statusCode}")]
        public IActionResult HTTPCodeStatusHandler(int? statusCode)
        {
            if (statusCode != null && (((int)statusCode) >= int.MinValue && ((int)statusCode) <= int.MaxValue))
            {
                if (hostingEnvironment.IsDevelopment())
                {
                    return View($"~/Views/shared/error{statusCode}.cshtml");
                }
                else
                {
                    var statusCodeResult = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
                    if (statusCode == 404)
                    {
                        ViewBag.ErrorMessage = "Sorry, the page you have requested cannot be found";
                        if (statusCodeResult != null)
                        {
                            //ViewBag.Path = statusCodeResult.OriginalPath;
                            //ViewBag.QS = statusCodeResult.OriginalQueryString;
                            logger.LogWarning($"404 Error ocurred.Path :{((statusCodeResult.OriginalPath is "/") ? "/Home": statusCodeResult.OriginalPath )} And Query String {((statusCodeResult.OriginalQueryString is null) ? "/Home":statusCodeResult.OriginalQueryString) }");
                        }
                        return View($"~/Views/shared/error{statusCode}.cshtml");
                    }
                }
                return View();
            }
            return Error();
        }
        [Route("Error")]
        [AllowAnonymous]
        [HttpGet]
        public IActionResult Error()
        {
            var exceptionDetails = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

            logger.LogError($"The path {exceptionDetails.Path} threw andexception {exceptionDetails.Error}");

            ViewBag.ExceptionPath = exceptionDetails.Path;
            ViewBag.ExceptionMessage = exceptionDetails.Error.Message;
            ViewBag.StackTrace = exceptionDetails.Error.StackTrace;

            return View("~/Views/shared/Error.cshtml");
        }
    }

</code>```

答:
Configure the cookies AccessDenied Path option that solved the issue</p>

```<code>            services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = new PathString("/Account/AccessDenied");
            });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When a logged in user request the access to an action method where doesnt meet the minimum required  role it the error action method returns a null object from  IExceptionHandlerPathFeature, it doesnt really change anything if it runs  on development,staging or production also I noticed when I tried to use default exception pages the exception page returned was blank, now I had to use custom exception pages to avoid this, I am not sure if this is related somehow

Startup.cs

public class Startup
    {
        private IConfiguration _config;

        public Startup(IConfiguration config)
        {
            _config = config;
        }

        public void ConfigureServices(IServiceCollection services)
        {

            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {   options.Password.RequiredLength = 8;
                options.Password.RequireDigit = true;
                options.Password.RequiredUniqueChars = 2;
                options.Password.RequireNonAlphanumeric = true;
            }).AddEntityFrameworkStores<AppDbContext>()/*.AddDefaultTokenProviders()*/;

            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));
            services.AddMvc(options=>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddXmlDataContractSerializerFormatters();
            //services.AddSingleton<IEmployeeRepository, EmployeeRepository>();
            services.AddScoped<IEmployeeRepository, SQLEmployeeRepository>();
            services.AddSingleton<IDepartmentRepository, DepartmentRepository>();
        }

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

            if (env.IsDevelopment())
            {

                app.UseDeveloperExceptionPage(new DeveloperExceptionPageOptions()
                {
                    SourceCodeLineCount = 0,
                });
            }
            else
            {

                //app.UseStatusCodePagesWithReExecute("/Error/{0}").UseMiddleware<ErrorController>("/Error/{0}");
                //app.UseStatusCodePagesWithReExecute("/Error/");
                app.UseExceptionHandler("/Error");
            }

            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseMvc(route =>
            {
                route.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");

            });
            app.UseStaticFiles();

        }
    }

ErrorController.cs

public class ErrorController : Controller
    {
        private readonly IHostingEnvironment hostingEnvironment;
        private readonly ILogger<ErrorController> logger;
        public ErrorController(IHostingEnvironment _hostingEnvironment, ILogger<ErrorController> _logger)
        {
            logger = _logger;
            hostingEnvironment = _hostingEnvironment;
        }
        // GET: /<controller>/
        [Route("Error/{statusCode}")]
        public IActionResult HTTPCodeStatusHandler(int? statusCode)
        {
            if (statusCode != null && (((int)statusCode) >= int.MinValue && ((int)statusCode) <= int.MaxValue))
            {
                if (hostingEnvironment.IsDevelopment())
                {
                    return View($"~/Views/shared/error{statusCode}.cshtml");
                }
                else
                {
                    var statusCodeResult = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
                    if (statusCode == 404)
                    {
                        ViewBag.ErrorMessage = "Sorry, the page you have requested cannot be found";
                        if (statusCodeResult != null)
                        {
                            //ViewBag.Path = statusCodeResult.OriginalPath;
                            //ViewBag.QS = statusCodeResult.OriginalQueryString;
                            logger.LogWarning($"404 Error ocurred.Path :{((statusCodeResult.OriginalPath is "/") ? "/Home": statusCodeResult.OriginalPath )} And Query String {((statusCodeResult.OriginalQueryString is null) ? "/Home":statusCodeResult.OriginalQueryString) }");
                        }
                        return View($"~/Views/shared/error{statusCode}.cshtml");
                    }
                }
                return View();
            }
            return Error();
        }
        [Route("Error")]
        [AllowAnonymous]
        [HttpGet]
        public IActionResult Error()
        {
            var exceptionDetails = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

            logger.LogError($"The path {exceptionDetails.Path} threw andexception {exceptionDetails.Error}");

            ViewBag.ExceptionPath = exceptionDetails.Path;
            ViewBag.ExceptionMessage = exceptionDetails.Error.Message;
            ViewBag.StackTrace = exceptionDetails.Error.StackTrace;

            return View("~/Views/shared/Error.cshtml");
        }
    }

Body:
Configure the cookies AccessDenied Path option that solved the issue

            services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = new PathString("/Account/AccessDenied");
            });


问:
attributeChangedCallback doesn't get called even after defining observedAttributes
In the following code, attributeChangedCallback never gets called even if the 'content' attribute is created, changed or removed.

```<code>class Square extends HTMLElement {

    static get observedAttributes() {

        return ['content'];
    }
    constructor(val) {
        super();
        console.log('inside constructor');
        this.attachShadow({mode: 'open'});
        this.shadowRoot.appendChild(document.createElement('button'));

        this.button = this.shadowRoot.querySelector('button');
        this.button.className = "square";

        this.content = val;

        console.log('constructor ended');
    }

    get content() {
        console.log('inside getter');
        return this.button.getAttribute('content');
    }
    set content(val) {
        console.log('setter being executed, val being: ', val);
        // pass null to represent empty square
        if (val !== null) {
            this.button.setAttribute('content', val);

        } else {
            if (this.button.hasAttribute('content')) {
                this.button.removeAttribute('content');
            }
        }

    }
    connectedCallback() {
        //console.log('connected callback being executed now');
    }

    // not working :(
    attributeChangedCallback(name, oldValue, newValue) {
        console.log('attribute changed callback being executed now');
        if (name === 'content') {
            this.button.innerHTML = newValue?newValue:" ";
        }
    }
}
customElements.define('square-box', Square);
</code>```

Based on the best practices given here, I want the side-effect of attribute change (updation of innerHTML in my case) to take place in attributeChangedCallback. However when I move this updation to the setter, the code works fine.

答:
```<code>set content(val) {
        console.log('setter being executed, val being: ', val);
        // pass null to represent empty square
        if (val !== null) {
            this.button.setAttribute('content', val);

        } else {
            if (this.button.hasAttribute('content')) {
                this.button.removeAttribute('content');
            }
        }

    }
</code>```

You are mixing up parents & children

You are defining a setter on your Element <square-box> (►parent element)

When you do this.button.setAttribute('content', val);

You are changing a attribute of your <button> Element (►child element)

This will never trigger the attributeChangedCallback of (►parent) <square-box>

because its attributes were not changed

You either have to go "up the DOM" with .getRootNode() and/or .host to set attributes of parent elements.

or use Custom Events (bubbling up the DOM) to notify parents that children have done/changed something

I presume you meant to do

```<code>set content(val) {
        //  loose ==null comparison for null AND undefined,
        //  element.content=null; will remove the attribute
        if (val==null)
            this.removeAttribute('content');
        else
        //  but you DO want .content(0) (0==false) set as "0"
            this.setAttribute('content', val);
    }
</code>```

Body:
In the following code, attributeChangedCallback never gets called even if the 'content' attribute is created, changed or removed.

class Square extends HTMLElement {

    static get observedAttributes() {

        return ['content'];
    }
    constructor(val) {
        super();
        console.log('inside constructor');
        this.attachShadow({mode: 'open'});
        this.shadowRoot.appendChild(document.createElement('button'));

        this.button = this.shadowRoot.querySelector('button');
        this.button.className = "square";

        this.content = val;

        console.log('constructor ended');
    }

    get content() {
        console.log('inside getter');
        return this.button.getAttribute('content');
    }
    set content(val) {
        console.log('setter being executed, val being: ', val);
        // pass null to represent empty square
        if (val !== null) {
            this.button.setAttribute('content', val);

        } else {
            if (this.button.hasAttribute('content')) {
                this.button.removeAttribute('content');
            }
        }

    }
    connectedCallback() {
        //console.log('connected callback being executed now');
    }

    // not working :(
    attributeChangedCallback(name, oldValue, newValue) {
        console.log('attribute changed callback being executed now');
        if (name === 'content') {
            this.button.innerHTML = newValue?newValue:" ";
        }
    }
}
customElements.define('square-box', Square);

Based on the best practices given here, I want the side-effect of attribute change (updation of innerHTML in my case) to take place in attributeChangedCallback. However when I move this updation to the setter, the code works fine.

Body:
set content(val) {
        console.log('setter being executed, val being: ', val);
        // pass null to represent empty square
        if (val !== null) {
            this.button.setAttribute('content', val);

        } else {
            if (this.button.hasAttribute('content')) {
                this.button.removeAttribute('content');
            }
        }

    }

You are mixing up parents & children

You are defining a setter on your Element <square-box> (►parent element)

When you do this.button.setAttribute('content', val);

You are changing a attribute of your <button> Element (►child element)

This will never trigger the attributeChangedCallback of (►parent) <square-box>

because its attributes were not changed

You either have to go "up the DOM" with .getRootNode() and/or .host to set attributes of parent elements.

or use Custom Events (bubbling up the DOM) to notify parents that children have done/changed something

I presume you meant to do

set content(val) {
        //  loose ==null comparison for null AND undefined,
        //  element.content=null; will remove the attribute
        if (val==null)
            this.removeAttribute('content');
        else
        //  but you DO want .content(0) (0==false) set as "0"
            this.setAttribute('content', val);
    }


问:
javascript regular expression to check for IP addresses
I have several ip addresses like:

115.42.150.37

115.42.150.38

115.42.150.50

What type of regular expression should I write if I want to search for the all the 3 ip addresses? Eg, if I do 115.42.150.* (I will be able to search for all 3 ip addresses)

What I can do now is something like: /[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}/ but it can't seems to work well.

Thanks.

答:
Simple Method

```<code>const invalidIp = ipAddress
   .split(".")
   .map(ip => Number(ip) >= 0 && Number(ip) <= 255)
   .includes(false);

if(invalidIp){
 // IP address is invalid
 // throw error here
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Simple Method

const invalidIp = ipAddress
   .split(".")
   .map(ip => Number(ip) >= 0 && Number(ip) <= 255)
   .includes(false);

if(invalidIp){
 // IP address is invalid
 // throw error here
}


问:
How to fuse a small pandas.dataframe into a larger one based on values of a column?
I have two pandas.dataframe df1 and df2:

```<code>>>>import pandas as pd
>>>import numpy as np
>>>from random import random
>>>df1=pd.DataFrame({'x1':range(10), 'y1':np.repeat(0,10).tolist()})
>>>df2=pd.DataFrame({'x2':range(0,10,2), 'y2':[random() for _ in range(5)]})
>>>df1
   x1  y1
0   0   0
1   1   0
2   2   0
3   3   0
4   4   0
5   5   0
6   6   0
7   7   0
8   8   0
9   9   0
>>>df2
   x2        y2
0   0  0.075922
1   2  0.606703
2   4  0.272918
3   6  0.842641
4   8  0.576636
</code>```

Now I want to fuse df2 into df1. This is to say, I want to change the values of y1 in df1 into the values of y2 in df2 when the value of x1 in df1 is equal to the value of x2 in df2. The final result I need is like the following:

```<code>>>>df1
   x1        y1
0   0  0.075922
1   1  0
2   2  0.606703
3   3  0
4   4  0.272918
5   5  0
6   6  0.842641
7   7  0
8   8  0.576636
9   9  0
</code>```

Although I can use the follow codes to get the above result:

```<code>>>> for i in range(df1.shape[0]):
...     for j in range(df2.shape[0]):
...             if df1.iloc[i,0] == df2.iloc[j,0]:
...                     df1.iloc[i,1]=df2.iloc[j,1]
...
</code>```

I think there must be better ways to achieve this. Do you know what they are? Thank you in advance.

答:
Another method, adding the two dataframes together:

```<code># first give df2 the same column names as df2
df2.columns = ['x1','y1']

#now set 'x1' as the index for both dfs (since this is what you want to 'join' on)
df1 = df1.set_index('x1')
df2 = df2.set_index('x1')

print(df1)

   y1
x1
0    0
1    0
2    0
3    0
4    0
5    0
6    0
7    0
8    0
9    0

print(df2)

          y1
x1
0   0.525232
2   0.907628
4   0.612100
6   0.497420
8   0.656509

#now you can simply add the two df's to eachother
df_new = df1 + df2
print(df_new)

        y1
x1
0   0.317418
1        NaN
2   0.581443
3        NaN
4   0.728766
5        NaN
6   0.495450
7        NaN
8   0.171131
9        NaN
</code>```

Two problems:

The dataframe has NA's where you want 0's. These are the positions where df2 was not defined. Those positions were effectively equal to NA in df2, and NA + anything = NA. This can be fixed with a
fillna

You want 'x1' to be a column, not the index so just reset the index

```<code>df_new=df_new.reset_index().fillna(0)

print(df_new)

x1        y1
0   0  0.118903
1   1  0.000000
2   2  0.465557
3   3  0.000000
4   4  0.533266
5   5  0.000000
6   6  0.518484
7   7  0.000000
8   8  0.308733
9   9  0.000000
</code>```

Body:
I have two pandas.dataframe df1 and df2:

>>>import pandas as pd
>>>import numpy as np
>>>from random import random
>>>df1=pd.DataFrame({'x1':range(10), 'y1':np.repeat(0,10).tolist()})
>>>df2=pd.DataFrame({'x2':range(0,10,2), 'y2':[random() for _ in range(5)]})
>>>df1
   x1  y1
0   0   0
1   1   0
2   2   0
3   3   0
4   4   0
5   5   0
6   6   0
7   7   0
8   8   0
9   9   0
>>>df2
   x2        y2
0   0  0.075922
1   2  0.606703
2   4  0.272918
3   6  0.842641
4   8  0.576636

Now I want to fuse df2 into df1. This is to say, I want to change the values of y1 in df1 into the values of y2 in df2 when the value of x1 in df1 is equal to the value of x2 in df2. The final result I need is like the following:

>>>df1
   x1        y1
0   0  0.075922
1   1  0
2   2  0.606703
3   3  0
4   4  0.272918
5   5  0
6   6  0.842641
7   7  0
8   8  0.576636
9   9  0

Although I can use the follow codes to get the above result:

>>> for i in range(df1.shape[0]):
...     for j in range(df2.shape[0]):
...             if df1.iloc[i,0] == df2.iloc[j,0]:
...                     df1.iloc[i,1]=df2.iloc[j,1]
...

I think there must be better ways to achieve this. Do you know what they are? Thank you in advance.

Body:
Another method, adding the two dataframes together:

# first give df2 the same column names as df2
df2.columns = ['x1','y1']

#now set 'x1' as the index for both dfs (since this is what you want to 'join' on)
df1 = df1.set_index('x1')
df2 = df2.set_index('x1')

print(df1)

   y1
x1
0    0
1    0
2    0
3    0
4    0
5    0
6    0
7    0
8    0
9    0

print(df2)

          y1
x1
0   0.525232
2   0.907628
4   0.612100
6   0.497420
8   0.656509

#now you can simply add the two df's to eachother
df_new = df1 + df2
print(df_new)

        y1
x1
0   0.317418
1        NaN
2   0.581443
3        NaN
4   0.728766
5        NaN
6   0.495450
7        NaN
8   0.171131
9        NaN

Two problems:

The dataframe has NA's where you want 0's. These are the positions where df2 was not defined. Those positions were effectively equal to NA in df2, and NA + anything = NA. This can be fixed with a
fillna

You want 'x1' to be a column, not the index so just reset the index

df_new=df_new.reset_index().fillna(0)

print(df_new)

x1        y1
0   0  0.118903
1   1  0.000000
2   2  0.465557
3   3  0.000000
4   4  0.533266
5   5  0.000000
6   6  0.518484
7   7  0.000000
8   8  0.308733
9   9  0.000000


问:
How to create a leaflet choropleth map of US counties
With the code below I get my dataframe with US county data

```<code>library(raster)
library(leaflet)
library(tidyverse)

# Get USA polygon data
USA <- getData("GADM", country = "usa", level = 2)

### Get data
mydata <- read.csv("https://www.betydb.org/miscanthus_county_avg_yield.csv",
                   stringsAsFactors = FALSE)
</code>```

My object is to crate an interactive leaflet choropleth map of Avg_yield so first I fortify my USA polygon data

```<code>library(rgeos)
library(maptools)
library(ggplot2)
states.shp.f <- fortify(USA, region = "NAME_2")
</code>```

Then I subset my dataset and merge it with the fortified:

```<code>mydata2<-mydata[,c("COUNTY_NAME","Avg_yield")]
colnames(mydata2)[1]<-"id"

## merge shape file with data
merge.shp.coef <- merge(states.shp.f, mydata2, by = "id")
</code>```

but now I have a dataset with every county name many times and also some counties have different values of Avg_yield. Whats the proper way to process those data in order to use the leaflet code like:

```<code>leaflet() %>%
  addProviderTiles("OpenStreetMap.Mapnik") %>%
  setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
  addPolygons(data = USA, stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
              fillColor = ~mypal(mydata$Avg_yield),
              popup = paste("Region: ", USA$NAME_2, "<br>",
                            "Avg_yield: ", mydata$Avg_yield, "<br>")) %>%
  addLegend(position = "bottomleft", pal = mypal, values = mydata$Avg_yield,
            title = "Avg_yield",
            opacity = 1)
</code>```

答:
The propoer way to do this is to transform your polygon object into a sf object
with st_as_sf()

Here you have a working example :
(I did used some other data for the polygon, I thought yours too precise and require a lot of resources, plus I made it work with shiny)

```<code>library(leaflet)
library(tidyverse)
library(ggplot2)
library(sf)
library(shiny)

USA <- st_read(dsn = '[your path]/cb_2018_us_county_500k.shp')

### Get data
mydata <- read.csv("https://www.betydb.org/miscanthus_county_avg_yield.csv",
                   stringsAsFactors = FALSE)

states_sf <- st_as_sf(USA)

mydata2<-mydata[,c("COUNTY_NAME","Avg_yield")]
colnames(mydata2)[1]<-"NAME"

## merge shape file with data
states_sf_coef <- left_join(states_sf, mydata2, by = "NAME")

ui <- fluidPage(

  leafletOutput("map", height = "100vh")
)

server <- function(input, output, session) {

  bins <- c(0, 5, 10, 15, 20, 25, 30, 35, 40)
  mypal <- colorBin("YlOrRd", domain = states_sf_coef$Avg_yield, bins = bins)

  #Sortie map
  output$map <- renderLeaflet({
    leaflet()%>%
      addProviderTiles("OpenStreetMap.Mapnik")%>%
      setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
      addPolygons(
        data = states_sf_coef,
        fillColor = ~mypal(states_sf_coef$Avg_yield),
        stroke = FALSE,
        smoothFactor = 0.2,
        fillOpacity = 0.3,
        popup = paste("Region: ", states_sf_coef$NAME_2, "<br>",
                      "Avg_yield: ", states_sf_coef$Avg_yield, "<br>"))%>%
      addLegend(position = "bottomleft",
                pal = mypal,
                values = states_sf_coef$Avg_yield,
                title = "Avg_yield",
                opacity = 1)
  })

}

# Create Shiny app ----
shinyApp(ui = ui, server = server)
</code>```

Body:
With the code below I get my dataframe with US county data

library(raster)
library(leaflet)
library(tidyverse)

# Get USA polygon data
USA <- getData("GADM", country = "usa", level = 2)

### Get data
mydata <- read.csv("https://www.betydb.org/miscanthus_county_avg_yield.csv",
                   stringsAsFactors = FALSE)

My object is to crate an interactive leaflet choropleth map of Avg_yield so first I fortify my USA polygon data

library(rgeos)
library(maptools)
library(ggplot2)
states.shp.f <- fortify(USA, region = "NAME_2")

Then I subset my dataset and merge it with the fortified:

mydata2<-mydata[,c("COUNTY_NAME","Avg_yield")]
colnames(mydata2)[1]<-"id"

## merge shape file with data
merge.shp.coef <- merge(states.shp.f, mydata2, by = "id")

but now I have a dataset with every county name many times and also some counties have different values of Avg_yield. Whats the proper way to process those data in order to use the leaflet code like:

leaflet() %>%
  addProviderTiles("OpenStreetMap.Mapnik") %>%
  setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
  addPolygons(data = USA, stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
              fillColor = ~mypal(mydata$Avg_yield),
              popup = paste("Region: ", USA$NAME_2, "
",
                            "Avg_yield: ", mydata$Avg_yield, "
")) %>%
  addLegend(position = "bottomleft", pal = mypal, values = mydata$Avg_yield,
            title = "Avg_yield",
            opacity = 1)

Body:
The propoer way to do this is to transform your polygon object into a sf object
with st_as_sf()

Here you have a working example :
(I did used some other data for the polygon, I thought yours too precise and require a lot of resources, plus I made it work with shiny)

library(leaflet)
library(tidyverse)
library(ggplot2)
library(sf)
library(shiny)

USA <- st_read(dsn = '[your path]/cb_2018_us_county_500k.shp')

### Get data
mydata <- read.csv("https://www.betydb.org/miscanthus_county_avg_yield.csv",
                   stringsAsFactors = FALSE)

states_sf <- st_as_sf(USA)

mydata2<-mydata[,c("COUNTY_NAME","Avg_yield")]
colnames(mydata2)[1]<-"NAME"

## merge shape file with data
states_sf_coef <- left_join(states_sf, mydata2, by = "NAME")

ui <- fluidPage(

  leafletOutput("map", height = "100vh")
)

server <- function(input, output, session) {

  bins <- c(0, 5, 10, 15, 20, 25, 30, 35, 40)
  mypal <- colorBin("YlOrRd", domain = states_sf_coef$Avg_yield, bins = bins)

  #Sortie map
  output$map <- renderLeaflet({
    leaflet()%>%
      addProviderTiles("OpenStreetMap.Mapnik")%>%
      setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
      addPolygons(
        data = states_sf_coef,
        fillColor = ~mypal(states_sf_coef$Avg_yield),
        stroke = FALSE,
        smoothFactor = 0.2,
        fillOpacity = 0.3,
        popup = paste("Region: ", states_sf_coef$NAME_2, "<br>",
                      "Avg_yield: ", states_sf_coef$Avg_yield, "<br>"))%>%
      addLegend(position = "bottomleft",
                pal = mypal,
                values = states_sf_coef$Avg_yield,
                title = "Avg_yield",
                opacity = 1)
  })

}

# Create Shiny app ----
shinyApp(ui = ui, server = server)


问:
How to get active product's cancel subscription in In-App Purchase in iOS?
I've done successfully in-app purchase in my application with following demo: https://www.logisticinfotech.com/blog/ios-swift-in-app-subscription-with-receipt-validation

Issue: how to get the current active product which was canceled subscription with receipt data?

Thanks in advance.

答:
You get it the same way as they do with expiration_date in getExpirationDateFromResponse().

Note: The cancellation_date field is added to the receipt only when the subscription was canceled by Apple customer support.

Edit: How to get expiration_intent?

Based on the function getExpirationDateFromResponse(jsonResponse:) (from the link in your question) you could access expiration_intent like this:

```<code>guard let unifiedReceipt = jsonResponse["unified_receipt"] as? NSDictionary,
    let pendingRenewalInfos = unifiedReceipt["pending_renewal_info"] as? NSArray,
    let latestInfo = pendingRenewalInfos.firstObject as? NSDictionary,
    let expirationIntent = latestInfo["expiration_intent"] as? String else { fatalError("Couldn‘t determine expiration intent") }
print("expiration_intent \(expirationIntent)")
</code>```

Body:
You get it the same way as they do with expiration_date in getExpirationDateFromResponse().

Note: The cancellation_date field is added to the receipt only when the subscription was canceled by Apple customer support.

Edit: How to get expiration_intent?

Based on the function getExpirationDateFromResponse(jsonResponse:) (from the link in your question) you could access expiration_intent like this:

guard let unifiedReceipt = jsonResponse["unified_receipt"] as? NSDictionary,
    let pendingRenewalInfos = unifiedReceipt["pending_renewal_info"] as? NSArray,
    let latestInfo = pendingRenewalInfos.firstObject as? NSDictionary,
    let expirationIntent = latestInfo["expiration_intent"] as? String else { fatalError("Couldn‘t determine expiration intent") }
print("expiration_intent \(expirationIntent)")


问:
Transfer data from C# Class to XML File
I want to transfer a variable containing DateTime string to the XML file. Is there any way to access data from C# Class in XML File.

Here's my C# Code:

```<code>DateTime dt = DateTime.Today.AddHours(17);
string datetime = dt.ToString("yyyy-MM-ddTHH:mm:ss");
</code>```

Here's my XML Code where I need to access this data string:

```<code><ProductLastModifiedDate>2020-02-21T09:00:00+05:30</ProductLastModifiedDate>
</code>```

In the above XML Code I want to set dateTime retrieved from C# class file.

答:
Another approach is using XmlDocument

```<code>DateTime dt = DateTime.Today.AddHours(17);
string datetime = dt.ToString("yyyy-MM-ddTHH:mm:ss");

var xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
xmlDoc.SelectSingleNode("ProductLastModifiedDate").InnerText = datetime;
xmlDoc.Save(filePath);
</code>```

OUTPUT

```<code><ProductLastModifiedDate>2020-02-20T17:00:00</ProductLastModifiedDate>
</code>```

Title: Transfer data from C# Class to XML File

Body:
I want to transfer a variable containing DateTime string to the XML file. Is there any way to access data from C# Class in XML File.

Here's my C# Code:

DateTime dt = DateTime.Today.AddHours(17);
string datetime = dt.ToString("yyyy-MM-ddTHH:mm:ss");

Here's my XML Code where I need to access this data string:

<ProductLastModifiedDate>2020-02-21T09:00:00+05:30</ProductLastModifiedDate>

In the above XML Code I want to set dateTime retrieved from C# class file.

Body:
Another approach is using XmlDocument

DateTime dt = DateTime.Today.AddHours(17);
string datetime = dt.ToString("yyyy-MM-ddTHH:mm:ss");

var xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
xmlDoc.SelectSingleNode("ProductLastModifiedDate").InnerText = datetime;
xmlDoc.Save(filePath);

OUTPUT

<ProductLastModifiedDate>2020-02-20T17:00:00</ProductLastModifiedDate>


问:
Am trying to check if the student ClassID and the Class_Schedule ClassID match

var sched = db.Class_Schedule.Select(p=>p.ClassID);

var classStudents = db.Students.Where(p => p.Enrollments.Select(q=>q.ClassID).Equals(sched));
return View(classStudents.ToList());
```

I am trying to check the ClassID of the student through the enrollment table and see if it matches with the ClassID of the Class_Schedule table.

This is the exception I am getting:

'System.NotSupportedException: 'Cannot compare elements of type 'System.Collections.Generic.IEnumerable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types, enumeration types and entity types are supported.''

答:
use the Intersect

var sched = db.Class_Schedule.Select(p => p.ClassID).ToList();
var classStudents = db.Students.Where(p => p.Enrollments.Select(q=>q.ClassID).ToList().Intersect(sched).Any());
```

Body:
var sched = db.Class_Schedule.Select(p=>p.ClassID);

var classStudents = db.Students.Where(p => p.Enrollments.Select(q=>q.ClassID).Equals(sched));
return View(classStudents.ToList());

I am trying to check the ClassID of the student through the enrollment table and see if it matches with the ClassID of the Class_Schedule table.

This is the exception I am getting:

'System.NotSupportedException: 'Cannot compare elements of type 'System.Collections.Generic.IEnumerable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types, enumeration types and entity types are supported.''


问:
Can NSScrollView scroll if setHasHorizontalScroller:NO?
Is it possible to 'hide' the scrollers of an NSScrollView and still get gestural scrolling behavior?</p>

答:
Why don't you just try it?

To answer the question: Yes, if the user has mouse with a scroll wheel or a a scrolling-capable touchpad, it is still possible to scroll the view, despite the scrollers being invisible.

ContentLicense: CC BY-SA 3.0


问:
Is firebase functions.https.onCall a background function?
I am looking at rate limiting quotas on firebase for a singular busy function (called when logging in) and saw that there is a 1000 limit for background functions.
https://firebase.google.com/docs/functions/quotas#additional_quotas_for_background_functions

I just want to check that functions.https.onCall is a https function and not a background function, thus not being limited. If 1000 people all load their data at one, I don't want it to fall over.

答:
I found it in Google Cloud Functions documentation. The definition is:

You use background functions when you want to have your Cloud Function invoked indirectly in response to an event, such as a message on a Pub/Sub topic, a change in a Cloud Storage bucket, or a Firebase event.

This depends on your trigger. If you invoke your function via http call its not background function for sure.

I hope it will help!


问:
Is it possible to remove a class from an imported gradle library?
I'm searching and trying already one day long to remove a class from an imported library over gradle without really getting it to work, should this be possible with Android+gradle? How to do this?

For example if I include a library like so:

```<code>implementation 'org.bouncycastle:bcpkix-jdk15on:1.64'
</code>```

How to remove a class by name from it? The latest thing I tried was setting in build.gradle:

```<code>android {
  sourceSets.main.java.filter.exclude '**/QTeslaKeyEncodingTests.*'
}
</code>```

Following also doesn't work:

```<code>jar {
    sourceSets {
        main {
            java {
                exclude '**/QTeslaKeyEncodingTests.java'
                exclude '**/QTeslaKeyEncodingTests.class'
            }
        }
    }
}
</code>```

This also doesn't:

```<code>android{
  packagingOptions {
    exclude 'org.bouncycastle/pqc/crypto/qtesla/QTeslaKeyEncodingTests.class'
  }
}
</code>```

Context: why do I need this currently: when you execute "gradlew testDebug" all tests in the project run, including those present in the imported libs. I also don't know if this is a bug from bouncyCastle that they included those tests in the library but it's a problem because many tests fail.

答:
Use this code to exclude files from test target as you are interested in excluding the files while running your tests. </p>

```<code>sourceSets {

     androidTest {
         java {
             exclude '**/QTeslaKeyEncodingTests.java'
             exclude '**/QTeslaKeyEncodingTests.class'
        }
     }
  }
</code>```

Body:
I'm searching and trying already one day long to remove a class from an imported library over gradle without really getting it to work, should this be possible with Android+gradle? How to do this?

For example if I include a library like so:

implementation 'org.bouncycastle:bcpkix-jdk15on:1.64'

How to remove a class by name from it? The latest thing I tried was setting in build.gradle:

android {
  sourceSets.main.java.filter.exclude '**/QTeslaKeyEncodingTests.*'
}

Following also doesn't work:

jar {
    sourceSets {
        main {
            java {
                exclude '**/QTeslaKeyEncodingTests.java'
                exclude '**/QTeslaKeyEncodingTests.class'
            }
        }
    }
}

This also doesn't:

android{
  packagingOptions {
    exclude 'org.bouncycastle/pqc/crypto/qtesla/QTeslaKeyEncodingTests.class'
  }
}

Context: why do I need this currently: when you execute "gradlew testDebug" all tests in the project run, including those present in the imported libs. I also don't know if this is a bug from bouncyCastle that they included those tests in the library but it's a problem because many tests fail.

Body:
Use this code to exclude files from test target as you are interested in excluding the files while running your tests.

sourceSets {

     androidTest {
         java {
             exclude '**/QTeslaKeyEncodingTests.java'
             exclude '**/QTeslaKeyEncodingTests.class'
        }
     }
  }


问:
is it possible to set focus for element?
I have two element on the page:

```<code> <input tabindex="0" type="text" (keydown)="keydownInputSearch($event)" (click)="showSearchResultContent = !showSearchResultContent" #inputSearch>
</code>```

And block:

```<code> <div #searchList class="SearchList" *ngIf="showSearchResult()" tabindex="-1"></div>
</code>```

Problem is when block #searchLis is exist I can not set focus back to #inputSearch.

I have tried:

```<code> this.inputSearch.nativeElement.focus();
</code>```

No errors, no effect. I suppose problem is that #searchList has tabindex="-1" and #inputSearchhas less:  tabindex="0".

But by defaul input should have focus automatically.

答:
You're almost there. Just focus on the input in ngAfterViewInit

```<code> ngAfterViewInit() {
   this.inputSearch.nativeElement.focus();
 }
</code>```

Stackblitz: https://stackblitz.com/edit/hello-angular-6-1svrgt

Body:
I have two element on the page:

 <input tabindex="0" type="text" (keydown)="keydownInputSearch($event)" (click)="showSearchResultContent = !showSearchResultContent" #inputSearch>

And block:

Problem is when block #searchLis is exist I can not set focus back to #inputSearch.

I have tried:

 this.inputSearch.nativeElement.focus();

No errors, no effect. I suppose problem is that #searchList has tabindex="-1" and #inputSearchhas less:  tabindex="0".

But by defaul input should have focus automatically.

Body:
You're almost there. Just focus on the input in ngAfterViewInit

 ngAfterViewInit() {
   this.inputSearch.nativeElement.focus();
 }

Stackblitz: https://stackblitz.com/edit/hello-angular-6-1svrgt


问:
Restore a node after being purged due to resources pressure
I have a k8s cluster setup using kubespray.

Last week one of my k8s nodes have very low storage, so all the pods has been evicted, include some important pods like calico-node, kube-proxy (I thought that these pods are critical and never been evicted no matter what)

After that all the calico-node pods become not ready, when I check the log, it is said that:
Warning: Readiness probe failed: calico/node is not ready: BIRD is not ready: BGP not established with 192.168.0.xxx, where 192.168.0.xxx is the IP of above problematic node.

My question is how can I restore that node? is it safe to just run the kubespray's cluster.yml again?

My k8s version is v1.13.3

Thanks.

答:
When node has a disk pressure its status changes to NotReady and a taint is added to the node: Taints: node.kubernetes.io/disk-pressure:NoSchedule.

All pods running on this node are getting evicted, except api-server, kube-controller and kube-scheduler- eviction manager will save those pods from getting evicted with error message: cannot evict a critical static pod [...]

Once the node is freed from disk pressure it will change its status to Ready and previously added taint will be removed. You can check it by running kubectl describe node <node_name>. In the conditions field you should see that DiskPressure has changed status to False which means that node has enough space available. Similar information can be also found in Events field.

```<code>  Normal   NodeReady                1s                     kubelet, node1     Node node1 status is now: NodeReady
  Normal   NodeHasNoDiskPressure    1s (x2 over 1s)        kubelet, node1     Node node1 status is now: NodeHasNoDiskPressure
</code>```

After confirming that the node is ready with sufficient disk space you can restart kubelet and run kubespray's cluster.yml- the pods will be redeployed on the node. You just have to make sure that node is ready to handle deployments.

Body:
When node has a disk pressure its status changes to NotReady and a taint is added to the node: Taints: node.kubernetes.io/disk-pressure:NoSchedule.

All pods running on this node are getting evicted, except api-server, kube-controller and kube-scheduler- eviction manager will save those pods from getting evicted with error message: cannot evict a critical static pod [...]

Once the node is freed from disk pressure it will change its status to Ready and previously added taint will be removed. You can check it by running kubectl describe node <node_name>. In the conditions field you should see that DiskPressure has changed status to False which means that node has enough space available. Similar information can be also found in Events field.

  Normal   NodeReady                1s                     kubelet, node1     Node node1 status is now: NodeReady
  Normal   NodeHasNoDiskPressure    1s (x2 over 1s)        kubelet, node1     Node node1 status is now: NodeHasNoDiskPressure

After confirming that the node is ready with sufficient disk space you can restart kubelet and run kubespray's cluster.yml- the pods will be redeployed on the node. You just have to make sure that node is ready to handle deployments.


问:
How to run sequential Tasks in an ExecutorService
I would like to execute different tasks for each player in an event executor, but make sure that the tasks submitted for each player are in order. Here is a picture to hopefully explain in better.

Extra Information:

I know which player will be effected for each task

I receive the tasks for each player in a pseudo-random order. (I will not know the order of task input before hand)

I need each player to basically have their own "thread" so that their tasks execute in order of insertion.

What I have tried:

Currently I am using Executors.newSingleThreadExecutor() inside of each player object to mimic this functionality, but I don't think this will scale well with a lot of players. Hence why I am asking here to find a better method.

答:
You can just create a singleEventExecutorService for each player.

```<code>class PlayerEventHandler {
    private Map<Player, ExecutorService> executors = new ConcurrentHashMap<>();

    public void handleEvent(PlayerEvent e) {
        ExecutorService executor = executors.computeIfAbsent(e.getPlayer(), Executors.newSingleThreadExecutor());
        executor.submit(e.execute());
    }
}
</code>```

Although this would probably behave much worse for 600 players than a single thread executor. However, you can probably group the players in some way so that a reasonable amount of players share an executor.

```<code>class PlayerEventHandler {
    private Map<PlayerGroup, ExecutorService> executors = new ConcurrentHashMap<>();

    public void handleEvent(PlayerEvent e) {
        PlayerGroup group = determineGroup(e.getPlayer());
        ExecutorService executor = executors.computeIfAbsent(group, Executors.newSingleThreadExecutor());
        executor.submit(e.execute());
    }
}
</code>```

This will probably become a problem if the players change dynamically during runtime, because then you can end up with a single thread handling a lot of players, while another group has become empty over time.

It really depends on your actual case.

Body:
You can just create a singleEventExecutorService for each player.

class PlayerEventHandler {
    private Map<Player, ExecutorService> executors = new ConcurrentHashMap<>();

    public void handleEvent(PlayerEvent e) {
        ExecutorService executor = executors.computeIfAbsent(e.getPlayer(), Executors.newSingleThreadExecutor());
        executor.submit(e.execute());
    }
}

Although this would probably behave much worse for 600 players than a single thread executor. However, you can probably group the players in some way so that a reasonable amount of players share an executor.

class PlayerEventHandler {
    private Map<PlayerGroup, ExecutorService> executors = new ConcurrentHashMap<>();

    public void handleEvent(PlayerEvent e) {
        PlayerGroup group = determineGroup(e.getPlayer());
        ExecutorService executor = executors.computeIfAbsent(group, Executors.newSingleThreadExecutor());
        executor.submit(e.execute());
    }
}

This will probably become a problem if the players change dynamically during runtime, because then you can end up with a single thread handling a lot of players, while another group has become empty over time.

It really depends on your actual case.


问:
python/django - "Cannot use ImageField because Pillow is not installed"
I'm joining a project, so I want to set up the environnment, so what I did is :

```<code>pip install -r requirements.txt
</code>```

This fully installed all requirements including django 1.7.0, Pillow 2.4.0 and some others.

Then I want to build the database :

```<code>python manage.py migrate
</code>```

And boom, error, I get the following :

```<code>CommandError: System check identified some issues:

ERRORS:
stu.chan.icon: (fields.E210) Cannot use ImageField because Pillow is not installed.
    HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install pillow".
stu.chan.image: (fields.E210) Cannot use ImageField because Pillow is not installed.
    HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install pillow".
stu.Piec.icon: (fields.E210) Cannot use ImageField because Pillow is not installed.
    HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install pillow".
</code>```

... like I didn't install Pillow.
So I checked the installed package (with this technique), and Pillow 2.4.0 IS installed.

Then, I also tried to force reinstall : pip install --upgrade --force-reinstall Pillow==2.4.0

But, nothing to do I get the same error when running migrate.

I'm using python 3.4.0 and django 1.7.0 on a mac OS X 10.6.7 wrapped in virtualenv 1.11.6 with pip downgraded to pip 1.2.1 (because of some well-known-yet-not-fully-resolved-nor-understood issue with pip and ssl).

All of the code above is within virtualenv (bin/activate done).

Do you have any ideas on why this problem and how to resolve it?

- - - - - - EDIT - - - - - -

When I run the above force-reinstall command, (so many code gets outpouted I can't paste it all but) although it finishes with "Successfully installed Pillow", there's some warnings in the code :

```<code>building 'PIL._imaging' extension
 (blabla code)
    _imaging.c:975:13: warning: array index of '1' indexes past the end of an array (that contains 1 elements) [-Warray-bounds]
        value = PyTuple_GET_ITEM(xy, 1);
                ^~~~~~~~~~~~~~~~~~~~~~~
    /usr/local/include/python3.4m/tupleobject.h:58:34: note: instantiated from:
    #define PyTuple_GET_ITEM(op, i) (((PyTupleObject *)(op))->ob_item[i])
                                     ^
    /usr/local/include/python3.4m/tupleobject.h:27:5: note: array 'ob_item' declared here
        PyObject *ob_item[1];
        ^
    1 warning generated.

(blabla code)
   libImaging/Unpack.c:867:1: warning: unused function 'copy3' [-Wunused-function]
    copy3(UINT8* out, const UINT8* in, int pixels)
    ^
    1 warning generated.
</code>```

答:
What worked for me was to uninstall Pillow from user folder and install it with sudo.

Initial install was:

```<code>$ pip3 install Pillow --user
</code>```

installed to: ~/.local/lib/python3.7/site-packages/Pillow-7.0.0.dist-info

So first uninstalled it and then installed with sudo:

```<code>$ pip3 uninstall Pillow
$ sudo pip3 install Pillow
</code>```

new location: /usr/local/lib64/python3.7/site-packages/Pillow-7.0.0.dist-info and problem was fixed.

Body:
I'm joining a project, so I want to set up the environnment, so what I did is :

pip install -r requirements.txt

This fully installed all requirements including django 1.7.0, Pillow 2.4.0 and some others.

Then I want to build the database :

python manage.py migrate

And boom, error, I get the following :

CommandError: System check identified some issues:

ERRORS:
stu.chan.icon: (fields.E210) Cannot use ImageField because Pillow is not installed.
    HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install pillow".
stu.chan.image: (fields.E210) Cannot use ImageField because Pillow is not installed.
    HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install pillow".
stu.Piec.icon: (fields.E210) Cannot use ImageField because Pillow is not installed.
    HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install pillow".

... like I didn't install Pillow.
So I checked the installed package (with this technique), and Pillow 2.4.0 IS installed.

Then, I also tried to force reinstall : pip install --upgrade --force-reinstall Pillow==2.4.0

But, nothing to do I get the same error when running migrate.

I'm using python 3.4.0 and django 1.7.0 on a mac OS X 10.6.7 wrapped in virtualenv 1.11.6 with pip downgraded to pip 1.2.1 (because of some well-known-yet-not-fully-resolved-nor-understood issue with pip and ssl).

All of the code above is within virtualenv (bin/activate done).

Do you have any ideas on why this problem and how to resolve it?

- - - - - - EDIT - - - - - -

When I run the above force-reinstall command, (so many code gets outpouted I can't paste it all but) although it finishes with "Successfully installed Pillow", there's some warnings in the code :

building 'PIL._imaging' extension
 (blabla code)
    _imaging.c:975:13: warning: array index of '1' indexes past the end of an array (that contains 1 elements) [-Warray-bounds]
        value = PyTuple_GET_ITEM(xy, 1);
                ^~~~~~~~~~~~~~~~~~~~~~~
    /usr/local/include/python3.4m/tupleobject.h:58:34: note: instantiated from:
    #define PyTuple_GET_ITEM(op, i) (((PyTupleObject *)(op))->ob_item[i])
                                     ^
    /usr/local/include/python3.4m/tupleobject.h:27:5: note: array 'ob_item' declared here
        PyObject *ob_item[1];
        ^
    1 warning generated.

(blabla code)
   libImaging/Unpack.c:867:1: warning: unused function 'copy3' [-Wunused-function]
    copy3(UINT8* out, const UINT8* in, int pixels)
    ^
    1 warning generated.

Body:
What worked for me was to uninstall Pillow from user folder and install it with sudo.

Initial install was:

$ pip3 install Pillow --user

installed to: ~/.local/lib/python3.7/site-packages/Pillow-7.0.0.dist-info

So first uninstalled it and then installed with sudo:

$ pip3 uninstall Pillow
$ sudo pip3 install Pillow

new location: /usr/local/lib64/python3.7/site-packages/Pillow-7.0.0.dist-info and problem was fixed.


问:
Bigger value without greater than or less than operators
this is just for fun.

Can you give me a way to determine the greater value of two numbers? You can use other operators except greater than or less than operator.

Use any tool you like (programming language, pencil paper, etc.).
And another thing you cannot do the following:

int main()
{
    int num1, num2;
    cin >> num1 >> num2;

    if( (num1-num2) + abs(num1-num2) )
        cout << num1 << " is bigger" << endl;
    else
        cout << num2 << " is bigger" << endl;
    return 0;
}
```

答:
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>

cout << std::max(num1, num2) << " is bigger" << endl;
</code>```


答:
sched in your example is of type IEnumerable<string>, and the result of p.Enrollments.Select(q=>q.ClassID) is too. However, .Equals() can only compare, as your error states, primitive types (string, int, etc) but you're calling it on an IEnumerable with an IEnumerable argument so it fails.

What you want to do, is search through Students where they have Any enrollment that's in their schedule. So instead try

```<code>var classStudents = db.Students.Where(s => s.Enrollments.Any(e => sched.Contains(e.ClassID)));
</code>```

Title: Am trying to check if the student ClassID and the Class_Schedule ClassID match

Body:
sched in your example is of type IEnumerable<string>, and the result of p.Enrollments.Select(q=>q.ClassID) is too. However, .Equals() can only compare, as your error states, primitive types (string, int, etc) but you're calling it on an IEnumerable with an IEnumerable argument so it fails.

What you want to do, is search through Students where they have Any enrollment that's in their schedule. So instead try

var classStudents = db.Students.Where(s => s.Enrollments.Any(e => sched.Contains(e.ClassID)));


问:
iOS Web App: Use back swipe gesture to go back
I adapted my website according to the official guide over at

https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html

Since I made the changes my website looks like an app when I add it as a bookmark to the homescreen. However, my web app relies on the go-back button/gesture even if there is no page refresh. But the gesture does not work out of the box. What can I do to activate it? I read that iOS 12.2 should support the gesture.

答:
This should work when you set your display to standalone in your webmanifest.

Checkout this link for more documentation:
https://developer.mozilla.org/en-US/docs/Web/Manifest#display


问:
Java regex split on whitespace /not preceded
I would like to split  a string:"x=   2-3   y=3 z=   this,   that"
I would split this up on one or more whitespaces, that are not preceded by a '=' or a ','
meaning group one: "x=   2-3"
              two: "y=3"
              three: "z=   this,   that"
I have an expression that kinda does it but its only good if = or , has only one whitespace after it.

```<code>(?<![,=])\\s+
</code>```

答:
If you want to use the negative lookahead, you could assert what is on the left is a pattern which would match for example x=   2-3 and match the following whitespace chars.

Use a negated character class [^\\h=,] to match any char except what it listed.

```<code>(?<=[^\\h=,]=\\h{0,100}[^\\h=,]{1,100})\\h+
</code>```

Regex demo | Java demo

The regex demo has a different engine selected only to show the matches.

In Java you have to use double escapes and you could use \h to match 1+ horizontal whitespace chars in stead of \s

Java does not support infinite width in a lookbehind, but does support a finite width.

For example

```<code>String s = "x=   2-3   y=3 z=   this,   that";
String regex = "(?<=[^\\h=,]=\\h{0,100}[^\\h=,]{1,100})\\h+";
String parts[] = s.split(regex);

for (String part : parts)
    System.out.println(part);
</code>```

Output

```<code>x=   2-3
y=3
z=   this,   that
</code>```

Body:
I would like to split  a string:"x=   2-3   y=3 z=   this,   that"
I would split this up on one or more whitespaces, that are not preceded by a '=' or a ','
meaning group one: "x=   2-3"
              two: "y=3"
              three: "z=   this,   that"
I have an expression that kinda does it but its only good if = or , has only one whitespace after it.

(?<![,=])\\s+

Body:
If you want to use the negative lookahead, you could assert what is on the left is a pattern which would match for example x=   2-3 and match the following whitespace chars.

Use a negated character class [^\\h=,] to match any char except what it listed.

(?<=[^\\h=,]=\\h{0,100}[^\\h=,]{1,100})\\h+

Regex demo | Java demo

The regex demo has a different engine selected only to show the matches.

In Java you have to use double escapes and you could use \h to match 1+ horizontal whitespace chars in stead of \s

Java does not support infinite width in a lookbehind, but does support a finite width.

For example

String s = "x=   2-3   y=3 z=   this,   that";
String regex = "(?<=[^\\h=,]=\\h{0,100}[^\\h=,]{1,100})\\h+";
String parts[] = s.split(regex);

for (String part : parts)
    System.out.println(part);

Output

x=   2-3
y=3
z=   this,   that


问:
Conditional formatting in excel based on previous left cell
I have table like this.

I want to conditionally format columns worked hours where worked hours are 1,5 less then existing Capacity In Hours, and to get table like this

答: Depending on which version of Excel you are using you can simply click on Conditional Formatting -> New Rule -> Use a formula to determine which cells to format then simply add the relevant formula (referencing the cell on the left) in the Format values where this formula is true box


问:
Is there a lax, permissive XML parser for PHP?
I'm looking for a parser that will allow me to successfully parse broken xml, taking a "best guess" approach - for instance.

```<code>    <thingy>
       <description>
           something <b>with</b> bogus<br>
           markup not wrapped in CDATA
       </description>
    </thingy>
</code>```

Ideally, it will yield a thingy object, with a description property and whatever tag soup inside.

Other suggestions on how to attack the problem (other than having valid markup to start with) welcome.

Non-php solutions (Beautiful Soup (python) for instance) are not outside the pale, but I'd prefer to stick to the prevailing skill-set in the company

Thanks!

答:
You could use DOMDocument::loadHTML() (or DOMDocument::loadhtmlfile()) to convert your broken XML to proper XML. If you don't like dealing with DOMDocument objectsThen use saveXML() and load the resulting XML string with SimpleXML.

```<code>$dom = DOMDocument::loadHTMLfile($filepath);
if (!$dom)
{
    throw new Exception("Could not load the lax XML file");
}
// Now you can work with your XML file using the $dom object.

// If you'd like using SimpleXML, do the following steps.
$xml = new SimpleXML($dom->saveXML());
unset($dom);
</code>```

I've tried this script:

```<code><?php
$dom = new DOMDocument();
$dom->loadHTMLFile('badformatted.xml');
if (!$dom)
{
    die('error');
}
$nodes = $dom->getElementsByTagName('description');
for ($i = 0; $i < $nodes->length; $i++)
{
    echo "Node content: ".$nodes->item($i)->textContent."\n";
}
</code>```

The output when executing this from the CLI:

```<code>carlos@marmolada:~/xml$ php test.php

Warning: DOMDocument::loadHTMLFile(): Tag thingy invalid in badformatted.xml, line: 1 in /home/carlos/xml/test.php on line 3

Warning: DOMDocument::loadHTMLFile(): Tag description invalid in badformatted.xml, line: 2 in /home/carlos/xml/test.php on line 3
Node content:
                something with bogus
                markup not wrapped in CDATA

carlos@marmolada:~/xml$
</code>```

edit: some minor corrections and error treatment.

edit2: Change to non-static call to avoid E_STRICT error, added test case.

Body:
I'm looking for a parser that will allow me to successfully parse broken xml, taking a "best guess" approach - for instance.

    <thingy>
       <description>
           something with bogus

           markup not wrapped in CDATA
       </description>
    </thingy>

Ideally, it will yield a thingy object, with a description property and whatever tag soup inside.

Other suggestions on how to attack the problem (other than having valid markup to start with) welcome.

Non-php solutions (Beautiful Soup (python) for instance) are not outside the pale, but I'd prefer to stick to the prevailing skill-set in the company

Thanks!

Body:
You could use DOMDocument::loadHTML() (or DOMDocument::loadhtmlfile()) to convert your broken XML to proper XML. If you don't like dealing with DOMDocument objectsThen use saveXML() and load the resulting XML string with SimpleXML.

$dom = DOMDocument::loadHTMLfile($filepath);
if (!$dom)
{
    throw new Exception("Could not load the lax XML file");
}
// Now you can work with your XML file using the $dom object.

// If you'd like using SimpleXML, do the following steps.
$xml = new SimpleXML($dom->saveXML());
unset($dom);

I've tried this script:

<?php
$dom = new DOMDocument();
$dom->loadHTMLFile('badformatted.xml');
if (!$dom)
{
    die('error');
}
$nodes = $dom->getElementsByTagName('description');
for ($i = 0; $i < $nodes->length; $i++)
{
    echo "Node content: ".$nodes->item($i)->textContent."\n";
}

The output when executing this from the CLI:

carlos@marmolada:~/xml$ php test.php

Warning: DOMDocument::loadHTMLFile(): Tag thingy invalid in badformatted.xml, line: 1 in /home/carlos/xml/test.php on line 3

Warning: DOMDocument::loadHTMLFile(): Tag description invalid in badformatted.xml, line: 2 in /home/carlos/xml/test.php on line 3
Node content:
                something with bogus
                markup not wrapped in CDATA

carlos@marmolada:~/xml$

edit: some minor corrections and error treatment.

edit2: Change to non-static call to avoid E_STRICT error, added test case.