问:
Unit testing an AuthorizeAttribute on an ASP.NET Core MVC API controller
I have a ASP.NET Core MVC API with controllers that need to be unit tested.

Controller:

```<code>using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace TransitApi.Api.Controllers
{
    [Route("api/foo")]
    public class FooController : Controller
    {
        private IFooRepository FooRepository { get; }

        public FooController(IFooRepository fooRepository)
        {
            FooRepository = fooRepository;
        }

        [HttpGet]
        [Authorize("scopes:getfoos")]
        public async Task<IActionResult> GetAsync()
        {
            var foos = await FooRepository.GetAsync();
            return Json(foos);
        }
    }
}
</code>```

It is essential that I am able to unit test the effectiveness of the AuthorizeAttribute. We have had issues in our code base with missing attributes and incorrect scopes. This answer is exactly what I am looking for, but not having a ActionInvoker method in Microsoft.AspNetCore.Mvc.Controller means I am not able to do it this way.

Unit Test:

```<code>[Fact]
public void GetAsync_InvalidScope_ReturnsUnauthorizedResult()
{
    // Arrange
    var fooRepository = new StubFooRepository();
    var controller = new FooController(fooRepository)
    {
        ControllerContext = new ControllerContext
        {
            HttpContext = new FakeHttpContext()
            // User unfortunately not available in HttpContext
            //,User = new User() { Scopes = "none" }
        }
    };

    // Act
    var result = controller.GetAsync().Result;

    // Assert
    Assert.IsType<UnauthorizedResult>(result);
}
</code>```

How can I unit test that users without the correct scopes are denied access to my controller method?

Currently I have settled for testing merely the presence of an AuthorizeAttribute as follows, but this is really not good enough:

```<code>    [Fact]
    public void GetAsync_Analysis_HasAuthorizeAttribute()
    {
        // Arrange
        var fooRepository = new StubFooRepository();
        var controller = new FooController(fooRepository)
        {
            ControllerContext = new ControllerContext
            {
                HttpContext = new FakeHttpContext()
            }
        };

        // Act
        var type = controller.GetType();
        var methodInfo = type.GetMethod("GetAsync", new Type[] { });
        var attributes = methodInfo.GetCustomAttributes(typeof(AuthorizeAttribute), true);

        // Assert
        Assert.True(attributes.Any());
    }
</code>```

答:
First remeove IAuthorizationHandler

```<code>var authorizationDescriptor = services.FirstOrDefault(d => d.ServiceType == typeof(IAuthorizationHandler));
                if (authorizationDescriptor != null)
                    services.Remove(authorizationDescriptor);
</code>```

Then add

```<code>services.AddScoped<IAuthorizationHandler, TestAllowAnonymous>();

public class TestAllowAnonymous : IAuthorizationHandler
        {
            public Task HandleAsync(AuthorizationHandlerContext context)
            {
                foreach (IAuthorizationRequirement requirement in context.PendingRequirements.ToList())
                    context.Succeed(requirement); //Simply pass all requirementsreturn Task.CompletedTask;
                return Task.CompletedTask;
            }

        }
</code>```

Body:
I have a ASP.NET Core MVC API with controllers that need to be unit tested.

Controller:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace TransitApi.Api.Controllers
{
    [Route("api/foo")]
    public class FooController : Controller
    {
        private IFooRepository FooRepository { get; }

        public FooController(IFooRepository fooRepository)
        {
            FooRepository = fooRepository;
        }

        [HttpGet]
        [Authorize("scopes:getfoos")]
        public async Task<IActionResult> GetAsync()
        {
            var foos = await FooRepository.GetAsync();
            return Json(foos);
        }
    }
}

It is essential that I am able to unit test the effectiveness of the AuthorizeAttribute. We have had issues in our code base with missing attributes and incorrect scopes. This answer is exactly what I am looking for, but not having a ActionInvoker method in Microsoft.AspNetCore.Mvc.Controller means I am not able to do it this way.

Unit Test:

[Fact]
public void GetAsync_InvalidScope_ReturnsUnauthorizedResult()
{
    // Arrange
    var fooRepository = new StubFooRepository();
    var controller = new FooController(fooRepository)
    {
        ControllerContext = new ControllerContext
        {
            HttpContext = new FakeHttpContext()
            // User unfortunately not available in HttpContext
            //,User = new User() { Scopes = "none" }
        }
    };

    // Act
    var result = controller.GetAsync().Result;

    // Assert
    Assert.IsType<UnauthorizedResult>(result);
}

How can I unit test that users without the correct scopes are denied access to my controller method?

Currently I have settled for testing merely the presence of an AuthorizeAttribute as follows, but this is really not good enough:

    [Fact]
    public void GetAsync_Analysis_HasAuthorizeAttribute()
    {
        // Arrange
        var fooRepository = new StubFooRepository();
        var controller = new FooController(fooRepository)
        {
            ControllerContext = new ControllerContext
            {
                HttpContext = new FakeHttpContext()
            }
        };

        // Act
        var type = controller.GetType();
        var methodInfo = type.GetMethod("GetAsync", new Type[] { });
        var attributes = methodInfo.GetCustomAttributes(typeof(AuthorizeAttribute), true);

        // Assert
        Assert.True(attributes.Any());
    }

Body:
First remeove IAuthorizationHandler

var authorizationDescriptor = services.FirstOrDefault(d => d.ServiceType == typeof(IAuthorizationHandler));
                if (authorizationDescriptor != null)
                    services.Remove(authorizationDescriptor);

Then add

services.AddScoped<IAuthorizationHandler, TestAllowAnonymous>();

public class TestAllowAnonymous : IAuthorizationHandler
        {
            public Task HandleAsync(AuthorizationHandlerContext context)
            {
                foreach (IAuthorizationRequirement requirement in context.PendingRequirements.ToList())
                    context.Succeed(requirement); //Simply pass all requirementsreturn Task.CompletedTask;
                return Task.CompletedTask;
            }

        }


来源: stackexchange

问:
How to trace the source error of ERROR TypeError: You provided 'undefined' where a stream was expected?
I know this error has been talked about many times - but in my case i really don't know how to start debugging it since i have a component with a lot of subscriptions and i can't trace it's source... any help will do.

I'm using catchError for all the subscriptions and i guess it's not that kind of error...

Here is an example of how i'm implementing the subscriptions:

```<code> this.subs.push(this.apiService.isWorkListLayout$.pipe(
  tap(res => {
    this.formSrv.isDoneLoadingApache$.next(false);
    this.isWorkListLayout = res;
  }),
  switchMap(() => this.apiService.userDataForDialog$),
  tap(patientObj => {
    this.patient = patientObj;
  }),
  switchMap(() => this.isWorkListLayout ? this.apiService.getUsersComponentsData(this.patient) : EMPTY),
  catchError((err) => {
    throw 'Error in source. Details: ' + err;
  })
).subscribe((response) => {
  if (!!response && _.has(response, 'components')) {
    this.filterForm.reset();
    this.setPlaceHolderToFields(response.components, true);

    const formModeData = {
      areEditable: true,
      shouldApacheScoreCalc: true,
    };
    this.formSrv.isDoneLoadingApache$.next(true);
    this.formSrv.setFormMode(this.filterForm, formModeData);
  }
}));
</code>```

答:
Maybe there is a http interceptor that returns undefined in some cases. I just looked at the issue here: https://github.com/ngx-translate/core/issues/1113#issuecomment-614616925

Do you use any interceptors?

ContentLicense: CC BY-SA 4.0

Body:
I know this error has been talked about many times - but in my case i really don't know how to start debugging it since i have a component with a lot of subscriptions and i can't trace it's source... any help will do.

I'm using catchError for all the subscriptions and i guess it's not that kind of error...

Here is an example of how i'm implementing the subscriptions:

 this.subs.push(this.apiService.isWorkListLayout$.pipe(
  tap(res => {
    this.formSrv.isDoneLoadingApache$.next(false);
    this.isWorkListLayout = res;
  }),
  switchMap(() => this.apiService.userDataForDialog$),
  tap(patientObj => {
    this.patient = patientObj;
  }),
  switchMap(() => this.isWorkListLayout ? this.apiService.getUsersComponentsData(this.patient) : EMPTY),
  catchError((err) => {
    throw 'Error in source. Details: ' + err;
  })
).subscribe((response) => {
  if (!!response && _.has(response, 'components')) {
    this.filterForm.reset();
    this.setPlaceHolderToFields(response.components, true);

    const formModeData = {
      areEditable: true,
      shouldApacheScoreCalc: true,
    };
    this.formSrv.isDoneLoadingApache$.next(true);
    this.formSrv.setFormMode(this.filterForm, formModeData);
  }
}));


问:
Express & Csurf rejects Vue (Axios) post request
I am currently dealing with forms and decided to test sending an email onchange mid registration to the server and give responsive feedback to users.

On Vue component creation I get the csrf token and store it for future posts. I attach it to the headers as 'X-CSRF-Token'. I send the token and still receive the invalid CSRF token error. I have verified the data in headers and the csrf token is in-fact being sent but just being rejected or the header is missing something.

Screenshot of error and response

```<code>//App.js
var createError = require('http-errors');
var cors = require('cors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var csurf = require('csurf')
var Mongoose = require('mongoose')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var productRouter = require('./routes/products')
var app = express();

// DB things
var db
dbConnect();

app.use(cors())
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser())
app.use(csurf({ cookie:true }))

app.use('/api/', indexRouter);
app.use('/api/users', usersRouter);
app.use('/api/products', productRouter)

//index routes
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.json({
    message:'respond with a resource blank',
  });
});

router.get('/getCSRF/', function(req, res, next) {
  res.json({
    csrf:req.csrfToken(),
  });
});

module.exports = router;
</code>```

Below is the route I try posting to

```<code>// Users Check Email Post Route
router.post('/checkEmail',function(req,res,next){
  email = req.body.email
  console.log(email)
  User.findOne(function(err,user){
    if (err) { return res.json({ err:err })}
    else { return res.json({ user:true }) }
  })
})
</code>```

Here is the method used in Vue to post

```<code>checkEmail: function () {
    var headers = {
      'Accept': 'application/json',
      'Access-Control-Allow-Origin': '*' ,
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
      'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type,
       Accept',
      'Content-Type':'application/x-www-form-urlencoded',
      'X-CSRF-Token':this.$store.getters.getCSRF,
    }

    axios.post('http://localhost:8000/api/users/checkEmail', {
      email: this.user.Email
    },headers )
    .then(function (response) {
      console.log(response)
    })
    .catch(function (error) {
      console.log(error.response)
    });
},
</code>```

The issue is pretty common and I have gone through over 20 posts and tried their solutions but it did not help at all. I've tried using csurf independently on the same route(didn't work). I've tried all manner of headers. Your help will be greatly appreciated .

EDIT: Uploading to show proper headers pre-post. Pre-post logs of data

答:
Your way of sending the token via router.get('/getCSRF/', ...) does not seem very secure to me, as any attacker could also easily get this token via this get request.

If you use app.use(csurf({ cookie:true })), then Express will validate every POST/PUT/DELETE request based on a cookie, but you need to set this cookie yourself.
(Csurf sets a cookie named _csrf but this is not the actual CSRF token)

I got it working this way:

Nodejs:

app.use(cookieParser());
app.use(
    csrf({
        // compare the XSRF-TOKEN cookie with the X-XSRF-TOKEN header on every post request
        cookie: {
            secure: true,
            sameSite: 'strict',
        },
    })
);

app.use(function (req, res, next) {
    // set the XSRF-TOKEN cookie so the client can send it back in the X-XSRF-TOKEN header
    res.cookie('XSRF-TOKEN', req.csrfToken());
    next();
});
```
<p>I used Nuxt as my client. Nuxt.config.js:</p>
<pre class="lang-js prettyprint-override"><code>modules: [
    '@nuxtjs/axios',
],

axios: {
    credentials: true, // this will take the XSRF-TOKEN from the cookie and set it in the X-XSRF-TOKEN header
    baseURL: nuxtBaseUrl,
    browserBaseURL: nuxtBrowserBaseUrl,
},

publicRuntimeConfig: {
    axios: {
      credentials: true, // this will take the XSRF-TOKEN from the cookie and set it in the X-XSRF-TOKEN header
      baseURL: nuxtBaseUrl,
      browserBaseURL: nuxtBrowserBaseUrl,
    },
},
</code>```

Alternative without nuxt:

const instance = axios.create({
  baseURL: 'https://my-server/',
  withCredentials: true, // this will take the XSRF-TOKEN from the cookie and set it in the X-XSRF-TOKEN header
});

instance.post('http://my-server/api/users/checkEmail', {
    email: this.user.Email
}
```

ContentLicense: CC BY-SA 3.0

Body:
I am currently dealing with forms and decided to test sending an email onchange mid registration to the server and give responsive feedback to users.

On Vue component creation I get the csrf token and store it for future posts. I attach it to the headers as 'X-CSRF-Token'. I send the token and still receive the invalid CSRF token error. I have verified the data in headers and the csrf token is in-fact being sent but just being rejected or the header is missing something.

Screenshot of error and response

//App.js
var createError = require('http-errors');
var cors = require('cors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var csurf = require('csurf')
var Mongoose = require('mongoose')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var productRouter = require('./routes/products')
var app = express();

// DB things
var db
dbConnect();

app.use(cors())
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser())
app.use(csurf({ cookie:true }))

app.use('/api/', indexRouter);
app.use('/api/users', usersRouter);
app.use('/api/products', productRouter)

//index routes
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.json({
    message:'respond with a resource blank',
  });
});

router.get('/getCSRF/', function(req, res, next) {
  res.json({
    csrf:req.csrfToken(),
  });
});

module.exports = router;

Below is the route I try posting to

// Users Check Email Post Route
router.post('/checkEmail',function(req,res,next){
  email = req.body.email
  console.log(email)
  User.findOne(function(err,user){
    if (err) { return res.json({ err:err })}
    else { return res.json({ user:true }) }
  })
})

Here is the method used in Vue to post

checkEmail: function () {
    var headers = {
      'Accept': 'application/json',
      'Access-Control-Allow-Origin': '*' ,
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
      'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type,
       Accept',
      'Content-Type':'application/x-www-form-urlencoded',
      'X-CSRF-Token':this.$store.getters.getCSRF,
    }

    axios.post('http://localhost:8000/api/users/checkEmail', {
      email: this.user.Email
    },headers )
    .then(function (response) {
      console.log(response)
    })
    .catch(function (error) {
      console.log(error.response)
    });
},

The issue is pretty common and I have gone through over 20 posts and tried their solutions but it did not help at all. I've tried using csurf independently on the same route(didn't work). I've tried all manner of headers. Your help will be greatly appreciated .

EDIT: Uploading to show proper headers pre-post. Pre-post logs of data

Body:
Your way of sending the token via router.get('/getCSRF/', ...) does not seem very secure to me, as any attacker could also easily get this token via this get request.

If you use app.use(csurf({ cookie:true })), then Express will validate every POST/PUT/DELETE request based on a cookie, but you need to set this cookie yourself.
(Csurf sets a cookie named _csrf but this is not the actual CSRF token)

I got it working this way:

Nodejs:

app.use(cookieParser());
app.use(
    csrf({
        // compare the XSRF-TOKEN cookie with the X-XSRF-TOKEN header on every post request
        cookie: {
            secure: true,
            sameSite: 'strict',
        },
    })
);

app.use(function (req, res, next) {
    // set the XSRF-TOKEN cookie so the client can send it back in the X-XSRF-TOKEN header
    res.cookie('XSRF-TOKEN', req.csrfToken());
    next();
});

I used Nuxt as my client. Nuxt.config.js:

modules: [
    '@nuxtjs/axios',
],

axios: {
    credentials: true, // this will take the XSRF-TOKEN from the cookie and set it in the X-XSRF-TOKEN header
    baseURL: nuxtBaseUrl,
    browserBaseURL: nuxtBrowserBaseUrl,
},

publicRuntimeConfig: {
    axios: {
      credentials: true, // this will take the XSRF-TOKEN from the cookie and set it in the X-XSRF-TOKEN header
      baseURL: nuxtBaseUrl,
      browserBaseURL: nuxtBrowserBaseUrl,
    },
},

Alternative without nuxt:

const instance = axios.create({
  baseURL: 'https://my-server/',
  withCredentials: true, // this will take the XSRF-TOKEN from the cookie and set it in the X-XSRF-TOKEN header
});

instance.post('http://my-server/api/users/checkEmail', {
    email: this.user.Email
}


问:
How to count sequential repeats of a value (allowing for one skip)
I am trying to produce a variable that counts how many times a "1" appeared sequentially in the preceding rows for a different variable. However, I need the count to persist even if there is one row missing a 1. (i.e., 10111011 should register as an 8). The code I use to count sequential 1s is:

The following code provides an example of the kind of thing I'm trying to do:

```<code>input <- c(1,0,1,1,0,1,1,0,1,0,1)
dfseq <- data.frame(input)
dfseq$seq <- sequence(rle(as.character(dfseq$input))$lengths)
</code>```

which produces the following dataframe:

```<code>data_struc <-
  structure(list(
    input = c(1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1),
    seq = c(1L,
            1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L)
  ),
  row.names = c(NA,-11L),
  class = "data.frame")
</code>```

However, I want the sequence to allow for one row of "failure" on the sequence, such that it continues to count consecutive ones even if one row contains a 0 and then the 1s continue. It should only stop counting once two 0s appear consecutively

答:
I'd use a lagged variable with an OR condition:</p>
```<code>library(dplyr)
dfseq %>% mutate(
  cum_result = cumsum(input == 1 | (lag(input) == 1 & lead(input, default = 1) == 1))
)
#    input seq cum_result
# 1      1   1          1
# 2      0   1          2
# 3      1   1          3
# 4      1   2          4
# 5      0   1          5
# 6      1   1          6
# 7      1   2          7
# 8      0   1          8
# 9      1   1          9
# 10     0   1         10
# 11     1   1         11
</code>```

Body:
I am trying to produce a variable that counts how many times a "1" appeared sequentially in the preceding rows for a different variable. However, I need the count to persist even if there is one row missing a 1. (i.e., 10111011 should register as an 8). The code I use to count sequential 1s is:

The following code provides an example of the kind of thing I'm trying to do:

input <- c(1,0,1,1,0,1,1,0,1,0,1)
dfseq <- data.frame(input)
dfseq$seq <- sequence(rle(as.character(dfseq$input))$lengths)

which produces the following dataframe:

data_struc <-
  structure(list(
    input = c(1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1),
    seq = c(1L,
            1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L)
  ),
  row.names = c(NA,-11L),
  class = "data.frame")

However, I want the sequence to allow for one row of "failure" on the sequence, such that it continues to count consecutive ones even if one row contains a 0 and then the 1s continue. It should only stop counting once two 0s appear consecutively

Body:
I'd use a lagged variable with an OR condition:

library(dplyr)
dfseq %>% mutate(
  cum_result = cumsum(input == 1 | (lag(input) == 1 & lead(input, default = 1) == 1))
)
#    input seq cum_result
# 1      1   1          1
# 2      0   1          2
# 3      1   1          3
# 4      1   2          4
# 5      0   1          5
# 6      1   1          6
# 7      1   2          7
# 8      0   1          8
# 9      1   1          9
# 10     0   1         10
# 11     1   1         11


问:
Append results from a shell command to a list in Python
I wrote a shell command inside Python to collect the IPv4 address in a server.

```<code># cat ipv4.py
#!/usr/bin/env python3
import os
ipv4_regex = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = f"ip a s eth0 | egrep -o 'inet {ipv4_regex}' | cut -d' ' -f2"
os.system(os_cmd)
</code>```

Output:

```<code># ./ipv4.py
192.168.0.2
192.168.0.3
192.168.0.4
</code>```

How do I append each IPv4 address from the above output to a list in Python?.

答:
First of all, the return of the os.system() method you are invocating is not directly what you are expecting.
Instead, try using os.popen(), it is the same, essentialy, as the subprocess check_output() method:

```<code>import os
ipv4_regex = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = f"ip a s eth0 | egrep -o 'inet {ipv4_regex}' | cut -d' ' -f2"
x = os.popen(os_cmd).read()
</code>```

Afterwards you can do some treatment in order get the return in the desired structure, creating a list from each line of x as example:

```<code>ips_list = x.split('\n')
</code>```

Body:
I wrote a shell command inside Python to collect the IPv4 address in a server.

# cat ipv4.py
#!/usr/bin/env python3
import os
ipv4_regex = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = f"ip a s eth0 | egrep -o 'inet {ipv4_regex}' | cut -d' ' -f2"
os.system(os_cmd)

Output:

# ./ipv4.py
192.168.0.2
192.168.0.3
192.168.0.4

How do I append each IPv4 address from the above output to a list in Python?.

Body:
First of all, the return of the os.system() method you are invocating is not directly what you are expecting.
Instead, try using os.popen(), it is the same, essentialy, as the subprocess check_output() method:

import os
ipv4_regex = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = f"ip a s eth0 | egrep -o 'inet {ipv4_regex}' | cut -d' ' -f2"
x = os.popen(os_cmd).read()

Afterwards you can do some treatment in order get the return in the desired structure, creating a list from each line of x as example:

ips_list = x.split('\n')


问:
Is it safe to only escape HTML instead of using a library like DOMPurify to prevent XSS?
I'm currently using this answer to escape my HTML before inserting it into a
 using dangerouslySetInnerHTML in my app.

However, I noticed there are also libraries like DOMPurify, which purport to be the safer approach to escaping HTML. Except that it's approximately 1000x larger of a solution, so I'm wondering if it's necessary.

I notice that the first solution in my answer seems to work well enough. I tried entering  into the message box and it seemed to be escaped properly. For my purposes I'm only doing a couple simple markup transformations (bolding, italics, etc.).

Is what I'm doing enough, or do I need a more powerful solution like DOMPurify? I rather not add the dependency if it's not necessary.

答:
In its basic form? Yes, it is safe when used like this:

```<code><p id="example"></p>
<script>
let escapedText = escapeHtml(userInput);
document.getElementById("example").innerHTML = escapedText;
</script>
</code>```

However, once you start modifying the escaped text and adding your own HTML tags to it, you may accidentally introduce a vector to XSS. Here is an example with a link specified by user input:

```<code><p id="example"></p>
<script>
let escapedLink = escapeHtml(userInput);
document.getElementById("example").innerHTML = `<a href="${escapedLink}">Click here</a>`;
</script>
</code>```

This demonstrates two shortcomings:

The attacker could set the link to javascript:alert(1) and achieve XSS.

Legitimate links could not be inserted, as the HTML escape blocks the / character.

This is a simple example and there are many less obvious ways to mess up badly here. Using a good HTML purifier library, such as DOMPurify, not only helps against XSS and similar vulnerabilities, but also lets you implement or even accept user input for custom HTML.

Body:
In its basic form? Yes, it is safe when used like this:

<p id="example"></p>
<script>
let escapedText = escapeHtml(userInput);
document.getElementById("example").innerHTML = escapedText;
</script>

However, once you start modifying the escaped text and adding your own HTML tags to it, you may accidentally introduce a vector to XSS. Here is an example with a link specified by user input:

<p id="example"></p>
<script>
let escapedLink = escapeHtml(userInput);
document.getElementById("example").innerHTML = `<a href="${escapedLink}">Click here</a>`;
</script>

This demonstrates two shortcomings:

The attacker could set the link to javascript:alert(1) and achieve XSS.

Legitimate links could not be inserted, as the HTML escape blocks the / character.

This is a simple example and there are many less obvious ways to mess up badly here. Using a good HTML purifier library, such as DOMPurify, not only helps against XSS and similar vulnerabilities, but also lets you implement or even accept user input for custom HTML.


问:
Laravel 8.4 – Remove Public from URL
I am working on creating a website that converts text into speech. I am using the script from codecanyon which is Developed with PHP 7.4.x and Laravel 8.4.x . The issue I am facing is that I don't want to show /public URL as a permalink to access the website. Now, if I type mywebsite.com/pubic then the website is accessible otherwise if I write mywebsite.com then it only shows the files. I followed some of the previous queries posted on StackOverflow but got no results.
The topic I followed is Laravel 5 – Remove Public from URL
I tried even by renaming server.php , copying .htaccess and rewriting it. But those all resulted in a screen showing up errors or even blank.

My .htaccess file is;

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</code>```

答: The content of public folder should go to the public folder of your server (fe it's public_html on my server), and everything else should be stored in a different folder (fe laravel_mywebsite). Then you should go to public_html/index.php and change the folder paths based on where you put your Laravel app.</p>

Title: Laravel 8.4 – Remove Public from URL

Body:
I am working on creating a website that converts text into speech. I am using the script from codecanyon which is Developed with PHP 7.4.x and Laravel 8.4.x . The issue I am facing is that I don't want to show /public URL as a permalink to access the website. Now, if I type mywebsite.com/pubic then the website is accessible otherwise if I write mywebsite.com then it only shows the files. I followed some of the previous queries posted on StackOverflow but got no results.
The topic I followed is Laravel 5 – Remove Public from URL
I tried even by renaming server.php , copying .htaccess and rewriting it. But those all resulted in a screen showing up errors or even blank.

My .htaccess file is;

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]


问:
Importing Json directly into class
I want to import  Json file into a class

This is a toy Json file I have

```<code>{
    "a": {
        "Name": "foo",
        "Age": 2
    },
    "b": {
        "Name": "bar",
        "Age": 3
    }
}
</code>```

I import the Json files inside the class Params using the following code.
Then I use this information to create two persons, a and b

```<code>public class Params
{
    JObject m_params;

    Params()
    {
        using (StreamReader file = File.OpenText(filename))
        using (JsonTextReader reader = new JsonTextReader(file))
        {
            m_params = (JObject)JToken.ReadFrom(reader);
        }
        Person Person1 = new Person(m_params["a"]);
        Person Person2 = new Person(m_params["b"]);
    }
}
</code>```

Now here's the implementation of Person

```<code>public class Person
{
    string Name;
    int Age;
    Person(JToken data)
    {
        Name = data["Name"];
        Age = data["Age"];
    }
}
</code>```

This works, but I feel it should be an easier way to do that.

If instead of just having name and age I have 100 parameters, the initialization of Person will be 100 lines of code.

If there a way of directly assigning data["Name"] to Person.Name and do the rest for all the parameters of Person?

How could my importing be improved, so when I have a lot of people with a lot of fields I can import everything easily?

答:
It looks like you are using the Newtonsoft.JSON NuGet-Package.

If so, there is a JsonConvert-Class that exposes the DeserializeObject<T>-Method to archive this.

The tricky bit here is that your Persons are contained in a Dictionary, so the following code should work for you:

public class Params
{
    Params()
    {
        string json = File.ReadAllText(filename);

        var dictionary = JsonConvert.DeserializeObject<Dictionary<string, Person>>(json);
        var person1 = dictionary["a"];
        var person2 = dictionary["b"];
    }
}

```
<pre class="lang-cs prettyprint-override"><code>
public class Person
{
    string Name;
    int Age;
    // Remove the constructor or add a parameterless one
}

</code>```

Title: Importing Json directly into class

Body:
I want to import  Json file into a class

This is a toy Json file I have

{
    "a": {
        "Name": "foo",
        "Age": 2
    },
    "b": {
        "Name": "bar",
        "Age": 3
    }
}

I import the Json files inside the class Params using the following code.
Then I use this information to create two persons, a and b

public class Params
{
    JObject m_params;

    Params()
    {
        using (StreamReader file = File.OpenText(filename))
        using (JsonTextReader reader = new JsonTextReader(file))
        {
            m_params = (JObject)JToken.ReadFrom(reader);
        }
        Person Person1 = new Person(m_params["a"]);
        Person Person2 = new Person(m_params["b"]);
    }
}

Now here's the implementation of Person

public class Person
{
    string Name;
    int Age;
    Person(JToken data)
    {
        Name = data["Name"];
        Age = data["Age"];
    }
}

This works, but I feel it should be an easier way to do that.

If instead of just having name and age I have 100 parameters, the initialization of Person will be 100 lines of code.

If there a way of directly assigning data["Name"] to Person.Name and do the rest for all the parameters of Person?

How could my importing be improved, so when I have a lot of people with a lot of fields I can import everything easily?

Body:
It looks like you are using the Newtonsoft.JSON NuGet-Package.

If so, there is a JsonConvert-Class that exposes the DeserializeObject<T>-Method to archive this.

The tricky bit here is that your Persons are contained in a Dictionary, so the following code should work for you:

public class Params
{
    Params()
    {
        string json = File.ReadAllText(filename);

        var dictionary = JsonConvert.DeserializeObject<Dictionary<string, Person>>(json);
        var person1 = dictionary["a"];
        var person2 = dictionary["b"];
    }
}

public class Person
{
    string Name;
    int Age;
    // Remove the constructor or add a parameterless one
}


问:
How to get character after space in JavaScript
I am working on avatar component in React where I want to get the first character and character after space and give the result to the avatar and display the abbreviated version of the full name. For example:

```<code>var fullName = ahmed hosny;

//I am able to get the first character like this:

fullName.charAt(0).toUpperCase() // this prints 'A'
</code>```

How can I get 'H' from hosny?

答:
Use regex for this.

For first occurrence

console.log(fullName.match(/(?<= )./))
// returns [ 'h', index: 6, input: 'ahmed hosny', groups: undefined ]
```
<p><strong>For all occurrences</strong></p>
<pre class="lang-js prettyprint-override"><code>console.log(fullName.match(/(?<= )./g))
// returns array of all characters after space
</code>```

Body:
I am working on avatar component in React where I want to get the first character and character after space and give the result to the avatar and display the abbreviated version of the full name. For example:

var fullName = ahmed hosny;

//I am able to get the first character like this:

fullName.charAt(0).toUpperCase() // this prints 'A'

How can I get 'H' from hosny?

Body:
Use regex for this.

For first occurrence

console.log(fullName.match(/(?<= )./))
// returns [ 'h', index: 6, input: 'ahmed hosny', groups: undefined ]

For all occurrences

console.log(fullName.match(/(?<= )./g))
// returns array of all characters after space


问:
How to improve "select min(my_col)" query in MySQL without adding and index
The query below takes about a minute to run on my MySQL instance (running on a fairly beefy machine with 64G memory, 2T disc, 2.30Ghz CPU with 8 cores and 16 logical, and the query is running on localhost).  This same query runs in less than a second on a SQL Server database I have access to.  Unfortunately, I do not have access to the SQL Server host or the DBA, etc.

```<code>select min(visit_start_date)
from visit_occurrence;
</code>```

The table has been set to ENGINE=MyISAM and default-storage-engine=INNODB and innodb_buffer_pool_size=16G are set in my.ini.

Is there some configuration I could be missing that would cause this query to run so slowly on MySQL? How can I fix it?

I have a large number of tables and queries I will need to support so I would really like to be able to fix this issue globally rather than having to create indexes everywhere I have slow queries.

The SQL Server database does not seem to have an index on the column being queried as shown below.

EDIT:

Untagged MS Sql Server, I had tagged it hoping for the help of our MS Sql Server colleagues with information that Sql Server had some way of structuring data and/or queries that would make this type of query run faster on that platform v other such as MySql

Removed image of code to more closely conform with community standards

You never know if there is a magic go-faster button if you don't ask (ENGINE=MyISAM is sometimes kind of like a magic go-faster button for some queries in MySql).  I'm kind of fishing for a potential hardware or clustering solution here.  Is Apache Ignite a potential solution here?

Thanks again to the community for all of your support and help.  I hope this fixes most of the issues that have been raised for this post.

SECOND EDIT:
Is the partitioning/sharding described in the links below a potential solution here?

https://user3141592.medium.com/how-to-scale-mysql-42ebd2841fa6

https://dev.mysql.com/doc/refman/8.0/en/partitioning-overview.html

THIRD EDIT: A note on community standards.

Part of our community standards is explicitly to be welcoming, inclusive, and to be nice.

https://stackoverflow.blog/2018/04/26/stack-overflow-isnt-very-welcoming-its-time-for-that-to-change/?fbclid=IwAR1gr6r2qmXs506SAV3H_h6H8LoFy3mlXucfa-fqiiEXMHUR3aF_tdoZGsw

https://meta.stackexchange.com/questions/240839/the-new-new-be-nice-policy-code-of-conduct-updated-with-your-feedback).

The MS Sql Server tag was used here as one of the systems I'm comparing is MS Sql Server.  We're really working with very limited information here.  I have two systems: My MySql system, which is knowable as I'm running it, and the MS Sql Server running the same database in someone else's system that I have very little information about (all I have is a read only sql prompt).  I am comparing apples and oranges: The same query runs well on the orange (MS Sql Server) and does not run well on the apple (My MySql instance).  I'd like to know why so I can make an informed decision about how to get my queries to run in a reasonable amount of time. How do I get my apple to look like an orange?  Do I switch to MS Sql Server?  Do I need to deploy on different hardware?  Is the other system running some kind of in memory caching system on top of their database instance?  Most of these possibilities would require a non trivial amount of time to explore and validate.  So yes, I would like help from MS Sql Server experts that might know if there are caching options, transactional v warehouse options, etc. that could be set that would make a world of difference, that would be magic go-fast buttons.

The magic go-fast button comment was perhaps a little bit condescending.

The picture showing the indexes was shown as I was just trying to make the point that the other system does not seem to have an index on the column being queried.  I this case a picture was worth a thousand words.

答:
Whether in MyISAM or InnoDB. or even SQL Server, your query

select min(visit_start_date) from visit_occurrence;
```
<p>can be satisfied almost instantaneously by this index, because it uses a so-called loose index scan.</p>
<pre class="lang-sql prettyprint-override"><code>CREATE INDEX visit_start_date ON visit_occurrence (visit_start_date);
</code>```

A query with an aggregate function like MIN() is always a GROUP BY query. But if the GROUP BY clause isn't present in the SQL statement, the server groups by the entire table.

You mentioned a query that can be satisfied immediately when using MyISAM. That's SELECT COUNT(*) FROM whatever_table. Behind the scenes MyISAM keeps table metadata showing the total number of rows in the table, so that query comes back right away. The transactional storage engine InnoDB doesn't do that. It supports so much concurrency that its designers didn't include the total row count in their metadata, because it would be wrong in so many circumstances that it wasn't worth the risk.

Index design isn't a black art. But it is an art informed by the kind of measurements we get from EXPLAIN (or ANALYZE or EXPLAIN ANALYZE). A basic truth of database-driven apps (in any make of database server) is that indexing needs to be revisited as the app grows. The good news: changing, adding, or dropping indexes doesn't change your data.

Body:
The query below takes about a minute to run on my MySQL instance (running on a fairly beefy machine with 64G memory, 2T disc, 2.30Ghz CPU with 8 cores and 16 logical, and the query is running on localhost).  This same query runs in less than a second on a SQL Server database I have access to.  Unfortunately, I do not have access to the SQL Server host or the DBA, etc.

select min(visit_start_date)
from visit_occurrence;

The table has been set to ENGINE=MyISAM and default-storage-engine=INNODB and innodb_buffer_pool_size=16G are set in my.ini.

Is there some configuration I could be missing that would cause this query to run so slowly on MySQL? How can I fix it?

I have a large number of tables and queries I will need to support so I would really like to be able to fix this issue globally rather than having to create indexes everywhere I have slow queries.

The SQL Server database does not seem to have an index on the column being queried as shown below.

EDIT:

Untagged MS Sql Server, I had tagged it hoping for the help of our MS Sql Server colleagues with information that Sql Server had some way of structuring data and/or queries that would make this type of query run faster on that platform v other such as MySql

Removed image of code to more closely conform with community standards

You never know if there is a magic go-faster button if you don't ask (ENGINE=MyISAM is sometimes kind of like a magic go-faster button for some queries in MySql).  I'm kind of fishing for a potential hardware or clustering solution here.  Is Apache Ignite a potential solution here?

Thanks again to the community for all of your support and help.  I hope this fixes most of the issues that have been raised for this post.

SECOND EDIT:
Is the partitioning/sharding described in the links below a potential solution here?

https://user3141592.medium.com/how-to-scale-mysql-42ebd2841fa6

https://dev.mysql.com/doc/refman/8.0/en/partitioning-overview.html

THIRD EDIT: A note on community standards.

Part of our community standards is explicitly to be welcoming, inclusive, and to be nice.

https://stackoverflow.blog/2018/04/26/stack-overflow-isnt-very-welcoming-its-time-for-that-to-change/?fbclid=IwAR1gr6r2qmXs506SAV3H_h6H8LoFy3mlXucfa-fqiiEXMHUR3aF_tdoZGsw

https://meta.stackexchange.com/questions/240839/the-new-new-be-nice-policy-code-of-conduct-updated-with-your-feedback).

The MS Sql Server tag was used here as one of the systems I'm comparing is MS Sql Server.  We're really working with very limited information here.  I have two systems: My MySql system, which is knowable as I'm running it, and the MS Sql Server running the same database in someone else's system that I have very little information about (all I have is a read only sql prompt).  I am comparing apples and oranges: The same query runs well on the orange (MS Sql Server) and does not run well on the apple (My MySql instance).  I'd like to know why so I can make an informed decision about how to get my queries to run in a reasonable amount of time. How do I get my apple to look like an orange?  Do I switch to MS Sql Server?  Do I need to deploy on different hardware?  Is the other system running some kind of in memory caching system on top of their database instance?  Most of these possibilities would require a non trivial amount of time to explore and validate.  So yes, I would like help from MS Sql Server experts that might know if there are caching options, transactional v warehouse options, etc. that could be set that would make a world of difference, that would be magic go-fast buttons.

The magic go-fast button comment was perhaps a little bit condescending.

The picture showing the indexes was shown as I was just trying to make the point that the other system does not seem to have an index on the column being queried.  I this case a picture was worth a thousand words.

Body:
Whether in MyISAM or InnoDB. or even SQL Server, your query

select min(visit_start_date) from visit_occurrence;

can be satisfied almost instantaneously by this index, because it uses a so-called loose index scan.

CREATE INDEX visit_start_date ON visit_occurrence (visit_start_date);

A query with an aggregate function like MIN() is always a GROUP BY query. But if the GROUP BY clause isn't present in the SQL statement, the server groups by the entire table.

You mentioned a query that can be satisfied immediately when using MyISAM. That's SELECT COUNT(*) FROM whatever_table. Behind the scenes MyISAM keeps table metadata showing the total number of rows in the table, so that query comes back right away. The transactional storage engine InnoDB doesn't do that. It supports so much concurrency that its designers didn't include the total row count in their metadata, because it would be wrong in so many circumstances that it wasn't worth the risk.

Index design isn't a black art. But it is an art informed by the kind of measurements we get from EXPLAIN (or ANALYZE or EXPLAIN ANALYZE). A basic truth of database-driven apps (in any make of database server) is that indexing needs to be revisited as the app grows. The good news: changing, adding, or dropping indexes doesn't change your data.


问:
Have user continue to run test in step load after x amount of users have ramped up (python) (locust)
My use case is as below: I am trying to run a test programmatically where in i want users to ramp up to a certain amount of users. Then once the ramp up is finished i want the combined ramped up users to continue the test for an hour.

Below is the code, by which i can have users (5 in total) ramp up until time_limit (300) is reached. Now i want to have these users run for an hour after the ramping up has finished. Any suggestions what changes i need to make to the code?

```<code>import math
from locust import HttpUser, TaskSet, task, constant
from locust import LoadTestShape

class StepLoadShape(LoadTestShape):
    """
    A step load shape

    Keyword arguments:

        step_time -- Time between steps
        step_load -- User increase amount at each step
        spawn_rate -- Users to stop/start per second at every step
        time_limit -- Time limit in seconds

    """
    # this below config led to 5 users in total
    step_time = 60
    step_load = 1
    spawn_rate = 1
    time_limit = 300

    def tick(self):
        run_time = self.get_run_time()

        if run_time > self.time_limit:
            return None

        current_step = math.floor(run_time / self.step_time) + 1
        return (current_step * self.step_load, self.spawn_rate)

class UserBehavior(HttpUser):
    wait_time=constant(1)
    host="https://google.com"

    @task
    def launch_URL(self):
        token = "XXXXXXXXXXX"

        headers={
        "Content-Type":"application/json",
        "Authorization":"Bearer " + token,
        "id":"TEST_QA"}

        with self.client.get("/google.com?clientId=test&userId=user_1",headers=headers,catch_response=True) as response:
            if ("Descriptor") in response.json():
                if response.status_code == 200:
                    response.success()
                else:
                    response.failure("HTTP 200OK not received")
            else:
                response.failure("Valid response not returned")
</code>```

答: Yes i am checking that and did replace that with response.text() and that fixed it. Thanks!</p>

Body:
My use case is as below: I am trying to run a test programmatically where in i want users to ramp up to a certain amount of users. Then once the ramp up is finished i want the combined ramped up users to continue the test for an hour.

Below is the code, by which i can have users (5 in total) ramp up until time_limit (300) is reached. Now i want to have these users run for an hour after the ramping up has finished. Any suggestions what changes i need to make to the code?

import math
from locust import HttpUser, TaskSet, task, constant
from locust import LoadTestShape

class StepLoadShape(LoadTestShape):
    """
    A step load shape

    Keyword arguments:

        step_time -- Time between steps
        step_load -- User increase amount at each step
        spawn_rate -- Users to stop/start per second at every step
        time_limit -- Time limit in seconds

    """
    # this below config led to 5 users in total
    step_time = 60
    step_load = 1
    spawn_rate = 1
    time_limit = 300

    def tick(self):
        run_time = self.get_run_time()

        if run_time > self.time_limit:
            return None

        current_step = math.floor(run_time / self.step_time) + 1
        return (current_step * self.step_load, self.spawn_rate)

class UserBehavior(HttpUser):
    wait_time=constant(1)
    host="https://google.com"

    @task
    def launch_URL(self):
        token = "XXXXXXXXXXX"

        headers={
        "Content-Type":"application/json",
        "Authorization":"Bearer " + token,
        "id":"TEST_QA"}

        with self.client.get("/google.com?clientId=test&userId=user_1",headers=headers,catch_response=True) as response:
            if ("Descriptor") in response.json():
                if response.status_code == 200:
                    response.success()
                else:
                    response.failure("HTTP 200OK not received")
            else:
                response.failure("Valid response not returned")


问:
How can resolve **Uncaught Reference Error: io is not defined at client.js:1:16** error?
I am trying to create a real time chat app project using node and socket but when I try to run this using nodemon then it gives me error like

```<code>Uncaught ReferenceError: io is not defined
    at client.js:1:16
</code>```

and

```<code>GET http://localhost:3000/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)
</code>```

plz help me to get out from this frustration.
here are respective code:-

```<code>const express=require("express");

const http=require("http");

const app=express();

const server=http.createServer(app);

const io=require("socket.io")(server)

app.get("/",function (req,res) {
    res.sendFile(__dirname+"/index.html");
})

app.use(express.static(__dirname+"/public"))

io.on("connection",(socket)=> {
    console.log('Connected');

})

app.listen(process.env.PORT || 3000,function(){
    console.log('Running....');
})
</code>```

code at client.js:-

```<code>const socket = io()
let name;
let textarea=document.querySelector("#textarea");
let msgArea=document.querySelector(".mssg_area");
do{
    name = prompt("what do your friends call you?");
}while(!name);

textarea.addEventListener("keyup",function (e) {
    if(e.key==="Enter"){
        sendMessage(e.target.value);
    }
})

function sendMessage(message) {
    let msg={
        user:name,
        message:message
    }
    appendMessage(msg,"outgoing")
}

function appendMessage(msg,type) {
    let mainDiv=document.createElement("div")
    let className=type
    mainDiv.classList.add(className,"message")

    let markUp=`
    <h4>${msg.user}</h4>
    <p>${msg.message}</p>
    `
    mainDiv.innerHTML=markUp
    msgArea.appendChild(mainDiv)
}
</code>```

It would be very helpful to me if you resolve this issue. Thank you in advance!!

答:
Be sure, you have installed socket.io module. If not installed, install this by using command -
npm install socket.io</p>

Body:
I am trying to create a real time chat app project using node and socket but when I try to run this using nodemon then it gives me error like

Uncaught ReferenceError: io is not defined
    at client.js:1:16

and

GET http://localhost:3000/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)

plz help me to get out from this frustration.
here are respective code:-

const express=require("express");

const http=require("http");

const app=express();

const server=http.createServer(app);

const io=require("socket.io")(server)

app.get("/",function (req,res) {
    res.sendFile(__dirname+"/index.html");
})

app.use(express.static(__dirname+"/public"))

io.on("connection",(socket)=> {
    console.log('Connected');

})

app.listen(process.env.PORT || 3000,function(){
    console.log('Running....');
})

code at client.js:-

const socket = io()
let name;
let textarea=document.querySelector("#textarea");
let msgArea=document.querySelector(".mssg_area");
do{
    name = prompt("what do your friends call you?");
}while(!name);

textarea.addEventListener("keyup",function (e) {
    if(e.key==="Enter"){
        sendMessage(e.target.value);
    }
})

function sendMessage(message) {
    let msg={
        user:name,
        message:message
    }
    appendMessage(msg,"outgoing")
}

function appendMessage(msg,type) {
    let mainDiv=document.createElement("div")
    let className=type
    mainDiv.classList.add(className,"message")

    let markUp=`

${msg.user}

${msg.message}

    `
    mainDiv.innerHTML=markUp
    msgArea.appendChild(mainDiv)
}

It would be very helpful to me if you resolve this issue. Thank you in advance!!


问:
Browser not rendering PDF correctly in Laravel

Localhost is fine but when uploaded to server not working

My Code

```<code>public function printSalesRecord()
{

    $setPaperSize = 'A4';
    $pdf = App::make('dompdf');

    $pdf = PDF::loadView('salesrecord/PrintSalesRecord')->setPaper($setPaperSize)->setOrientation('portraite');

    return $pdf->stream();

}
</code>```

This is what i get on my browser

%PDF-1.3 1 0 obj << /Type /Catalog /Outlines 2 0 R /Pages 3 0 R >> endobj 2 0 obj << /Type /Outlines /Count 0 >> endobj 3 0 obj << /Type /Pages /Kids [6 0 R ] /Count 1 /Resources << /ProcSet 4 0 R /Font << /F1 8 0 R >> >> /MediaBox [0.000 0.000 595.280 841.890] >> endobj 4 0 obj [/PDF /Text ] endobj 5 0 obj << /Creator (DOMPDF) /CreationDate (D:20161122092040+00'00') /ModDate (D:20161122092040+00'00') >> endobj 6 0 obj << /Type /Page /Parent 3 0 R /Contents 7 0 R >> endobj 7 0 obj << /Filter /FlateDecode /Length 73 >> stream x��2�300P@&�ҹ�B�M���-L�L�,BR����B��5JR�K�Drr�f�B���k��� endstream endobj 8 0 obj << /Type /Font /Subtype /Type1 /Name /F1 /BaseFont /Times-Roman /Encoding /WinAnsiEncoding >> endobj xref 0 9 0000000000 65535 f 0000000009 00000 n 0000000074 00000 n 0000000120 00000 n 0000000274 00000 n 0000000303 00000 n 0000000417 00000 n 0000000480 00000 n 0000000624 00000 n trailer << /Size 9 /Root 1 0 R /Info 5 0 R >> startxref 733 %%EOF

答:
Had the same problem, add this at the end of the script or function:</p>
```<code>exit();
</code>```

Body:
Localhost is fine but when uploaded to server not working

My Code

public function printSalesRecord()
{

    $setPaperSize = 'A4';
    $pdf = App::make('dompdf');

    $pdf = PDF::loadView('salesrecord/PrintSalesRecord')->setPaper($setPaperSize)->setOrientation('portraite');

    return $pdf->stream();

}

This is what i get on my browser

%PDF-1.3 1 0 obj << /Type /Catalog /Outlines 2 0 R /Pages 3 0 R >> endobj 2 0 obj << /Type /Outlines /Count 0 >> endobj 3 0 obj << /Type /Pages /Kids [6 0 R ] /Count 1 /Resources << /ProcSet 4 0 R /Font << /F1 8 0 R >> >> /MediaBox [0.000 0.000 595.280 841.890] >> endobj 4 0 obj [/PDF /Text ] endobj 5 0 obj << /Creator (DOMPDF) /CreationDate (D:20161122092040+00'00') /ModDate (D:20161122092040+00'00') >> endobj 6 0 obj << /Type /Page /Parent 3 0 R /Contents 7 0 R >> endobj 7 0 obj << /Filter /FlateDecode /Length 73 >> stream x��2�300P@&�ҹ�B�M���-L�L�,BR����B��5JR�K�Drr�f�B���k��� endstream endobj 8 0 obj << /Type /Font /Subtype /Type1 /Name /F1 /BaseFont /Times-Roman /Encoding /WinAnsiEncoding >> endobj xref 0 9 0000000000 65535 f 0000000009 00000 n 0000000074 00000 n 0000000120 00000 n 0000000274 00000 n 0000000303 00000 n 0000000417 00000 n 0000000480 00000 n 0000000624 00000 n trailer << /Size 9 /Root 1 0 R /Info 5 0 R >> startxref 733 %%EOF

Body:
Had the same problem, add this at the end of the script or function:

exit();


问:
How do PUT, POST or PATCH request differ ultimately?
The data, being sent over a PUT/PATCH/POST request, ultimately ends up in the database.

Now whether we are inserting a new resource or updating or modifying an existing one - it all depends upon the database operation being carried out.

Even if we send a POST and ultimately perform just an update in the database, it does not impact anywhere at all, isn't it?!

Hence, do they actually differ - apart from a purely conceptual point of view?

答:
Hence, do they actually differ - apart from a purely conceptual point of view?

The semantics differ - what the messages mean, and what general purpose components are allowed to assume is going on.

The meanings are just those described by the references listed in the HTTP method registry.  Today, that means that POST and PUT are described by HTTP semantics; PATCH is described by RFC 5789.

Loosely: PUT means that the request content is a proposed replacement for the current representation of some resource -- it's the method we would use to upload or replace a single web page if we were using the HTTP protocol to do that.

PATCH means that the request content is a patch document - which is to say a proposed edit to the current representation of some resource.  So instead of sending the entire HTML document with PUT, you might instead just send a fix to the spelling error in the title element.

POST is... well, POST is everything else.

POST serves many useful purposes in HTTP, including the general purpose of “this action isn’t worth standardizing.” -- Fielding 2009

The POST method has the fewest constraints on its semantics (which is why we can use it for anything), but the consequence is that the HTTP application itself has to be very conservative with it.

Webber 2011 includes a good discussion of the implementations of the fact that HTTP is an application protocol.

Now whether we are inserting a new resource or updating or modifying an existing one - it all depends upon the database operation being carried out.

The HTTP method tells us what the request means - it doesn't place any constraints on how your implementation works.

See Fielding, 2002:

HTTP does not attempt to require the results of a GET to be safe.  What it does is require that the semantics of the operation be safe, and therefore it is a fault of the implementation, not the interface or the user of that interface, if anything happens as a result that causes loss of property (money, BTW, is considered property for the sake of this definition).

The HTTP methods are part of the "transfer of documents over a network" domain - ie they are part of the facade that allows us to pretend that the bank/book store/cat video archive you are implementing is just another "web site".


问:
c# wrong number when calculating percentage
trying to calculate and subtract the price of something, but keeps coming up wrong, and adds an extra 500m to it and cannot understand why.

here is my code

```<code>        var discountPercentage = 50 / 100;
        discountedPrice= (decimal)(discountPercentage * 150000M + 10000M +  0);
</code>```

the answer keeps giving me 85000.0M where it should be 80000, which is half of the combined amount (150000M + 10000M)

答:
I think your parenthesis are placed wrong in discountPercentage. It has to do with priority of operations.

```<code>discountPercentage * (150000M + 10000M +  0);
</code>```

Body:
trying to calculate and subtract the price of something, but keeps coming up wrong, and adds an extra 500m to it and cannot understand why.

here is my code

        var discountPercentage = 50 / 100;
        discountedPrice= (decimal)(discountPercentage * 150000M + 10000M +  0);

the answer keeps giving me 85000.0M where it should be 80000, which is half of the combined amount (150000M + 10000M)

Body:
I think your parenthesis are placed wrong in discountPercentage. It has to do with priority of operations.

discountPercentage * (150000M + 10000M +  0);


问:
Populating an HTML table from an external XML
I have come across a problem while fetching data from an external XML document with JS. I have been following the w3schools tutorial for AJAX XML so far, but I ran into something I couldn't solve. I have a XML that looks like this:

```<code><root>
 <document-id>
    <author>Tom Riddle</autor>
    <title>abzy</title>
    <year>1995</year>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <title>abzy</title>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <year>1995</year>
 </document-id>
</root>
</code>```

I want to dynamically access the data inside the XML and create a table while doing so. It works fine for the one DOM Element all documents share, but it gives me an error as soon as I include year or title. I guess it's because the tags are empty in some parts of the tree. Is there a way to ignore empty tags and only write something in the column if there is a value inside? Thank you for your time and knowledge.

THIS IS THE ASSOCIATED HTML

```<code><body>
    <header>
        <h1>Reading Data from XML Files</h1>
    </header>
    <main>

        <button type="button" onclick="loadDoc()">Get my CD collection</button>

        <table id="demo">

        </table>

    </main>
    <script>
       function loadDoc() {
          const xhttp = new XMLHttpRequest();
          xhttp.onload = function() {
            myFunction(this);
          }
          xhttp.open("GET", "books.xml");
          xhttp.send();
        }
        function myFunction(xml) {
          const xmlDoc = xml.responseXML;
          const x = xmlDoc.getElementsByTagName("document-id");
          console.log(x)
          let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";
          for (let i = 0; i <x.length; i++) {
            table += "<tr><td>" +
            x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
            "</td><td>" +
            x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue +
            "</tr>";
          }
          document.getElementById("demo").innerHTML = table;
        }
    </script>
</body>
</code>```

答:
Check for existence before you try to access the children.</p>
```<code>function getText(node, tag) {
  var elem = node.getElementsByTagName(tag);
  return elem ? elem.[0].childNodes[0].nodeValue : '';
}

for (let i = 0; i <x.length; i++) {
    var cells = ['author', 'title', 'year'].map(function (tag) {
      return "<td>" + getText(x[i], tag) + "</td>";
    }).join("");

    table += "<tr>" + cells + "</tr>");
}
</code>```

Body:
I have come across a problem while fetching data from an external XML document with JS. I have been following the w3schools tutorial for AJAX XML so far, but I ran into something I couldn't solve. I have a XML that looks like this:

<root>
 <document-id>
    <author>Tom Riddle</autor>
    <title>abzy</title>
    <year>1995</year>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <title>abzy</title>
 </document-id>
 <document-id>
    <author>Tom Riddle</autor>
    <year>1995</year>
 </document-id>
</root>

I want to dynamically access the data inside the XML and create a table while doing so. It works fine for the one DOM Element all documents share, but it gives me an error as soon as I include year or title. I guess it's because the tags are empty in some parts of the tree. Is there a way to ignore empty tags and only write something in the column if there is a value inside? Thank you for your time and knowledge.

THIS IS THE ASSOCIATED HTML

Reading Data from XML Files

        <button type="button" onclick="loadDoc()">Get my CD collection</button>

Body:
Check for existence before you try to access the children.

function getText(node, tag) {
  var elem = node.getElementsByTagName(tag);
  return elem ? elem.[0].childNodes[0].nodeValue : '';
}

for (let i = 0; i <x.length; i++) {
    var cells = ['author', 'title', 'year'].map(function (tag) {
      return "<td>" + getText(x[i], tag) + "</td>";
    }).join("");

    table += "<tr>" + cells + "</tr>");
}


问:
Best way to transfer struct from one process to another?
I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:

```<code>typedef struct tagTDATA {
         BYTE c1;
         DWORD dw1;
         DWORD dw2;
         char ch[255];
} TDATA, *PTDATA;
</code>```

Cant use Boost. The best way its Win API. And i don't need code solution just point me in right direction. Thanks.

答: ReadProcessMemory and WriteProcessMemory ought to be able to do the trick for you.</p>

Body:
I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:

typedef struct tagTDATA {
         BYTE c1;
         DWORD dw1;
         DWORD dw2;
         char ch[255];
} TDATA, *PTDATA;

Cant use Boost. The best way its Win API. And i don't need code solution just point me in right direction. Thanks.


问:
Save PDF file as images with same quality as original PDF
I want to save each page of a pdf file as a single image file:

```<code>import fitz
doc = fitz.open('file.pdf')
for i in range(doc.page_count):
    page = doc[i]
    pix = page.get_pixmap()
    pix.save(f'page-{i}.png')
    pix.pil_save(f'page-{i}.jpg', optimize = False, dpi = (1500, 1500))
</code>```

The images are in worse quality than in the original pdf file, no matter which resolution I choose. How can I save them with the same or a similar quality?

答:
Just a simple configuration, Add the dpi option in get_pixmap()

```<code>import fitz
doc = fitz.open('file.pdf')
resolution_parameter = 300
for i in range(doc.page_count):
    page = doc[i]
    pix = page.get_pixmap(dpi = resolution_parameter)
    pix.save(f'page-{i}.png')
    pix.pil_save(f'page-{i}.jpg', optimize = False, dpi = (1500, 1500))
</code>```

Body:
I want to save each page of a pdf file as a single image file:

import fitz
doc = fitz.open('file.pdf')
for i in range(doc.page_count):
    page = doc[i]
    pix = page.get_pixmap()
    pix.save(f'page-{i}.png')
    pix.pil_save(f'page-{i}.jpg', optimize = False, dpi = (1500, 1500))

The images are in worse quality than in the original pdf file, no matter which resolution I choose. How can I save them with the same or a similar quality?

Body:
Just a simple configuration, Add the dpi option in get_pixmap()

import fitz
doc = fitz.open('file.pdf')
resolution_parameter = 300
for i in range(doc.page_count):
    page = doc[i]
    pix = page.get_pixmap(dpi = resolution_parameter)
    pix.save(f'page-{i}.png')
    pix.pil_save(f'page-{i}.jpg', optimize = False, dpi = (1500, 1500))


答:
You'll need the subprocess module to capture output from a process.

You'll probably have a better time finding your matches in Python rather than build a shell pipeline.

```<code>import re
import subprocess
import shlex

match_re = re.compile(
    r"inet ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})"
)

def get_ips(interface_name):
    ips = match_re.findall(
        subprocess.check_output(
            f"ip a s {shlex.quote(interface_name)}",
            shell=True,
            encoding="utf-8",
        )
    )
    return ips

print(get_ips("eno1"))
</code>```

This directly prints out (e.g.)

```<code>['192.168.1.20']
</code>```

since findall() gets you the first capture group from the regexp.

Title: Append results from a shell command to a list in Python

Body:
I wrote a shell command inside Python to collect the IPv4 address in a server.

# cat ipv4.py
#!/usr/bin/env python3
import os
ipv4_regex = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = f"ip a s eth0 | egrep -o 'inet {ipv4_regex}' | cut -d' ' -f2"
os.system(os_cmd)

Output:

# ./ipv4.py
192.168.0.2
192.168.0.3
192.168.0.4

How do I append each IPv4 address from the above output to a list in Python?.

Body:
You'll need the subprocess module to capture output from a process.

You'll probably have a better time finding your matches in Python rather than build a shell pipeline.

import re
import subprocess
import shlex

match_re = re.compile(
    r"inet ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})"
)

def get_ips(interface_name):
    ips = match_re.findall(
        subprocess.check_output(
            f"ip a s {shlex.quote(interface_name)}",
            shell=True,
            encoding="utf-8",
        )
    )
    return ips

print(get_ips("eno1"))

This directly prints out (e.g.)

['192.168.1.20']

since findall() gets you the first capture group from the regexp.


问:
How to replicate behavior of standard list elements to instantiate child items in WPF?
I'm creating a Wizard control based on Selector. My plan is that it will behave in the similar way to TabControl, ListBox, etc. - by having its own child items.

What I already did is:

public class Wizard : Selector
{
    // ...

    protected override DependencyObject GetContainerForItemOverride() => new WizardPage();

    protected override bool IsItemItsOwnContainerOverride(object item) => item is WizardPage;

    // ...
```
<p>The relevant part ControlTemplate for my control looks like this:</p>
<pre class="lang-xml prettyprint-override"><code><Style TargetType="{x:Type c:Wizard}">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <Grid />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type c:Wizard}">
                <DockPanel Background="{TemplateBinding Background}"
                    Margin="{TemplateBinding Padding}">
                    <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Right">
                        <Button Name="BackButton" MinWidth="75" Command="{x:Static c:WizardCommands.PreviousPage}"
                        Content="{TemplateBinding BackButtonContent}" Style="{StaticResource WizardButton}">
                            <Button.Visibility>
                                <MultiBinding Converter="{StaticResource WizardPageButtonVisibilityConverter}">
                                    <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="BackButtonVisibility" />
                                    <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="SelectedItem.BackButtonVisibility" />
                                </MultiBinding>
                            </Button.Visibility>
                        </Button>
                        <Button Name="NextButton" Command="{x:Static c:WizardCommands.NextPage}"
                        Content="{TemplateBinding NextButtonContent}" Style="{StaticResource WizardButton}">
                            <Button.Visibility>
                                <MultiBinding Converter="{StaticResource WizardPageButtonVisibilityConverter}">
                                    <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="NextButtonVisibility" />
                                    <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="SelectedItem.NextButtonVisibility" />
                                </MultiBinding>
                            </Button.Visibility>
                        </Button>
                        <Button Name="FinishButton" Command="{x:Static c:WizardCommands.Finish}" Content="{TemplateBinding FinishButtonContent}"
                        Style="{StaticResource WizardButton}">
                            <Button.Visibility>
                                <MultiBinding Converter="{StaticResource WizardPageButtonVisibilityConverter}">
                                    <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="FinishButtonVisibility" />
                                    <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="SelectedItem.FinishButtonVisibility" />
                                </MultiBinding>
                            </Button.Visibility>
                        </Button>
                        <Button Name="CancelButton" Command="{x:Static c:WizardCommands.Cancel}" Content="{TemplateBinding CancelButtonContent}"
                        Style="{StaticResource WizardButton}">
                            <Button.Visibility>
                                <MultiBinding Converter="{StaticResource WizardPageButtonVisibilityConverter}">
                                    <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="CancelButtonVisibility" />
                                    <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="SelectedItem.CancelButtonVisibility" />
                                </MultiBinding>
                            </Button.Visibility>
                        </Button>
                    </StackPanel>

                    <ContentPresenter Content="{Binding SelectedItem, RelativeSource={RelativeSource TemplatedParent}}" />
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

However, when I assign an ObservableCollection<BaseViewModel> along with specific DataTemplates...

<c:Wizard Grid.Column="1" ItemsSource="{Binding WizardSteps}">
    <c:Wizard.Resources>
        <DataTemplate DataType="{x:Type vm:WizardStep1ViewModel}">
            <Border Background="Red" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type vm:WizardStep2ViewModel}">
            <Border Background="Green" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type vm:WizardStep3ViewModel}">
            <Border Background="Blue" />
        </DataTemplate>
    </c:Wizard.Resources>
</c:Wizard>
```

...then the DataTemplates are instantiated and shown properly, but no WizardPages are being created in the meantime.

How can I fix it?

答:
Your ControlTemplate should include an ItemsPresenter for a WizardPage to get created for each item in the source collection, e.g.:

```<code><Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="c:Wizard">
            <ItemsPresenter />
        </ControlTemplate>
    </Setter.Value>
</Setter>
</code>```

Body:
I'm creating a Wizard control based on Selector. My plan is that it will behave in the similar way to TabControl, ListBox, etc. - by having its own child items.

What I already did is:

public class Wizard : Selector
{
    // ...

    protected override DependencyObject GetContainerForItemOverride() => new WizardPage();

    protected override bool IsItemItsOwnContainerOverride(object item) => item is WizardPage;

    // ...

The relevant part ControlTemplate for my control looks like this:

However, when I assign an ObservableCollection<BaseViewModel> along with specific DataTemplates...

<c:Wizard Grid.Column="1" ItemsSource="{Binding WizardSteps}">
    <c:Wizard.Resources>
        <DataTemplate DataType="{x:Type vm:WizardStep1ViewModel}">
            <Border Background="Red" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type vm:WizardStep2ViewModel}">
            <Border Background="Green" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type vm:WizardStep3ViewModel}">
            <Border Background="Blue" />
        </DataTemplate>
    </c:Wizard.Resources>
</c:Wizard>

...then the DataTemplates are instantiated and shown properly, but no WizardPages are being created in the meantime.

How can I fix it?

Body:
Your ControlTemplate should include an ItemsPresenter for a WizardPage to get created for each item in the source collection, e.g.:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="c:Wizard">
            <ItemsPresenter />
        </ControlTemplate>
    </Setter.Value>
</Setter>


问:
Is there any chance to simply call method in new thread?
my problem is that when I run the android app, it takes a minute for this method to run if the printer is offline. I would like to run it on another thread in the background and the original thread could run uninterrupted. Thanks for any advice, happy codding!</p>
```<code>public class MainActivity extends WebView {
public PrinterManager printerManager;
public final int REQUEST_COARSE_LOCATION_PERMISSIONS = 52;
private JSPlugin plugin;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mBluetoothReceiver, filter);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_COARSE_LOCATION_PERMISSIONS: {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //printerManager.connectDefaultPrinter(0);
                //printerManager.connectDefaultPrinter(1);

                printerManager.connectAll(); <----- This method call i want to do in new thread
            } else {
                Toast.makeText(this,
                        "NO Bluetooth RIGHTS",
                        Toast.LENGTH_LONG).show();
            }
            return;
        }
    }
}
</code>```

答:
You could simply create a Thread object and put your method into it.

Here the code that should work for your case:

```<code>public class MainActivity extends WebView {
    public PrinterManager printerManager;
    public final int REQUEST_COARSE_LOCATION_PERMISSIONS = 52;
    private JSPlugin plugin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBluetoothReceiver, filter);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_COARSE_LOCATION_PERMISSIONS: {
                if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    ConnectingThread connectingThread = new ConnectingThread();
                    connectingThread.start();
                } else {
                    Toast.makeText(this, "NO Bluetooth RIGHTS", Toast.LENGTH_LONG).show();
                }
                return;
            }
        }
    }

    private class ConnectingThread extends Thread {

        public ConnectingThread() {
        }

        public void run() {
            // You can set a low priority, if you want, using:
            //Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            printerManager.connectAll();
        }
    }
}
</code>```

Basing on your management needs, you can decide to place the definition of your connectingThread in a different position.

Body:
my problem is that when I run the android app, it takes a minute for this method to run if the printer is offline. I would like to run it on another thread in the background and the original thread could run uninterrupted. Thanks for any advice, happy codding!

public class MainActivity extends WebView {
public PrinterManager printerManager;
public final int REQUEST_COARSE_LOCATION_PERMISSIONS = 52;
private JSPlugin plugin;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mBluetoothReceiver, filter);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_COARSE_LOCATION_PERMISSIONS: {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //printerManager.connectDefaultPrinter(0);
                //printerManager.connectDefaultPrinter(1);

                printerManager.connectAll(); <----- This method call i want to do in new thread
            } else {
                Toast.makeText(this,
                        "NO Bluetooth RIGHTS",
                        Toast.LENGTH_LONG).show();
            }
            return;
        }
    }
}

Body:
You could simply create a Thread object and put your method into it.

Here the code that should work for your case:

public class MainActivity extends WebView {
    public PrinterManager printerManager;
    public final int REQUEST_COARSE_LOCATION_PERMISSIONS = 52;
    private JSPlugin plugin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBluetoothReceiver, filter);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_COARSE_LOCATION_PERMISSIONS: {
                if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    ConnectingThread connectingThread = new ConnectingThread();
                    connectingThread.start();
                } else {
                    Toast.makeText(this, "NO Bluetooth RIGHTS", Toast.LENGTH_LONG).show();
                }
                return;
            }
        }
    }

    private class ConnectingThread extends Thread {

        public ConnectingThread() {
        }

        public void run() {
            // You can set a low priority, if you want, using:
            //Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            printerManager.connectAll();
        }
    }
}

Basing on your management needs, you can decide to place the definition of your connectingThread in a different position.


问:
I am with problems to do a query with array column in PostgreSQL with Spring Data
Entity

I have it entity with a property that is text[]:

```<code>    @Entity(name = "entityname")
@Table(name = "tablename")
@ToString
@TypeDefs({
  @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class),
  @TypeDef(name = "list-array", typeClass = ListArrayType.class)
})
public class EntityClass extends Audit
...

  @Type(type = "list-array")
  @Column(name = "participants", columnDefinition = "text[]")
  private List<String> participants;
  ....
</code>```

Repository

I want to execute and findAll with a filter. This filter is Specification spec

```<code>data = entityRepository.findAll(filter, pageRequest);
</code>```

The filter was implemented according to Specification:

```<code>public class Filter<T> implements Specification<T> {

  private final List<Condition> conditions = new ArrayList<>();

  public void addCondition(Condition condition) {
    this.conditions.add(condition);
  }

  private List<Predicate> buildPredicates(Root root, CriteriaQuery query, CriteriaBuilder cb) {
    List<Predicate> predicates = new ArrayList<>();
    for (Condition condition : conditions) {
      predicates.add(buildPredicate(condition, root, query, cb));
    }
    return predicates;
  }

  public Predicate buildPredicate(
      Condition condition, Root root, CriteriaQuery query, CriteriaBuilder cb) {
    if (!condition.getType().getValue().contains(condition.getComparison())) {
      throw new RuntimeException("UNSUPPORTED_COMPARISON_FOR_SPECIFIED_TYPE");
    }
    switch (condition.getComparison()) {
      case EQ:
        if (condition.getValue().getClass().isArray()) {
          final Predicate[] predicatesList =
              Arrays.stream((Object[]) condition.getValue())
                  .map(conditionValue -> cb.equal(root.get(condition.getField()), conditionValue))
                  .toArray(Predicate[]::new);
          return cb.or(predicatesList);
        }
        return cb.equal(root.get(condition.getField()), condition.getValue());
      case GT:
        if (condition.getType().equals(FilterFieldTypes.DATE)) {
          return cb.greaterThan(
              root.<Date>get(condition.getField()),
              new Date(condition.getValueAsNumber().longValue()));
        } else {
          return cb.gt(root.get(condition.getField()), condition.getValueAsNumber());
        }
      case GTE:
        if (condition.getType().equals(FilterFieldTypes.DATE)) {
          return cb.greaterThanOrEqualTo(
              root.<Date>get(condition.getField()),
              new Date(condition.getValueAsNumber().longValue()));
        } else {
          return cb.ge(root.get(condition.getField()), condition.getValueAsNumber());
        }
      case LT:
        if (condition.getType().equals(FilterFieldTypes.DATE)) {
          return cb.lessThan(
              root.<Date>get(condition.getField()),
              new Date(condition.getValueAsNumber().longValue()));
        } else {
          return cb.lt(root.get(condition.getField()), condition.getValueAsNumber());
        }
      case LTE:
        if (condition.getType().equals(FilterFieldTypes.DATE)) {
          return cb.lessThanOrEqualTo(
              root.<Date>get(condition.getField()),
              new Date(condition.getValueAsNumber().longValue()));
        } else {
          return cb.le(root.get(condition.getField()), condition.getValueAsNumber());
        }
      case FULL_TEXT:
        return cb.isTrue(cb.function("fts", Boolean.class, cb.literal(condition.getValue())));
      case JSONB_ARRAY_IN:
        return cb.isTrue(
            cb.function(
                "jsonb_extract_path_text", Boolean.class, cb.literal(condition.getValue())));
      case JSONB_PATH_EQ:
        return cb.isTrue(
            cb.function(
                "jsonb_array_contains",
                Boolean.class,
                cb.literal(condition.getField()),
                cb.literal(condition.getValue())));
      case IN:
        List<String> dataList = Arrays.asList(condition.getValue().toString());
        return cb.in(root.get(condition.getField())).value(dataList);

      default:
        throw new RuntimeException("UNSUPPORTED_COMPARISON");
    }
  }

  public int getConditionsCount() {
    return conditions.size();
  }

  @Override
  public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
    List<Predicate> predicates = buildPredicates(root, query, cb);
    return predicates.size() > 1 ? cb.and(predicates.toArray(Predicate[]::new)) : predicates.get(0);
  }
}
</code>```

I am having problems with the implementation of my CASE IN:

```<code>      case IN:
        List<String> dataList = Arrays.asList(condition.getValue().toString());
        return cb.in(root.get(condition.getField())).value(dataList);
</code>```

It produces the following error in it class:

```<code>public class ListArrayTypeDescriptor extends AbstractArrayTypeDescriptor<Object> {

...

    @Override
    public Object unwrap(Object value, Class type, WrapperOptions options) {
        if (value instanceof Object[]) {
            return value;
        } else if (value instanceof List) {
            return super.unwrap(((List) value).toArray(), type, options);
        } else {
            throw new UnsupportedOperationException("The provided " + value + " is not a Object[] or List!");
        }
    }

...
</code>```

And the stack trace shows it message:

```<code>java.lang.UnsupportedOperationException: The provided d08d7785-1153-4bb3-b58c-6c79bf5a37f8 is not a Object[] or List!
    at com.vladmihalcea.hibernate.type.array.internal.ListArrayTypeDescriptor.unwrap(ListArrayTypeDescriptor.java:60)
    at

</code>```

Do you have an idea about that is wrong in the implementation of my CASE IN?

答:
I was trying many options until that found it solution:

case ANY:
List predicates = new ArrayList<>();
Expression delimiter = cb.literal(",");

```<code>    predicates.add(cb.like(
        cb.function(
            "array_to_string", String.class, root.get(condition.getField()), delimiter),
        "%" + condition.getValue().toString().toLowerCase() + "%"));
  return cb.and(predicates.toArray(new Predicate[0]));
</code>```

I hope help if someone needs to implement "ANY" with criteriabuilder.

Body:
Entity

I have it entity with a property that is text[]:

    @Entity(name = "entityname")
@Table(name = "tablename")
@ToString
@TypeDefs({
  @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class),
  @TypeDef(name = "list-array", typeClass = ListArrayType.class)
})
public class EntityClass extends Audit
...

  @Type(type = "list-array")
  @Column(name = "participants", columnDefinition = "text[]")
  private List<String> participants;
  ....

Repository

I want to execute and findAll with a filter. This filter is Specification spec

data = entityRepository.findAll(filter, pageRequest);

The filter was implemented according to Specification:

public class Filter<T> implements Specification<T> {

  private final List<Condition> conditions = new ArrayList<>();

  public void addCondition(Condition condition) {
    this.conditions.add(condition);
  }

  private List<Predicate> buildPredicates(Root root, CriteriaQuery query, CriteriaBuilder cb) {
    List<Predicate> predicates = new ArrayList<>();
    for (Condition condition : conditions) {
      predicates.add(buildPredicate(condition, root, query, cb));
    }
    return predicates;
  }

  public Predicate buildPredicate(
      Condition condition, Root root, CriteriaQuery query, CriteriaBuilder cb) {
    if (!condition.getType().getValue().contains(condition.getComparison())) {
      throw new RuntimeException("UNSUPPORTED_COMPARISON_FOR_SPECIFIED_TYPE");
    }
    switch (condition.getComparison()) {
      case EQ:
        if (condition.getValue().getClass().isArray()) {
          final Predicate[] predicatesList =
              Arrays.stream((Object[]) condition.getValue())
                  .map(conditionValue -> cb.equal(root.get(condition.getField()), conditionValue))
                  .toArray(Predicate[]::new);
          return cb.or(predicatesList);
        }
        return cb.equal(root.get(condition.getField()), condition.getValue());
      case GT:
        if (condition.getType().equals(FilterFieldTypes.DATE)) {
          return cb.greaterThan(
              root.<Date>get(condition.getField()),
              new Date(condition.getValueAsNumber().longValue()));
        } else {
          return cb.gt(root.get(condition.getField()), condition.getValueAsNumber());
        }
      case GTE:
        if (condition.getType().equals(FilterFieldTypes.DATE)) {
          return cb.greaterThanOrEqualTo(
              root.<Date>get(condition.getField()),
              new Date(condition.getValueAsNumber().longValue()));
        } else {
          return cb.ge(root.get(condition.getField()), condition.getValueAsNumber());
        }
      case LT:
        if (condition.getType().equals(FilterFieldTypes.DATE)) {
          return cb.lessThan(
              root.<Date>get(condition.getField()),
              new Date(condition.getValueAsNumber().longValue()));
        } else {
          return cb.lt(root.get(condition.getField()), condition.getValueAsNumber());
        }
      case LTE:
        if (condition.getType().equals(FilterFieldTypes.DATE)) {
          return cb.lessThanOrEqualTo(
              root.<Date>get(condition.getField()),
              new Date(condition.getValueAsNumber().longValue()));
        } else {
          return cb.le(root.get(condition.getField()), condition.getValueAsNumber());
        }
      case FULL_TEXT:
        return cb.isTrue(cb.function("fts", Boolean.class, cb.literal(condition.getValue())));
      case JSONB_ARRAY_IN:
        return cb.isTrue(
            cb.function(
                "jsonb_extract_path_text", Boolean.class, cb.literal(condition.getValue())));
      case JSONB_PATH_EQ:
        return cb.isTrue(
            cb.function(
                "jsonb_array_contains",
                Boolean.class,
                cb.literal(condition.getField()),
                cb.literal(condition.getValue())));
      case IN:
        List<String> dataList = Arrays.asList(condition.getValue().toString());
        return cb.in(root.get(condition.getField())).value(dataList);

      default:
        throw new RuntimeException("UNSUPPORTED_COMPARISON");
    }
  }

  public int getConditionsCount() {
    return conditions.size();
  }

  @Override
  public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
    List<Predicate> predicates = buildPredicates(root, query, cb);
    return predicates.size() > 1 ? cb.and(predicates.toArray(Predicate[]::new)) : predicates.get(0);
  }
}

I am having problems with the implementation of my CASE IN:

      case IN:
        List<String> dataList = Arrays.asList(condition.getValue().toString());
        return cb.in(root.get(condition.getField())).value(dataList);

It produces the following error in it class:

public class ListArrayTypeDescriptor extends AbstractArrayTypeDescriptor<Object> {

...

    @Override
    public Object unwrap(Object value, Class type, WrapperOptions options) {
        if (value instanceof Object[]) {
            return value;
        } else if (value instanceof List) {
            return super.unwrap(((List) value).toArray(), type, options);
        } else {
            throw new UnsupportedOperationException("The provided " + value + " is not a Object[] or List!");
        }
    }

...

And the stack trace shows it message:

java.lang.UnsupportedOperationException: The provided d08d7785-1153-4bb3-b58c-6c79bf5a37f8 is not a Object[] or List!
    at com.vladmihalcea.hibernate.type.array.internal.ListArrayTypeDescriptor.unwrap(ListArrayTypeDescriptor.java:60)
    at

Do you have an idea about that is wrong in the implementation of my CASE IN?

Body:
I was trying many options until that found it solution:

case ANY:
List predicates = new ArrayList<>();
Expression delimiter = cb.literal(",");

    predicates.add(cb.like(
        cb.function(
            "array_to_string", String.class, root.get(condition.getField()), delimiter),
        "%" + condition.getValue().toString().toLowerCase() + "%"));
  return cb.and(predicates.toArray(new Predicate[0]));

I hope help if someone needs to implement "ANY" with criteriabuilder.


问:
i am trying to create a virtual environment in python but I get the error: failed to find interpreter for Builtin discover of python_spec=python3.5
Morining All,

i am trying to create a virtual environment in Python with virtualenv, I'm using the command:

```<code>virtualenv -p python3.5 MyVirtualEnv
</code>```

but I get the error:

```<code>RuntimeError: failed to find interpreter for Builtin discover of python_spec='python3.5'
</code>```

Now on my Mac (with M1 chip) I have Python 3.8 but I need a virtual environment because I have to use the ZS library that runs only in older python version.

答: You don't need to install python 3.5 in your virtualenv instead install it on your system and then set it as a Project SDK which will install itself all required things in /venv folder.</p>

Body:
Morining All,

i am trying to create a virtual environment in Python with virtualenv, I'm using the command:

virtualenv -p python3.5 MyVirtualEnv

but I get the error:

RuntimeError: failed to find interpreter for Builtin discover of python_spec='python3.5'

Now on my Mac (with M1 chip) I have Python 3.8 but I need a virtual environment because I have to use the ZS library that runs only in older python version.